From 502e3e1df83ac712dfa630cfbdaa0de1152cd53c Mon Sep 17 00:00:00 2001 From: sebastien <sebastien@ac1d8469-bf42-47a9-8791-bf33cf982152> Date: Wed, 16 Dec 2009 17:17:34 +0000 Subject: [PATCH] Beautified MATLAB code (Unix newline convention + Emacs indentation), except: AIM, swz, particle git-svn-id: https://www.dynare.org/svn/dynare/trunk@3250 ac1d8469-bf42-47a9-8791-bf33cf982152 --- matlab/AIM/dynAIMsolver1.m | 284 +- matlab/AnalyseComputationalEnviroment.m | 430 +-- matlab/CheckPath.m | 88 +- matlab/DiffuseKalmanSmoother1.m | 354 +- matlab/DiffuseKalmanSmoother1_Z.m | 416 +-- matlab/DiffuseKalmanSmoother3.m | 282 +- matlab/DiffuseKalmanSmoother3_Z.m | 270 +- matlab/DiffuseKalmanSmootherH1_Z.m | 424 +-- matlab/DiffuseKalmanSmootherH3.m | 270 +- matlab/DiffuseKalmanSmootherH3_Z.m | 270 +- matlab/DiffuseKalmanSmootherH3corr.m | 78 +- matlab/DiffuseLikelihood1.m | 260 +- matlab/DiffuseLikelihood1_Z.m | 260 +- matlab/DiffuseLikelihood3.m | 390 +- matlab/DiffuseLikelihood3_Z.m | 360 +- matlab/DiffuseLikelihoodH1.m | 262 +- matlab/DiffuseLikelihoodH1_Z.m | 264 +- matlab/DiffuseLikelihoodH3.m | 356 +- matlab/DiffuseLikelihoodH3_Z.m | 364 +- matlab/DiffuseLikelihoodH3corr.m | 102 +- matlab/DsgeLikelihood.m | 528 +-- matlab/DsgeLikelihood_hh.m | 495 ++- matlab/DsgeSmoother.m | 526 +-- matlab/DsgeVarLikelihood.m | 78 +- matlab/GetAllPosteriorDraws.m | 180 +- matlab/GetOneDraw.m | 78 +- matlab/GetPosteriorParametersStatistics.m | 96 +- matlab/MakeAllFigures.m | 336 +- matlab/McMCDiagnostics_core.m | 186 +- matlab/PlotPosteriorDistributions.m | 376 +- matlab/PosteriorFilterSmootherAndForecast.m | 546 +-- matlab/PosteriorIRF.m | 288 +- matlab/ReshapeMatFiles.m | 366 +- matlab/UnivariateSpectralDensity.m | 356 +- .../add_auxiliary_variables_to_steadystate.m | 49 +- matlab/autoregressive_process_specification.m | 48 +- matlab/bfgsi.m | 16 +- matlab/bicgstab_.m | 34 +- matlab/bksup1.m | 6 +- matlab/bksupk.m | 30 +- matlab/block_mfs_steadystate.m | 16 +- matlab/bseastr.m | 42 +- matlab/bvar_density.m | 78 +- matlab/bvar_forecast.m | 268 +- matlab/bvar_irf.m | 220 +- matlab/bvar_toolbox.m | 388 +- matlab/calib.m | 244 +- matlab/calib_obj.m | 81 +- matlab/calib_obj2.m | 60 +- matlab/check.m | 110 +- matlab/check_list_of_variables.m | 220 +- matlab/check_model.m | 72 +- matlab/check_name.m | 2 +- matlab/check_posterior_analysis_data.m | 142 +- matlab/check_prior_analysis_data.m | 136 +- matlab/compute_mh_covariance_matrix.m | 8 +- matlab/compute_model_moments.m | 62 +- matlab/compute_moments_varendo.m | 138 +- matlab/conditional_variance_decomposition.m | 74 +- ...ional_variance_decomposition_mc_analysis.m | 134 +- matlab/correlation_mc_analysis.m | 212 +- matlab/cosn.m | 82 +- matlab/covariance_mc_analysis.m | 130 +- matlab/csminit.m | 282 +- matlab/csminwel.m | 616 ++-- matlab/csolve.m | 200 +- matlab/datatomfile.m | 126 +- matlab/dcompare.m | 26 +- matlab/diag_vech.m | 8 +- matlab/disp_dr.m | 312 +- matlab/disp_dr_sparse.m | 342 +- matlab/disp_identification.m | 214 +- matlab/disp_model_summary.m | 30 +- matlab/disp_moments.m | 102 +- matlab/disp_th_moments.m | 110 +- ...splay_conditional_variance_decomposition.m | 76 +- matlab/distributions/compute_prior_mode.m | 94 +- .../inverse_gamma_specification.m | 48 +- .../distributions/mode_and_variance_to_mean.m | 284 +- .../distributions/multivariate_normal_pdf.m | 6 +- .../distributions/multivariate_student_pdf.m | 8 +- matlab/distributions/rand_inverse_wishart.m | 18 +- matlab/distributions/rand_matrix_normal.m | 8 +- .../distributions/rand_multivariate_normal.m | 2 +- .../distributions/rand_multivariate_student.m | 4 +- matlab/dr1.m | 1152 +++--- matlab/dr11_sparse.m | 978 ++--- matlab/dr1_sparse.m | 246 +- matlab/dsample.m | 24 +- matlab/dsge_posterior_kernel.m | 476 +-- ...tical_conditional_variance_decomposition.m | 2 +- .../dsge_simulated_theoretical_correlation.m | 2 +- ...lated_theoretical_variance_decomposition.m | 2 +- matlab/dy_date.m | 9 +- matlab/dyn2vec.m | 60 +- matlab/dyn_ramsey_dynamic_.m | 478 +-- matlab/dyn_ramsey_static_.m | 275 +- matlab/dynare.m | 50 +- matlab/dynare_config.m | 20 +- matlab/dynare_estimation_1.m | 3172 ++++++++--------- matlab/dynare_estimation_init.m | 508 +-- matlab/dynare_graph.m | 112 +- matlab/dynare_graph_close.m | 60 +- matlab/dynare_graph_init.m | 157 +- matlab/dynare_identification.m | 738 ++-- matlab/dynare_resolve.m | 152 +- matlab/dynare_sensitivity.m | 792 ++-- matlab/dynare_solve.m | 84 +- matlab/dynare_squeeze.m | 30 +- matlab/dynasave.m | 20 +- matlab/dynatype.m | 18 +- matlab/dynsec2hms.m | 10 +- matlab/dyntable.m | 38 +- matlab/erase_compiled_function.m | 48 +- matlab/evaluate_likelihood.m | 196 +- matlab/evaluate_posterior_kernel.m | 12 +- matlab/evaluate_prior.m | 60 +- matlab/extended_path.m | 252 +- matlab/fMessageStatus.m | 66 +- matlab/fParallel.m | 232 +- matlab/f_var.m | 6 +- matlab/ffill.m | 22 +- matlab/forcst.m | 93 +- matlab/forcst2.m | 120 +- matlab/forcst2a.m | 92 +- matlab/forcst_unc.m | 306 +- matlab/forecast.m | 284 +- matlab/forecast_graphs.m | 190 +- matlab/formdata.m | 156 +- matlab/ftest.m | 32 +- matlab/gcompare.m | 20 +- matlab/generalized_cholesky2.m | 54 +- matlab/gensylv/sylvester3.m | 74 +- matlab/gensylv/sylvester3a.m | 18 +- matlab/gensylv/sylvester3mr.m | 114 +- matlab/getH.m | 640 ++-- matlab/getJJ.m | 278 +- matlab/get_date_of_a_file.m | 16 +- matlab/get_moments_size.m | 90 +- matlab/get_name_of_the_last_mh_file.m | 46 +- matlab/get_param_by_name.m | 78 +- matlab/get_posterior_parameters.m | 176 +- matlab/get_prior_info.m | 270 +- matlab/get_variance_of_endogenous_variables.m | 128 +- matlab/global_initialization.m | 468 +-- matlab/gmhmaxlik.m | 556 +-- matlab/graph_decomp.m | 164 +- matlab/hessian.m | 160 +- matlab/homotopy1.m | 162 +- matlab/homotopy2.m | 103 +- matlab/homotopy3.m | 250 +- matlab/identification_checks.m | 290 +- matlab/imcforecast.m | 2 +- matlab/independent_metropolis_hastings.m | 50 +- matlab/independent_metropolis_hastings_core.m | 378 +- matlab/indnv.m | 12 +- matlab/initial_estimation_checks.m | 96 +- matlab/initialize_from_mode.m | 119 +- matlab/initvalf.m | 72 +- matlab/irf.m | 28 +- matlab/isconst.m | 8 +- matlab/isint.m | 16 +- matlab/ispd.m | 8 +- matlab/k_order_pert.m | 150 +- matlab/kalman/build_selection_matrix.m | 8 +- .../kalman/likelihood/diffuse_kalman_filter.m | 204 +- matlab/kalman/likelihood/kalman_filter.m | 96 +- ...ssing_observations_diffuse_kalman_filter.m | 258 +- .../missing_observations_kalman_filter.m | 132 +- .../univariate_diffuse_kalman_filter.m | 4 +- .../univariate_diffuse_kalman_filter_corr.m | 4 +- .../univariate_kalman_filter_corr.m | 246 +- matlab/kalman/steady_state_kalman_gain.m | 2 +- matlab/kalman_transition_matrix.m | 28 +- matlab/kronecker/A_times_B_kronecker_C.m | 2 +- matlab/lnsrch1.m | 128 +- matlab/lpdfgam.m | 16 +- matlab/lpdfgbeta.m | 16 +- matlab/lpdfig1.m | 16 +- matlab/lpdfig2.m | 16 +- matlab/lyapunov_symm.m | 232 +- matlab/make_ex_.m | 44 +- matlab/make_y_.m | 60 +- matlab/marginal_density.m | 94 +- matlab/masterParallel.m | 578 +-- matlab/matlab_ver_less_than.m | 16 +- matlab/maximize_prior_density.m | 27 +- matlab/mcompare.m | 44 +- matlab/metropolis_draw.m | 140 +- matlab/metropolis_hastings_initialization.m | 28 +- matlab/mh_autocorrelation_function.m | 2 +- matlab/mh_optimal_bandwidth.m | 18 +- matlab/minus_logged_prior_density.m | 4 +- matlab/missing/ordeig/ordeig.m | 92 +- matlab/missing/rows_columns/columns.m | 2 +- matlab/missing/rows_columns/rows.m | 2 +- matlab/missing/stats/betacdf.m | 36 +- matlab/missing/stats/betainv.m | 76 +- matlab/missing/stats/betapdf.m | 36 +- matlab/missing/stats/betarnd.m | 2 +- matlab/missing/stats/chi2inv.m | 12 +- matlab/missing/stats/common_size.m | 40 +- matlab/missing/stats/exprnd.m | 14 +- matlab/missing/stats/gamcdf.m | 30 +- matlab/missing/stats/gaminv.m | 62 +- matlab/missing/stats/gampdf.m | 48 +- matlab/missing/stats/gamrnd.m | 505 ++- matlab/missing/stats/normcdf.m | 34 +- matlab/missing/stats/norminv.m | 42 +- matlab/missing/stats/normpdf.m | 36 +- matlab/missing/stats/stdnormal_cdf.m | 12 +- matlab/missing/stats/stdnormal_inv.m | 6 +- matlab/missing/stats/stdnormal_pdf.m | 20 +- matlab/missing_DiffuseKalmanSmoother1.m | 414 +-- matlab/missing_DiffuseKalmanSmoother1_Z.m | 476 +-- matlab/missing_DiffuseKalmanSmoother3.m | 256 +- matlab/missing_DiffuseKalmanSmoother3_Z.m | 242 +- matlab/mode_check.m | 8 +- matlab/model_diagnostics.m | 236 +- matlab/model_info.m | 218 +- matlab/mr_gstep.m | 304 +- matlab/mr_hessian.m | 656 ++-- matlab/mult_elimination.m | 241 +- matlab/my_subplot.m | 24 +- matlab/mydelete.m | 66 +- matlab/name2index.m | 134 +- matlab/newrat.m | 550 +-- matlab/numgrad.m | 70 +- matlab/numgrad3.m | 50 +- matlab/numgrad5.m | 74 +- matlab/octave_ver_less_than.m | 14 +- matlab/osr.m | 52 +- matlab/osr1.m | 144 +- matlab/osr_obj.m | 46 +- matlab/perfect_foresight_simulation.m | 342 +- matlab/plot_icforecast.m | 30 +- matlab/plot_priors.m | 28 +- matlab/pm3.m | 188 +- matlab/posterior_analysis.m | 124 +- matlab/posterior_moments.m | 22 +- matlab/print_info.m | 124 +- matlab/prior_analysis.m | 126 +- matlab/prior_bounds.m | 108 +- matlab/prior_draw.m | 26 +- matlab/prior_posterior_statistics.m | 634 ++-- matlab/prior_sampler.m | 224 +- matlab/prior_statistics.m | 8 +- matlab/qr2.m | 82 +- matlab/qz/mjdgges.m | 2 +- matlab/qz/qzdiv.m | 32 +- matlab/qz/qzswitch.m | 70 +- matlab/ramsey_policy.m | 186 +- matlab/random_walk_metropolis_hastings.m | 50 +- matlab/random_walk_metropolis_hastings_core.m | 370 +- matlab/read_data_.m | 126 +- matlab/read_variables.m | 176 +- matlab/recursive_moments.m | 102 +- matlab/resid.m | 74 +- matlab/resol.m | 74 +- matlab/restricted_steadystate.m | 22 +- matlab/row_header_width.m | 68 +- matlab/rplot.m | 78 +- matlab/save_params_and_steady_state.m | 38 +- matlab/save_results.m | 76 +- matlab/selec_posterior_draws.m | 228 +- matlab/selif.m | 2 +- .../send_endogenous_variables_to_workspace.m | 10 +- matlab/set_all_parameters.m | 206 +- matlab/set_default_option.m | 8 +- matlab/set_param_value.m | 58 +- matlab/set_parameters.m | 146 +- matlab/set_prior.m | 430 +-- matlab/set_shocks.m | 30 +- matlab/set_state_space.m | 50 +- matlab/shock_decomposition.m | 188 +- matlab/simk.m | 494 +-- matlab/simul.m | 74 +- matlab/simult.m | 32 +- matlab/simult_.m | 140 +- matlab/simultxdet.m | 172 +- matlab/size_of_the_reduced_form_model.m | 12 +- matlab/solve1.m | 138 +- matlab/solve_one_boundary.m | 732 ++-- matlab/solve_two_boundaries.m | 578 +-- matlab/steady.m | 62 +- matlab/steady_.m | 94 +- matlab/stoch_simul.m | 408 +-- matlab/stoch_simul_sparse.m | 424 +-- matlab/struct2local.m | 56 +- matlab/subset.m | 192 +- matlab/symmetric_matrix_index.m | 2 +- matlab/th_autocovariances.m | 459 ++- matlab/threads/multi/set_dynare_threads.m | 78 +- matlab/threads/single/isopmenmp.m | 6 +- matlab/trace_plot.m | 2 +- matlab/transition_matrix.m | 127 +- matlab/uniform_specification.m | 88 +- matlab/unvech.m | 20 +- matlab/var_sample_moments.m | 232 +- matlab/variance_decomposition_mc_analysis.m | 124 +- matlab/varlist_indices.m | 94 +- matlab/vech.m | 16 +- matlab/vnorm.m | 174 +- matlab/warning_config.m | 32 +- matlab/writedata.m | 104 +- matlab/writedata_text.m | 106 +- 306 files changed, 25616 insertions(+), 25630 deletions(-) diff --git a/matlab/AIM/dynAIMsolver1.m b/matlab/AIM/dynAIMsolver1.m index a1b25183d9..b115f3c079 100644 --- a/matlab/AIM/dynAIMsolver1.m +++ b/matlab/AIM/dynAIMsolver1.m @@ -1,142 +1,142 @@ -function [dr,aimcode,rts]=dynAIMsolver1(jacobia_,M_,dr) -% function [dr,aimcode]=dynAIMsolver1(jacobia_,M_,dr) -% Maps Dynare jacobia to AIM 1st order model solver designed and developed by Gary ANderson -% and derives the solution for gy=dr.hgx and gu=dr.hgu from the AIM outputs -% AIM System is given as a sum: -% i.e. for i=-$...+& SUM(Hi*xt+i)= �*zt, t = 0, . . . ,? -% and its input as single array of matrices: [H-$... Hi ... H+&] -% and its solution as xt=SUM( Bi*xt+i) + @*�*zt for i=-$...-1 -% with the output in form bb=[B-$... Bi ... B-1] and @=inv(Ho+H1*B-1) -% Dynare jacobian = [fy'-$... fy'i ... fy'+& fu'] -% where [fy'-$... fy'i ... fy'+&]=[H-$... Hi ... H+&] and fu'= � -% -% INPUTS -% jacobia_ [matrix] 1st order derivative of the model -% dr [matlab structure] Decision rules for stochastic simulations. -% M_ [matlab structure] Definition of the model. -% -% OUTPUTS -% dr [matlab structure] Decision rules for stochastic simulations. -% aimcode [integer] 1: the model defines variables uniquely -% aimcode is resolved in AIMerr as -% (c==1) e='Aim: unique solution.'; -% (c==2) e='Aim: roots not correctly computed by real_schur.'; -% (c==3) e='Aim: too many big roots.'; -% (c==35) e='Aim: too many big roots, and q(:,right) is singular.'; -% (c==4) e='Aim: too few big roots.'; -% (c==45) e='Aim: too few big roots, and q(:,right) is singular.'; -% (c==5) e='Aim: q(:,right) is singular.'; -% (c==61) e='Aim: too many exact shiftrights.'; -% (c==62) e='Aim: too many numeric shiftrights.'; -% else e='Aimerr: return code not properly specified'; -% -% SPECIAL REQUIREMENTS -% Dynare use: -% 1) the lognormal block in DR1 is being invoked for some models and changing -% values of ghx and ghy. We need to return the AIM output -% values before that block and run the block with the current returned values -% of gy (i.e. dr.ghx) and gu (dr.ghu) if it is needed even when the AIM is used -% (it does not depend on mjdgges output). -% -% 2) passing in aa={Q'|1}*jacobia_ can produce ~ one order closer -% results to the Dynare solutiion then when if plain jacobia_ is passed, -% i.e. diff < e-14 for aa and diff < *e-13 for jacobia_ if Q' is used. -% -% GP July 2008 - -% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. - -aimcode=-1; -neq= size(jacobia_,1); % no of equations -lags=M_.maximum_endo_lag; % no of lags and leads -leads=M_.maximum_endo_lead; -klen=(leads+lags+1); % total lenght -theAIM_H=zeros(neq, neq*klen); % alloc space -lli=M_.lead_lag_incidence'; -% "sparse" the compact jacobia into AIM H aray of matrices -% without exogenous shoc -theAIM_H(:,find(lli(:)))=jacobia_(:,nonzeros(lli(:))); -condn = 1.e-10;%SPAmalg uses this in zero tests -uprbnd = 1 + 1.e-6;%allow unit roots -% forward only models - AIM must have at least 1 lead and 1 lag. -if lags ==0 - theAIM_H =[zeros(neq) theAIM_H]; - lags=1; - klen=(leads+lags+1); -end -% backward looking only models -if leads ==0 - theAIM_H =[theAIM_H zeros(neq)]; - leads=1; - klen=(leads+lags+1); -end -%disp('gensysToAMA:running ama'); -try % try to run AIM - [bb,rts,ia,nexact,nnumeric,lgroots,aimcode] =... - SPAmalg(theAIM_H,neq, lags,leads,condn,uprbnd); -catch - err = lasterror; - disp(['Dynare AIM Solver error:' sprintf('%s; ID:%s',err.message, err.identifier)]); - rethrow(lasterror); -end -if aimcode==1 %if OK - col_order=[]; - for i =1:lags - col_order=[((i-1)*neq)+dr.order_var' col_order]; - end - bb_ord= bb(dr.order_var,col_order); % derive ordered gy - - % variables are present in the state space at the lag at which they - % appear and at all smaller lags. The are ordered from smaller to - % higher lag (reversed order of M_.lead_lag_incidence rows for lagged - % variables) - i_lagged_vars = flipud(cumsum(M_.lead_lag_incidence(1:M_.maximum_lag,dr.order_var),1))'; - - dr.ghx= bb_ord(:,find(i_lagged_vars(:))); % get columns reported in - % Dynare solution - if M_.exo_nbr % if there are exogenous shocks then derive gu for the shocks: - % get H0 and H+1=HM - % theH0= theAIM_H (:,M_.maximum_endo_lag*neq+1: (M_.maximum_endo_lag+1)*neq); - %theH0= theAIM_H (:,lags*neq+1: (lags+1)*neq); - % theHP= theAIM_H (:,(M_.maximum_endo_lag+1)*neq+1: (M_.maximum_endo_lag+2)*neq); - %theHP= theAIM_H (:,(lags+1)*neq+1: (lags+2)*neq); - theAIM_Psi= - jacobia_(:, size(nonzeros(lli(:)))+1:end);% - %? = inv(H0 + H1B1) - %phi= (theH0+theHP*sparse(bb(:,(lags-1)*neq+1:end)))\eye( neq); - %AIM_ghu=phi*theAIM_Psi; - %dr.ghu =AIM_ghu(dr.order_var,:); % order gu - % Using AIM SPObstruct - scof = SPObstruct(theAIM_H,bb,neq,lags,leads); - scof1= scof(:,(lags)*neq+1:end); - scof1= scof1(:,dr.order_var); - dr.ghu =scof1\theAIM_Psi; - else - dr.ghu = []; - end -else - err=SPAimerr(aimcode); - %warning('Error in AIM: aimcode=%d, erro=%s', aimcode, err);; - disp(['Error in AIM: aimcode=' sprintf('%d : %s',aimcode, err)]); - if aimcode < 1 || aimcode > 5 % too big exception, use mjdgges - error('Error in AIM: aimcode=%d ; %s', aimcode, err); - end -% if aimcode > 5 -% disp(['Error in AIM: aimcode=' sprintf('%d : %s',aimcode, err)]); -% aimcode=5; -% end -end +function [dr,aimcode,rts]=dynAIMsolver1(jacobia_,M_,dr) +% function [dr,aimcode]=dynAIMsolver1(jacobia_,M_,dr) +% Maps Dynare jacobia to AIM 1st order model solver designed and developed by Gary ANderson +% and derives the solution for gy=dr.hgx and gu=dr.hgu from the AIM outputs +% AIM System is given as a sum: +% i.e. for i=-$...+& SUM(Hi*xt+i)= �*zt, t = 0, . . . ,? +% and its input as single array of matrices: [H-$... Hi ... H+&] +% and its solution as xt=SUM( Bi*xt+i) + @*�*zt for i=-$...-1 +% with the output in form bb=[B-$... Bi ... B-1] and @=inv(Ho+H1*B-1) +% Dynare jacobian = [fy'-$... fy'i ... fy'+& fu'] +% where [fy'-$... fy'i ... fy'+&]=[H-$... Hi ... H+&] and fu'= � +% +% INPUTS +% jacobia_ [matrix] 1st order derivative of the model +% dr [matlab structure] Decision rules for stochastic simulations. +% M_ [matlab structure] Definition of the model. +% +% OUTPUTS +% dr [matlab structure] Decision rules for stochastic simulations. +% aimcode [integer] 1: the model defines variables uniquely +% aimcode is resolved in AIMerr as +% (c==1) e='Aim: unique solution.'; +% (c==2) e='Aim: roots not correctly computed by real_schur.'; +% (c==3) e='Aim: too many big roots.'; +% (c==35) e='Aim: too many big roots, and q(:,right) is singular.'; +% (c==4) e='Aim: too few big roots.'; +% (c==45) e='Aim: too few big roots, and q(:,right) is singular.'; +% (c==5) e='Aim: q(:,right) is singular.'; +% (c==61) e='Aim: too many exact shiftrights.'; +% (c==62) e='Aim: too many numeric shiftrights.'; +% else e='Aimerr: return code not properly specified'; +% +% SPECIAL REQUIREMENTS +% Dynare use: +% 1) the lognormal block in DR1 is being invoked for some models and changing +% values of ghx and ghy. We need to return the AIM output +% values before that block and run the block with the current returned values +% of gy (i.e. dr.ghx) and gu (dr.ghu) if it is needed even when the AIM is used +% (it does not depend on mjdgges output). +% +% 2) passing in aa={Q'|1}*jacobia_ can produce ~ one order closer +% results to the Dynare solutiion then when if plain jacobia_ is passed, +% i.e. diff < e-14 for aa and diff < *e-13 for jacobia_ if Q' is used. +% +% GP July 2008 + +% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. + +aimcode=-1; +neq= size(jacobia_,1); % no of equations +lags=M_.maximum_endo_lag; % no of lags and leads +leads=M_.maximum_endo_lead; +klen=(leads+lags+1); % total lenght +theAIM_H=zeros(neq, neq*klen); % alloc space +lli=M_.lead_lag_incidence'; +% "sparse" the compact jacobia into AIM H aray of matrices +% without exogenous shoc +theAIM_H(:,find(lli(:)))=jacobia_(:,nonzeros(lli(:))); +condn = 1.e-10;%SPAmalg uses this in zero tests +uprbnd = 1 + 1.e-6;%allow unit roots + % forward only models - AIM must have at least 1 lead and 1 lag. +if lags ==0 + theAIM_H =[zeros(neq) theAIM_H]; + lags=1; + klen=(leads+lags+1); +end +% backward looking only models +if leads ==0 + theAIM_H =[theAIM_H zeros(neq)]; + leads=1; + klen=(leads+lags+1); +end +%disp('gensysToAMA:running ama'); +try % try to run AIM + [bb,rts,ia,nexact,nnumeric,lgroots,aimcode] =... + SPAmalg(theAIM_H,neq, lags,leads,condn,uprbnd); +catch + err = lasterror; + disp(['Dynare AIM Solver error:' sprintf('%s; ID:%s',err.message, err.identifier)]); + rethrow(lasterror); +end +if aimcode==1 %if OK + col_order=[]; + for i =1:lags + col_order=[((i-1)*neq)+dr.order_var' col_order]; + end + bb_ord= bb(dr.order_var,col_order); % derive ordered gy + + % variables are present in the state space at the lag at which they + % appear and at all smaller lags. The are ordered from smaller to + % higher lag (reversed order of M_.lead_lag_incidence rows for lagged + % variables) + i_lagged_vars = flipud(cumsum(M_.lead_lag_incidence(1:M_.maximum_lag,dr.order_var),1))'; + + dr.ghx= bb_ord(:,find(i_lagged_vars(:))); % get columns reported in + % Dynare solution + if M_.exo_nbr % if there are exogenous shocks then derive gu for the shocks: + % get H0 and H+1=HM + % theH0= theAIM_H (:,M_.maximum_endo_lag*neq+1: (M_.maximum_endo_lag+1)*neq); + %theH0= theAIM_H (:,lags*neq+1: (lags+1)*neq); + % theHP= theAIM_H (:,(M_.maximum_endo_lag+1)*neq+1: (M_.maximum_endo_lag+2)*neq); + %theHP= theAIM_H (:,(lags+1)*neq+1: (lags+2)*neq); + theAIM_Psi= - jacobia_(:, size(nonzeros(lli(:)))+1:end);% + %? = inv(H0 + H1B1) + %phi= (theH0+theHP*sparse(bb(:,(lags-1)*neq+1:end)))\eye( neq); + %AIM_ghu=phi*theAIM_Psi; + %dr.ghu =AIM_ghu(dr.order_var,:); % order gu + % Using AIM SPObstruct + scof = SPObstruct(theAIM_H,bb,neq,lags,leads); + scof1= scof(:,(lags)*neq+1:end); + scof1= scof1(:,dr.order_var); + dr.ghu =scof1\theAIM_Psi; + else + dr.ghu = []; + end +else + err=SPAimerr(aimcode); + %warning('Error in AIM: aimcode=%d, erro=%s', aimcode, err);; + disp(['Error in AIM: aimcode=' sprintf('%d : %s',aimcode, err)]); + if aimcode < 1 || aimcode > 5 % too big exception, use mjdgges + error('Error in AIM: aimcode=%d ; %s', aimcode, err); + end + % if aimcode > 5 + % disp(['Error in AIM: aimcode=' sprintf('%d : %s',aimcode, err)]); + % aimcode=5; + % end +end diff --git a/matlab/AnalyseComputationalEnviroment.m b/matlab/AnalyseComputationalEnviroment.m index f29490a413..0028bcbbae 100644 --- a/matlab/AnalyseComputationalEnviroment.m +++ b/matlab/AnalyseComputationalEnviroment.m @@ -1,215 +1,215 @@ -function [ErrorCode] = AnalyseComputationalEnviroment(DataInput) -% Input/Output description: -% -% DataInput is the strcture option_.parallel, with the follow fields: -% -% Local Define the computation place: 1 is on local machine, 0 remote -% PcName Intuitive: contain the computer name. -% NumCPU Intuitive: contain the CPU number. -% user Intuitive: contain the use name for the PcName. -% passwd Intuitive: contain the password for the user name in PcName. -% RemoteDrive Drive used for Local/Remote computation (data exchange, etc) must be contain 'RemoteFolder'. -% RemoteFolder Folder in RemoteDrive used for Local/Remote computation. -% -% This information is typed by the user using the *.mod file, -% the goal of this function is to check if it correct. -% -% -% The variable ErrorCode is initialized at 0. If there are non problems with -% Local, PcName connections,... in general with parallel software execution, -% the ErrorCode is unchanged, in the others cases 1, 2 , ... The values -% table is below. -% -% -% Table for ErrorCode Values. -% -% ErrorCode -> 0 Initial Value -> No Error Detected!!! -% ErrorCode -> > 1 When an error happens. The value 1, 2, 3... are -% used to specify the kind of error. -% -% Value 1: The variable 'Local' has a bad value! -% -% Value 2: The variable 'NumCPU' has a bad value. Parallel Dynare -% require an input data like [s:d] with s<=d, in this case we -% have s>d! -% 2.1 The user asks to use more CPU of those available. -% 2.2 There are CPU not used! -% -% Value 3: The remote computer is unreachable!!! -% -% Value 4: The user name and/or password is/are incorrect on the -% remote computer! -% -% Value 5: It is impossible write/read file on remote computer. -% -% Then at the point call of this function it is possible react in a best way, in accord -% with the ErrorCode. - -% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. - -ErrorCode=0; - - -% The function is composed by two main blocks, determined by the 'Local' -% variable. - -if ((DataInput.Local == 0) |(DataInput.Local == 1)) - % Continue it is Ok! -else - ErrorCode=1; - return - -end - - -%%%%%%%%%% Local Machine %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -% In this case we need to check only the variable 'NumCPU'. - -% We run the parallel code on local computer, so the others fields are automatically -% fixed by Dynare. Then the user can also fill them with wrong values. - -if (DataInput.Local == 1) - - yn=isempty(DataInput.NumCPU); - - if yn==1 - ErrorCode=2; - return - end - - % We look for the information on local computer hardware. - - si=[]; - de=[]; - - [si de]=system(['psinfo \\']); - - RealNumCPU=-1; - RealNumCPU=GiveCPUnumber(de); - -% Trasforming the input data provided in a form [n1:n2] in a single numerical -% value. - - DataInput.NumCPU=length(DataInput.NumCPU); - - if DataInput.NumCPU == RealNumCPU - % It is Ok! - end - - if DataInput.NumCPU > RealNumCPU - ErrorCode=2.1; - - end - if DataInput.NumCPU < RealNumCPU - ErrorCode=2.2; - end -end - -%%%%%%%%%% Remote Machine %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -% In this case we need more sophisticated check. - - -if (DataInput.Local == 0) - - si=[]; - de=[]; - - [si de]=system(['ping ', DataInput.PcName]); - - if si==1 - % It is impossiblie to be connected to the - % remote computer. - - ErrorCode=3; - return; - end - - - % -> IL CODICE SEGUENTE E' DA CONTROLLARE E VERIFICARE! - - % The Local Machine can be connetted with Remote Computer. - % Now we verify if user name and password are correct and if remote - % drive and remote folder exist on the remote computer and it is - % possible to exchange data with them. - - si=[]; - de=[]; - - [si de]=system(['psinfo \\', DataInput.PcName, ' -u ',DataInput.user, ' -p ',DataInput.passwd ]); - - if si<0 - % It is possible to be connected to the remote computer but it is not usable because the user - % name and/or password is/are incorrect. - - ErrorCodeComputer=4; - return; - else - % Username and Password are correct! - end - - % Now we verify if it possible to exchange data with the remote - % computer: - - - fid = fopen('Tracing.txt','w+'); - fclose (fid); - - % ATTENZIONE: verificare perche sembra funzionare anche se il RemoteFolder non - % esiste. - - Status=movefile('Tracing.txt', ['\\',DataInput.PcName,'\',DataInput.RemoteDrive,'$\',DataInput.RemoteFolder]); - - if Status==1 - % Remote Drive/Folder exist on Remote computer and - % it is possible to exchange data with him. - else - - % Move file error! - ErrorCodeComputer=5; - return; - end - - % At this point we can to analyze the remote computer hardware. - - - RealNumCPU=-1; - RealNumCPU=GiveCPUnumber(de); - -% Trasforming the input data provided in a form [n1:n2] in a single numerical -% value. - - - DataInput.NumCPU=length(DataInput.NumCPU); - - if DataInput.NumCPU == RealNumCPU - % It is Ok! - end - - if DataInput.NumCPU > RealNumCPU - ErrorCode=2.1; - - end - if DataInput.NumCPU < RealNumCPU - ErrorCode=2.2; - end - -end - - +function [ErrorCode] = AnalyseComputationalEnviroment(DataInput) +% Input/Output description: +% +% DataInput is the strcture option_.parallel, with the follow fields: +% +% Local Define the computation place: 1 is on local machine, 0 remote +% PcName Intuitive: contain the computer name. +% NumCPU Intuitive: contain the CPU number. +% user Intuitive: contain the use name for the PcName. +% passwd Intuitive: contain the password for the user name in PcName. +% RemoteDrive Drive used for Local/Remote computation (data exchange, etc) must be contain 'RemoteFolder'. +% RemoteFolder Folder in RemoteDrive used for Local/Remote computation. +% +% This information is typed by the user using the *.mod file, +% the goal of this function is to check if it correct. +% +% +% The variable ErrorCode is initialized at 0. If there are non problems with +% Local, PcName connections,... in general with parallel software execution, +% the ErrorCode is unchanged, in the others cases 1, 2 , ... The values +% table is below. +% +% +% Table for ErrorCode Values. +% +% ErrorCode -> 0 Initial Value -> No Error Detected!!! +% ErrorCode -> > 1 When an error happens. The value 1, 2, 3... are +% used to specify the kind of error. +% +% Value 1: The variable 'Local' has a bad value! +% +% Value 2: The variable 'NumCPU' has a bad value. Parallel Dynare +% require an input data like [s:d] with s<=d, in this case we +% have s>d! +% 2.1 The user asks to use more CPU of those available. +% 2.2 There are CPU not used! +% +% Value 3: The remote computer is unreachable!!! +% +% Value 4: The user name and/or password is/are incorrect on the +% remote computer! +% +% Value 5: It is impossible write/read file on remote computer. +% +% Then at the point call of this function it is possible react in a best way, in accord +% with the ErrorCode. + +% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. + +ErrorCode=0; + + +% The function is composed by two main blocks, determined by the 'Local' +% variable. + +if ((DataInput.Local == 0) |(DataInput.Local == 1)) + % Continue it is Ok! +else + ErrorCode=1; + return + +end + + +%%%%%%%%%% Local Machine %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% In this case we need to check only the variable 'NumCPU'. + +% We run the parallel code on local computer, so the others fields are automatically +% fixed by Dynare. Then the user can also fill them with wrong values. + +if (DataInput.Local == 1) + + yn=isempty(DataInput.NumCPU); + + if yn==1 + ErrorCode=2; + return + end + + % We look for the information on local computer hardware. + + si=[]; + de=[]; + + [si de]=system(['psinfo \\']); + + RealNumCPU=-1; + RealNumCPU=GiveCPUnumber(de); + + % Trasforming the input data provided in a form [n1:n2] in a single numerical + % value. + + DataInput.NumCPU=length(DataInput.NumCPU); + + if DataInput.NumCPU == RealNumCPU + % It is Ok! + end + + if DataInput.NumCPU > RealNumCPU + ErrorCode=2.1; + + end + if DataInput.NumCPU < RealNumCPU + ErrorCode=2.2; + end +end + +%%%%%%%%%% Remote Machine %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% In this case we need more sophisticated check. + + +if (DataInput.Local == 0) + + si=[]; + de=[]; + + [si de]=system(['ping ', DataInput.PcName]); + + if si==1 + % It is impossiblie to be connected to the + % remote computer. + + ErrorCode=3; + return; + end + + + % -> IL CODICE SEGUENTE E' DA CONTROLLARE E VERIFICARE! + + % The Local Machine can be connetted with Remote Computer. + % Now we verify if user name and password are correct and if remote + % drive and remote folder exist on the remote computer and it is + % possible to exchange data with them. + + si=[]; + de=[]; + + [si de]=system(['psinfo \\', DataInput.PcName, ' -u ',DataInput.user, ' -p ',DataInput.passwd ]); + + if si<0 + % It is possible to be connected to the remote computer but it is not usable because the user + % name and/or password is/are incorrect. + + ErrorCodeComputer=4; + return; + else + % Username and Password are correct! + end + + % Now we verify if it possible to exchange data with the remote + % computer: + + + fid = fopen('Tracing.txt','w+'); + fclose (fid); + + % ATTENZIONE: verificare perche sembra funzionare anche se il RemoteFolder non + % esiste. + + Status=movefile('Tracing.txt', ['\\',DataInput.PcName,'\',DataInput.RemoteDrive,'$\',DataInput.RemoteFolder]); + + if Status==1 + % Remote Drive/Folder exist on Remote computer and + % it is possible to exchange data with him. + else + + % Move file error! + ErrorCodeComputer=5; + return; + end + + % At this point we can to analyze the remote computer hardware. + + + RealNumCPU=-1; + RealNumCPU=GiveCPUnumber(de); + + % Trasforming the input data provided in a form [n1:n2] in a single numerical + % value. + + + DataInput.NumCPU=length(DataInput.NumCPU); + + if DataInput.NumCPU == RealNumCPU + % It is Ok! + end + + if DataInput.NumCPU > RealNumCPU + ErrorCode=2.1; + + end + if DataInput.NumCPU < RealNumCPU + ErrorCode=2.2; + end + +end + + diff --git a/matlab/CheckPath.m b/matlab/CheckPath.m index 734efa7192..fdaa2dd3ae 100644 --- a/matlab/CheckPath.m +++ b/matlab/CheckPath.m @@ -1,44 +1,44 @@ -function DirectoryName = CheckPath(type) -% Creates the subfolder "./M_.dname/type" if it does not exist yet. -% -% INPUTS -% type [string] Name of the subfolder. -% -% OUTPUTS -% none. -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2005-2009 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 <http://www.gnu.org/licenses/>. - -global M_ - -DirectoryName = [ M_.dname '/' type ]; - -if ~isdir(M_.dname) - % Make sure there isn't a file with the same name, see trac ticket #47 - delete(M_.dname) - mkdir('.', M_.dname); -end - -if ~isdir(DirectoryName) - % Make sure there isn't a file with the same name, see trac ticket #47 - delete(DirectoryName) - mkdir('.',DirectoryName); -end +function DirectoryName = CheckPath(type) +% Creates the subfolder "./M_.dname/type" if it does not exist yet. +% +% INPUTS +% type [string] Name of the subfolder. +% +% OUTPUTS +% none. +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2005-2009 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 <http://www.gnu.org/licenses/>. + +global M_ + +DirectoryName = [ M_.dname '/' type ]; + +if ~isdir(M_.dname) + % Make sure there isn't a file with the same name, see trac ticket #47 + delete(M_.dname) + mkdir('.', M_.dname); +end + +if ~isdir(DirectoryName) + % Make sure there isn't a file with the same name, see trac ticket #47 + delete(DirectoryName) + mkdir('.',DirectoryName); +end diff --git a/matlab/DiffuseKalmanSmoother1.m b/matlab/DiffuseKalmanSmoother1.m index da3a2c7f39..395a58ef04 100644 --- a/matlab/DiffuseKalmanSmoother1.m +++ b/matlab/DiffuseKalmanSmoother1.m @@ -1,177 +1,177 @@ -function [alphahat,etahat,atilde, aK] = DiffuseKalmanSmoother1(T,R,Q,Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf) - -% function [alphahat,etahat,a, aK] = DiffuseKalmanSmoother1(T,R,Q,Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf) -% Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix -% -% INPUTS -% T: mm*mm matrix -% R: mm*rr matrix -% Q: rr*rr matrix -% Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros -% Pstar1: mm*mm variance-covariance matrix with stationary variables -% Y: pp*1 vector -% trend -% pp: number of observed variables -% mm: number of state variables -% smpl: sample size -% mf: observed variables index in the state vector -% -% OUTPUTS -% alphahat: smoothed state variables (a_{t|T}) -% etahat: smoothed shocks -% atilde: matrix of updated variables (a_{t|t}) -% aK: 3D array of k step ahead filtered state variables (a_{t+k|t}) - -% SPECIAL REQUIREMENTS -% See "Filtering and Smoothing of State Vector for Diffuse State Space -% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series -% Analysis, vol. 24(1), pp. 85-98). - -% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. - -% modified by M. Ratto: -% new output argument aK (1-step to k-step predictions) -% new options_.nk: the max step ahed prediction in aK (default is 4) -% new crit1 value for rank of Pinf -% it is assured that P is symmetric - - -global options_ - -nk = options_.nk; -spinf = size(Pinf1); -spstar = size(Pstar1); -v = zeros(pp,smpl); -a = zeros(mm,smpl+1); -atilde = zeros(mm,smpl); -aK = zeros(nk,mm,smpl+1); -iF = zeros(pp,pp,smpl); -Fstar = zeros(pp,pp,smpl); -iFinf = zeros(pp,pp,smpl); -K = zeros(mm,pp,smpl); -L = zeros(mm,mm,smpl); -Linf = zeros(mm,mm,smpl); -Kstar = zeros(mm,pp,smpl); -P = zeros(mm,mm,smpl+1); -Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1; -Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1; -crit = options_.kalman_tol; -crit1 = 1.e-8; -steady = smpl; -rr = size(Q,1); -QQ = R*Q*transpose(R); -QRt = Q*transpose(R); -alphahat = zeros(mm,smpl); -etahat = zeros(rr,smpl); -r = zeros(mm,smpl+1); - -Z = zeros(pp,mm); -for i=1:pp; - Z(i,mf(i)) = 1; -end - -t = 0; -while rank(Pinf(:,:,t+1),crit1) & t<smpl - t = t+1; - v(:,t) = Y(:,t) - a(mf,t) - trend(:,t); - if rcond(Pinf(mf,mf,t)) < crit - return - end - iFinf(:,:,t) = inv(Pinf(mf,mf,t)); - PZI = Pinf(:,mf,t)*iFinf(:,:,t); - atilde(:,t) = a(:,t) + PZI*v(:,t); - Kinf(:,:,t) = T*PZI; - a(:,t+1) = T*atilde(:,t); - aK(1,:,t+1) = a(:,t+1); - for jnk=2:nk, - aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); - end - Linf(:,:,t) = T - Kinf(:,:,t)*Z; - Fstar(:,:,t) = Pstar(mf,mf,t); - Kstar(:,:,t) = (T*Pstar(:,mf,t)-Kinf(:,:,t)*Fstar(:,:,t))*iFinf(:,:,t); - Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)-T*Pstar(:,mf,t)*transpose(Kinf(:,:,t))-Kinf(:,:,t)*Pinf(mf,mf,t)*transpose(Kstar(:,:,t)) + QQ; - Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T)-T*Pinf(:,mf,t)*transpose(Kinf(:,:,t)); -end -d = t; -P(:,:,d+1) = Pstar(:,:,d+1); -iFinf = iFinf(:,:,1:d); -Linf = Linf(:,:,1:d); -Fstar = Fstar(:,:,1:d); -Kstar = Kstar(:,:,1:d); -Pstar = Pstar(:,:,1:d); -Pinf = Pinf(:,:,1:d); -notsteady = 1; -while notsteady & t<smpl - t = t+1; - v(:,t) = Y(:,t) - a(mf,t) - trend(:,t); - P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); - if rcond(P(mf,mf,t)) < crit - return - end - iF(:,:,t) = inv(P(mf,mf,t)); - PZI = P(:,mf,t)*iF(:,:,t); - atilde(:,t) = a(:,t) + PZI*v(:,t); - K(:,:,t) = T*PZI; - L(:,:,t) = T-K(:,:,t)*Z; - a(:,t+1) = T*atilde(:,t); - aK(1,:,t+1) = a(:,t+1); - for jnk=2:nk, - aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); - end - P(:,:,t+1) = T*P(:,:,t)*transpose(T)-T*P(:,mf,t)*transpose(K(:,:,t)) + QQ; - notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); -end -if t<smpl - PZI_s = PZI; - K_s = K(:,:,t); - iF_s = iF(:,:,t); - P_s = P(:,:,t+1); - t_steady = t+1; - P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1])); - iF = cat(3,iF(:,:,1:t),repmat(inv(P_s(mf,mf)),[1 1 smpl-t_steady+1])); - L = cat(3,L(:,:,1:t),repmat(T-K_s*Z,[1 1 smpl-t_steady+1])); - K = cat(3,K(:,:,1:t),repmat(T*P_s(:,mf)*iF_s,[1 1 smpl-t_steady+1])); -end -while t<smpl - t=t+1; - v(:,t) = Y(:,t) - a(mf,t) - trend(:,t); - atilde(:,t) = a(:,t) + PZI*v(:,t); - a(:,t+1) = T*a(:,t) + K_s*v(:,t); - aK(1,:,t+1) = a(:,t+1); - for jnk=2:nk, - aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); - end -end -t = smpl+1; -while t>d+1 - t = t-1; - r(:,t) = Z'*iF(:,:,t)*v(:,t) + L(:,:,t)'*r(:,t+1); - alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t); - etahat(:,t) = QRt*r(:,t); -end -if d - r0 = zeros(mm,d+1); - r0(:,d+1) = r(:,d+1); - r1 = zeros(mm,d+1); - for t = d:-1:1 - r0(:,t) = Linf(:,:,t)'*r0(:,t+1); - r1(:,t) = Z'*(iFinf(:,:,t)*v(:,t)-Kstar(:,:,t)'*r0(:,t+1)) + Linf(:,:,t)'*r1(:,t+1); - alphahat(:,t) = a(:,t) + Pstar(:,:,t)*r0(:,t) + Pinf(:,:,t)*r1(:,t); - etahat(:,t) = QRt*r0(:,t); - end -end +function [alphahat,etahat,atilde, aK] = DiffuseKalmanSmoother1(T,R,Q,Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf) + +% function [alphahat,etahat,a, aK] = DiffuseKalmanSmoother1(T,R,Q,Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf) +% Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix +% +% INPUTS +% T: mm*mm matrix +% R: mm*rr matrix +% Q: rr*rr matrix +% Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros +% Pstar1: mm*mm variance-covariance matrix with stationary variables +% Y: pp*1 vector +% trend +% pp: number of observed variables +% mm: number of state variables +% smpl: sample size +% mf: observed variables index in the state vector +% +% OUTPUTS +% alphahat: smoothed state variables (a_{t|T}) +% etahat: smoothed shocks +% atilde: matrix of updated variables (a_{t|t}) +% aK: 3D array of k step ahead filtered state variables (a_{t+k|t}) + +% SPECIAL REQUIREMENTS +% See "Filtering and Smoothing of State Vector for Diffuse State Space +% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series +% Analysis, vol. 24(1), pp. 85-98). + +% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. + +% modified by M. Ratto: +% new output argument aK (1-step to k-step predictions) +% new options_.nk: the max step ahed prediction in aK (default is 4) +% new crit1 value for rank of Pinf +% it is assured that P is symmetric + + +global options_ + +nk = options_.nk; +spinf = size(Pinf1); +spstar = size(Pstar1); +v = zeros(pp,smpl); +a = zeros(mm,smpl+1); +atilde = zeros(mm,smpl); +aK = zeros(nk,mm,smpl+1); +iF = zeros(pp,pp,smpl); +Fstar = zeros(pp,pp,smpl); +iFinf = zeros(pp,pp,smpl); +K = zeros(mm,pp,smpl); +L = zeros(mm,mm,smpl); +Linf = zeros(mm,mm,smpl); +Kstar = zeros(mm,pp,smpl); +P = zeros(mm,mm,smpl+1); +Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1; +Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1; +crit = options_.kalman_tol; +crit1 = 1.e-8; +steady = smpl; +rr = size(Q,1); +QQ = R*Q*transpose(R); +QRt = Q*transpose(R); +alphahat = zeros(mm,smpl); +etahat = zeros(rr,smpl); +r = zeros(mm,smpl+1); + +Z = zeros(pp,mm); +for i=1:pp; + Z(i,mf(i)) = 1; +end + +t = 0; +while rank(Pinf(:,:,t+1),crit1) & t<smpl + t = t+1; + v(:,t) = Y(:,t) - a(mf,t) - trend(:,t); + if rcond(Pinf(mf,mf,t)) < crit + return + end + iFinf(:,:,t) = inv(Pinf(mf,mf,t)); + PZI = Pinf(:,mf,t)*iFinf(:,:,t); + atilde(:,t) = a(:,t) + PZI*v(:,t); + Kinf(:,:,t) = T*PZI; + a(:,t+1) = T*atilde(:,t); + aK(1,:,t+1) = a(:,t+1); + for jnk=2:nk, + aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); + end + Linf(:,:,t) = T - Kinf(:,:,t)*Z; + Fstar(:,:,t) = Pstar(mf,mf,t); + Kstar(:,:,t) = (T*Pstar(:,mf,t)-Kinf(:,:,t)*Fstar(:,:,t))*iFinf(:,:,t); + Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)-T*Pstar(:,mf,t)*transpose(Kinf(:,:,t))-Kinf(:,:,t)*Pinf(mf,mf,t)*transpose(Kstar(:,:,t)) + QQ; + Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T)-T*Pinf(:,mf,t)*transpose(Kinf(:,:,t)); +end +d = t; +P(:,:,d+1) = Pstar(:,:,d+1); +iFinf = iFinf(:,:,1:d); +Linf = Linf(:,:,1:d); +Fstar = Fstar(:,:,1:d); +Kstar = Kstar(:,:,1:d); +Pstar = Pstar(:,:,1:d); +Pinf = Pinf(:,:,1:d); +notsteady = 1; +while notsteady & t<smpl + t = t+1; + v(:,t) = Y(:,t) - a(mf,t) - trend(:,t); + P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); + if rcond(P(mf,mf,t)) < crit + return + end + iF(:,:,t) = inv(P(mf,mf,t)); + PZI = P(:,mf,t)*iF(:,:,t); + atilde(:,t) = a(:,t) + PZI*v(:,t); + K(:,:,t) = T*PZI; + L(:,:,t) = T-K(:,:,t)*Z; + a(:,t+1) = T*atilde(:,t); + aK(1,:,t+1) = a(:,t+1); + for jnk=2:nk, + aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); + end + P(:,:,t+1) = T*P(:,:,t)*transpose(T)-T*P(:,mf,t)*transpose(K(:,:,t)) + QQ; + notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); +end +if t<smpl + PZI_s = PZI; + K_s = K(:,:,t); + iF_s = iF(:,:,t); + P_s = P(:,:,t+1); + t_steady = t+1; + P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1])); + iF = cat(3,iF(:,:,1:t),repmat(inv(P_s(mf,mf)),[1 1 smpl-t_steady+1])); + L = cat(3,L(:,:,1:t),repmat(T-K_s*Z,[1 1 smpl-t_steady+1])); + K = cat(3,K(:,:,1:t),repmat(T*P_s(:,mf)*iF_s,[1 1 smpl-t_steady+1])); +end +while t<smpl + t=t+1; + v(:,t) = Y(:,t) - a(mf,t) - trend(:,t); + atilde(:,t) = a(:,t) + PZI*v(:,t); + a(:,t+1) = T*a(:,t) + K_s*v(:,t); + aK(1,:,t+1) = a(:,t+1); + for jnk=2:nk, + aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); + end +end +t = smpl+1; +while t>d+1 + t = t-1; + r(:,t) = Z'*iF(:,:,t)*v(:,t) + L(:,:,t)'*r(:,t+1); + alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t); + etahat(:,t) = QRt*r(:,t); +end +if d + r0 = zeros(mm,d+1); + r0(:,d+1) = r(:,d+1); + r1 = zeros(mm,d+1); + for t = d:-1:1 + r0(:,t) = Linf(:,:,t)'*r0(:,t+1); + r1(:,t) = Z'*(iFinf(:,:,t)*v(:,t)-Kstar(:,:,t)'*r0(:,t+1)) + Linf(:,:,t)'*r1(:,t+1); + alphahat(:,t) = a(:,t) + Pstar(:,:,t)*r0(:,t) + Pinf(:,:,t)*r1(:,t); + etahat(:,t) = QRt*r0(:,t); + end +end diff --git a/matlab/DiffuseKalmanSmoother1_Z.m b/matlab/DiffuseKalmanSmoother1_Z.m index 2b043245a3..9a1f4e28e0 100644 --- a/matlab/DiffuseKalmanSmoother1_Z.m +++ b/matlab/DiffuseKalmanSmoother1_Z.m @@ -1,208 +1,208 @@ -function [alphahat,etahat,atilde,P,aK,PK,d,decomp] = DiffuseKalmanSmoother1_Z(T,Z,R,Q,Pinf1,Pstar1,Y,pp,mm,smpl) - -% function [alphahat,etahat,a, aK] = DiffuseKalmanSmoother1(T,Z,R,Q,Pinf1,Pstar1,Y,pp,mm,smpl) -% Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix -% -% INPUTS -% T: mm*mm matrix -% Z: pp*mm matrix -% R: mm*rr matrix -% Q: rr*rr matrix -% Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros -% Pstar1: mm*mm variance-covariance matrix with stationary variables -% Y: pp*1 vector -% pp: number of observed variables -% mm: number of state variables -% smpl: sample size -% -% OUTPUTS -% alphahat: smoothed variables (a_{t|T}) -% etahat: smoothed shocks -% atilde: matrix of updated variables (a_{t|t}) -% aK: 3D array of k step ahead filtered state variables (a_{t+k|t) -% (meaningless for periods 1:d) -% P: 3D array of one-step ahead forecast error variance -% matrices -% PK: 4D array of k-step ahead forecast error variance -% matrices (meaningless for periods 1:d) -% d: number of periods where filter remains in diffuse part -% (should be equal to the order of integration of the model) -% decomp: decomposition of the effect of shocks on filtered values -% -% SPECIAL REQUIREMENTS -% See "Filtering and Smoothing of State Vector for Diffuse State Space -% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series -% Analysis, vol. 24(1), pp. 85-98). - -% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. - -% modified by M. Ratto: -% new output argument aK (1-step to k-step predictions) -% new options_.nk: the max step ahed prediction in aK (default is 4) -% new crit1 value for rank of Pinf -% it is assured that P is symmetric - - -global options_ - -d = 0; -decomp = []; -nk = options_.nk; -spinf = size(Pinf1); -spstar = size(Pstar1); -v = zeros(pp,smpl); -a = zeros(mm,smpl+1); -atilde = zeros(mm,smpl); -aK = zeros(nk,mm,smpl+nk); -PK = zeros(nk,mm,mm,smpl+nk); -iF = zeros(pp,pp,smpl); -Fstar = zeros(pp,pp,smpl); -iFinf = zeros(pp,pp,smpl); -K = zeros(mm,pp,smpl); -L = zeros(mm,mm,smpl); -Linf = zeros(mm,mm,smpl); -Kstar = zeros(mm,pp,smpl); -P = zeros(mm,mm,smpl+1); -Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1; -Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1; -crit = options_.kalman_tol; -crit1 = 1.e-8; -steady = smpl; -rr = size(Q,1); -QQ = R*Q*transpose(R); -QRt = Q*transpose(R); -alphahat = zeros(mm,smpl); -etahat = zeros(rr,smpl); -r = zeros(mm,smpl+1); - -t = 0; -while rank(Pinf(:,:,t+1),crit1) & t<smpl - t = t+1; - v(:,t)= Y(:,t) - Z*a(:,t); - F = Z*Pinf(:,:,t)*Z'; - if rcond(F) < crit - return - end - iFinf(:,:,t) = inv(F); - PZI = Pinf(:,:,t)*Z'*iFinf(:,:,t); - atilde(:,t) = a(:,t) + PZI*v(:,t); - Kinf(:,:,t) = T*PZI; - a(:,t+1) = T*atilde(:,t); - aK(1,:,t+1) = a(:,t+1); - % isn't a meaningless as long as we are in the diffuse part? MJ - for jnk=2:nk, - aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); - end - Linf(:,:,t) = T - Kinf(:,:,t)*Z; - Fstar(:,:,t) = Z*Pstar(:,:,t)*Z'; - Kstar(:,:,t) = (T*Pstar(:,:,t)*Z'-Kinf(:,:,t)*Fstar(:,:,t))*iFinf(:,:,t); - Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'-T*Pstar(:,:,t)*Z'*Kinf(:,:,t)'-Kinf(:,:,t)*F*Kstar(:,:,t)' + QQ; - Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'-T*Pinf(:,:,t)*Z'*Kinf(:,:,t)'; -end -d = t; -P(:,:,d+1) = Pstar(:,:,d+1); -iFinf = iFinf(:,:,1:d); -Linf = Linf(:,:,1:d); -Fstar = Fstar(:,:,1:d); -Kstar = Kstar(:,:,1:d); -Pstar = Pstar(:,:,1:d); -Pinf = Pinf(:,:,1:d); -notsteady = 1; -while notsteady & t<smpl - t = t+1; - v(:,t) = Y(:,t) - Z*a(:,t); - P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); - F = Z*P(:,:,t)*Z'; - if rcond(F) < crit - return - end - iF(:,:,t) = inv(F); - PZI = P(:,:,t)*Z'*iF(:,:,t); - atilde(:,t) = a(:,t) + PZI*v(:,t); - K(:,:,t) = T*PZI; - L(:,:,t) = T-K(:,:,t)*Z; - a(:,t+1) = T*atilde(:,t); - Pf = P(:,:,t); - for jnk=1:nk, - Pf = T*Pf*T' + QQ; - aK(jnk,:,t+jnk) = T^jnk*atilde(:,t); - PK(jnk,:,:,t+jnk) = Pf; - end - P(:,:,t+1) = T*P(:,:,t)*T'-T*P(:,:,t)*Z'*K(:,:,t)' + QQ; - notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); -end -if t<smpl - PZI_s = PZI; - K_s = K(:,:,t); - iF_s = iF(:,:,t); - P_s = P(:,:,t+1); - P = cat(3,P(:,:,1:t),repmat(P_s,[1 1 smpl-t])); - iF = cat(3,iF(:,:,1:t),repmat(iF_s,[1 1 smpl-t])); - L = cat(3,L(:,:,1:t),repmat(T-K_s*Z,[1 1 smpl-t])); - K = cat(3,K(:,:,1:t),repmat(T*P_s*Z'*iF_s,[1 1 smpl-t])); -end -while t<smpl - t=t+1; - v(:,t) = Y(:,t) - Z*a(:,t); - atilde(:,t) = a(:,t) + PZI*v(:,t); - a(:,t+1) = T*atilde(:,t); - Pf = P(:,:,t); - for jnk=1:nk, - Pf = T*Pf*T' + QQ; - aK(jnk,:,t+jnk) = T^jnk*atilde(:,t); - PK(jnk,:,:,t+jnk) = Pf; - end -end -t = smpl+1; -while t>d+1 - t = t-1; - r(:,t) = Z'*iF(:,:,t)*v(:,t) + L(:,:,t)'*r(:,t+1); - alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t); - etahat(:,t) = QRt*r(:,t); -end -if d - r0 = zeros(mm,d+1); - r0(:,d+1) = r(:,d+1); - r1 = zeros(mm,d+1); - for t = d:-1:1 - r0(:,t) = Linf(:,:,t)'*r0(:,t+1); - r1(:,t) = Z'*(iFinf(:,:,t)*v(:,t)-Kstar(:,:,t)'*r0(:,t+1)) + Linf(:,:,t)'*r1(:,t+1); - alphahat(:,t) = a(:,t) + Pstar(:,:,t)*r0(:,t) + Pinf(:,:,t)*r1(:,t); - etahat(:,t) = QRt*r0(:,t); - end -end - -if nargout > 7 - decomp = zeros(nk,mm,rr,smpl+nk); - ZRQinv = inv(Z*QQ*Z'); - for t = max(d,1):smpl - ri_d = Z'*iF(:,:,t)*v(:,t); - - % calculate eta_tm1t - eta_tm1t = QRt*ri_d; - % calculate decomposition - Ttok = eye(mm,mm); - for h = 1:nk - for j=1:rr - eta=zeros(rr,1); - eta(j) = eta_tm1t(j); - decomp(h,:,j,t+h) = T^(h-1)*P(:,:,t)*Z'*ZRQinv*Z*R*eta; - end - end - end -end +function [alphahat,etahat,atilde,P,aK,PK,d,decomp] = DiffuseKalmanSmoother1_Z(T,Z,R,Q,Pinf1,Pstar1,Y,pp,mm,smpl) + +% function [alphahat,etahat,a, aK] = DiffuseKalmanSmoother1(T,Z,R,Q,Pinf1,Pstar1,Y,pp,mm,smpl) +% Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix +% +% INPUTS +% T: mm*mm matrix +% Z: pp*mm matrix +% R: mm*rr matrix +% Q: rr*rr matrix +% Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros +% Pstar1: mm*mm variance-covariance matrix with stationary variables +% Y: pp*1 vector +% pp: number of observed variables +% mm: number of state variables +% smpl: sample size +% +% OUTPUTS +% alphahat: smoothed variables (a_{t|T}) +% etahat: smoothed shocks +% atilde: matrix of updated variables (a_{t|t}) +% aK: 3D array of k step ahead filtered state variables (a_{t+k|t) +% (meaningless for periods 1:d) +% P: 3D array of one-step ahead forecast error variance +% matrices +% PK: 4D array of k-step ahead forecast error variance +% matrices (meaningless for periods 1:d) +% d: number of periods where filter remains in diffuse part +% (should be equal to the order of integration of the model) +% decomp: decomposition of the effect of shocks on filtered values +% +% SPECIAL REQUIREMENTS +% See "Filtering and Smoothing of State Vector for Diffuse State Space +% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series +% Analysis, vol. 24(1), pp. 85-98). + +% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. + +% modified by M. Ratto: +% new output argument aK (1-step to k-step predictions) +% new options_.nk: the max step ahed prediction in aK (default is 4) +% new crit1 value for rank of Pinf +% it is assured that P is symmetric + + +global options_ + +d = 0; +decomp = []; +nk = options_.nk; +spinf = size(Pinf1); +spstar = size(Pstar1); +v = zeros(pp,smpl); +a = zeros(mm,smpl+1); +atilde = zeros(mm,smpl); +aK = zeros(nk,mm,smpl+nk); +PK = zeros(nk,mm,mm,smpl+nk); +iF = zeros(pp,pp,smpl); +Fstar = zeros(pp,pp,smpl); +iFinf = zeros(pp,pp,smpl); +K = zeros(mm,pp,smpl); +L = zeros(mm,mm,smpl); +Linf = zeros(mm,mm,smpl); +Kstar = zeros(mm,pp,smpl); +P = zeros(mm,mm,smpl+1); +Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1; +Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1; +crit = options_.kalman_tol; +crit1 = 1.e-8; +steady = smpl; +rr = size(Q,1); +QQ = R*Q*transpose(R); +QRt = Q*transpose(R); +alphahat = zeros(mm,smpl); +etahat = zeros(rr,smpl); +r = zeros(mm,smpl+1); + +t = 0; +while rank(Pinf(:,:,t+1),crit1) & t<smpl + t = t+1; + v(:,t)= Y(:,t) - Z*a(:,t); + F = Z*Pinf(:,:,t)*Z'; + if rcond(F) < crit + return + end + iFinf(:,:,t) = inv(F); + PZI = Pinf(:,:,t)*Z'*iFinf(:,:,t); + atilde(:,t) = a(:,t) + PZI*v(:,t); + Kinf(:,:,t) = T*PZI; + a(:,t+1) = T*atilde(:,t); + aK(1,:,t+1) = a(:,t+1); + % isn't a meaningless as long as we are in the diffuse part? MJ + for jnk=2:nk, + aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); + end + Linf(:,:,t) = T - Kinf(:,:,t)*Z; + Fstar(:,:,t) = Z*Pstar(:,:,t)*Z'; + Kstar(:,:,t) = (T*Pstar(:,:,t)*Z'-Kinf(:,:,t)*Fstar(:,:,t))*iFinf(:,:,t); + Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'-T*Pstar(:,:,t)*Z'*Kinf(:,:,t)'-Kinf(:,:,t)*F*Kstar(:,:,t)' + QQ; + Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'-T*Pinf(:,:,t)*Z'*Kinf(:,:,t)'; +end +d = t; +P(:,:,d+1) = Pstar(:,:,d+1); +iFinf = iFinf(:,:,1:d); +Linf = Linf(:,:,1:d); +Fstar = Fstar(:,:,1:d); +Kstar = Kstar(:,:,1:d); +Pstar = Pstar(:,:,1:d); +Pinf = Pinf(:,:,1:d); +notsteady = 1; +while notsteady & t<smpl + t = t+1; + v(:,t) = Y(:,t) - Z*a(:,t); + P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); + F = Z*P(:,:,t)*Z'; + if rcond(F) < crit + return + end + iF(:,:,t) = inv(F); + PZI = P(:,:,t)*Z'*iF(:,:,t); + atilde(:,t) = a(:,t) + PZI*v(:,t); + K(:,:,t) = T*PZI; + L(:,:,t) = T-K(:,:,t)*Z; + a(:,t+1) = T*atilde(:,t); + Pf = P(:,:,t); + for jnk=1:nk, + Pf = T*Pf*T' + QQ; + aK(jnk,:,t+jnk) = T^jnk*atilde(:,t); + PK(jnk,:,:,t+jnk) = Pf; + end + P(:,:,t+1) = T*P(:,:,t)*T'-T*P(:,:,t)*Z'*K(:,:,t)' + QQ; + notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); +end +if t<smpl + PZI_s = PZI; + K_s = K(:,:,t); + iF_s = iF(:,:,t); + P_s = P(:,:,t+1); + P = cat(3,P(:,:,1:t),repmat(P_s,[1 1 smpl-t])); + iF = cat(3,iF(:,:,1:t),repmat(iF_s,[1 1 smpl-t])); + L = cat(3,L(:,:,1:t),repmat(T-K_s*Z,[1 1 smpl-t])); + K = cat(3,K(:,:,1:t),repmat(T*P_s*Z'*iF_s,[1 1 smpl-t])); +end +while t<smpl + t=t+1; + v(:,t) = Y(:,t) - Z*a(:,t); + atilde(:,t) = a(:,t) + PZI*v(:,t); + a(:,t+1) = T*atilde(:,t); + Pf = P(:,:,t); + for jnk=1:nk, + Pf = T*Pf*T' + QQ; + aK(jnk,:,t+jnk) = T^jnk*atilde(:,t); + PK(jnk,:,:,t+jnk) = Pf; + end +end +t = smpl+1; +while t>d+1 + t = t-1; + r(:,t) = Z'*iF(:,:,t)*v(:,t) + L(:,:,t)'*r(:,t+1); + alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t); + etahat(:,t) = QRt*r(:,t); +end +if d + r0 = zeros(mm,d+1); + r0(:,d+1) = r(:,d+1); + r1 = zeros(mm,d+1); + for t = d:-1:1 + r0(:,t) = Linf(:,:,t)'*r0(:,t+1); + r1(:,t) = Z'*(iFinf(:,:,t)*v(:,t)-Kstar(:,:,t)'*r0(:,t+1)) + Linf(:,:,t)'*r1(:,t+1); + alphahat(:,t) = a(:,t) + Pstar(:,:,t)*r0(:,t) + Pinf(:,:,t)*r1(:,t); + etahat(:,t) = QRt*r0(:,t); + end +end + +if nargout > 7 + decomp = zeros(nk,mm,rr,smpl+nk); + ZRQinv = inv(Z*QQ*Z'); + for t = max(d,1):smpl + ri_d = Z'*iF(:,:,t)*v(:,t); + + % calculate eta_tm1t + eta_tm1t = QRt*ri_d; + % calculate decomposition + Ttok = eye(mm,mm); + for h = 1:nk + for j=1:rr + eta=zeros(rr,1); + eta(j) = eta_tm1t(j); + decomp(h,:,j,t+h) = T^(h-1)*P(:,:,t)*Z'*ZRQinv*Z*R*eta; + end + end + end +end diff --git a/matlab/DiffuseKalmanSmoother3.m b/matlab/DiffuseKalmanSmoother3.m index f9d52a91b5..f95ef036a3 100644 --- a/matlab/DiffuseKalmanSmoother3.m +++ b/matlab/DiffuseKalmanSmoother3.m @@ -70,9 +70,9 @@ aK = zeros(nk,mm,smpl+nk); PK = zeros(nk,mm,mm,smpl+nk); if isempty(options_.diffuse_d), - smpl_diff = 1; + smpl_diff = 1; else - smpl_diff=rank(Pinf1); + smpl_diff=rank(Pinf1); end Fstar = zeros(pp,smpl_diff); @@ -101,81 +101,81 @@ r = zeros(mm,smpl+1); Z = zeros(pp,mm); for i=1:pp; - Z(i,mf(i)) = 1; + Z(i,mf(i)) = 1; end t = 0; icc=0; newRank = rank(Pinf(:,:,1),crit1); while newRank & t < smpl - t = t+1; - a(:,t) = a1(:,t); - Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); - Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1)); - Pstar1(:,:,t) = Pstar(:,:,t); - Pinf1(:,:,t) = Pinf(:,:,t); - for i=1:pp - v(i,t) = Y(i,t)-a(mf(i),t)-trend(i,t); - Fstar(i,t) = Pstar(mf(i),mf(i),t); - Finf(i,t) = Pinf(mf(i),mf(i),t); - Kstar(:,i,t) = Pstar(:,mf(i),t); - if Finf(i,t) > crit & newRank, % original MJ: if Finf(i,t) > crit - icc=icc+1; - Kinf(:,i,t) = Pinf(:,mf(i),t); - Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t); - L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Z(i,:)/Finf(i,t); - a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t); - Pstar(:,:,t) = Pstar(:,:,t) + ... - Kinf(:,i,t)*transpose(Kinf(:,i,t))*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ... - (Kstar(:,i,t)*transpose(Kinf(:,i,t)) +... - Kinf(:,i,t)*transpose(Kstar(:,i,t)))/Finf(i,t); - Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*transpose(Kinf(:,i,t))/Finf(i,t); - Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); - Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1)); - % new terminiation criteria by M. Ratto - P0=Pinf(:,:,t); - % newRank = any(diag(P0(mf,mf))>crit); - % if newRank==0, id = i; end, - if ~isempty(options_.diffuse_d), - newRank = (icc<options_.diffuse_d); - %if newRank & any(diag(P0(mf,mf))>crit)==0; - if newRank & (any(diag(P0(mf,mf))>crit)==0 & rank(P0,crit1)==0); - disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF') - options_.diffuse_d = icc; - newRank=0; + t = t+1; + a(:,t) = a1(:,t); + Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); + Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1)); + Pstar1(:,:,t) = Pstar(:,:,t); + Pinf1(:,:,t) = Pinf(:,:,t); + for i=1:pp + v(i,t) = Y(i,t)-a(mf(i),t)-trend(i,t); + Fstar(i,t) = Pstar(mf(i),mf(i),t); + Finf(i,t) = Pinf(mf(i),mf(i),t); + Kstar(:,i,t) = Pstar(:,mf(i),t); + if Finf(i,t) > crit & newRank, % original MJ: if Finf(i,t) > crit + icc=icc+1; + Kinf(:,i,t) = Pinf(:,mf(i),t); + Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t); + L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Z(i,:)/Finf(i,t); + a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t); + Pstar(:,:,t) = Pstar(:,:,t) + ... + Kinf(:,i,t)*transpose(Kinf(:,i,t))*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ... + (Kstar(:,i,t)*transpose(Kinf(:,i,t)) +... + Kinf(:,i,t)*transpose(Kstar(:,i,t)))/Finf(i,t); + Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*transpose(Kinf(:,i,t))/Finf(i,t); + Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); + Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1)); + % new terminiation criteria by M. Ratto + P0=Pinf(:,:,t); + % newRank = any(diag(P0(mf,mf))>crit); + % if newRank==0, id = i; end, + if ~isempty(options_.diffuse_d), + newRank = (icc<options_.diffuse_d); + %if newRank & any(diag(P0(mf,mf))>crit)==0; + if newRank & (any(diag(P0(mf,mf))>crit)==0 & rank(P0,crit1)==0); + disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF') + options_.diffuse_d = icc; + newRank=0; + end + else + %newRank = any(diag(P0(mf,mf))>crit); + newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1)); + if newRank==0, + options_.diffuse_d = icc; + end + end, + % if newRank==0, + % options_.diffuse_d=i; %this is buggy + % end + % end new terminiation criteria by M. Ratto + elseif Fstar(i,t) > crit + %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition + %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that + %% rank(Pinf)=0. [st�phane,11-03-2004]. + Li(:,:,i,t) = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t); % we need to store Li for DKF smoother + a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t); + Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*transpose(Kstar(:,i,t))/Fstar(i,t); + Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); end - else - %newRank = any(diag(P0(mf,mf))>crit); - newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1)); - if newRank==0, - options_.diffuse_d = icc; - end - end, - % if newRank==0, - % options_.diffuse_d=i; %this is buggy - % end - % end new terminiation criteria by M. Ratto - elseif Fstar(i,t) > crit - %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition - %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that - %% rank(Pinf)=0. [st�phane,11-03-2004]. - Li(:,:,i,t) = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t); % we need to store Li for DKF smoother - a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t); - Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*transpose(Kstar(:,i,t))/Fstar(i,t); - Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); end - end - a1(:,t+1) = T*a(:,t); - for jnk=1:nk, - aK(jnk,:,t+jnk) = T^jnk*a(:,t); - end - Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)+ QQ; - Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T); - P0=Pinf(:,:,t+1); - if newRank, - %newRank = any(diag(P0(mf,mf))>crit); - newRank = rank(P0,crit1); - end + a1(:,t+1) = T*a(:,t); + for jnk=1:nk, + aK(jnk,:,t+jnk) = T^jnk*a(:,t); + end + Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)+ QQ; + Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T); + P0=Pinf(:,:,t+1); + if newRank, + %newRank = any(diag(P0(mf,mf))>crit); + newRank = rank(P0,crit1); + end end @@ -192,96 +192,96 @@ Pstar1 = Pstar1(:,:,1:d); Pinf1 = Pinf1(:,:,1:d); notsteady = 1; while notsteady & t<smpl - t = t+1; - a(:,t) = a1(:,t); - P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); - P1(:,:,t) = P(:,:,t); - for i=1:pp - v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t); - Fi(i,t) = P(mf(i),mf(i),t); - Ki(:,i,t) = P(:,mf(i),t); - if Fi(i,t) > crit - Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t); - a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t); - P(:,:,t) = P(:,:,t) - Ki(:,i,t)*transpose(Ki(:,i,t))/Fi(i,t); - P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); + t = t+1; + a(:,t) = a1(:,t); + P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); + P1(:,:,t) = P(:,:,t); + for i=1:pp + v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t); + Fi(i,t) = P(mf(i),mf(i),t); + Ki(:,i,t) = P(:,mf(i),t); + if Fi(i,t) > crit + Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t); + a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t); + P(:,:,t) = P(:,:,t) - Ki(:,i,t)*transpose(Ki(:,i,t))/Fi(i,t); + P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); + end + end + a1(:,t+1) = T*a(:,t); + Pf = P(:,:,t); + for jnk=1:nk, + Pf = T*Pf*T' + QQ; + aK(jnk,:,t+jnk) = T^jnk*a(:,t); + PK(jnk,:,:,t+jnk) = Pf; end - end - a1(:,t+1) = T*a(:,t); - Pf = P(:,:,t); - for jnk=1:nk, - Pf = T*Pf*T' + QQ; - aK(jnk,:,t+jnk) = T^jnk*a(:,t); - PK(jnk,:,:,t+jnk) = Pf; - end - P(:,:,t+1) = T*P(:,:,t)*transpose(T) + QQ; - notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); + P(:,:,t+1) = T*P(:,:,t)*transpose(T) + QQ; + notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); end P_s=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); Fi_s = Fi(:,t); Ki_s = Ki(:,:,t); L_s =Li(:,:,:,t); if t<smpl - t_steady = t+1; - P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1])); - Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t_steady+1])); - Li = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t_steady+1])); - Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t_steady+1])); + t_steady = t+1; + P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1])); + Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t_steady+1])); + Li = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t_steady+1])); + Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t_steady+1])); end while t<smpl - t=t+1; - a(:,t) = a1(:,t); - for i=1:pp - v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t); - if Fi_s(i) > crit - a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i); + t=t+1; + a(:,t) = a1(:,t); + for i=1:pp + v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t); + if Fi_s(i) > crit + a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i); + end + end + a1(:,t+1) = T*a(:,t); + Pf = P(:,:,t); + for jnk=1:nk, + Pf = T*Pf*T' + QQ; + aK(jnk,:,t+jnk) = T^jnk*a(:,t); + PK(jnk,:,:,t+jnk) = Pf; end - end - a1(:,t+1) = T*a(:,t); - Pf = P(:,:,t); - for jnk=1:nk, - Pf = T*Pf*T' + QQ; - aK(jnk,:,t+jnk) = T^jnk*a(:,t); - PK(jnk,:,:,t+jnk) = Pf; - end end ri=zeros(mm,1); t = smpl+1; while t>d+1 - t = t-1; - for i=pp:-1:1 - if Fi(i,t) > crit - ri = Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri; - end - end - r(:,t) = ri; - alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t); - etahat(:,t) = QRt*r(:,t); - ri = T'*ri; -end -if d - r0 = zeros(mm,d); - r0(:,d) = ri; - r1 = zeros(mm,d); - for t = d:-1:1 + t = t-1; for i=pp:-1:1 - if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d), % use of options_.diffuse_d to be sure of DKF termination - %r1(:,t) = transpose(Z)*v(:,t)/Finf(i,t) + ... BUG HERE in transpose(Z) - r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ... - L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t); - r0(:,t) = Linf(:,:,i,t)'*r0(:,t); - elseif Fstar(i,t) > crit % step needed whe Finf == 0 - r0(:,t) = Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t); - end + if Fi(i,t) > crit + ri = Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri; + end end - alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t); - r(:,t) = r0(:,t); + r(:,t) = ri; + alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t); etahat(:,t) = QRt*r(:,t); - if t > 1 - r0(:,t-1) = T'*r0(:,t); - r1(:,t-1) = T'*r1(:,t); + ri = T'*ri; +end +if d + r0 = zeros(mm,d); + r0(:,d) = ri; + r1 = zeros(mm,d); + for t = d:-1:1 + for i=pp:-1:1 + if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d), % use of options_.diffuse_d to be sure of DKF termination + %r1(:,t) = transpose(Z)*v(:,t)/Finf(i,t) + ... BUG HERE in transpose(Z) + r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ... + L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t); + r0(:,t) = Linf(:,:,i,t)'*r0(:,t); + elseif Fstar(i,t) > crit % step needed whe Finf == 0 + r0(:,t) = Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t); + end + end + alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t); + r(:,t) = r0(:,t); + etahat(:,t) = QRt*r(:,t); + if t > 1 + r0(:,t-1) = T'*r0(:,t); + r1(:,t-1) = T'*r1(:,t); + end end - end end if nargout > 7 diff --git a/matlab/DiffuseKalmanSmoother3_Z.m b/matlab/DiffuseKalmanSmoother3_Z.m index 216f726367..a977b2ab17 100644 --- a/matlab/DiffuseKalmanSmoother3_Z.m +++ b/matlab/DiffuseKalmanSmoother3_Z.m @@ -76,9 +76,9 @@ a1 = zeros(mm,smpl+1); aK = zeros(nk,mm,smpl+nk); if isempty(options_.diffuse_d), - smpl_diff = 1; + smpl_diff = 1; else - smpl_diff=rank(Pinf1); + smpl_diff=rank(Pinf1); end Fstar = zeros(pp,smpl_diff); @@ -111,67 +111,67 @@ t = 0; icc=0; newRank = rank(Pinf(:,:,1),crit1); while newRank & t < smpl - t = t+1; - a(:,t) = a1(:,t); - Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)'; - Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)'; - Pstar1(:,:,t) = Pstar(:,:,t); - Pinf1(:,:,t) = Pinf(:,:,t); - for i=1:pp - Zi = Z(i,:); - v(i,t) = Y(i,t)-Zi*a(:,t); - Fstar(i,t) = Zi*Pstar(:,:,t)*Zi'; - Finf(i,t) = Zi*Pinf(:,:,t)*Zi'; - Kstar(:,i,t) = Pstar(:,:,t)*Zi'; - if Finf(i,t) > crit & newRank - icc=icc+1; - Kinf(:,i,t) = Pinf(:,:,t)*Zi'; - Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t); - L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Zi/Finf(i,t); - a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t); - Pstar(:,:,t) = Pstar(:,:,t) + ... - Kinf(:,i,t)*Kinf(:,i,t)'*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ... - (Kstar(:,i,t)*Kinf(:,i,t)' +... - Kinf(:,i,t)*Kstar(:,i,t)')/Finf(i,t); - Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*Kinf(:,i,t)'/Finf(i,t); - Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)'; - Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)'; - % new terminiation criteria by M. Ratto - P0=Pinf(:,:,t); - if ~isempty(options_.diffuse_d), - newRank = (icc<options_.diffuse_d); - if newRank & (any(diag(Z*P0*Z')>crit)==0 & rank(P0,crit1)==0); - disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF') - options_.diffuse_d = icc; - newRank=0; + t = t+1; + a(:,t) = a1(:,t); + Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)'; + Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)'; + Pstar1(:,:,t) = Pstar(:,:,t); + Pinf1(:,:,t) = Pinf(:,:,t); + for i=1:pp + Zi = Z(i,:); + v(i,t) = Y(i,t)-Zi*a(:,t); + Fstar(i,t) = Zi*Pstar(:,:,t)*Zi'; + Finf(i,t) = Zi*Pinf(:,:,t)*Zi'; + Kstar(:,i,t) = Pstar(:,:,t)*Zi'; + if Finf(i,t) > crit & newRank + icc=icc+1; + Kinf(:,i,t) = Pinf(:,:,t)*Zi'; + Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t); + L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Zi/Finf(i,t); + a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t); + Pstar(:,:,t) = Pstar(:,:,t) + ... + Kinf(:,i,t)*Kinf(:,i,t)'*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ... + (Kstar(:,i,t)*Kinf(:,i,t)' +... + Kinf(:,i,t)*Kstar(:,i,t)')/Finf(i,t); + Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*Kinf(:,i,t)'/Finf(i,t); + Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)'; + Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)'; + % new terminiation criteria by M. Ratto + P0=Pinf(:,:,t); + if ~isempty(options_.diffuse_d), + newRank = (icc<options_.diffuse_d); + if newRank & (any(diag(Z*P0*Z')>crit)==0 & rank(P0,crit1)==0); + disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF') + options_.diffuse_d = icc; + newRank=0; + end + else + newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1)); + if newRank==0, + options_.diffuse_d = icc; + end + end, + % end new terminiation criteria by M. Ratto + elseif Fstar(i,t) > crit + %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition + %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that + %% rank(Pinf)=0. [st�phane,11-03-2004]. + Li(:,:,i,t) = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t); % we need to store Li for DKF smoother + a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t); + Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*Kstar(:,i,t)'/Fstar(i,t); + Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)'; end - else - newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1)); - if newRank==0, - options_.diffuse_d = icc; - end - end, - % end new terminiation criteria by M. Ratto - elseif Fstar(i,t) > crit - %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition - %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that - %% rank(Pinf)=0. [st�phane,11-03-2004]. - Li(:,:,i,t) = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t); % we need to store Li for DKF smoother - a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t); - Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*Kstar(:,i,t)'/Fstar(i,t); - Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)'; end - end - a1(:,t+1) = T*a(:,t); - for jnk=1:nk, - aK(jnk,:,t+jnk) = T^jnk*a(:,t); - end - Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'+ QQ; - Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'; - P0=Pinf(:,:,t+1); - if newRank, - newRank = rank(P0,crit1); - end + a1(:,t+1) = T*a(:,t); + for jnk=1:nk, + aK(jnk,:,t+jnk) = T^jnk*a(:,t); + end + Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'+ QQ; + Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'; + P0=Pinf(:,:,t+1); + if newRank, + newRank = rank(P0,crit1); + end end @@ -188,31 +188,31 @@ Pstar1 = Pstar1(:,:,1:d); Pinf1 = Pinf1(:,:,1:d); notsteady = 1; while notsteady & t<smpl - t = t+1; - a(:,t) = a1(:,t); - P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)'; - P1(:,:,t) = P(:,:,t); - for i=1:pp - Zi = Z(i,:); - v(i,t) = Y(i,t) - Zi*a(:,t); - Fi(i,t) = Zi*P(:,:,t)*Zi'; - Ki(:,i,t) = P(:,:,t)*Zi'; - if Fi(i,t) > crit - Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t); - a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t); - P(:,:,t) = P(:,:,t) - Ki(:,i,t)*Ki(:,i,t)'/Fi(i,t); - P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)'; + t = t+1; + a(:,t) = a1(:,t); + P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)'; + P1(:,:,t) = P(:,:,t); + for i=1:pp + Zi = Z(i,:); + v(i,t) = Y(i,t) - Zi*a(:,t); + Fi(i,t) = Zi*P(:,:,t)*Zi'; + Ki(:,i,t) = P(:,:,t)*Zi'; + if Fi(i,t) > crit + Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t); + a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t); + P(:,:,t) = P(:,:,t) - Ki(:,i,t)*Ki(:,i,t)'/Fi(i,t); + P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)'; + end + end + a1(:,t+1) = T*a(:,t); + Pf = P(:,:,t); + for jnk=1:nk, + Pf = T*Pf*T' + QQ; + aK(jnk,:,t+jnk) = T^jnk*a(:,t); + PK(jnk,:,:,t+jnk) = Pf; end - end - a1(:,t+1) = T*a(:,t); - Pf = P(:,:,t); - for jnk=1:nk, - Pf = T*Pf*T' + QQ; - aK(jnk,:,t+jnk) = T^jnk*a(:,t); - PK(jnk,:,:,t+jnk) = Pf; - end - P(:,:,t+1) = T*P(:,:,t)*T' + QQ; - notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); + P(:,:,t+1) = T*P(:,:,t)*T' + QQ; + notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); end P_s=tril(P(:,:,t))+tril(P(:,:,t),-1)'; P1_s=tril(P1(:,:,t))+tril(P1(:,:,t),-1)'; @@ -220,67 +220,67 @@ Fi_s = Fi(:,t); Ki_s = Ki(:,:,t); L_s =Li(:,:,:,t); if t<smpl - P = cat(3,P(:,:,1:t),repmat(P_s,[1 1 smpl-t])); - P1 = cat(3,P1(:,:,1:t),repmat(P1_s,[1 1 smpl-t])); - Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t])); - Li = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t])); - Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t])); + P = cat(3,P(:,:,1:t),repmat(P_s,[1 1 smpl-t])); + P1 = cat(3,P1(:,:,1:t),repmat(P1_s,[1 1 smpl-t])); + Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t])); + Li = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t])); + Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t])); end while t<smpl - t=t+1; - a(:,t) = a1(:,t); - for i=1:pp - Zi = Z(i,:); - v(i,t) = Y(i,t) - Zi*a(:,t); - if Fi_s(i) > crit - a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i); + t=t+1; + a(:,t) = a1(:,t); + for i=1:pp + Zi = Z(i,:); + v(i,t) = Y(i,t) - Zi*a(:,t); + if Fi_s(i) > crit + a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i); + end + end + a1(:,t+1) = T*a(:,t); + Pf = P(:,:,t); + for jnk=1:nk, + Pf = T*Pf*T' + QQ; + aK(jnk,:,t+jnk) = T^jnk*a(:,t); + PK(jnk,:,:,t+jnk) = Pf; end - end - a1(:,t+1) = T*a(:,t); - Pf = P(:,:,t); - for jnk=1:nk, - Pf = T*Pf*T' + QQ; - aK(jnk,:,t+jnk) = T^jnk*a(:,t); - PK(jnk,:,:,t+jnk) = Pf; - end end ri=zeros(mm,1); t = smpl+1; while t > d+1 - t = t-1; - for i=pp:-1:1 - if Fi(i,t) > crit - ri = Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri; + t = t-1; + for i=pp:-1:1 + if Fi(i,t) > crit + ri = Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri; + end end - end - r(:,t) = ri; - alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t); - etahat(:,t) = QRt*r(:,t); - ri = T'*ri; + r(:,t) = ri; + alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t); + etahat(:,t) = QRt*r(:,t); + ri = T'*ri; end if d - r0 = zeros(mm,d); - r0(:,d) = ri; - r1 = zeros(mm,d); - for t = d:-1:1 - for i=pp:-1:1 -% if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d), % use of options_.diffuse_d to be sure of DKF termination - if Finf(i,t) > crit - r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ... - L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t); - r0(:,t) = Linf(:,:,i,t)'*r0(:,t); - elseif Fstar(i,t) > crit % step needed whe Finf == 0 - r0(:,t) = Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t); - end - end - alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t); - r(:,t) = r0(:,t); - etahat(:,t) = QRt*r(:,t); - if t > 1 - r0(:,t-1) = T'*r0(:,t); - r1(:,t-1) = T'*r1(:,t); + r0 = zeros(mm,d); + r0(:,d) = ri; + r1 = zeros(mm,d); + for t = d:-1:1 + for i=pp:-1:1 + % if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d), % use of options_.diffuse_d to be sure of DKF termination + if Finf(i,t) > crit + r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ... + L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t); + r0(:,t) = Linf(:,:,i,t)'*r0(:,t); + elseif Fstar(i,t) > crit % step needed whe Finf == 0 + r0(:,t) = Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t); + end + end + alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t); + r(:,t) = r0(:,t); + etahat(:,t) = QRt*r(:,t); + if t > 1 + r0(:,t-1) = T'*r0(:,t); + r1(:,t-1) = T'*r1(:,t); + end end - end end if nargout > 7 diff --git a/matlab/DiffuseKalmanSmootherH1_Z.m b/matlab/DiffuseKalmanSmootherH1_Z.m index 73d5569df3..e56803c56a 100644 --- a/matlab/DiffuseKalmanSmootherH1_Z.m +++ b/matlab/DiffuseKalmanSmootherH1_Z.m @@ -1,212 +1,212 @@ -function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,d,decomp] = DiffuseKalmanSmootherH1_Z(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl) - -% function [alphahat,etahat,atilde, aK] = DiffuseKalmanSmootherH1_Z(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl) -% Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix -% -% INPUTS -% T: mm*mm matrix -% Z: pp*mm matrix -% R: mm*rr matrix -% Q: rr*rr matrix -% H: pp*pp matrix variance of measurement errors -% Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros -% Pstar1: mm*mm variance-covariance matrix with stationary variables -% Y: pp*1 vector -% pp: number of observed variables -% mm: number of state variables -% smpl: sample size -% -% OUTPUTS -% alphahat: smoothed variables (a_{t|T}) -% epsilonhat:smoothed measurement errors -% etahat: smoothed shocks -% atilde: matrix of updated variables (a_{t|t}) -% aK: 3D array of k step ahead filtered state variables (a_{t+k|t) -% (meaningless for periods 1:d) -% P: 3D array of one-step ahead forecast error variance -% matrices -% PK: 4D array of k-step ahead forecast error variance -% matrices (meaningless for periods 1:d) -% d: number of periods where filter remains in diffuse part -% (should be equal to the order of integration of the model) -% decomp: decomposition of the effect of shocks on filtered values -% -% SPECIAL REQUIREMENTS -% See "Filtering and Smoothing of State Vector for Diffuse State Space -% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series -% Analysis, vol. 24(1), pp. 85-98). - -% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. - -% modified by M. Ratto: -% new output argument aK (1-step to k-step predictions) -% new options_.nk: the max step ahed prediction in aK (default is 4) -% new crit1 value for rank of Pinf -% it is assured that P is symmetric - - -global options_ - -d = 0; -decomp = []; -nk = options_.nk; -spinf = size(Pinf1); -spstar = size(Pstar1); -v = zeros(pp,smpl); -a = zeros(mm,smpl+1); -atilde = zeros(mm,smpl); -aK = zeros(nk,mm,smpl+nk); -PK = zeros(nk,mm,mm,smpl+nk); -iF = zeros(pp,pp,smpl); -Fstar = zeros(pp,pp,smpl); -iFinf = zeros(pp,pp,smpl); -K = zeros(mm,pp,smpl); -L = zeros(mm,mm,smpl); -Linf = zeros(mm,mm,smpl); -Kstar = zeros(mm,pp,smpl); -P = zeros(mm,mm,smpl+1); -Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1; -Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1; -crit = options_.kalman_tol; -crit1 = 1.e-8; -steady = smpl; -rr = size(Q,1); -QQ = R*Q*transpose(R); -QRt = Q*transpose(R); -alphahat = zeros(mm,smpl); -etahat = zeros(rr,smpl); -epsilonhat = zeros(size(Y)); -r = zeros(mm,smpl+1); - -t = 0; -while rank(Pinf(:,:,t+1),crit1) & t<smpl - t = t+1; - v(:,t)= Y(:,t) - Z*a(:,t); - F = Z*Pinf(:,:,t)*Z'; - if rcond(F) < crit - return - end - iFinf(:,:,t) = inv(F); - PZI = Pinf(:,:,t)*Z'*iFinf(:,:,t); - atilde(:,t) = a(:,t) + PZI*v(:,t); - Kinf(:,:,t) = T*PZI; - a(:,t+1) = T*atilde(:,t); - aK(1,:,t+1) = a(:,t+1); - % isn't a meaningless as long as we are in the diffuse part? MJ - for jnk=2:nk, - aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); - end - Linf(:,:,t) = T - Kinf(:,:,t)*Z; - Fstar(:,:,t) = Z*Pstar(:,:,t)*Z' + H; - Kstar(:,:,t) = (T*Pstar(:,:,t)*Z'-Kinf(:,:,t)*Fstar(:,:,t))*iFinf(:,:,t); - Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'-T*Pstar(:,:,t)*Z'*Kinf(:,:,t)'-Kinf(:,:,t)*F*Kstar(:,:,t)' + QQ; - Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'-T*Pinf(:,:,t)*Z'*Kinf(:,:,t)'; -end -d = t; -P(:,:,d+1) = Pstar(:,:,d+1); -iFinf = iFinf(:,:,1:d); -Linf = Linf(:,:,1:d); -Fstar = Fstar(:,:,1:d); -Kstar = Kstar(:,:,1:d); -Pstar = Pstar(:,:,1:d); -Pinf = Pinf(:,:,1:d); -notsteady = 1; -while notsteady & t<smpl - t = t+1; - v(:,t) = Y(:,t) - Z*a(:,t); - P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); - F = Z*P(:,:,t)*Z' + H; - if rcond(F) < crit - return - end - iF(:,:,t) = inv(F); - PZI = P(:,:,t)*Z'*iF(:,:,t); - atilde(:,t) = a(:,t) + PZI*v(:,t); - K(:,:,t) = T*PZI; - L(:,:,t) = T-K(:,:,t)*Z; - a(:,t+1) = T*atilde(:,t); - Pf = P(:,:,t); - for jnk=1:nk, - Pf = T*Pf*T' + QQ; - aK(jnk,:,t+jnk) = T^jnk*atilde(:,t); - PK(jnk,:,:,t+jnk) = Pf; - end - P(:,:,t+1) = T*P(:,:,t)*T'-T*P(:,:,t)*Z'*K(:,:,t)' + QQ; - notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); -end -if t<smpl - PZI_s = PZI; - K_s = K(:,:,t); - iF_s = iF(:,:,t); - P_s = P(:,:,t+1); - P = cat(3,P(:,:,1:t),repmat(P_s,[1 1 smpl-t])); - iF = cat(3,iF(:,:,1:t),repmat(iF_s,[1 1 smpl-t])); - L = cat(3,L(:,:,1:t),repmat(T-K_s*Z,[1 1 smpl-t])); - K = cat(3,K(:,:,1:t),repmat(T*P_s*Z'*iF_s,[1 1 smpl-t])); -end -while t<smpl - t=t+1; - v(:,t) = Y(:,t) - Z*a(:,t); - atilde(:,t) = a(:,t) + PZI*v(:,t); - a(:,t+1) = T*atilde(:,t); - Pf = P(:,:,t); - for jnk=1:nk, - Pf = T*Pf*T' + QQ; - aK(jnk,:,t+jnk) = T^jnk*atilde(:,t); - PK(jnk,:,:,t+jnk) = Pf; - end -end -t = smpl+1; -while t>d+1 - t = t-1; - r(:,t) = Z'*iF(:,:,t)*v(:,t) + L(:,:,t)'*r(:,t+1); - alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t); - etahat(:,t) = QRt*r(:,t); -end -if d - r0 = zeros(mm,d+1); - r0(:,d+1) = r(:,d+1); - r1 = zeros(mm,d+1); - for t = d:-1:1 - r0(:,t) = Linf(:,:,t)'*r0(:,t+1); - r1(:,t) = Z'*(iFinf(:,:,t)*v(:,t)-Kstar(:,:,t)'*r0(:,t+1)) + Linf(:,:,t)'*r1(:,t+1); - alphahat(:,t) = a(:,t) + Pstar(:,:,t)*r0(:,t) + Pinf(:,:,t)*r1(:,t); - etahat(:,t) = QRt*r0(:,t); - end -end - -if nargout > 7 - decomp = zeros(nk,mm,rr,smpl+nk); - ZRQinv = inv(Z*QQ*Z'); - for t = max(d,1):smpl - ri_d = Z'*iF(:,:,t)*v(:,t); - - % calculate eta_tm1t - eta_tm1t = QRt*ri_d; - % calculate decomposition - Ttok = eye(mm,mm); - for h = 1:nk - for j=1:rr - eta=zeros(rr,1); - eta(j) = eta_tm1t(j); - decomp(h,:,j,t+h) = T^(h-1)*P(:,:,t)*Z'*ZRQinv*Z*R*eta; - end - end - end -end -epsilonhat = Y-Z*alphahat; +function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,d,decomp] = DiffuseKalmanSmootherH1_Z(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl) + +% function [alphahat,etahat,atilde, aK] = DiffuseKalmanSmootherH1_Z(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl) +% Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix +% +% INPUTS +% T: mm*mm matrix +% Z: pp*mm matrix +% R: mm*rr matrix +% Q: rr*rr matrix +% H: pp*pp matrix variance of measurement errors +% Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros +% Pstar1: mm*mm variance-covariance matrix with stationary variables +% Y: pp*1 vector +% pp: number of observed variables +% mm: number of state variables +% smpl: sample size +% +% OUTPUTS +% alphahat: smoothed variables (a_{t|T}) +% epsilonhat:smoothed measurement errors +% etahat: smoothed shocks +% atilde: matrix of updated variables (a_{t|t}) +% aK: 3D array of k step ahead filtered state variables (a_{t+k|t) +% (meaningless for periods 1:d) +% P: 3D array of one-step ahead forecast error variance +% matrices +% PK: 4D array of k-step ahead forecast error variance +% matrices (meaningless for periods 1:d) +% d: number of periods where filter remains in diffuse part +% (should be equal to the order of integration of the model) +% decomp: decomposition of the effect of shocks on filtered values +% +% SPECIAL REQUIREMENTS +% See "Filtering and Smoothing of State Vector for Diffuse State Space +% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series +% Analysis, vol. 24(1), pp. 85-98). + +% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. + +% modified by M. Ratto: +% new output argument aK (1-step to k-step predictions) +% new options_.nk: the max step ahed prediction in aK (default is 4) +% new crit1 value for rank of Pinf +% it is assured that P is symmetric + + +global options_ + +d = 0; +decomp = []; +nk = options_.nk; +spinf = size(Pinf1); +spstar = size(Pstar1); +v = zeros(pp,smpl); +a = zeros(mm,smpl+1); +atilde = zeros(mm,smpl); +aK = zeros(nk,mm,smpl+nk); +PK = zeros(nk,mm,mm,smpl+nk); +iF = zeros(pp,pp,smpl); +Fstar = zeros(pp,pp,smpl); +iFinf = zeros(pp,pp,smpl); +K = zeros(mm,pp,smpl); +L = zeros(mm,mm,smpl); +Linf = zeros(mm,mm,smpl); +Kstar = zeros(mm,pp,smpl); +P = zeros(mm,mm,smpl+1); +Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1; +Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1; +crit = options_.kalman_tol; +crit1 = 1.e-8; +steady = smpl; +rr = size(Q,1); +QQ = R*Q*transpose(R); +QRt = Q*transpose(R); +alphahat = zeros(mm,smpl); +etahat = zeros(rr,smpl); +epsilonhat = zeros(size(Y)); +r = zeros(mm,smpl+1); + +t = 0; +while rank(Pinf(:,:,t+1),crit1) & t<smpl + t = t+1; + v(:,t)= Y(:,t) - Z*a(:,t); + F = Z*Pinf(:,:,t)*Z'; + if rcond(F) < crit + return + end + iFinf(:,:,t) = inv(F); + PZI = Pinf(:,:,t)*Z'*iFinf(:,:,t); + atilde(:,t) = a(:,t) + PZI*v(:,t); + Kinf(:,:,t) = T*PZI; + a(:,t+1) = T*atilde(:,t); + aK(1,:,t+1) = a(:,t+1); + % isn't a meaningless as long as we are in the diffuse part? MJ + for jnk=2:nk, + aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); + end + Linf(:,:,t) = T - Kinf(:,:,t)*Z; + Fstar(:,:,t) = Z*Pstar(:,:,t)*Z' + H; + Kstar(:,:,t) = (T*Pstar(:,:,t)*Z'-Kinf(:,:,t)*Fstar(:,:,t))*iFinf(:,:,t); + Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'-T*Pstar(:,:,t)*Z'*Kinf(:,:,t)'-Kinf(:,:,t)*F*Kstar(:,:,t)' + QQ; + Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'-T*Pinf(:,:,t)*Z'*Kinf(:,:,t)'; +end +d = t; +P(:,:,d+1) = Pstar(:,:,d+1); +iFinf = iFinf(:,:,1:d); +Linf = Linf(:,:,1:d); +Fstar = Fstar(:,:,1:d); +Kstar = Kstar(:,:,1:d); +Pstar = Pstar(:,:,1:d); +Pinf = Pinf(:,:,1:d); +notsteady = 1; +while notsteady & t<smpl + t = t+1; + v(:,t) = Y(:,t) - Z*a(:,t); + P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); + F = Z*P(:,:,t)*Z' + H; + if rcond(F) < crit + return + end + iF(:,:,t) = inv(F); + PZI = P(:,:,t)*Z'*iF(:,:,t); + atilde(:,t) = a(:,t) + PZI*v(:,t); + K(:,:,t) = T*PZI; + L(:,:,t) = T-K(:,:,t)*Z; + a(:,t+1) = T*atilde(:,t); + Pf = P(:,:,t); + for jnk=1:nk, + Pf = T*Pf*T' + QQ; + aK(jnk,:,t+jnk) = T^jnk*atilde(:,t); + PK(jnk,:,:,t+jnk) = Pf; + end + P(:,:,t+1) = T*P(:,:,t)*T'-T*P(:,:,t)*Z'*K(:,:,t)' + QQ; + notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); +end +if t<smpl + PZI_s = PZI; + K_s = K(:,:,t); + iF_s = iF(:,:,t); + P_s = P(:,:,t+1); + P = cat(3,P(:,:,1:t),repmat(P_s,[1 1 smpl-t])); + iF = cat(3,iF(:,:,1:t),repmat(iF_s,[1 1 smpl-t])); + L = cat(3,L(:,:,1:t),repmat(T-K_s*Z,[1 1 smpl-t])); + K = cat(3,K(:,:,1:t),repmat(T*P_s*Z'*iF_s,[1 1 smpl-t])); +end +while t<smpl + t=t+1; + v(:,t) = Y(:,t) - Z*a(:,t); + atilde(:,t) = a(:,t) + PZI*v(:,t); + a(:,t+1) = T*atilde(:,t); + Pf = P(:,:,t); + for jnk=1:nk, + Pf = T*Pf*T' + QQ; + aK(jnk,:,t+jnk) = T^jnk*atilde(:,t); + PK(jnk,:,:,t+jnk) = Pf; + end +end +t = smpl+1; +while t>d+1 + t = t-1; + r(:,t) = Z'*iF(:,:,t)*v(:,t) + L(:,:,t)'*r(:,t+1); + alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t); + etahat(:,t) = QRt*r(:,t); +end +if d + r0 = zeros(mm,d+1); + r0(:,d+1) = r(:,d+1); + r1 = zeros(mm,d+1); + for t = d:-1:1 + r0(:,t) = Linf(:,:,t)'*r0(:,t+1); + r1(:,t) = Z'*(iFinf(:,:,t)*v(:,t)-Kstar(:,:,t)'*r0(:,t+1)) + Linf(:,:,t)'*r1(:,t+1); + alphahat(:,t) = a(:,t) + Pstar(:,:,t)*r0(:,t) + Pinf(:,:,t)*r1(:,t); + etahat(:,t) = QRt*r0(:,t); + end +end + +if nargout > 7 + decomp = zeros(nk,mm,rr,smpl+nk); + ZRQinv = inv(Z*QQ*Z'); + for t = max(d,1):smpl + ri_d = Z'*iF(:,:,t)*v(:,t); + + % calculate eta_tm1t + eta_tm1t = QRt*ri_d; + % calculate decomposition + Ttok = eye(mm,mm); + for h = 1:nk + for j=1:rr + eta=zeros(rr,1); + eta(j) = eta_tm1t(j); + decomp(h,:,j,t+h) = T^(h-1)*P(:,:,t)*Z'*ZRQinv*Z*R*eta; + end + end + end +end +epsilonhat = Y-Z*alphahat; diff --git a/matlab/DiffuseKalmanSmootherH3.m b/matlab/DiffuseKalmanSmootherH3.m index fd2764d87c..382902c46e 100644 --- a/matlab/DiffuseKalmanSmootherH3.m +++ b/matlab/DiffuseKalmanSmootherH3.m @@ -68,9 +68,9 @@ a1 = zeros(mm,smpl+1); aK = zeros(nk,mm,smpl+nk); if isempty(options_.diffuse_d), - smpl_diff = 1; + smpl_diff = 1; else - smpl_diff=rank(Pinf1); + smpl_diff=rank(Pinf1); end Fstar = zeros(pp,smpl_diff); @@ -99,81 +99,81 @@ r = zeros(mm,smpl+1); Z = zeros(pp,mm); for i=1:pp; - Z(i,mf(i)) = 1; + Z(i,mf(i)) = 1; end t = 0; icc=0; newRank = rank(Pinf(:,:,1),crit1); while newRank & t < smpl - t = t+1; - a(:,t) = a1(:,t); - Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); - Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1)); - Pstar1(:,:,t) = Pstar(:,:,t); - Pinf1(:,:,t) = Pinf(:,:,t); - for i=1:pp - v(i,t) = Y(i,t)-a(mf(i),t)-trend(i,t); - Fstar(i,t) = Pstar(mf(i),mf(i),t) + H(i,i); - Finf(i,t) = Pinf(mf(i),mf(i),t); - Kstar(:,i,t) = Pstar(:,mf(i),t); - if Finf(i,t) > crit & newRank, % original MJ: if Finf(i,t) > crit - icc=icc+1; - Kinf(:,i,t) = Pinf(:,mf(i),t); - Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t); - L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Z(i,:)/Finf(i,t); - a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t); - Pstar(:,:,t) = Pstar(:,:,t) + ... - Kinf(:,i,t)*transpose(Kinf(:,i,t))*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ... - (Kstar(:,i,t)*transpose(Kinf(:,i,t)) +... - Kinf(:,i,t)*transpose(Kstar(:,i,t)))/Finf(i,t); - Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*transpose(Kinf(:,i,t))/Finf(i,t); - Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); - Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1)); - % new terminiation criteria by M. Ratto - P0=Pinf(:,:,t); - % newRank = any(diag(P0(mf,mf))>crit); - % if newRank==0, options_.diffuse_d = i; end, - if ~isempty(options_.diffuse_d), - newRank = (icc<options_.diffuse_d); - %if newRank & any(diag(P0(mf,mf))>crit)==0; - if newRank & (any(diag(P0(mf,mf))>crit)==0 & rank(P0,crit1)==0); - disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF') - options_.diffuse_d = icc; - newRank=0; - end - else - %newRank = any(diag(P0(mf,mf))>crit); - newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1)); - if newRank==0, - options_.diffuse_d = icc; - end - end, -% if newRank==0, -% options_.diffuse_d=i; % this line is buggy! -% end - % end new terminiation criteria by M. Ratto - elseif Fstar(i,t) > crit - %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition - %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that - %% rank(Pinf)=0. [st�phane,11-03-2004]. - Li(:,:,i,t) = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t); % we need to store Li for DKF smoother - a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t); - Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*transpose(Kstar(:,i,t))/Fstar(i,t); - Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); + t = t+1; + a(:,t) = a1(:,t); + Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); + Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1)); + Pstar1(:,:,t) = Pstar(:,:,t); + Pinf1(:,:,t) = Pinf(:,:,t); + for i=1:pp + v(i,t) = Y(i,t)-a(mf(i),t)-trend(i,t); + Fstar(i,t) = Pstar(mf(i),mf(i),t) + H(i,i); + Finf(i,t) = Pinf(mf(i),mf(i),t); + Kstar(:,i,t) = Pstar(:,mf(i),t); + if Finf(i,t) > crit & newRank, % original MJ: if Finf(i,t) > crit + icc=icc+1; + Kinf(:,i,t) = Pinf(:,mf(i),t); + Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t); + L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Z(i,:)/Finf(i,t); + a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t); + Pstar(:,:,t) = Pstar(:,:,t) + ... + Kinf(:,i,t)*transpose(Kinf(:,i,t))*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ... + (Kstar(:,i,t)*transpose(Kinf(:,i,t)) +... + Kinf(:,i,t)*transpose(Kstar(:,i,t)))/Finf(i,t); + Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*transpose(Kinf(:,i,t))/Finf(i,t); + Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); + Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1)); + % new terminiation criteria by M. Ratto + P0=Pinf(:,:,t); + % newRank = any(diag(P0(mf,mf))>crit); + % if newRank==0, options_.diffuse_d = i; end, + if ~isempty(options_.diffuse_d), + newRank = (icc<options_.diffuse_d); + %if newRank & any(diag(P0(mf,mf))>crit)==0; + if newRank & (any(diag(P0(mf,mf))>crit)==0 & rank(P0,crit1)==0); + disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF') + options_.diffuse_d = icc; + newRank=0; + end + else + %newRank = any(diag(P0(mf,mf))>crit); + newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1)); + if newRank==0, + options_.diffuse_d = icc; + end + end, + % if newRank==0, + % options_.diffuse_d=i; % this line is buggy! + % end + % end new terminiation criteria by M. Ratto + elseif Fstar(i,t) > crit + %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition + %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that + %% rank(Pinf)=0. [st�phane,11-03-2004]. + Li(:,:,i,t) = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t); % we need to store Li for DKF smoother + a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t); + Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*transpose(Kstar(:,i,t))/Fstar(i,t); + Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); + end + end + a1(:,t+1) = T*a(:,t); + for jnk=1:nk, + aK(jnk,:,t+jnk) = T^jnk*a(:,t); + end + Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)+ QQ; + Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T); + P0=Pinf(:,:,t+1); + if newRank, + %newRank = any(diag(P0(mf,mf))>crit); + newRank = rank(P0,crit1); end - end - a1(:,t+1) = T*a(:,t); - for jnk=1:nk, - aK(jnk,:,t+jnk) = T^jnk*a(:,t); - end - Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)+ QQ; - Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T); - P0=Pinf(:,:,t+1); - if newRank, - %newRank = any(diag(P0(mf,mf))>crit); - newRank = rank(P0,crit1); - end end @@ -190,89 +190,89 @@ Pstar1 = Pstar1(:,:,1:d); Pinf1 = Pinf1(:,:,1:d); notsteady = 1; while notsteady & t<smpl - t = t+1; - a(:,t) = a1(:,t); - P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); - P1(:,:,t) = P(:,:,t); - for i=1:pp - v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t); - Fi(i,t) = P(mf(i),mf(i),t)+H(i,i); - Ki(:,i,t) = P(:,mf(i),t); - if Fi(i,t) > crit - Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t); - a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t); - P(:,:,t) = P(:,:,t) - Ki(:,i,t)*transpose(Ki(:,i,t))/Fi(i,t); - P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); + t = t+1; + a(:,t) = a1(:,t); + P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); + P1(:,:,t) = P(:,:,t); + for i=1:pp + v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t); + Fi(i,t) = P(mf(i),mf(i),t)+H(i,i); + Ki(:,i,t) = P(:,mf(i),t); + if Fi(i,t) > crit + Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t); + a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t); + P(:,:,t) = P(:,:,t) - Ki(:,i,t)*transpose(Ki(:,i,t))/Fi(i,t); + P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); + end + end + a1(:,t+1) = T*a(:,t); + for jnk=1:nk, + aK(jnk,:,t+jnk) = T^jnk*a(:,t); end - end - a1(:,t+1) = T*a(:,t); - for jnk=1:nk, - aK(jnk,:,t+jnk) = T^jnk*a(:,t); - end - P(:,:,t+1) = T*P(:,:,t)*transpose(T) + QQ; - notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); + P(:,:,t+1) = T*P(:,:,t)*transpose(T) + QQ; + notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); end P_s=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); Fi_s = Fi(:,t); Ki_s = Ki(:,:,t); L_s =Li(:,:,:,t); if t<smpl - t_steady = t+1; - P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1])); - Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t_steady+1])); - Li = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t_steady+1])); - Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t_steady+1])); + t_steady = t+1; + P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1])); + Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t_steady+1])); + Li = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t_steady+1])); + Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t_steady+1])); end while t<smpl - t=t+1; - a(:,t) = a1(:,t); - for i=1:pp - v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t); - if Fi_s(i) > crit - a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i); + t=t+1; + a(:,t) = a1(:,t); + for i=1:pp + v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t); + if Fi_s(i) > crit + a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i); + end + end + a1(:,t+1) = T*a(:,t); + for jnk=1:nk, + aK(jnk,:,t+jnk) = T^jnk*a(:,t); end - end - a1(:,t+1) = T*a(:,t); - for jnk=1:nk, - aK(jnk,:,t+jnk) = T^jnk*a(:,t); - end end ri=zeros(mm,1); t = smpl+1; while t>d+1 - t = t-1; - for i=pp:-1:1 - if Fi(i,t) > crit - ri=Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri; - end - end - r(:,t) = ri; - alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t); - etahat(:,t) = QRt*r(:,t); - ri = T'*ri; -end -if d - r0 = zeros(mm,d); - r0(:,d) = ri; - r1 = zeros(mm,d); - for t = d:-1:1 + t = t-1; for i=pp:-1:1 - if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d), % use of options_.diffuse_d to be sure of DKF termination - r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ... - L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t); - r0(:,t) = Linf(:,:,i,t)'*r0(:,t); - elseif Fstar(i,t) > crit % step needed whe Finf == 0 - r0(:,t)=Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t); - end + if Fi(i,t) > crit + ri=Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri; + end end - alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t); - r(:,t) = r0(:,t); + r(:,t) = ri; + alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t); etahat(:,t) = QRt*r(:,t); - if t > 1 - r0(:,t-1) = transpose(T)*r0(:,t); - r1(:,t-1) = transpose(T)*r1(:,t); + ri = T'*ri; +end +if d + r0 = zeros(mm,d); + r0(:,d) = ri; + r1 = zeros(mm,d); + for t = d:-1:1 + for i=pp:-1:1 + if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d), % use of options_.diffuse_d to be sure of DKF termination + r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ... + L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t); + r0(:,t) = Linf(:,:,i,t)'*r0(:,t); + elseif Fstar(i,t) > crit % step needed whe Finf == 0 + r0(:,t)=Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t); + end + end + alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t); + r(:,t) = r0(:,t); + etahat(:,t) = QRt*r(:,t); + if t > 1 + r0(:,t-1) = transpose(T)*r0(:,t); + r1(:,t-1) = transpose(T)*r1(:,t); + end end - end end epsilonhat = Y-alphahat(mf,:)-trend; diff --git a/matlab/DiffuseKalmanSmootherH3_Z.m b/matlab/DiffuseKalmanSmootherH3_Z.m index 5dc6109a05..c01b833867 100644 --- a/matlab/DiffuseKalmanSmootherH3_Z.m +++ b/matlab/DiffuseKalmanSmootherH3_Z.m @@ -77,9 +77,9 @@ a1 = zeros(mm,smpl+1); aK = zeros(nk,mm,smpl+nk); if isempty(options_.diffuse_d), - smpl_diff = 1; + smpl_diff = 1; else - smpl_diff=rank(Pinf1); + smpl_diff=rank(Pinf1); end Fstar = zeros(pp,smpl_diff); @@ -112,67 +112,67 @@ t = 0; icc=0; newRank = rank(Pinf(:,:,1),crit1); while newRank & t < smpl - t = t+1; - a(:,t) = a1(:,t); - Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)'; - Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)'; - Pstar1(:,:,t) = Pstar(:,:,t); - Pinf1(:,:,t) = Pinf(:,:,t); - for i=1:pp - Zi = Z(i,:); - v(i,t) = Y(i,t)-Zi*a(:,t); - Fstar(i,t) = Zi*Pstar(:,:,t)*Zi' +H(i,i); - Finf(i,t) = Zi*Pinf(:,:,t)*Zi'; - Kstar(:,i,t) = Pstar(:,:,t)*Zi'; - if Finf(i,t) > crit & newRank - icc=icc+1; - Kinf(:,i,t) = Pinf(:,:,t)*Zi'; - Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t); - L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Zi/Finf(i,t); - a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t); - Pstar(:,:,t) = Pstar(:,:,t) + ... - Kinf(:,i,t)*Kinf(:,i,t)'*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ... - (Kstar(:,i,t)*Kinf(:,i,t)' +... - Kinf(:,i,t)*Kstar(:,i,t)')/Finf(i,t); - Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*Kinf(:,i,t)'/Finf(i,t); - Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)'; - Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)'; - % new terminiation criteria by M. Ratto - P0=Pinf(:,:,t); - if ~isempty(options_.diffuse_d), - newRank = (icc<options_.diffuse_d); - if newRank & (any(diag(Z*P0*Z')>crit)==0 & rank(P0,crit1)==0); - disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF') - options_.diffuse_d = icc; - newRank=0; + t = t+1; + a(:,t) = a1(:,t); + Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)'; + Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)'; + Pstar1(:,:,t) = Pstar(:,:,t); + Pinf1(:,:,t) = Pinf(:,:,t); + for i=1:pp + Zi = Z(i,:); + v(i,t) = Y(i,t)-Zi*a(:,t); + Fstar(i,t) = Zi*Pstar(:,:,t)*Zi' +H(i,i); + Finf(i,t) = Zi*Pinf(:,:,t)*Zi'; + Kstar(:,i,t) = Pstar(:,:,t)*Zi'; + if Finf(i,t) > crit & newRank + icc=icc+1; + Kinf(:,i,t) = Pinf(:,:,t)*Zi'; + Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t); + L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Zi/Finf(i,t); + a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t); + Pstar(:,:,t) = Pstar(:,:,t) + ... + Kinf(:,i,t)*Kinf(:,i,t)'*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ... + (Kstar(:,i,t)*Kinf(:,i,t)' +... + Kinf(:,i,t)*Kstar(:,i,t)')/Finf(i,t); + Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*Kinf(:,i,t)'/Finf(i,t); + Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)'; + Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)'; + % new terminiation criteria by M. Ratto + P0=Pinf(:,:,t); + if ~isempty(options_.diffuse_d), + newRank = (icc<options_.diffuse_d); + if newRank & (any(diag(Z*P0*Z')>crit)==0 & rank(P0,crit1)==0); + disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF') + options_.diffuse_d = icc; + newRank=0; + end + else + newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1)); + if newRank==0, + options_.diffuse_d = icc; + end + end, + % end new terminiation criteria by M. Ratto + elseif Fstar(i,t) > crit + %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition + %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that + %% rank(Pinf)=0. [st�phane,11-03-2004]. + Li(:,:,i,t) = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t); % we need to store Li for DKF smoother + a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t); + Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*Kstar(:,i,t)'/Fstar(i,t); + Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)'; end - else - newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1)); - if newRank==0, - options_.diffuse_d = icc; - end - end, - % end new terminiation criteria by M. Ratto - elseif Fstar(i,t) > crit - %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition - %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that - %% rank(Pinf)=0. [st�phane,11-03-2004]. - Li(:,:,i,t) = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t); % we need to store Li for DKF smoother - a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t); - Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*Kstar(:,i,t)'/Fstar(i,t); - Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)'; end - end - a1(:,t+1) = T*a(:,t); - for jnk=1:nk, - aK(jnk,:,t+jnk) = T^jnk*a(:,t); - end - Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'+ QQ; - Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'; - P0=Pinf(:,:,t+1); - if newRank, - newRank = rank(P0,crit1); - end + a1(:,t+1) = T*a(:,t); + for jnk=1:nk, + aK(jnk,:,t+jnk) = T^jnk*a(:,t); + end + Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'+ QQ; + Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'; + P0=Pinf(:,:,t+1); + if newRank, + newRank = rank(P0,crit1); + end end @@ -189,31 +189,31 @@ Pstar1 = Pstar1(:,:,1:d); Pinf1 = Pinf1(:,:,1:d); notsteady = 1; while notsteady & t<smpl - t = t+1; - a(:,t) = a1(:,t); - P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)'; - P1(:,:,t) = P(:,:,t); - for i=1:pp - Zi = Z(i,:); - v(i,t) = Y(i,t) - Zi*a(:,t); - Fi(i,t) = Zi*P(:,:,t)*Zi' + H(i,i); - Ki(:,i,t) = P(:,:,t)*Zi'; - if Fi(i,t) > crit - Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t); - a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t); - P(:,:,t) = P(:,:,t) - Ki(:,i,t)*Ki(:,i,t)'/Fi(i,t); - P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)'; + t = t+1; + a(:,t) = a1(:,t); + P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)'; + P1(:,:,t) = P(:,:,t); + for i=1:pp + Zi = Z(i,:); + v(i,t) = Y(i,t) - Zi*a(:,t); + Fi(i,t) = Zi*P(:,:,t)*Zi' + H(i,i); + Ki(:,i,t) = P(:,:,t)*Zi'; + if Fi(i,t) > crit + Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t); + a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t); + P(:,:,t) = P(:,:,t) - Ki(:,i,t)*Ki(:,i,t)'/Fi(i,t); + P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)'; + end + end + a1(:,t+1) = T*a(:,t); + Pf = P(:,:,t); + for jnk=1:nk, + Pf = T*Pf*T' + QQ; + aK(jnk,:,t+jnk) = T^jnk*a(:,t); + PK(jnk,:,:,t+jnk) = Pf; end - end - a1(:,t+1) = T*a(:,t); - Pf = P(:,:,t); - for jnk=1:nk, - Pf = T*Pf*T' + QQ; - aK(jnk,:,t+jnk) = T^jnk*a(:,t); - PK(jnk,:,:,t+jnk) = Pf; - end - P(:,:,t+1) = T*P(:,:,t)*T' + QQ; - notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); + P(:,:,t+1) = T*P(:,:,t)*T' + QQ; + notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); end P_s=tril(P(:,:,t))+tril(P(:,:,t),-1)'; P1_s=tril(P1(:,:,t))+tril(P1(:,:,t),-1)'; @@ -221,67 +221,67 @@ Fi_s = Fi(:,t); Ki_s = Ki(:,:,t); L_s =Li(:,:,:,t); if t<smpl - P = cat(3,P(:,:,1:t),repmat(P_s,[1 1 smpl-t])); - P1 = cat(3,P1(:,:,1:t),repmat(P1_s,[1 1 smpl-t])); - Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t])); - Li = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t])); - Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t])); + P = cat(3,P(:,:,1:t),repmat(P_s,[1 1 smpl-t])); + P1 = cat(3,P1(:,:,1:t),repmat(P1_s,[1 1 smpl-t])); + Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t])); + Li = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t])); + Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t])); end while t<smpl - t=t+1; - a(:,t) = a1(:,t); - for i=1:pp - Zi = Z(i,:); - v(i,t) = Y(i,t) - Zi*a(:,t); - if Fi_s(i) > crit - a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i); + t=t+1; + a(:,t) = a1(:,t); + for i=1:pp + Zi = Z(i,:); + v(i,t) = Y(i,t) - Zi*a(:,t); + if Fi_s(i) > crit + a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i); + end + end + a1(:,t+1) = T*a(:,t); + Pf = P(:,:,t); + for jnk=1:nk, + Pf = T*Pf*T' + QQ; + aK(jnk,:,t+jnk) = T^jnk*a(:,t); + PK(jnk,:,:,t+jnk) = Pf; end - end - a1(:,t+1) = T*a(:,t); - Pf = P(:,:,t); - for jnk=1:nk, - Pf = T*Pf*T' + QQ; - aK(jnk,:,t+jnk) = T^jnk*a(:,t); - PK(jnk,:,:,t+jnk) = Pf; - end end ri=zeros(mm,1); t = smpl+1; while t>d+1 - t = t-1; - for i=pp:-1:1 - if Fi(i,t) > crit - ri = Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri; + t = t-1; + for i=pp:-1:1 + if Fi(i,t) > crit + ri = Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri; + end end - end - r(:,t) = ri; - alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t); - etahat(:,t) = QRt*r(:,t); - ri = T'*ri; + r(:,t) = ri; + alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t); + etahat(:,t) = QRt*r(:,t); + ri = T'*ri; end if d - r0 = zeros(mm,d); - r0(:,d) = ri; - r1 = zeros(mm,d); - for t = d:-1:2 - for i=pp:-1:1 -% if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d), % use of options_.diffuse_d to be sure of DKF termination - if Finf(i,t) > crit - r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ... - L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t); - r0(:,t) = Linf(:,:,i,t)'*r0(:,t); - elseif Fstar(i,t) > crit % step needed whe Finf == 0 - r0(:,t) = Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t); - end - end - alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t); - r(:,t) = r0(:,t); - etahat(:,t) = QRt*r(:,t); - if t > 1 - r0(:,t-1) = T'*r0(:,t); - r1(:,t-1) = T'*r1(:,t); + r0 = zeros(mm,d); + r0(:,d) = ri; + r1 = zeros(mm,d); + for t = d:-1:2 + for i=pp:-1:1 + % if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d), % use of options_.diffuse_d to be sure of DKF termination + if Finf(i,t) > crit + r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ... + L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t); + r0(:,t) = Linf(:,:,i,t)'*r0(:,t); + elseif Fstar(i,t) > crit % step needed whe Finf == 0 + r0(:,t) = Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t); + end + end + alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t); + r(:,t) = r0(:,t); + etahat(:,t) = QRt*r(:,t); + if t > 1 + r0(:,t-1) = T'*r0(:,t); + r1(:,t-1) = T'*r1(:,t); + end end - end end if nargout > 7 diff --git a/matlab/DiffuseKalmanSmootherH3corr.m b/matlab/DiffuseKalmanSmootherH3corr.m index 5fe780745a..a692b2dbf7 100644 --- a/matlab/DiffuseKalmanSmootherH3corr.m +++ b/matlab/DiffuseKalmanSmootherH3corr.m @@ -54,7 +54,7 @@ T = cat(1,cat(2,T,zeros(mm,pp)),zeros(pp,mm+pp)); R = cat(1,cat(2,R,zeros(mm,pp)),cat(2,zeros(pp,rr),eye(pp))); Q = cat(1,cat(2,Q,zeros(rr,pp)),cat(2,zeros(pp,rr),H)); if size(Pinf1,1) % Otherwise Pinf = 0 (no unit root) - Pinf1 = cat(1,cat(2,Pinf1,zeros(mm,pp)),zeros(pp,mm+pp)); + Pinf1 = cat(1,cat(2,Pinf1,zeros(mm,pp)),zeros(pp,mm+pp)); end Pstar1 = cat(1,cat(2,Pstar1,zeros(mm,pp)),cat(2,zeros(pp,mm),H)); spinf = size(Pinf1); @@ -88,8 +88,8 @@ epsilonhat = zeros(pp,smpl); r = zeros(mm+pp,smpl+1); Z = zeros(pp,mm+pp); for i=1:pp; - Z(i,mf(i)) = 1; - Z(i,mm+i) = 1; + Z(i,mf(i)) = 1; + Z(i,mm+i) = 1; end %% [1] Kalman filter... t = 0; @@ -99,28 +99,28 @@ while newRank & t < smpl a(:,t) = a1(:,t); Pstar1(:,:,t) = Pstar(:,:,t); Pinf1(:,:,t) = Pinf(:,:,t); - for i=1:pp - v(i,t) = Y(i,t)-a(mf(i),t)-a(mm+i,t)-trend(i,t); - Fstar(i,t) = Pstar(mf(i),mf(i),t)+Pstar(mm+i,mm+i,t); - Finf(i,t) = Pinf(mf(i),mf(i),t); - Kstar(:,i,t) = Pstar(:,mf(i),t)+Pstar(:,mm+i,t); - if Finf(i,t) > crit - Kinf(:,i,t) = Pinf(:,mf(i),t); + for i=1:pp + v(i,t) = Y(i,t)-a(mf(i),t)-a(mm+i,t)-trend(i,t); + Fstar(i,t) = Pstar(mf(i),mf(i),t)+Pstar(mm+i,mm+i,t); + Finf(i,t) = Pinf(mf(i),mf(i),t); + Kstar(:,i,t) = Pstar(:,mf(i),t)+Pstar(:,mm+i,t); + if Finf(i,t) > crit + Kinf(:,i,t) = Pinf(:,mf(i),t); Linf(:,:,i,t) = eye(mm+pp) - Kinf(:,i,t)*Z(i,:)/Finf(i,t); L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Z(i,:)/Finf(i,t); - a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t); - Pstar(:,:,t) = Pstar(:,:,t) + ... + a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t); + Pstar(:,:,t) = Pstar(:,:,t) + ... Kinf(:,i,t)*transpose(Kinf(:,i,t))*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ... - (Kstar(:,i,t)*transpose(Kinf(:,i,t)) +... - Kinf(:,i,t)*transpose(Kstar(:,i,t)))/Finf(i,t); - Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*transpose(Kinf(:,i,t))/Finf(i,t); - else %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition - %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that - %% rank(Pinf)=0. [st�phane,11-03-2004]. - a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t); - Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*transpose(Kstar(:,i,t))/Fstar(i,t); + (Kstar(:,i,t)*transpose(Kinf(:,i,t)) +... + Kinf(:,i,t)*transpose(Kstar(:,i,t)))/Finf(i,t); + Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*transpose(Kinf(:,i,t))/Finf(i,t); + else %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition + %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that + %% rank(Pinf)=0. [st�phane,11-03-2004]. + a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t); + Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*transpose(Kstar(:,i,t))/Fstar(i,t); end - end + end a1(:,t+1) = T*a(:,t); for jnk=1:nk, aK(jnk,:,t+jnk) = T^jnk*a(:,t); @@ -147,11 +147,11 @@ while notsteady & t<smpl a(:,t) = a1(:,t); P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); P1(:,:,t) = P(:,:,t); - for i=1:pp + for i=1:pp v(i,t) = Y(i,t) - a(mf(i),t) - a(mm+i,t) - trend(i,t); - Fi(i,t) = P(mf(i),mf(i),t)+P(mm+i,mm+i,t); + Fi(i,t) = P(mf(i),mf(i),t)+P(mm+i,mm+i,t); Ki(:,i,t) = P(:,mf(i),t)+P(:,mm+i,t); - if Fi(i,t) > crit + if Fi(i,t) > crit Li(:,:,i,t) = eye(mm+pp)-Ki(:,i,t)*Z(i,:)/Fi(i,t); a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t); P(:,:,t) = P(:,:,t) - Ki(:,i,t)*transpose(Ki(:,i,t))/Fi(i,t); @@ -170,11 +170,11 @@ Fi_s = Fi(:,t); Ki_s = Ki(:,:,t); L_s =Li(:,:,:,t); if t<smpl - t_steady = t+1; - P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1])); - Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t_steady+1])); - Li = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t_steady+1])); - Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t_steady+1])); + t_steady = t+1; + P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1])); + Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t_steady+1])); + Li = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t_steady+1])); + Ki = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t_steady+1])); end while t<smpl t=t+1; @@ -219,16 +219,16 @@ if d L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t); r0(:,t) = transpose(Linf(:,:,i,t))*r0(:,t); end - end - alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t); - r(:,t-1) = r0(:,t); - tmp = QRt*r(:,t); - etahat(:,t) = tmp(1:rr); - epsilonhat(:,t) = tmp(rr+(1:pp)); - if t > 1 - r0(:,t-1) = T'*r0(:,t); - r1(:,t-1) = T'*r1(:,t); - end + end + alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t); + r(:,t-1) = r0(:,t); + tmp = QRt*r(:,t); + etahat(:,t) = tmp(1:rr); + epsilonhat(:,t) = tmp(rr+(1:pp)); + if t > 1 + r0(:,t-1) = T'*r0(:,t); + r1(:,t-1) = T'*r1(:,t); + end end end alphahat = alphahat(1:mm,:); \ No newline at end of file diff --git a/matlab/DiffuseLikelihood1.m b/matlab/DiffuseLikelihood1.m index 505912ce97..1059829f9a 100644 --- a/matlab/DiffuseLikelihood1.m +++ b/matlab/DiffuseLikelihood1.m @@ -1,130 +1,130 @@ -function [LIK, lik] = DiffuseLikelihood1(T,R,Q,Pinf,Pstar,Y,trend,start) - -% function [LIK, lik] = DiffuseLikelihood1(T,R,Q,Pinf,Pstar,Y,trend,start) -% Computes the diffuse likelihood without measurement error, in the case of a non-singular var-cov matrix -% -% INPUTS -% T: mm*mm matrix -% R: mm*rr matrix -% Q: rr*rr matrix -% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros -% Pstar: mm*mm variance-covariance matrix with stationary variables -% Y: pp*1 vector -% trend -% start: likelihood evaluation at 'start' -% -% OUTPUTS -% LIK: likelihood -% lik: density vector in each period -% -% SPECIAL REQUIREMENTS -% See "Filtering and Smoothing of State Vector for Diffuse State Space -% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series -% Analysis, vol. 24(1), pp. 85-98). - -% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. - -% M. Ratto added lik in output - - global bayestopt_ options_ - - mf = bayestopt_.mf; - smpl = size(Y,2); - mm = size(T,2); - pp = size(Y,1); - a = zeros(mm,1); - dF = 1; - QQ = R*Q*transpose(R); - t = 0; - lik = zeros(smpl,1); - LIK = Inf; - notsteady = 1; - crit = options_.kalman_tol; - while rank(Pinf,crit) & t < smpl - t = t+1; - v = Y(:,t)-a(mf)-trend(:,t); - Finf = Pinf(mf,mf); - if rcond(Finf) < crit - if ~all(abs(Finf(:)) < crit) - return - else - iFstar = inv(Pstar(mf,mf)); - dFstar = det(Pstar(mf,mf)); - Kstar = Pstar(:,mf)*iFstar; - lik(t) = log(dFstar) + transpose(v)*iFstar*v; - Pinf = T*Pinf*transpose(T); - Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kstar))*transpose(T)+QQ; - a = T*(a+Kstar*v); - end - else - lik(t) = log(det(Finf)); - iFinf = inv(Finf); - Kinf = Pinf(:,mf)*iFinf; %% premultiplication by the transition matrix T is removed (stephane) - Fstar = Pstar(mf,mf); - Kstar = (Pstar(:,mf)-Kinf*Fstar)*iFinf; %% premultiplication by the transition matrix T is removed (stephane) - Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kinf)-Pinf(:,mf)*transpose(Kstar))*transpose(T)+QQ; - Pinf = T*(Pinf-Pinf(:,mf)*transpose(Kinf))*transpose(T); - a = T*(a+Kinf*v); - end - end - if t == smpl - error(['There isn''t enough information to estimate the initial' ... - ' conditions of the nonstationary variables']); - end - F_singular = 1; - while notsteady & t < smpl - t = t+1; - v = Y(:,t)-a(mf)-trend(:,t); - F = Pstar(mf,mf); - oldPstar = Pstar; - dF = det(F); - if rcond(F) < crit - if ~all(abs(F(:))<crit) - return - else - a = T*a; - Pstar = T*Pstar*transpose(T)+QQ; - end - else - F_singular = 0; - iF = inv(F); - lik(t) = log(dF)+transpose(v)*iF*v; - K = Pstar(:,mf)*iF; %% premultiplication by the transition matrix T is removed (stephane) - a = T*(a+K*v); %% --> factorization of the transition matrix... - Pstar = T*(Pstar-K*Pstar(mf,:))*transpose(T)+QQ; %% ... idem (stephane) - end - notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit); - end - if F_singular == 1 - error(['The variance of the forecast error remains singular until the' ... - 'end of the sample']) - end - if t < smpl - t0 = t+1; - while t < smpl - t = t+1; - v = Y(:,t)-a(mf)-trend(:,t); - a = T*(a+K*v); - lik(t) = transpose(v)*iF*v; - end - lik(t0:smpl) = lik(t0:smpl) + log(dF); - end - % adding log-likelihhod constants - lik = (lik + pp*log(2*pi))/2; - - LIK = sum(lik(start:end)); % Minus the log-likelihood. \ No newline at end of file +function [LIK, lik] = DiffuseLikelihood1(T,R,Q,Pinf,Pstar,Y,trend,start) + +% function [LIK, lik] = DiffuseLikelihood1(T,R,Q,Pinf,Pstar,Y,trend,start) +% Computes the diffuse likelihood without measurement error, in the case of a non-singular var-cov matrix +% +% INPUTS +% T: mm*mm matrix +% R: mm*rr matrix +% Q: rr*rr matrix +% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros +% Pstar: mm*mm variance-covariance matrix with stationary variables +% Y: pp*1 vector +% trend +% start: likelihood evaluation at 'start' +% +% OUTPUTS +% LIK: likelihood +% lik: density vector in each period +% +% SPECIAL REQUIREMENTS +% See "Filtering and Smoothing of State Vector for Diffuse State Space +% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series +% Analysis, vol. 24(1), pp. 85-98). + +% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. + +% M. Ratto added lik in output + +global bayestopt_ options_ + +mf = bayestopt_.mf; +smpl = size(Y,2); +mm = size(T,2); +pp = size(Y,1); +a = zeros(mm,1); +dF = 1; +QQ = R*Q*transpose(R); +t = 0; +lik = zeros(smpl,1); +LIK = Inf; +notsteady = 1; +crit = options_.kalman_tol; +while rank(Pinf,crit) & t < smpl + t = t+1; + v = Y(:,t)-a(mf)-trend(:,t); + Finf = Pinf(mf,mf); + if rcond(Finf) < crit + if ~all(abs(Finf(:)) < crit) + return + else + iFstar = inv(Pstar(mf,mf)); + dFstar = det(Pstar(mf,mf)); + Kstar = Pstar(:,mf)*iFstar; + lik(t) = log(dFstar) + transpose(v)*iFstar*v; + Pinf = T*Pinf*transpose(T); + Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kstar))*transpose(T)+QQ; + a = T*(a+Kstar*v); + end + else + lik(t) = log(det(Finf)); + iFinf = inv(Finf); + Kinf = Pinf(:,mf)*iFinf; %% premultiplication by the transition matrix T is removed (stephane) + Fstar = Pstar(mf,mf); + Kstar = (Pstar(:,mf)-Kinf*Fstar)*iFinf; %% premultiplication by the transition matrix T is removed (stephane) + Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kinf)-Pinf(:,mf)*transpose(Kstar))*transpose(T)+QQ; + Pinf = T*(Pinf-Pinf(:,mf)*transpose(Kinf))*transpose(T); + a = T*(a+Kinf*v); + end +end +if t == smpl + error(['There isn''t enough information to estimate the initial' ... + ' conditions of the nonstationary variables']); +end +F_singular = 1; +while notsteady & t < smpl + t = t+1; + v = Y(:,t)-a(mf)-trend(:,t); + F = Pstar(mf,mf); + oldPstar = Pstar; + dF = det(F); + if rcond(F) < crit + if ~all(abs(F(:))<crit) + return + else + a = T*a; + Pstar = T*Pstar*transpose(T)+QQ; + end + else + F_singular = 0; + iF = inv(F); + lik(t) = log(dF)+transpose(v)*iF*v; + K = Pstar(:,mf)*iF; %% premultiplication by the transition matrix T is removed (stephane) + a = T*(a+K*v); %% --> factorization of the transition matrix... + Pstar = T*(Pstar-K*Pstar(mf,:))*transpose(T)+QQ; %% ... idem (stephane) + end + notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit); +end +if F_singular == 1 + error(['The variance of the forecast error remains singular until the' ... + 'end of the sample']) +end +if t < smpl + t0 = t+1; + while t < smpl + t = t+1; + v = Y(:,t)-a(mf)-trend(:,t); + a = T*(a+K*v); + lik(t) = transpose(v)*iF*v; + end + lik(t0:smpl) = lik(t0:smpl) + log(dF); +end +% adding log-likelihhod constants +lik = (lik + pp*log(2*pi))/2; + +LIK = sum(lik(start:end)); % Minus the log-likelihood. \ No newline at end of file diff --git a/matlab/DiffuseLikelihood1_Z.m b/matlab/DiffuseLikelihood1_Z.m index 0185777427..b0e21eb49b 100644 --- a/matlab/DiffuseLikelihood1_Z.m +++ b/matlab/DiffuseLikelihood1_Z.m @@ -1,130 +1,130 @@ -function [LIK, lik] = DiffuseLikelihood1_Z(T,Z,R,Q,Pinf,Pstar,Y,start) - -% function [LIK, lik] = DiffuseLikelihood1_Z(T,Z,R,Q,Pinf,Pstar,Y,start) -% Computes the diffuse likelihood without measurement error, in the case of a non-singular var-cov matrix -% -% INPUTS -% T: mm*mm matrix -% Z: pp,mm matrix -% R: mm*rr matrix -% Q: rr*rr matrix -% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros -% Pstar: mm*mm variance-covariance matrix with stationary variables -% Y: pp*1 vector -% start: likelihood evaluation at 'start' -% -% OUTPUTS -% LIK: likelihood -% lik: density vector in each period -% -% SPECIAL REQUIREMENTS -% See "Filtering and Smoothing of State Vector for Diffuse State Space -% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series -% Analysis, vol. 24(1), pp. 85-98). - -% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. - -% M. Ratto added lik in output - - global bayestopt_ options_ - - smpl = size(Y,2); - mm = size(T,2); - pp = size(Y,1); - a = zeros(mm,1); - dF = 1; - QQ = R*Q*transpose(R); - t = 0; - lik = zeros(smpl,1); - LIK = Inf; - notsteady = 1; - crit = options_.kalman_tol; - while rank(Pinf,crit) & t < smpl - t = t+1; - v = Y(:,t)-Z*a; - Finf = Z*Pinf*Z'; - if rcond(Finf) < crit - if ~all(abs(Finf(:)) < crit) - return - else - Fstar = Z*Pstar*Z'; - iFstar = inv(Fstar); - dFstar = det(Fstar); - Kstar = Pstar*Z'*iFstar; - lik(t) = log(dFstar) + v'*iFstar*v; - Pinf = T*Pinf*transpose(T); - Pstar = T*(Pstar-Pstar*Z'*Kstar')*T'+QQ; - a = T*(a+Kstar*v); - end - else - lik(t) = log(det(Finf)); - iFinf = inv(Finf); - Kinf = Pinf*Z'*iFinf; - Fstar = Z*Pstar*Z'; - Kstar = (Pstar*Z'-Kinf*Fstar)*iFinf; - Pstar = T*(Pstar-Pstar*Z'*Kinf'-Pinf*Z'*Kstar')*T'+QQ; - Pinf = T*(Pinf-Pinf*Z'*Kinf')*T'; - a = T*(a+Kinf*v); - end - end - if t == smpl - error(['There isn''t enough information to estimate the initial' ... - ' conditions of the nonstationary variables']); - end - F_singular = 1; - while notsteady & t < smpl - t = t+1; - v = Y(:,t)-Z*a; - F = Z*Pstar*Z'; - oldPstar = Pstar; - dF = det(F); - if rcond(F) < crit - if ~all(abs(F(:))<crit) - return - else - a = T*a; - Pstar = T*Pstar*T'+QQ; - end - else - F_singular = 0; - iF = inv(F); - lik(t) = log(dF)+v'*iF*v; - K = Pstar*Z'*iF; - a = T*(a+K*v); - Pstar = T*(Pstar-K*Z*Pstar)*T'+QQ; - end - notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit); - end - if F_singular == 1 - error(['The variance of the forecast error remains singular until the' ... - 'end of the sample']) - end - if t < smpl - t0 = t+1; - while t < smpl - t = t+1; - v = Y(:,t)-Z*a; - a = T*(a+K*v); - lik(t) = v'*iF*v; - end - lik(t0:smpl) = lik(t0:smpl) + log(dF); - end - % adding log-likelihhod constants - lik = (lik + pp*log(2*pi))/2; - - LIK = sum(lik(start:end)); % Minus the log-likelihood. \ No newline at end of file +function [LIK, lik] = DiffuseLikelihood1_Z(T,Z,R,Q,Pinf,Pstar,Y,start) + +% function [LIK, lik] = DiffuseLikelihood1_Z(T,Z,R,Q,Pinf,Pstar,Y,start) +% Computes the diffuse likelihood without measurement error, in the case of a non-singular var-cov matrix +% +% INPUTS +% T: mm*mm matrix +% Z: pp,mm matrix +% R: mm*rr matrix +% Q: rr*rr matrix +% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros +% Pstar: mm*mm variance-covariance matrix with stationary variables +% Y: pp*1 vector +% start: likelihood evaluation at 'start' +% +% OUTPUTS +% LIK: likelihood +% lik: density vector in each period +% +% SPECIAL REQUIREMENTS +% See "Filtering and Smoothing of State Vector for Diffuse State Space +% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series +% Analysis, vol. 24(1), pp. 85-98). + +% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. + +% M. Ratto added lik in output + +global bayestopt_ options_ + +smpl = size(Y,2); +mm = size(T,2); +pp = size(Y,1); +a = zeros(mm,1); +dF = 1; +QQ = R*Q*transpose(R); +t = 0; +lik = zeros(smpl,1); +LIK = Inf; +notsteady = 1; +crit = options_.kalman_tol; +while rank(Pinf,crit) & t < smpl + t = t+1; + v = Y(:,t)-Z*a; + Finf = Z*Pinf*Z'; + if rcond(Finf) < crit + if ~all(abs(Finf(:)) < crit) + return + else + Fstar = Z*Pstar*Z'; + iFstar = inv(Fstar); + dFstar = det(Fstar); + Kstar = Pstar*Z'*iFstar; + lik(t) = log(dFstar) + v'*iFstar*v; + Pinf = T*Pinf*transpose(T); + Pstar = T*(Pstar-Pstar*Z'*Kstar')*T'+QQ; + a = T*(a+Kstar*v); + end + else + lik(t) = log(det(Finf)); + iFinf = inv(Finf); + Kinf = Pinf*Z'*iFinf; + Fstar = Z*Pstar*Z'; + Kstar = (Pstar*Z'-Kinf*Fstar)*iFinf; + Pstar = T*(Pstar-Pstar*Z'*Kinf'-Pinf*Z'*Kstar')*T'+QQ; + Pinf = T*(Pinf-Pinf*Z'*Kinf')*T'; + a = T*(a+Kinf*v); + end +end +if t == smpl + error(['There isn''t enough information to estimate the initial' ... + ' conditions of the nonstationary variables']); +end +F_singular = 1; +while notsteady & t < smpl + t = t+1; + v = Y(:,t)-Z*a; + F = Z*Pstar*Z'; + oldPstar = Pstar; + dF = det(F); + if rcond(F) < crit + if ~all(abs(F(:))<crit) + return + else + a = T*a; + Pstar = T*Pstar*T'+QQ; + end + else + F_singular = 0; + iF = inv(F); + lik(t) = log(dF)+v'*iF*v; + K = Pstar*Z'*iF; + a = T*(a+K*v); + Pstar = T*(Pstar-K*Z*Pstar)*T'+QQ; + end + notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit); +end +if F_singular == 1 + error(['The variance of the forecast error remains singular until the' ... + 'end of the sample']) +end +if t < smpl + t0 = t+1; + while t < smpl + t = t+1; + v = Y(:,t)-Z*a; + a = T*(a+K*v); + lik(t) = v'*iF*v; + end + lik(t0:smpl) = lik(t0:smpl) + log(dF); +end +% adding log-likelihhod constants +lik = (lik + pp*log(2*pi))/2; + +LIK = sum(lik(start:end)); % Minus the log-likelihood. \ No newline at end of file diff --git a/matlab/DiffuseLikelihood3.m b/matlab/DiffuseLikelihood3.m index 9843a7477a..6e49355767 100644 --- a/matlab/DiffuseLikelihood3.m +++ b/matlab/DiffuseLikelihood3.m @@ -1,195 +1,195 @@ -function [LIK, lik] = DiffuseLikelihood3(T,R,Q,Pinf,Pstar,Y,trend,start)%//Z,T,R,Q,Pinf,Pstar,Y) - -% function [LIK, lik] = DiffuseLikelihood3(T,R,Q,Pinf,Pstar,Y,trend,start) -% Computes the diffuse likelihood without measurement error, in the case of -% a singular var-cov matrix. -% Univariate treatment of multivariate time series. -% -% INPUTS -% T: mm*mm matrix -% R: mm*rr matrix -% Q: rr*rr matrix -% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros -% Pstar: mm*mm variance-covariance matrix with stationary variables -% Y: pp*1 vector -% trend -% start: likelihood evaluation at 'start' -% -% OUTPUTS -% LIK: likelihood -% lik: density vector in each period -% -% SPECIAL REQUIREMENTS -% See "Filtering and Smoothing of State Vector for Diffuse State Space -% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series -% Analysis, vol. 24(1), pp. 85-98). - -% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. - -% M. Ratto added lik in output [October 2005] -% changes by M. Ratto [April 2005] -% introduced new options options_.diffuse_d for termination of DKF -% new icc counter for Finf steps in DKF -% new termination for DKF -% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non -% zero. -% [4/5/2005] correctyed bug in the modified verson of Ratto for rank of Pinf -% introduced a specific crit1 for the DKF termination - - -global bayestopt_ options_ - -mf = bayestopt_.mf; -pp = size(Y,1); -mm = size(T,1); -smpl = size(Y,2); -a = zeros(mm,1); -QQ = R*Q*transpose(R); -t = 0; -lik = zeros(smpl,1); -notsteady = 1; -crit = options_.kalman_tol; -crit1 = 1.e-6; -newRank = rank(Pinf,crit1); -icc=0; -while newRank & t < smpl - t = t+1; - for i=1:pp - v(i) = Y(i,t)-a(mf(i))-trend(i,t); - Fstar = Pstar(mf(i),mf(i)); - Finf = Pinf(mf(i),mf(i)); - Kstar = Pstar(:,mf(i)); - if Finf > crit & newRank, %added newRank criterion - icc=icc+1; - Kinf = Pinf(:,mf(i)); - a = a + Kinf*v(i)/Finf; - Pstar = Pstar + Kinf*transpose(Kinf)*Fstar/(Finf*Finf) - ... - (Kstar*transpose(Kinf)+Kinf*transpose(Kstar))/Finf; - Pinf = Pinf - Kinf*transpose(Kinf)/Finf; - lik(t) = lik(t) + log(Finf); - % start new termination criterion for DKF - if ~isempty(options_.diffuse_d), - newRank = (icc<options_.diffuse_d); - %if newRank & any(diag(Pinf(mf,mf))>crit)==0; % M. Ratto this line is BUGGY - if newRank & (any(diag(Pinf(mf,mf))>crit)==0 & rank(Pinf,crit1)==0); - options_.diffuse_d = icc; - newRank=0; - disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF') - disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)]) - disp('You may have to reset the optimisation') - end - else - %newRank = any(diag(Pinf(mf,mf))>crit); % M. Ratto this line is BUGGY - newRank = (any(diag(Pinf(mf,mf))>crit) | rank(Pinf,crit1)); - if newRank==0, - P0= T*Pinf*transpose(T); - %newRank = any(diag(P0(mf,mf))>crit); % M. Ratto this line is BUGGY - newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1)); % M. Ratto 11/10/2005 - if newRank==0, - options_.diffuse_d = icc; - end - end - end, - % end new termination and checks for DKF - elseif Fstar > crit - %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition - %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that - %% rank(Pinf)=0. [st�phane,11-03-2004]. - %if rank(Pinf,crit) == 0 - % the likelihood terms should alwasy be cumulated, not only - % when Pinf=0, otherwise the lik would depend on the ordering - % of observed variables - % presample options can be used to ignore initial time points - lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar; - %end - a = a + Kstar*v(i)/Fstar; - Pstar = Pstar - Kstar*transpose(Kstar)/Fstar; - else - %disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fstar)]) - end - end -% if all(abs(Pinf(:))<crit), -% oldRank = 0; -% else -% oldRank = rank(Pinf,crit); -% end - if newRank, - oldRank = rank(Pinf,crit1); - else - oldRank = 0; - end - a = T*a; - Pstar = T*Pstar*transpose(T)+QQ; - Pinf = T*Pinf*transpose(T); -% if all(abs(Pinf(:))<crit), -% newRank = 0; -% else -% newRank = rank(Pinf,crit); -% end - if newRank, - newRank = rank(Pinf,crit1); % new crit1 is used - end - if oldRank ~= newRank - disp('DiffuseLiklihood3 :: T does influence the rank of Pinf!') - end -end -if t == smpl - error(['There isn''t enough information to estimate the initial' ... - ' conditions of the nonstationary variables']); -end -while notsteady & t < smpl - t = t+1; - oldP = Pstar; - for i=1:pp - v(i) = Y(i,t) - a(mf(i)) - trend(i,t); - Fi = Pstar(mf(i),mf(i)); - if Fi > crit - Ki = Pstar(:,mf(i)); - a = a + Ki*v(i)/Fi; - Pstar = Pstar - Ki*transpose(Ki)/Fi; - lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; - else - %disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)]) - end - end - a = T*a; - Pstar = T*Pstar*transpose(T) + QQ; - notsteady = ~(max(max(abs(Pstar-oldP)))<crit); -end -while t < smpl - t = t+1; - Pstar = oldP; - for i=1:pp - v(i) = Y(i,t) - a(mf(i)) - trend(i,t); - Fi = Pstar(mf(i),mf(i)); - if Fi > crit - Ki = Pstar(:,mf(i)); - a = a + Ki*v(i)/Fi; - Pstar = Pstar - Ki*transpose(Ki)/Fi; - lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; - else - %disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)]) - end - end - a = T*a; -end - -% adding log-likelihhod constants -lik = (lik + pp*log(2*pi))/2; - -LIK = sum(lik(start:end)); % Minus the log-likelihood. +function [LIK, lik] = DiffuseLikelihood3(T,R,Q,Pinf,Pstar,Y,trend,start)%//Z,T,R,Q,Pinf,Pstar,Y) + +% function [LIK, lik] = DiffuseLikelihood3(T,R,Q,Pinf,Pstar,Y,trend,start) +% Computes the diffuse likelihood without measurement error, in the case of +% a singular var-cov matrix. +% Univariate treatment of multivariate time series. +% +% INPUTS +% T: mm*mm matrix +% R: mm*rr matrix +% Q: rr*rr matrix +% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros +% Pstar: mm*mm variance-covariance matrix with stationary variables +% Y: pp*1 vector +% trend +% start: likelihood evaluation at 'start' +% +% OUTPUTS +% LIK: likelihood +% lik: density vector in each period +% +% SPECIAL REQUIREMENTS +% See "Filtering and Smoothing of State Vector for Diffuse State Space +% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series +% Analysis, vol. 24(1), pp. 85-98). + +% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. + +% M. Ratto added lik in output [October 2005] +% changes by M. Ratto [April 2005] +% introduced new options options_.diffuse_d for termination of DKF +% new icc counter for Finf steps in DKF +% new termination for DKF +% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non +% zero. +% [4/5/2005] correctyed bug in the modified verson of Ratto for rank of Pinf +% introduced a specific crit1 for the DKF termination + + +global bayestopt_ options_ + +mf = bayestopt_.mf; +pp = size(Y,1); +mm = size(T,1); +smpl = size(Y,2); +a = zeros(mm,1); +QQ = R*Q*transpose(R); +t = 0; +lik = zeros(smpl,1); +notsteady = 1; +crit = options_.kalman_tol; +crit1 = 1.e-6; +newRank = rank(Pinf,crit1); +icc=0; +while newRank & t < smpl + t = t+1; + for i=1:pp + v(i) = Y(i,t)-a(mf(i))-trend(i,t); + Fstar = Pstar(mf(i),mf(i)); + Finf = Pinf(mf(i),mf(i)); + Kstar = Pstar(:,mf(i)); + if Finf > crit & newRank, %added newRank criterion + icc=icc+1; + Kinf = Pinf(:,mf(i)); + a = a + Kinf*v(i)/Finf; + Pstar = Pstar + Kinf*transpose(Kinf)*Fstar/(Finf*Finf) - ... + (Kstar*transpose(Kinf)+Kinf*transpose(Kstar))/Finf; + Pinf = Pinf - Kinf*transpose(Kinf)/Finf; + lik(t) = lik(t) + log(Finf); + % start new termination criterion for DKF + if ~isempty(options_.diffuse_d), + newRank = (icc<options_.diffuse_d); + %if newRank & any(diag(Pinf(mf,mf))>crit)==0; % M. Ratto this line is BUGGY + if newRank & (any(diag(Pinf(mf,mf))>crit)==0 & rank(Pinf,crit1)==0); + options_.diffuse_d = icc; + newRank=0; + disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF') + disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)]) + disp('You may have to reset the optimisation') + end + else + %newRank = any(diag(Pinf(mf,mf))>crit); % M. Ratto this line is BUGGY + newRank = (any(diag(Pinf(mf,mf))>crit) | rank(Pinf,crit1)); + if newRank==0, + P0= T*Pinf*transpose(T); + %newRank = any(diag(P0(mf,mf))>crit); % M. Ratto this line is BUGGY + newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1)); % M. Ratto 11/10/2005 + if newRank==0, + options_.diffuse_d = icc; + end + end + end, + % end new termination and checks for DKF + elseif Fstar > crit + %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition + %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that + %% rank(Pinf)=0. [st�phane,11-03-2004]. + %if rank(Pinf,crit) == 0 + % the likelihood terms should alwasy be cumulated, not only + % when Pinf=0, otherwise the lik would depend on the ordering + % of observed variables + % presample options can be used to ignore initial time points + lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar; + %end + a = a + Kstar*v(i)/Fstar; + Pstar = Pstar - Kstar*transpose(Kstar)/Fstar; + else + %disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fstar)]) + end + end + % if all(abs(Pinf(:))<crit), + % oldRank = 0; + % else + % oldRank = rank(Pinf,crit); + % end + if newRank, + oldRank = rank(Pinf,crit1); + else + oldRank = 0; + end + a = T*a; + Pstar = T*Pstar*transpose(T)+QQ; + Pinf = T*Pinf*transpose(T); + % if all(abs(Pinf(:))<crit), + % newRank = 0; + % else + % newRank = rank(Pinf,crit); + % end + if newRank, + newRank = rank(Pinf,crit1); % new crit1 is used + end + if oldRank ~= newRank + disp('DiffuseLiklihood3 :: T does influence the rank of Pinf!') + end +end +if t == smpl + error(['There isn''t enough information to estimate the initial' ... + ' conditions of the nonstationary variables']); +end +while notsteady & t < smpl + t = t+1; + oldP = Pstar; + for i=1:pp + v(i) = Y(i,t) - a(mf(i)) - trend(i,t); + Fi = Pstar(mf(i),mf(i)); + if Fi > crit + Ki = Pstar(:,mf(i)); + a = a + Ki*v(i)/Fi; + Pstar = Pstar - Ki*transpose(Ki)/Fi; + lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; + else + %disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)]) + end + end + a = T*a; + Pstar = T*Pstar*transpose(T) + QQ; + notsteady = ~(max(max(abs(Pstar-oldP)))<crit); +end +while t < smpl + t = t+1; + Pstar = oldP; + for i=1:pp + v(i) = Y(i,t) - a(mf(i)) - trend(i,t); + Fi = Pstar(mf(i),mf(i)); + if Fi > crit + Ki = Pstar(:,mf(i)); + a = a + Ki*v(i)/Fi; + Pstar = Pstar - Ki*transpose(Ki)/Fi; + lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; + else + %disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)]) + end + end + a = T*a; +end + +% adding log-likelihhod constants +lik = (lik + pp*log(2*pi))/2; + +LIK = sum(lik(start:end)); % Minus the log-likelihood. diff --git a/matlab/DiffuseLikelihood3_Z.m b/matlab/DiffuseLikelihood3_Z.m index 39447e2199..618e5366b3 100644 --- a/matlab/DiffuseLikelihood3_Z.m +++ b/matlab/DiffuseLikelihood3_Z.m @@ -1,180 +1,180 @@ -function [LIK, lik] = DiffuseLikelihood3_Z(T,Z,R,Q,Pinf,Pstar,Y,start) - -% function [LIK, lik] = DiffuseLikelihood3_Z(T,Z,R,Q,Pinf,Pstar,Y,start) -% Computes the diffuse likelihood without measurement error, in the case of -% a singular var-cov matrix. -% Univariate treatment of multivariate time series. -% -% INPUTS -% T: mm*mm matrix -% Z: pp*mm matrix -% R: mm*rr matrix -% Q: rr*rr matrix -% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros -% Pstar: mm*mm variance-covariance matrix with stationary variables -% Y: pp*1 vector -% start: likelihood evaluation at 'start' -% -% OUTPUTS -% LIK: likelihood -% lik: density vector in each period -% -% SPECIAL REQUIREMENTS -% See "Filtering and Smoothing of State Vector for Diffuse State Space -% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series -% Analysis, vol. 24(1), pp. 85-98). - -% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. - -% M. Ratto added lik in output [October 2005] -% changes by M. Ratto [April 2005] -% introduced new options options_.diffuse_d for termination of DKF -% new icc counter for Finf steps in DKF -% new termination for DKF -% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non -% zero. -% [4/5/2005] correctyed bug in the modified verson of Ratto for rank of Pinf -% introduced a specific crit1 for the DKF termination - - -global bayestopt_ options_ - -pp = size(Y,1); -mm = size(T,1); -smpl = size(Y,2); -a = zeros(mm,1); -QQ = R*Q*R'; -t = 0; -lik = zeros(smpl,1); -notsteady = 1; -crit = options_.kalman_tol; -crit1 = 1.e-6; -newRank = rank(Pinf,crit1); -icc=0; -while newRank & t < smpl - t = t+1; - for i=1:pp - Zi = Z(i,:); - v(i) = Y(i,t)-Zi*a; - Fstar = Zi*Pstar*Zi'; - Finf = Zi*Pinf*Zi'; - Kstar = Pstar*Zi'; - if Finf > crit & newRank - icc=icc+1; - Kinf = Pinf*Zi'; - a = a + Kinf*v(i)/Finf; - Pstar = Pstar + Kinf*Kinf'*Fstar/(Finf*Finf) - ... - (Kstar*Kinf'+Kinf*Kstar')/Finf; - Pinf = Pinf - Kinf*Kinf'/Finf; - lik(t) = lik(t) + log(Finf); - if ~isempty(options_.diffuse_d), - newRank = (icc<options_.diffuse_d); - if newRank & (any(diag(Z*Pinf*Z')>crit)==0 & rank(Pinf,crit1)==0); - options_.diffuse_d = icc; - newRank=0; - disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF') - disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)]) - disp('You may have to reset the optimisation') - end - else - newRank = (any(diag(Z*Pinf*Z')>crit) | rank(Pinf,crit1)); - if newRank==0, - P0= T*Pinf*T'; - newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1)); % M. Ratto 11/10/2005 - if newRank==0, - options_.diffuse_d = icc; - end - end - end, - elseif Fstar > crit - %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition - %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that - %% rank(Pinf)=0. [st�phane,11-03-2004]. - %if rank(Pinf,crit) == 0 - % the likelihood terms should alwasy be cumulated, not only - % when Pinf=0, otherwise the lik would depend on the ordering - % of observed variables - % presample options can be used to ignore initial time points - lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar; - a = a + Kstar*v(i)/Fstar; - Pstar = Pstar - Kstar*(Kstar'/Fstar); - else - %disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fstar)]) - end - end - if newRank, - oldRank = rank(Pinf,crit1); - else - oldRank = 0; - end - a = T*a; - Pstar = T*Pstar*T'+QQ; - Pinf = T*Pinf*T'; - if newRank, - newRank = rank(Pinf,crit1); - end - if oldRank ~= newRank - disp('DiffuseLiklihood3 :: T does influence the rank of Pinf!') - end -end -if t == smpl - error(['There isn''t enough information to estimate the initial' ... - ' conditions of the nonstationary variables']); -end -while notsteady & t < smpl - t = t+1; - oldP = Pstar; - for i=1:pp - Zi = Z(i,:); - v(i) = Y(i,t) - Zi*a; - Fi = Zi*Pstar*Zi'; - if Fi > crit - Ki = Pstar*Zi'; - a = a + Ki*v(i)/Fi; - Pstar = Pstar - Ki*(Ki'/Fi); - lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; - else - %disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)]) - end - end - a = T*a; - Pstar = T*Pstar*T' + QQ; - notsteady = ~(max(max(abs(Pstar-oldP)))<crit); -end -while t < smpl - t = t+1; - Pstar = oldP; - for i=1:pp - Zi = Z(i,:); - v(i) = Y(i,t) - Zi*a; - Fi = Zi*Pstar*Zi'; - if Fi > crit - Ki = Pstar*Zi'; - a = a + Ki*v(i)/Fi; - Pstar = Pstar - Ki*Ki'/Fi; - lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; - else - %disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)]) - end - end - a = T*a; -end -% adding log-likelihhod constants -lik = (lik + pp*log(2*pi))/2; - -LIK = sum(lik(start:end)); % Minus the log-likelihood. +function [LIK, lik] = DiffuseLikelihood3_Z(T,Z,R,Q,Pinf,Pstar,Y,start) + +% function [LIK, lik] = DiffuseLikelihood3_Z(T,Z,R,Q,Pinf,Pstar,Y,start) +% Computes the diffuse likelihood without measurement error, in the case of +% a singular var-cov matrix. +% Univariate treatment of multivariate time series. +% +% INPUTS +% T: mm*mm matrix +% Z: pp*mm matrix +% R: mm*rr matrix +% Q: rr*rr matrix +% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros +% Pstar: mm*mm variance-covariance matrix with stationary variables +% Y: pp*1 vector +% start: likelihood evaluation at 'start' +% +% OUTPUTS +% LIK: likelihood +% lik: density vector in each period +% +% SPECIAL REQUIREMENTS +% See "Filtering and Smoothing of State Vector for Diffuse State Space +% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series +% Analysis, vol. 24(1), pp. 85-98). + +% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. + +% M. Ratto added lik in output [October 2005] +% changes by M. Ratto [April 2005] +% introduced new options options_.diffuse_d for termination of DKF +% new icc counter for Finf steps in DKF +% new termination for DKF +% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non +% zero. +% [4/5/2005] correctyed bug in the modified verson of Ratto for rank of Pinf +% introduced a specific crit1 for the DKF termination + + +global bayestopt_ options_ + +pp = size(Y,1); +mm = size(T,1); +smpl = size(Y,2); +a = zeros(mm,1); +QQ = R*Q*R'; +t = 0; +lik = zeros(smpl,1); +notsteady = 1; +crit = options_.kalman_tol; +crit1 = 1.e-6; +newRank = rank(Pinf,crit1); +icc=0; +while newRank & t < smpl + t = t+1; + for i=1:pp + Zi = Z(i,:); + v(i) = Y(i,t)-Zi*a; + Fstar = Zi*Pstar*Zi'; + Finf = Zi*Pinf*Zi'; + Kstar = Pstar*Zi'; + if Finf > crit & newRank + icc=icc+1; + Kinf = Pinf*Zi'; + a = a + Kinf*v(i)/Finf; + Pstar = Pstar + Kinf*Kinf'*Fstar/(Finf*Finf) - ... + (Kstar*Kinf'+Kinf*Kstar')/Finf; + Pinf = Pinf - Kinf*Kinf'/Finf; + lik(t) = lik(t) + log(Finf); + if ~isempty(options_.diffuse_d), + newRank = (icc<options_.diffuse_d); + if newRank & (any(diag(Z*Pinf*Z')>crit)==0 & rank(Pinf,crit1)==0); + options_.diffuse_d = icc; + newRank=0; + disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF') + disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)]) + disp('You may have to reset the optimisation') + end + else + newRank = (any(diag(Z*Pinf*Z')>crit) | rank(Pinf,crit1)); + if newRank==0, + P0= T*Pinf*T'; + newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1)); % M. Ratto 11/10/2005 + if newRank==0, + options_.diffuse_d = icc; + end + end + end, + elseif Fstar > crit + %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition + %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that + %% rank(Pinf)=0. [st�phane,11-03-2004]. + %if rank(Pinf,crit) == 0 + % the likelihood terms should alwasy be cumulated, not only + % when Pinf=0, otherwise the lik would depend on the ordering + % of observed variables + % presample options can be used to ignore initial time points + lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar; + a = a + Kstar*v(i)/Fstar; + Pstar = Pstar - Kstar*(Kstar'/Fstar); + else + %disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fstar)]) + end + end + if newRank, + oldRank = rank(Pinf,crit1); + else + oldRank = 0; + end + a = T*a; + Pstar = T*Pstar*T'+QQ; + Pinf = T*Pinf*T'; + if newRank, + newRank = rank(Pinf,crit1); + end + if oldRank ~= newRank + disp('DiffuseLiklihood3 :: T does influence the rank of Pinf!') + end +end +if t == smpl + error(['There isn''t enough information to estimate the initial' ... + ' conditions of the nonstationary variables']); +end +while notsteady & t < smpl + t = t+1; + oldP = Pstar; + for i=1:pp + Zi = Z(i,:); + v(i) = Y(i,t) - Zi*a; + Fi = Zi*Pstar*Zi'; + if Fi > crit + Ki = Pstar*Zi'; + a = a + Ki*v(i)/Fi; + Pstar = Pstar - Ki*(Ki'/Fi); + lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; + else + %disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)]) + end + end + a = T*a; + Pstar = T*Pstar*T' + QQ; + notsteady = ~(max(max(abs(Pstar-oldP)))<crit); +end +while t < smpl + t = t+1; + Pstar = oldP; + for i=1:pp + Zi = Z(i,:); + v(i) = Y(i,t) - Zi*a; + Fi = Zi*Pstar*Zi'; + if Fi > crit + Ki = Pstar*Zi'; + a = a + Ki*v(i)/Fi; + Pstar = Pstar - Ki*Ki'/Fi; + lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; + else + %disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)]) + end + end + a = T*a; +end +% adding log-likelihhod constants +lik = (lik + pp*log(2*pi))/2; + +LIK = sum(lik(start:end)); % Minus the log-likelihood. diff --git a/matlab/DiffuseLikelihoodH1.m b/matlab/DiffuseLikelihoodH1.m index 6d2e6da850..44a8b7da7c 100644 --- a/matlab/DiffuseLikelihoodH1.m +++ b/matlab/DiffuseLikelihoodH1.m @@ -1,131 +1,131 @@ -function [LIK, lik] = DiffuseLikelihoodH1(T,R,Q,H,Pinf,Pstar,Y,trend,start) - -% function [LIK, lik] = DiffuseLikelihoodH1(T,R,Q,H,Pinf,Pstar,Y,trend,start) -% Computes the diffuse likelihood (H=measurement error) in the case of a non-singular var-cov matrix -% -% INPUTS -% T: mm*mm matrix -% R: mm*rr matrix -% Q: rr*rr matrix -% H: pp*pp matrix -% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros -% Pstar: mm*mm variance-covariance matrix with stationary variables -% Y: pp*1 vector -% trend -% start: likelihood evaluation at 'start' -% -% OUTPUTS -% LIK: likelihood -% lik: density vector in each period -% -% SPECIAL REQUIREMENTS -% See "Filtering and Smoothing of State Vector for Diffuse State Space -% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series -% Analysis, vol. 24(1), pp. 85-98). - -% Copyright (C) 2005-2008 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 <http://www.gnu.org/licenses/>. - -% M. Ratto added lik in output - - global bayestopt_ options_ - - mf = bayestopt_.mf; - smpl = size(Y,2); - mm = size(T,2); - pp = size(Y,1); - a = zeros(mm,1); - dF = 1; - QQ = R*Q*transpose(R); - t = 0; - lik = zeros(smpl,1); - LIK = Inf; - notsteady = 1; - crit = options_.kalman_tol; - while rank(Pinf,crit) & t < smpl - t = t+1; - v = Y(:,t)-a(mf)-trend(:,t); - Finf = Pinf(mf,mf); - if rcond(Finf) < crit - if ~all(abs(Finf(:))<crit) - return - else - iFstar = inv(Pstar(mf,mf)+H); - dFstar = det(Pstar(mf,mf)+H); - Kstar = Pstar(:,mf)*iFstar; - lik(t) = log(dFstar) + transpose(v)*iFstar*v; - Pinf = T*Pinf*transpose(T); - Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kstar))*transpose(T)+QQ; - a = T*(a+Kstar*v); - end - else - lik(t) = log(det(Finf)); - iFinf = inv(Finf); - Kinf = Pinf(:,mf)*iFinf; %% premultiplication by the transition matrix T is removed (stephane) - Fstar = Pstar(mf,mf)+H; - Kstar = (Pstar(:,mf)-Kinf*Fstar)*iFinf; %% premultiplication by the transition matrix T is removed (stephane) - Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kinf)-Pinf(:,mf)*transpose(Kstar))*transpose(T)+QQ; - Pinf = T*(Pinf-Pinf(:,mf)*transpose(Kinf))*transpose(T); - a = T*(a+Kinf*v); - end - end - if t == smpl - error(['There isn''t enough information to estimate the initial' ... - ' conditions of the nonstationary variables']); - end - F_singular = 1; - while notsteady & t < smpl - t = t+1; - v = Y(:,t)-a(mf)-trend(:,t); - F = Pstar(mf,mf)+H; - oldPstar = Pstar; - dF = det(F); - if rcond(F) < crit - if ~all(abs(F(:))<crit) - return - else - a = T*a; - Pstar = T*Pstar*transpose(T)+QQ; - end - else - F_singular = 0; - iF = inv(F); - lik(t) = log(dF)+transpose(v)*iF*v; - K = Pstar(:,mf)*iF; %% premultiplication by the transition matrix T is removed (stephane) - a = T*(a+K*v); %% --> factorization of the transition matrix... - Pstar = T*(Pstar-K*Pstar(mf,:))*transpose(T)+QQ; %% ... idem (stephane) - end - notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit); - end - if F_singular == 1 - error(['The variance of the forecast error remains singular until the' ... - 'end of the sample']) - end - if t < smpl - t0 = t+1; - while t < smpl - t = t+1; - v = Y(:,t)-a(mf)-trend(:,t); - a = T*(a+K*v); - lik(t) = transpose(v)*iF*v; - end - lik(t0:smpl) = lik(t0:smpl) + log(dF); - end - % adding log-likelihhod constants - lik = (lik + pp*log(2*pi))/2; - - LIK = sum(lik(start:end)); % Minus the log-likelihood. +function [LIK, lik] = DiffuseLikelihoodH1(T,R,Q,H,Pinf,Pstar,Y,trend,start) + +% function [LIK, lik] = DiffuseLikelihoodH1(T,R,Q,H,Pinf,Pstar,Y,trend,start) +% Computes the diffuse likelihood (H=measurement error) in the case of a non-singular var-cov matrix +% +% INPUTS +% T: mm*mm matrix +% R: mm*rr matrix +% Q: rr*rr matrix +% H: pp*pp matrix +% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros +% Pstar: mm*mm variance-covariance matrix with stationary variables +% Y: pp*1 vector +% trend +% start: likelihood evaluation at 'start' +% +% OUTPUTS +% LIK: likelihood +% lik: density vector in each period +% +% SPECIAL REQUIREMENTS +% See "Filtering and Smoothing of State Vector for Diffuse State Space +% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series +% Analysis, vol. 24(1), pp. 85-98). + +% Copyright (C) 2005-2008 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 <http://www.gnu.org/licenses/>. + +% M. Ratto added lik in output + +global bayestopt_ options_ + +mf = bayestopt_.mf; +smpl = size(Y,2); +mm = size(T,2); +pp = size(Y,1); +a = zeros(mm,1); +dF = 1; +QQ = R*Q*transpose(R); +t = 0; +lik = zeros(smpl,1); +LIK = Inf; +notsteady = 1; +crit = options_.kalman_tol; +while rank(Pinf,crit) & t < smpl + t = t+1; + v = Y(:,t)-a(mf)-trend(:,t); + Finf = Pinf(mf,mf); + if rcond(Finf) < crit + if ~all(abs(Finf(:))<crit) + return + else + iFstar = inv(Pstar(mf,mf)+H); + dFstar = det(Pstar(mf,mf)+H); + Kstar = Pstar(:,mf)*iFstar; + lik(t) = log(dFstar) + transpose(v)*iFstar*v; + Pinf = T*Pinf*transpose(T); + Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kstar))*transpose(T)+QQ; + a = T*(a+Kstar*v); + end + else + lik(t) = log(det(Finf)); + iFinf = inv(Finf); + Kinf = Pinf(:,mf)*iFinf; %% premultiplication by the transition matrix T is removed (stephane) + Fstar = Pstar(mf,mf)+H; + Kstar = (Pstar(:,mf)-Kinf*Fstar)*iFinf; %% premultiplication by the transition matrix T is removed (stephane) + Pstar = T*(Pstar-Pstar(:,mf)*transpose(Kinf)-Pinf(:,mf)*transpose(Kstar))*transpose(T)+QQ; + Pinf = T*(Pinf-Pinf(:,mf)*transpose(Kinf))*transpose(T); + a = T*(a+Kinf*v); + end +end +if t == smpl + error(['There isn''t enough information to estimate the initial' ... + ' conditions of the nonstationary variables']); +end +F_singular = 1; +while notsteady & t < smpl + t = t+1; + v = Y(:,t)-a(mf)-trend(:,t); + F = Pstar(mf,mf)+H; + oldPstar = Pstar; + dF = det(F); + if rcond(F) < crit + if ~all(abs(F(:))<crit) + return + else + a = T*a; + Pstar = T*Pstar*transpose(T)+QQ; + end + else + F_singular = 0; + iF = inv(F); + lik(t) = log(dF)+transpose(v)*iF*v; + K = Pstar(:,mf)*iF; %% premultiplication by the transition matrix T is removed (stephane) + a = T*(a+K*v); %% --> factorization of the transition matrix... + Pstar = T*(Pstar-K*Pstar(mf,:))*transpose(T)+QQ; %% ... idem (stephane) + end + notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit); +end +if F_singular == 1 + error(['The variance of the forecast error remains singular until the' ... + 'end of the sample']) +end +if t < smpl + t0 = t+1; + while t < smpl + t = t+1; + v = Y(:,t)-a(mf)-trend(:,t); + a = T*(a+K*v); + lik(t) = transpose(v)*iF*v; + end + lik(t0:smpl) = lik(t0:smpl) + log(dF); +end +% adding log-likelihhod constants +lik = (lik + pp*log(2*pi))/2; + +LIK = sum(lik(start:end)); % Minus the log-likelihood. diff --git a/matlab/DiffuseLikelihoodH1_Z.m b/matlab/DiffuseLikelihoodH1_Z.m index 2de68dc9ff..204570dca3 100644 --- a/matlab/DiffuseLikelihoodH1_Z.m +++ b/matlab/DiffuseLikelihoodH1_Z.m @@ -1,132 +1,132 @@ -function [LIK, lik] = DiffuseLikelihoodH1_Z(T,Z,R,Q,H,Pinf,Pstar,Y,start) - -% function [LIK, lik] = DiffuseLikelihoodH1_Z(T,Z,R,Q,H,Pinf,Pstar,Y,start) -% Computes the diffuse likelihood (H=measurement error) in the case of a non-singular var-cov matrix - -% -% INPUTS -% T: mm*mm matrix -% Z: pp,mm matrix -% R: mm*rr matrix -% Q: rr*rr matrix -% H: pp*pp matrix -% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros -% Pstar: mm*mm variance-covariance matrix with stationary variables -% Y: pp*1 vector -% start: likelihood evaluation at 'start' -% -% OUTPUTS -% LIK: likelihood -% lik: density vector in each period -% -% SPECIAL REQUIREMENTS -% See "Filtering and Smoothing of State Vector for Diffuse State Space -% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series -% Analysis, vol. 24(1), pp. 85-98). - -% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. - -% M. Ratto added lik in output - - global bayestopt_ options_ - - smpl = size(Y,2); - mm = size(T,2); - pp = size(Y,1); - a = zeros(mm,1); - dF = 1; - QQ = R*Q*transpose(R); - t = 0; - lik = zeros(smpl,1); - LIK = Inf; - notsteady = 1; - crit = options_.kalman_tol; - while rank(Pinf,crit) & t < smpl - t = t+1; - v = Y(:,t)-Z*a; - Finf = Z*Pinf*Z'; - if rcond(Finf) < crit - if ~all(abs(Finf(:)) < crit) - return - else - Fstar = Z*Pstar*Z'+H; - iFstar = inv(Fstar); - dFstar = det(Fstar); - Kstar = Pstar*Z'*iFstar; - lik(t) = log(dFstar) + v'*iFstar*v; - Pinf = T*Pinf*transpose(T); - Pstar = T*(Pstar-Pstar*Z'*Kstar')*T'+QQ; - a = T*(a+Kstar*v); - end - else - lik(t) = log(det(Finf)); - iFinf = inv(Finf); - Kinf = Pinf*Z'*iFinf; - Fstar = Z*Pstar*Z'+H; - Kstar = (Pstar*Z'-Kinf*Fstar)*iFinf; - Pstar = T*(Pstar-Pstar*Z'*Kinf'-Pinf*Z'*Kstar')*T'+QQ; - Pinf = T*(Pinf-Pinf*Z'*Kinf')*T'; - a = T*(a+Kinf*v); - end - end - if t == smpl - error(['There isn''t enough information to estimate the initial' ... - ' conditions of the nonstationary variables']); - end - F_singular = 1; - while notsteady & t < smpl - t = t+1; - v = Y(:,t)-Z*a; - F = Z*Pstar*Z'+H; - oldPstar = Pstar; - dF = det(F); - if rcond(F) < crit - if ~all(abs(F(:))<crit) - return - else - a = T*a; - Pstar = T*Pstar*T'+QQ; - end - else - F_singular = 0; - iF = inv(F); - lik(t) = log(dF)+v'*iF*v; - K = Pstar*Z'*iF; - a = T*(a+K*v); - Pstar = T*(Pstar-K*Z*Pstar)*T'+QQ; - end - notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit); - end - if F_singular == 1 - error(['The variance of the forecast error remains singular until the' ... - 'end of the sample']) - end - if t < smpl - t0 = t+1; - while t < smpl - t = t+1; - v = Y(:,t)-Z*a; - a = T*(a+K*v); - lik(t) = v'*iF*v; - end - lik(t0:smpl) = lik(t0:smpl) + log(dF); - end - % adding log-likelihhod constants - lik = (lik + pp*log(2*pi))/2; - - LIK = sum(lik(start:end)); % Minus the log-likelihood. \ No newline at end of file +function [LIK, lik] = DiffuseLikelihoodH1_Z(T,Z,R,Q,H,Pinf,Pstar,Y,start) + +% function [LIK, lik] = DiffuseLikelihoodH1_Z(T,Z,R,Q,H,Pinf,Pstar,Y,start) +% Computes the diffuse likelihood (H=measurement error) in the case of a non-singular var-cov matrix + +% +% INPUTS +% T: mm*mm matrix +% Z: pp,mm matrix +% R: mm*rr matrix +% Q: rr*rr matrix +% H: pp*pp matrix +% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros +% Pstar: mm*mm variance-covariance matrix with stationary variables +% Y: pp*1 vector +% start: likelihood evaluation at 'start' +% +% OUTPUTS +% LIK: likelihood +% lik: density vector in each period +% +% SPECIAL REQUIREMENTS +% See "Filtering and Smoothing of State Vector for Diffuse State Space +% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series +% Analysis, vol. 24(1), pp. 85-98). + +% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. + +% M. Ratto added lik in output + +global bayestopt_ options_ + +smpl = size(Y,2); +mm = size(T,2); +pp = size(Y,1); +a = zeros(mm,1); +dF = 1; +QQ = R*Q*transpose(R); +t = 0; +lik = zeros(smpl,1); +LIK = Inf; +notsteady = 1; +crit = options_.kalman_tol; +while rank(Pinf,crit) & t < smpl + t = t+1; + v = Y(:,t)-Z*a; + Finf = Z*Pinf*Z'; + if rcond(Finf) < crit + if ~all(abs(Finf(:)) < crit) + return + else + Fstar = Z*Pstar*Z'+H; + iFstar = inv(Fstar); + dFstar = det(Fstar); + Kstar = Pstar*Z'*iFstar; + lik(t) = log(dFstar) + v'*iFstar*v; + Pinf = T*Pinf*transpose(T); + Pstar = T*(Pstar-Pstar*Z'*Kstar')*T'+QQ; + a = T*(a+Kstar*v); + end + else + lik(t) = log(det(Finf)); + iFinf = inv(Finf); + Kinf = Pinf*Z'*iFinf; + Fstar = Z*Pstar*Z'+H; + Kstar = (Pstar*Z'-Kinf*Fstar)*iFinf; + Pstar = T*(Pstar-Pstar*Z'*Kinf'-Pinf*Z'*Kstar')*T'+QQ; + Pinf = T*(Pinf-Pinf*Z'*Kinf')*T'; + a = T*(a+Kinf*v); + end +end +if t == smpl + error(['There isn''t enough information to estimate the initial' ... + ' conditions of the nonstationary variables']); +end +F_singular = 1; +while notsteady & t < smpl + t = t+1; + v = Y(:,t)-Z*a; + F = Z*Pstar*Z'+H; + oldPstar = Pstar; + dF = det(F); + if rcond(F) < crit + if ~all(abs(F(:))<crit) + return + else + a = T*a; + Pstar = T*Pstar*T'+QQ; + end + else + F_singular = 0; + iF = inv(F); + lik(t) = log(dF)+v'*iF*v; + K = Pstar*Z'*iF; + a = T*(a+K*v); + Pstar = T*(Pstar-K*Z*Pstar)*T'+QQ; + end + notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit); +end +if F_singular == 1 + error(['The variance of the forecast error remains singular until the' ... + 'end of the sample']) +end +if t < smpl + t0 = t+1; + while t < smpl + t = t+1; + v = Y(:,t)-Z*a; + a = T*(a+K*v); + lik(t) = v'*iF*v; + end + lik(t0:smpl) = lik(t0:smpl) + log(dF); +end +% adding log-likelihhod constants +lik = (lik + pp*log(2*pi))/2; + +LIK = sum(lik(start:end)); % Minus the log-likelihood. \ No newline at end of file diff --git a/matlab/DiffuseLikelihoodH3.m b/matlab/DiffuseLikelihoodH3.m index fb9d395e44..333f81189d 100644 --- a/matlab/DiffuseLikelihoodH3.m +++ b/matlab/DiffuseLikelihoodH3.m @@ -1,178 +1,178 @@ -function [LIK, lik] = DiffuseLikelihoodH3(T,R,Q,H,Pinf,Pstar,Y,trend,start) - -% function [LIK, lik] = DiffuseLikelihoodH3(T,R,Q,H,Pinf,Pstar,Y,trend,start) -% Computes the diffuse likelihood with measurement error, in the case of -% a singular var-cov matrix. -% Univariate treatment of multivariate time series. -% -% INPUTS -% T: mm*mm matrix -% R: mm*rr matrix -% Q: rr*rr matrix -% H: pp*pp matrix -% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros -% Pstar: mm*mm variance-covariance matrix with stationary variables -% Y: pp*1 vector -% trend -% start: likelihood evaluation at 'start' -% -% OUTPUTS -% LIK: likelihood -% lik: density vector in each period -% -% SPECIAL REQUIREMENTS -% See "Filtering and Smoothing of State Vector for Diffuse State Space -% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series -% Analysis, vol. 24(1), pp. 85-98). - -% Copyright (C) 2005-2008 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 <http://www.gnu.org/licenses/>. - -% M. Ratto added lik in output [October 2005] -% changes by M. Ratto -% introduced new global variable id_ for termination of DKF -% introduced a persistent fmax, in order to keep track the max order of -% magnitude of the 'zero' values in Pinf at DKF termination -% new icc counter for Finf steps in DKF -% new termination for DKF -% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non -% zero. this bug is fixed. - -global bayestopt_ options_ - -mf = bayestopt_.mf; -pp = size(Y,1); -mm = size(T,1); -smpl = size(Y,2); -a = zeros(mm,1); -QQ = R*Q*transpose(R); -t = 0; -lik = zeros(smpl,1); -notsteady = 1; -crit = options_.kalman_tol; -crit1 = 1.e-6; -newRank = rank(Pinf,crit1); -icc = 0; -while newRank & t < smpl %% Matrix Finf is assumed to be zero - t = t+1; - for i=1:pp - v(i) = Y(i,t)-a(mf(i))-trend(i,t); - Fstar = Pstar(mf(i),mf(i))+H(i,i); - Finf = Pinf(mf(i),mf(i)); - Kstar = Pstar(:,mf(i)); - if Finf > crit & newRank - icc = icc + 1; - Kinf = Pinf(:,mf(i)); - a = a + Kinf*v(i)/Finf; - Pstar = Pstar + Kinf*transpose(Kinf)*Fstar/(Finf*Finf) - ... - (Kstar*transpose(Kinf)+Kinf*transpose(Kstar))/Finf; - Pinf = Pinf - Kinf*transpose(Kinf)/Finf; - lik(t) = lik(t) + log(Finf); - % start new termination criterion for DKF - if ~isempty(options_.diffuse_d), - newRank = (icc<options_.diffuse_d); - %if newRank & any(diag(Pinf(mf,mf))>crit)==0; % M. Ratto this line is BUGGY - if newRank & (any(diag(Pinf(mf,mf))>crit)==0 & rank(Pinf,crit1)==0); - options_.diffuse_d = icc; - newRank=0; - disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF') - disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)]) - disp('You may have to reset the optimisation') - end - else - %newRank = any(diag(Pinf(mf,mf))>crit); % M. Ratto this line is BUGGY - newRank = (any(diag(Pinf(mf,mf))>crit) | rank(Pinf,crit1)); - if newRank==0, - P0= T*Pinf*transpose(T); - %newRank = any(diag(P0(mf,mf))>crit); % M. Ratto this line is BUGGY - newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1)); % M. Ratto 10 Oct 2005 - if newRank==0, - options_.diffuse_d = icc; - end - end - end, - % end new termination and checks for DKF and fmax - elseif Finf > crit - %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition - %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that - %% rank(Pinf)=0. [st�phane,11-03-2004]. - %if rank(Pinf) == 0 - % the likelihood terms should alwasy be cumulated, not only - % when Pinf=0, otherwise the lik would depend on the ordering - % of observed variables - lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar; - %end - a = a + Kstar*v(i)/Fstar; - Pstar = Pstar - Kstar*transpose(Kstar)/Fstar; - else - % disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fi)]) - end - end - if newRank - oldRank = rank(Pinf,crit1); - else - oldRank = 0; - end - a = T*a; - Pstar = T*Pstar*transpose(T)+QQ; - Pinf = T*Pinf*transpose(T); - if newRank - newRank = rank(Pinf,crit1); - end - if oldRank ~= newRank - disp('DiffuseLiklihoodH3 :: T does influence the rank of Pinf!') - end -end -if t == smpl - error(['There isn''t enough information to estimate the initial' ... - ' conditions of the nonstationary variables']); -end -while notsteady & t < smpl - t = t+1; - for i=1:pp - v(i) = Y(i,t) - a(mf(i)) - trend(i,t); - Fi = Pstar(mf(i),mf(i))+H(i,i); - if Fi > crit - Ki = Pstar(:,mf(i)); - a = a + Ki*v(i)/Fi; - Pstar = Pstar - Ki*transpose(Ki)/Fi; - lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; - end - end - oldP = Pstar; - a = T*a; - Pstar = T*Pstar*transpose(T) + QQ; - notsteady = ~(max(max(abs(Pstar-oldP)))<crit); -end -while t < smpl - t = t+1; - for i=1:pp - v(i) = Y(i,t) - a(mf(i)) - trend(i,t); - Fi = Pstar(mf(i),mf(i))+H(i,i); - if Fi > crit - Ki = Pstar(:,mf(i)); - a = a + Ki*v(i)/Fi; - Pstar = Pstar - Ki*transpose(Ki)/Fi; - lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; - end - end - a = T*a; -end -% adding log-likelihhod constants -lik = (lik + pp*log(2*pi))/2; - -LIK = sum(lik(start:end)); % Minus the log-likelihood. +function [LIK, lik] = DiffuseLikelihoodH3(T,R,Q,H,Pinf,Pstar,Y,trend,start) + +% function [LIK, lik] = DiffuseLikelihoodH3(T,R,Q,H,Pinf,Pstar,Y,trend,start) +% Computes the diffuse likelihood with measurement error, in the case of +% a singular var-cov matrix. +% Univariate treatment of multivariate time series. +% +% INPUTS +% T: mm*mm matrix +% R: mm*rr matrix +% Q: rr*rr matrix +% H: pp*pp matrix +% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros +% Pstar: mm*mm variance-covariance matrix with stationary variables +% Y: pp*1 vector +% trend +% start: likelihood evaluation at 'start' +% +% OUTPUTS +% LIK: likelihood +% lik: density vector in each period +% +% SPECIAL REQUIREMENTS +% See "Filtering and Smoothing of State Vector for Diffuse State Space +% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series +% Analysis, vol. 24(1), pp. 85-98). + +% Copyright (C) 2005-2008 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 <http://www.gnu.org/licenses/>. + +% M. Ratto added lik in output [October 2005] +% changes by M. Ratto +% introduced new global variable id_ for termination of DKF +% introduced a persistent fmax, in order to keep track the max order of +% magnitude of the 'zero' values in Pinf at DKF termination +% new icc counter for Finf steps in DKF +% new termination for DKF +% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non +% zero. this bug is fixed. + +global bayestopt_ options_ + +mf = bayestopt_.mf; +pp = size(Y,1); +mm = size(T,1); +smpl = size(Y,2); +a = zeros(mm,1); +QQ = R*Q*transpose(R); +t = 0; +lik = zeros(smpl,1); +notsteady = 1; +crit = options_.kalman_tol; +crit1 = 1.e-6; +newRank = rank(Pinf,crit1); +icc = 0; +while newRank & t < smpl %% Matrix Finf is assumed to be zero + t = t+1; + for i=1:pp + v(i) = Y(i,t)-a(mf(i))-trend(i,t); + Fstar = Pstar(mf(i),mf(i))+H(i,i); + Finf = Pinf(mf(i),mf(i)); + Kstar = Pstar(:,mf(i)); + if Finf > crit & newRank + icc = icc + 1; + Kinf = Pinf(:,mf(i)); + a = a + Kinf*v(i)/Finf; + Pstar = Pstar + Kinf*transpose(Kinf)*Fstar/(Finf*Finf) - ... + (Kstar*transpose(Kinf)+Kinf*transpose(Kstar))/Finf; + Pinf = Pinf - Kinf*transpose(Kinf)/Finf; + lik(t) = lik(t) + log(Finf); + % start new termination criterion for DKF + if ~isempty(options_.diffuse_d), + newRank = (icc<options_.diffuse_d); + %if newRank & any(diag(Pinf(mf,mf))>crit)==0; % M. Ratto this line is BUGGY + if newRank & (any(diag(Pinf(mf,mf))>crit)==0 & rank(Pinf,crit1)==0); + options_.diffuse_d = icc; + newRank=0; + disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF') + disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)]) + disp('You may have to reset the optimisation') + end + else + %newRank = any(diag(Pinf(mf,mf))>crit); % M. Ratto this line is BUGGY + newRank = (any(diag(Pinf(mf,mf))>crit) | rank(Pinf,crit1)); + if newRank==0, + P0= T*Pinf*transpose(T); + %newRank = any(diag(P0(mf,mf))>crit); % M. Ratto this line is BUGGY + newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1)); % M. Ratto 10 Oct 2005 + if newRank==0, + options_.diffuse_d = icc; + end + end + end, + % end new termination and checks for DKF and fmax + elseif Finf > crit + %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition + %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that + %% rank(Pinf)=0. [st�phane,11-03-2004]. + %if rank(Pinf) == 0 + % the likelihood terms should alwasy be cumulated, not only + % when Pinf=0, otherwise the lik would depend on the ordering + % of observed variables + lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar; + %end + a = a + Kstar*v(i)/Fstar; + Pstar = Pstar - Kstar*transpose(Kstar)/Fstar; + else + % disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fi)]) + end + end + if newRank + oldRank = rank(Pinf,crit1); + else + oldRank = 0; + end + a = T*a; + Pstar = T*Pstar*transpose(T)+QQ; + Pinf = T*Pinf*transpose(T); + if newRank + newRank = rank(Pinf,crit1); + end + if oldRank ~= newRank + disp('DiffuseLiklihoodH3 :: T does influence the rank of Pinf!') + end +end +if t == smpl + error(['There isn''t enough information to estimate the initial' ... + ' conditions of the nonstationary variables']); +end +while notsteady & t < smpl + t = t+1; + for i=1:pp + v(i) = Y(i,t) - a(mf(i)) - trend(i,t); + Fi = Pstar(mf(i),mf(i))+H(i,i); + if Fi > crit + Ki = Pstar(:,mf(i)); + a = a + Ki*v(i)/Fi; + Pstar = Pstar - Ki*transpose(Ki)/Fi; + lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; + end + end + oldP = Pstar; + a = T*a; + Pstar = T*Pstar*transpose(T) + QQ; + notsteady = ~(max(max(abs(Pstar-oldP)))<crit); +end +while t < smpl + t = t+1; + for i=1:pp + v(i) = Y(i,t) - a(mf(i)) - trend(i,t); + Fi = Pstar(mf(i),mf(i))+H(i,i); + if Fi > crit + Ki = Pstar(:,mf(i)); + a = a + Ki*v(i)/Fi; + Pstar = Pstar - Ki*transpose(Ki)/Fi; + lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; + end + end + a = T*a; +end +% adding log-likelihhod constants +lik = (lik + pp*log(2*pi))/2; + +LIK = sum(lik(start:end)); % Minus the log-likelihood. diff --git a/matlab/DiffuseLikelihoodH3_Z.m b/matlab/DiffuseLikelihoodH3_Z.m index f995557e1b..91ee5bfe5a 100644 --- a/matlab/DiffuseLikelihoodH3_Z.m +++ b/matlab/DiffuseLikelihoodH3_Z.m @@ -1,182 +1,182 @@ -function [LIK, lik] = DiffuseLikelihoodH3_Z(T,Z,R,Q,H,Pinf,Pstar,Y,start) - -% function [LIK, lik] = DiffuseLikelihoodH3_A(T,R,Q,H,Pinf,Pstar,Y,start) -% Computes the diffuse likelihood without measurement error, in the case of -% a singular var-cov matrix. -% Univariate treatment of multivariate time series. -% -% INPUTS -% T: mm*mm matrix -% Z: pp*mm matrix -% R: mm*rr matrix -% Q: rr*rr matrix -% H: pp*pp matrix -% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros -% Pstar: mm*mm variance-covariance matrix with stationary variables -% Y: pp*1 vector -% start: likelihood evaluation at 'start' -% -% OUTPUTS -% LIK: likelihood -% lik: density vector in each period -% -% SPECIAL REQUIREMENTS -% See "Filtering and Smoothing of State Vector for Diffuse State Space -% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series -% Analysis, vol. 24(1), pp. 85-98). - -% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. - -% M. Ratto added lik in output [October 2005] -% changes by M. Ratto [April 2005] -% introduced new options options_.diffuse_d for termination of DKF -% new icc counter for Finf steps in DKF -% new termination for DKF -% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non -% zero. -% [4/5/2005] correctyed bug in the modified verson of Ratto for rank of Pinf -% introduced a specific crit1 for the DKF termination - - -global bayestopt_ options_ - -pp = size(Y,1); -mm = size(T,1); -smpl = size(Y,2); -a = zeros(mm,1); -QQ = R*Q*R'; -t = 0; -lik = zeros(smpl,1); -notsteady = 1; -crit = options_.kalman_tol; -crit1 = 1.e-6; -newRank = rank(Pinf,crit1); -icc=0; -while newRank & t < smpl - t = t+1; - for i=1:pp - Zi = Z(i,:); - v(i) = Y(i,t)-Zi*a; - Fstar = Zi*Pstar*Zi'+H(i,i); - Finf = Zi*Pinf*Zi'; - Kstar = Pstar*Zi'; - if Finf > crit & newRank - icc=icc+1; - Kinf = Pinf*Zi'; - a = a + Kinf*v(i)/Finf; - Pstar = Pstar + Kinf*Kinf'*Fstar/(Finf*Finf) - ... - (Kstar*Kinf'+Kinf*Kstar')/Finf; - Pinf = Pinf - Kinf*Kinf'/Finf; - lik(t) = lik(t) + log(Finf); - if ~isempty(options_.diffuse_d), - newRank = (icc<options_.diffuse_d); - if newRank & (any(diag(Z*Pinf*Z')>crit)==0 & rank(Pinf,crit1)==0); - options_.diffuse_d = icc; - newRank=0; - disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF') - disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)]) - disp('You may have to reset the optimisation') - end - else - newRank = (any(diag(Z*Pinf*Z')>crit) | rank(Pinf,crit1)); - if newRank==0, - P0= T*Pinf*T'; - newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1)); % M. Ratto 11/10/2005 - if newRank==0, - options_.diffuse_d = icc; - end - end - end, - elseif Fstar > crit - %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition - %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that - %% rank(Pinf)=0. [st�phane,11-03-2004]. - %if rank(Pinf,crit) == 0 - % the likelihood terms should alwasy be cumulated, not only - % when Pinf=0, otherwise the lik would depend on the ordering - % of observed variables - % presample options can be used to ignore initial time points - lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar; - a = a + Kstar*v(i)/Fstar; - Pstar = Pstar - Kstar*Kstar'/Fstar; - else - %disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fstar)]) - end - end - if newRank, - oldRank = rank(Pinf,crit1); - else - oldRank = 0; - end - a = T*a; - Pstar = T*Pstar*T'+QQ; - Pinf = T*Pinf*T'; - if newRank, - newRank = rank(Pinf,crit1); - end - if oldRank ~= newRank - disp('DiffuseLiklihoodH3 :: T does influence the rank of Pinf!') - end -end -if t == smpl - error(['There isn''t enough information to estimate the initial' ... - ' conditions of the nonstationary variables']); -end -while notsteady & t < smpl - t = t+1; - oldP = Pstar; - for i=1:pp - Zi = Z(i,:); - v(i) = Y(i,t) - Zi*a; - Fi = Zi*Pstar*Zi'+H(i,i); - if Fi > crit - Ki = Pstar*Zi'; - a = a + Ki*v(i)/Fi; - Pstar = Pstar - Ki*Ki'/Fi; - lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; - else - %disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)]) - end - end - a = T*a; - Pstar = T*Pstar*T' + QQ; - notsteady = ~(max(max(abs(Pstar-oldP)))<crit); -end -while t < smpl - t = t+1; - Pstar = oldP; - for i=1:pp - Zi = Z(i,:); - v(i) = Y(i,t) - Zi*a; - Fi = Zi*Pstar*Zi'+H(i,i); - if Fi > crit - Ki = Pstar*Zi'; - a = a + Ki*v(i)/Fi; - Pstar = Pstar - Ki*Ki'/Fi; - lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; - else - %disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)]) - end - end - a = T*a; -end -% adding log-likelihhod constants -lik = (lik + pp*log(2*pi))/2; - -LIK = sum(lik(start:end)); % Minus the log-likelihood. - +function [LIK, lik] = DiffuseLikelihoodH3_Z(T,Z,R,Q,H,Pinf,Pstar,Y,start) + +% function [LIK, lik] = DiffuseLikelihoodH3_A(T,R,Q,H,Pinf,Pstar,Y,start) +% Computes the diffuse likelihood without measurement error, in the case of +% a singular var-cov matrix. +% Univariate treatment of multivariate time series. +% +% INPUTS +% T: mm*mm matrix +% Z: pp*mm matrix +% R: mm*rr matrix +% Q: rr*rr matrix +% H: pp*pp matrix +% Pinf: mm*mm diagonal matrix with with q ones and m-q zeros +% Pstar: mm*mm variance-covariance matrix with stationary variables +% Y: pp*1 vector +% start: likelihood evaluation at 'start' +% +% OUTPUTS +% LIK: likelihood +% lik: density vector in each period +% +% SPECIAL REQUIREMENTS +% See "Filtering and Smoothing of State Vector for Diffuse State Space +% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series +% Analysis, vol. 24(1), pp. 85-98). + +% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. + +% M. Ratto added lik in output [October 2005] +% changes by M. Ratto [April 2005] +% introduced new options options_.diffuse_d for termination of DKF +% new icc counter for Finf steps in DKF +% new termination for DKF +% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non +% zero. +% [4/5/2005] correctyed bug in the modified verson of Ratto for rank of Pinf +% introduced a specific crit1 for the DKF termination + + +global bayestopt_ options_ + +pp = size(Y,1); +mm = size(T,1); +smpl = size(Y,2); +a = zeros(mm,1); +QQ = R*Q*R'; +t = 0; +lik = zeros(smpl,1); +notsteady = 1; +crit = options_.kalman_tol; +crit1 = 1.e-6; +newRank = rank(Pinf,crit1); +icc=0; +while newRank & t < smpl + t = t+1; + for i=1:pp + Zi = Z(i,:); + v(i) = Y(i,t)-Zi*a; + Fstar = Zi*Pstar*Zi'+H(i,i); + Finf = Zi*Pinf*Zi'; + Kstar = Pstar*Zi'; + if Finf > crit & newRank + icc=icc+1; + Kinf = Pinf*Zi'; + a = a + Kinf*v(i)/Finf; + Pstar = Pstar + Kinf*Kinf'*Fstar/(Finf*Finf) - ... + (Kstar*Kinf'+Kinf*Kstar')/Finf; + Pinf = Pinf - Kinf*Kinf'/Finf; + lik(t) = lik(t) + log(Finf); + if ~isempty(options_.diffuse_d), + newRank = (icc<options_.diffuse_d); + if newRank & (any(diag(Z*Pinf*Z')>crit)==0 & rank(Pinf,crit1)==0); + options_.diffuse_d = icc; + newRank=0; + disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF') + disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)]) + disp('You may have to reset the optimisation') + end + else + newRank = (any(diag(Z*Pinf*Z')>crit) | rank(Pinf,crit1)); + if newRank==0, + P0= T*Pinf*T'; + newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1)); % M. Ratto 11/10/2005 + if newRank==0, + options_.diffuse_d = icc; + end + end + end, + elseif Fstar > crit + %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition + %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that + %% rank(Pinf)=0. [st�phane,11-03-2004]. + %if rank(Pinf,crit) == 0 + % the likelihood terms should alwasy be cumulated, not only + % when Pinf=0, otherwise the lik would depend on the ordering + % of observed variables + % presample options can be used to ignore initial time points + lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar; + a = a + Kstar*v(i)/Fstar; + Pstar = Pstar - Kstar*Kstar'/Fstar; + else + %disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fstar)]) + end + end + if newRank, + oldRank = rank(Pinf,crit1); + else + oldRank = 0; + end + a = T*a; + Pstar = T*Pstar*T'+QQ; + Pinf = T*Pinf*T'; + if newRank, + newRank = rank(Pinf,crit1); + end + if oldRank ~= newRank + disp('DiffuseLiklihoodH3 :: T does influence the rank of Pinf!') + end +end +if t == smpl + error(['There isn''t enough information to estimate the initial' ... + ' conditions of the nonstationary variables']); +end +while notsteady & t < smpl + t = t+1; + oldP = Pstar; + for i=1:pp + Zi = Z(i,:); + v(i) = Y(i,t) - Zi*a; + Fi = Zi*Pstar*Zi'+H(i,i); + if Fi > crit + Ki = Pstar*Zi'; + a = a + Ki*v(i)/Fi; + Pstar = Pstar - Ki*Ki'/Fi; + lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; + else + %disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)]) + end + end + a = T*a; + Pstar = T*Pstar*T' + QQ; + notsteady = ~(max(max(abs(Pstar-oldP)))<crit); +end +while t < smpl + t = t+1; + Pstar = oldP; + for i=1:pp + Zi = Z(i,:); + v(i) = Y(i,t) - Zi*a; + Fi = Zi*Pstar*Zi'+H(i,i); + if Fi > crit + Ki = Pstar*Zi'; + a = a + Ki*v(i)/Fi; + Pstar = Pstar - Ki*Ki'/Fi; + lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; + else + %disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)]) + end + end + a = T*a; +end +% adding log-likelihhod constants +lik = (lik + pp*log(2*pi))/2; + +LIK = sum(lik(start:end)); % Minus the log-likelihood. + diff --git a/matlab/DiffuseLikelihoodH3corr.m b/matlab/DiffuseLikelihoodH3corr.m index 96f9ae3252..9bc36cef2e 100644 --- a/matlab/DiffuseLikelihoodH3corr.m +++ b/matlab/DiffuseLikelihoodH3corr.m @@ -20,7 +20,7 @@ function [LIK lik] = DiffuseLikelihoodH3corr(T,R,Q,H,Pinf,Pstar,Y,trend,start) % along with Dynare. If not, see <http://www.gnu.org/licenses/>. global bayestopt_ options_ - + mf = bayestopt_.mf; pp = size(Y,1); mm = size(T,1); @@ -30,7 +30,7 @@ T = cat(1,cat(2,T,zeros(mm,pp)),zeros(pp,mm+pp)); R = cat(1,cat(2,R,zeros(mm,pp)),cat(2,zeros(pp,rr),eye(pp))); Q = cat(1,cat(2,Q,zeros(rr,pp)),cat(2,zeros(pp,rr),H)); if size(Pinf,1) % Otherwise Pinf = 0 (no unit root) - Pinf = cat(1,cat(2,Pinf,zeros(mm,pp)),zeros(pp,mm+pp)); + Pinf = cat(1,cat(2,Pinf,zeros(mm,pp)),zeros(pp,mm+pp)); end Pstar = cat(1,cat(2,Pstar,zeros(mm,pp)),cat(2,zeros(pp,mm),H)); a = zeros(mm+pp,1); @@ -42,71 +42,71 @@ crit = options_.kalman_tol; newRank = rank(Pinf,crit); while rank(Pinf,crit) & t < smpl %% Matrix Finf is assumed to be zero - t = t+1; - for i=1:pp - v(i) = Y(i,t)-a(mf(i))-a(mm+i)-trend(i,t); - Fstar = Pstar(mf(i),mf(i))+Pstar(mm+i,mm+i); - Finf = Pinf(mf(i),mf(i)); - Kstar = Pstar(:,mf(i))+Pstar(:,mm+i); - if Finf > crit - Kinf = Pinf(:,mf(i)); - a = a + Kinf*v(i)/Finf; - Pstar = Pstar + Kinf*transpose(Kinf)*Fstar/(Finf*Finf) - ... - (Kstar*transpose(Kinf)+Kinf*transpose(Kstar))/Finf; - Pinf = Pinf - Kinf*transpose(Kinf)/Finf; - lik(t) = lik(t) + log(Finf); - else %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition - %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that - %% rank(Pinf)=0. [st�phane,11-03-2004]. - if rank(Pinf) == 0 - lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar; - end - a = a + Kstar*v(i)/Fstar; - Pstar = Pstar - Kstar*transpose(Kstar)/Fstar; - end - oldRank = rank(Pinf,crit); - a = T*a; - Pstar = T*Pstar*transpose(T)+QQ; - Pinf = T*Pinf*transpose(T); - newRank = rank(Pinf,crit); - if oldRank ~= newRank - disp('DiffuseLiklihoodH3 :: T does influence the rank of Pinf!') - end - end + t = t+1; + for i=1:pp + v(i) = Y(i,t)-a(mf(i))-a(mm+i)-trend(i,t); + Fstar = Pstar(mf(i),mf(i))+Pstar(mm+i,mm+i); + Finf = Pinf(mf(i),mf(i)); + Kstar = Pstar(:,mf(i))+Pstar(:,mm+i); + if Finf > crit + Kinf = Pinf(:,mf(i)); + a = a + Kinf*v(i)/Finf; + Pstar = Pstar + Kinf*transpose(Kinf)*Fstar/(Finf*Finf) - ... + (Kstar*transpose(Kinf)+Kinf*transpose(Kstar))/Finf; + Pinf = Pinf - Kinf*transpose(Kinf)/Finf; + lik(t) = lik(t) + log(Finf); + else %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition + %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that + %% rank(Pinf)=0. [st�phane,11-03-2004]. + if rank(Pinf) == 0 + lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar; + end + a = a + Kstar*v(i)/Fstar; + Pstar = Pstar - Kstar*transpose(Kstar)/Fstar; + end + oldRank = rank(Pinf,crit); + a = T*a; + Pstar = T*Pstar*transpose(T)+QQ; + Pinf = T*Pinf*transpose(T); + newRank = rank(Pinf,crit); + if oldRank ~= newRank + disp('DiffuseLiklihoodH3 :: T does influence the rank of Pinf!') + end + end end if t == smpl - error(['There isn''t enough information to estimate the initial' ... - ' conditions of the nonstationary variables']); + error(['There isn''t enough information to estimate the initial' ... + ' conditions of the nonstationary variables']); end while notsteady & t < smpl - t = t+1; - for i=1:pp - v(i) = Y(i,t) - a(mf(i)) - trend(i,t) -a(mm+i); - Fi = Pstar(mf(i),mf(i))+Pstar(mm+i,mm+i); - if Fi > crit - Ki = Pstar(:,mf(i))+Pstar(:,mm+i); + t = t+1; + for i=1:pp + v(i) = Y(i,t) - a(mf(i)) - trend(i,t) -a(mm+i); + Fi = Pstar(mf(i),mf(i))+Pstar(mm+i,mm+i); + if Fi > crit + Ki = Pstar(:,mf(i))+Pstar(:,mm+i); a = a + Ki*v(i)/Fi; Pstar = Pstar - Ki*transpose(Ki)/Fi; lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; - end - end + end + end oldP = Pstar; a = T*a; Pstar = T*Pstar*transpose(T) + QQ; notsteady = ~(max(max(abs(Pstar-oldP)))<crit); end while t < smpl - t = t+1; - for i=1:pp - v(i) = Y(i,t) - a(mf(i)) - trend(i,t) - a(mm+i); - Fi = Pstar(mf(i),mf(i))+Pstar(mm+i,mm+i); - if Fi > crit - Ki = Pstar(:,mf(i))+Pstar(:,mm+i); + t = t+1; + for i=1:pp + v(i) = Y(i,t) - a(mf(i)) - trend(i,t) - a(mm+i); + Fi = Pstar(mf(i),mf(i))+Pstar(mm+i,mm+i); + if Fi > crit + Ki = Pstar(:,mf(i))+Pstar(:,mm+i); a = a + Ki*v(i)/Fi; Pstar = Pstar - Ki*transpose(Ki)/Fi; lik(t) = lik(t) + log(Fi) + v(i)*v(i)/Fi; - end - end + end + end a = T*a; end % adding log-likelihhod constants diff --git a/matlab/DsgeLikelihood.m b/matlab/DsgeLikelihood.m index 50c4ab7e90..e9279e841b 100644 --- a/matlab/DsgeLikelihood.m +++ b/matlab/DsgeLikelihood.m @@ -38,290 +38,290 @@ function [fval,cost_flag,ys,trend_coeff,info] = DsgeLikelihood(xparam1,gend,data % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_ - fval = []; - ys = []; - trend_coeff = []; - cost_flag = 1; - nobs = size(options_.varobs,1); - %------------------------------------------------------------------------------ - % 1. Get the structural parameters & define penalties - %------------------------------------------------------------------------------ - if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb) - k = find(xparam1 < bayestopt_.lb); - fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2); - cost_flag = 0; - info = 41; - return; - end - if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub) - k = find(xparam1 > bayestopt_.ub); - fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2); - cost_flag = 0; - info = 42; - return; - end - Q = M_.Sigma_e; - H = M_.H; - for i=1:estim_params_.nvx +global bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_ +fval = []; +ys = []; +trend_coeff = []; +cost_flag = 1; +nobs = size(options_.varobs,1); +%------------------------------------------------------------------------------ +% 1. Get the structural parameters & define penalties +%------------------------------------------------------------------------------ +if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb) + k = find(xparam1 < bayestopt_.lb); + fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2); + cost_flag = 0; + info = 41; + return; +end +if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub) + k = find(xparam1 > bayestopt_.ub); + fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2); + cost_flag = 0; + info = 42; + return; +end +Q = M_.Sigma_e; +H = M_.H; +for i=1:estim_params_.nvx k =estim_params_.var_exo(i,1); Q(k,k) = xparam1(i)*xparam1(i); - end - offset = estim_params_.nvx; - if estim_params_.nvn +end +offset = estim_params_.nvx; +if estim_params_.nvn for i=1:estim_params_.nvn - k = estim_params_.var_endo(i,1); - H(k,k) = xparam1(i+offset)*xparam1(i+offset); + k = estim_params_.var_endo(i,1); + H(k,k) = xparam1(i+offset)*xparam1(i+offset); end offset = offset+estim_params_.nvn; - end - if estim_params_.ncx +end +if estim_params_.ncx for i=1:estim_params_.ncx - k1 =estim_params_.corrx(i,1); - k2 =estim_params_.corrx(i,2); - Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2)); - Q(k2,k1) = Q(k1,k2); + k1 =estim_params_.corrx(i,1); + k2 =estim_params_.corrx(i,2); + Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2)); + Q(k2,k1) = Q(k1,k2); end [CholQ,testQ] = chol(Q); if testQ %% The variance-covariance matrix of the structural innovations is not definite positive. - %% We have to compute the eigenvalues of this matrix in order to build the penalty. - a = diag(eig(Q)); - k = find(a < 0); - if k > 0 - fval = bayestopt_.penalty+sum(-a(k)); - cost_flag = 0; - info = 43; - return - end + %% We have to compute the eigenvalues of this matrix in order to build the penalty. + a = diag(eig(Q)); + k = find(a < 0); + if k > 0 + fval = bayestopt_.penalty+sum(-a(k)); + cost_flag = 0; + info = 43; + return + end end offset = offset+estim_params_.ncx; - end - if estim_params_.ncn +end +if estim_params_.ncn for i=1:estim_params_.ncn - k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1)); - k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2)); - H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2)); - H(k2,k1) = H(k1,k2); + k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1)); + k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2)); + H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2)); + H(k2,k1) = H(k1,k2); end [CholH,testH] = chol(H); if testH - a = diag(eig(H)); - k = find(a < 0); - if k > 0 - fval = bayestopt_.penalty+sum(-a(k)); - cost_flag = 0; - info = 44; - return - end + a = diag(eig(H)); + k = find(a < 0); + if k > 0 + fval = bayestopt_.penalty+sum(-a(k)); + cost_flag = 0; + info = 44; + return + end end offset = offset+estim_params_.ncn; - end - if estim_params_.np > 0 - M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end); - end - M_.Sigma_e = Q; - M_.H = H; - %------------------------------------------------------------------------------ - % 2. call model setup & reduction program - %------------------------------------------------------------------------------ - [T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,... - bayestopt_.restrict_columns,... - bayestopt_.restrict_aux); - if info(1) == 1 || info(1) == 2 || info(1) == 5 - fval = bayestopt_.penalty+1; - cost_flag = 0; - return - elseif info(1) == 3 || info(1) == 4 || info(1)==6 ||info(1) == 19 || info(1) == 20 || info(1) == 21 - fval = bayestopt_.penalty+info(2); - cost_flag = 0; - return - end - bayestopt_.mf = bayestopt_.mf1; - if options_.noconstant - constant = zeros(nobs,1); - else - if options_.loglinear - constant = log(SteadyState(bayestopt_.mfys)); - else - constant = SteadyState(bayestopt_.mfys); - end - end - if bayestopt_.with_trend +end +if estim_params_.np > 0 + M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end); +end +M_.Sigma_e = Q; +M_.H = H; +%------------------------------------------------------------------------------ +% 2. call model setup & reduction program +%------------------------------------------------------------------------------ +[T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,... + bayestopt_.restrict_columns,... + bayestopt_.restrict_aux); +if info(1) == 1 || info(1) == 2 || info(1) == 5 + fval = bayestopt_.penalty+1; + cost_flag = 0; + return +elseif info(1) == 3 || info(1) == 4 || info(1)==6 ||info(1) == 19 || info(1) == 20 || info(1) == 21 + fval = bayestopt_.penalty+info(2); + cost_flag = 0; + return +end +bayestopt_.mf = bayestopt_.mf1; +if options_.noconstant + constant = zeros(nobs,1); +else + if options_.loglinear + constant = log(SteadyState(bayestopt_.mfys)); + else + constant = SteadyState(bayestopt_.mfys); + end +end +if bayestopt_.with_trend trend_coeff = zeros(nobs,1); t = options_.trend_coeffs; for i=1:length(t) - if ~isempty(t{i}) - trend_coeff(i) = evalin('base',t{i}); - end + if ~isempty(t{i}) + trend_coeff(i) = evalin('base',t{i}); + end end trend = repmat(constant,1,gend)+trend_coeff*[1:gend]; - else +else trend = repmat(constant,1,gend); - end - start = options_.presample+1; - np = size(T,1); - mf = bayestopt_.mf; - no_missing_data_flag = (number_of_observations==gend*nobs); - %------------------------------------------------------------------------------ - % 3. Initial condition of the Kalman filter - %------------------------------------------------------------------------------ - kalman_algo = options_.kalman_algo; - if options_.lik_init == 1 % Kalman filter - if kalman_algo ~= 2 - kalman_algo = 1; - end - Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold); - Pinf = []; - elseif options_.lik_init == 2 % Old Diffuse Kalman filter - if kalman_algo ~= 2 - kalman_algo = 1; - end - Pstar = options_.Harvey_scale_factor*eye(np); - Pinf = []; - elseif options_.lik_init == 3 % Diffuse Kalman filter - if kalman_algo ~= 4 - kalman_algo = 3; - end - [QT,ST] = schur(T); - e1 = abs(ordeig(ST)) > 2-options_.qz_criterium; - [QT,ST] = ordschur(QT,ST,e1); - k = find(abs(ordeig(ST)) > 2-options_.qz_criterium); - nk = length(k); - nk1 = nk+1; - Pinf = zeros(np,np); - Pinf(1:nk,1:nk) = eye(nk); - Pstar = zeros(np,np); - B = QT'*R*Q*R'*QT; - for i=np:-1:nk+2 - if ST(i,i-1) == 0 - if i == np - c = zeros(np-nk,1); - else - c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... - ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i); - end - q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i); - Pstar(nk1:i,i) = q\(B(nk1:i,i)+c); - Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; - else - if i == np - c = zeros(np-nk,1); - c1 = zeros(np-nk,1); - else - c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... - ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i)+... - ST(i,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1); - c1 = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i-1,i+1:end)')+... - ST(i-1,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1)+... - ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i); - end - q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);... - -ST(nk1:i,nk1:i)*ST(i-1,i) eye(i-nk)-ST(nk1:i,nk1:i)*ST(i-1,i-1)]; - z = q\[B(nk1:i,i)+c;B(nk1:i,i-1)+c1]; - Pstar(nk1:i,i) = z(1:(i-nk)); - Pstar(nk1:i,i-1) = z(i-nk+1:end); - Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; - Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)'; - i = i - 1; - end - end - if i == nk+2 - c = ST(nk+1,:)*(Pstar(:,nk+2:end)*ST(nk1,nk+2:end)')+ST(nk1,nk1)*ST(nk1,nk+2:end)*Pstar(nk+2:end,nk1); - Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1)); - end - Z = QT(mf,:); - R1 = QT'*R; - [QQ,RR,EE] = qr(Z*ST(:,1:nk),0); - k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8); - if length(k) > 0 - k1 = EE(:,k); - dd =ones(nk,1); - dd(k1) = zeros(length(k1),1); - Pinf(1:nk,1:nk) = diag(dd); - end - end - if kalman_algo == 2 - end - kalman_tol = options_.kalman_tol; - riccati_tol = options_.riccati_tol; - mf = bayestopt_.mf1; - Y = data-trend; - %------------------------------------------------------------------------------ - % 4. Likelihood evaluation - %------------------------------------------------------------------------------ - if (kalman_algo==1)% Multivariate Kalman Filter - if no_missing_data_flag - LIK = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol); - else - LIK = ... - missing_observations_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol, ... - data_index,number_of_observations,no_more_missing_observations); - end - if isinf(LIK) - kalman_algo = 2; - end - end - if (kalman_algo==2)% Univariate Kalman Filter - no_correlation_flag = 1; - if length(H)==1 & H == 0 - H = zeros(nobs,1); - else - if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal... - H = diag(H); - else - no_correlation_flag = 0; - end - end - if no_correlation_flag - LIK = univariate_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations); - else - LIK = univariate_kalman_filter_corr(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations); - end - end - if (kalman_algo==3)% Multivariate Diffuse Kalman Filter - if no_missing_data_flag - LIK = diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol, ... - riccati_tol); - else - LIK = missing_observations_diffuse_kalman_filter(ST,R1,Q,H,Pinf, ... - Pstar,Y,start,Z,kalman_tol,riccati_tol,... - data_index,number_of_observations,... - no_more_missing_observations); - end - if isinf(LIK) - kalman_algo = 4; - end - end - if (kalman_algo==4)% Univariate Diffuse Kalman Filter - no_correlation_flag = 1; - if length(H)==1 & H == 0 - H = zeros(nobs,1); - else - if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal... - H = diag(H); - else - no_correlation_flag = 0; - end - end - if no_correlation_flag - LIK = univariate_diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y, ... - start,Z,kalman_tol,riccati_tol,data_index,... - number_of_observations,no_more_missing_observations); - else - LIK = univariate_diffuse_kalman_filter_corr(ST,R1,Q,H,Pinf,Pstar, ... - Y,start,Z,kalman_tol,riccati_tol,... - data_index,number_of_observations,... - no_more_missing_observations); - end - end - if imag(LIK) ~= 0 - likelihood = bayestopt_.penalty; - else - likelihood = LIK; - end - % ------------------------------------------------------------------------------ - % Adds prior if necessary - % ------------------------------------------------------------------------------ - lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4); - fval = (likelihood-lnprior); - options_.kalman_algo = kalman_algo; \ No newline at end of file +end +start = options_.presample+1; +np = size(T,1); +mf = bayestopt_.mf; +no_missing_data_flag = (number_of_observations==gend*nobs); +%------------------------------------------------------------------------------ +% 3. Initial condition of the Kalman filter +%------------------------------------------------------------------------------ +kalman_algo = options_.kalman_algo; +if options_.lik_init == 1 % Kalman filter + if kalman_algo ~= 2 + kalman_algo = 1; + end + Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold); + Pinf = []; +elseif options_.lik_init == 2 % Old Diffuse Kalman filter + if kalman_algo ~= 2 + kalman_algo = 1; + end + Pstar = options_.Harvey_scale_factor*eye(np); + Pinf = []; +elseif options_.lik_init == 3 % Diffuse Kalman filter + if kalman_algo ~= 4 + kalman_algo = 3; + end + [QT,ST] = schur(T); + e1 = abs(ordeig(ST)) > 2-options_.qz_criterium; + [QT,ST] = ordschur(QT,ST,e1); + k = find(abs(ordeig(ST)) > 2-options_.qz_criterium); + nk = length(k); + nk1 = nk+1; + Pinf = zeros(np,np); + Pinf(1:nk,1:nk) = eye(nk); + Pstar = zeros(np,np); + B = QT'*R*Q*R'*QT; + for i=np:-1:nk+2 + if ST(i,i-1) == 0 + if i == np + c = zeros(np-nk,1); + else + c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... + ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i); + end + q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i); + Pstar(nk1:i,i) = q\(B(nk1:i,i)+c); + Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; + else + if i == np + c = zeros(np-nk,1); + c1 = zeros(np-nk,1); + else + c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... + ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i)+... + ST(i,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1); + c1 = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i-1,i+1:end)')+... + ST(i-1,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1)+... + ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i); + end + q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);... + -ST(nk1:i,nk1:i)*ST(i-1,i) eye(i-nk)-ST(nk1:i,nk1:i)*ST(i-1,i-1)]; + z = q\[B(nk1:i,i)+c;B(nk1:i,i-1)+c1]; + Pstar(nk1:i,i) = z(1:(i-nk)); + Pstar(nk1:i,i-1) = z(i-nk+1:end); + Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; + Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)'; + i = i - 1; + end + end + if i == nk+2 + c = ST(nk+1,:)*(Pstar(:,nk+2:end)*ST(nk1,nk+2:end)')+ST(nk1,nk1)*ST(nk1,nk+2:end)*Pstar(nk+2:end,nk1); + Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1)); + end + Z = QT(mf,:); + R1 = QT'*R; + [QQ,RR,EE] = qr(Z*ST(:,1:nk),0); + k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8); + if length(k) > 0 + k1 = EE(:,k); + dd =ones(nk,1); + dd(k1) = zeros(length(k1),1); + Pinf(1:nk,1:nk) = diag(dd); + end +end +if kalman_algo == 2 +end +kalman_tol = options_.kalman_tol; +riccati_tol = options_.riccati_tol; +mf = bayestopt_.mf1; +Y = data-trend; +%------------------------------------------------------------------------------ +% 4. Likelihood evaluation +%------------------------------------------------------------------------------ +if (kalman_algo==1)% Multivariate Kalman Filter + if no_missing_data_flag + LIK = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol); + else + LIK = ... + missing_observations_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol, ... + data_index,number_of_observations,no_more_missing_observations); + end + if isinf(LIK) + kalman_algo = 2; + end +end +if (kalman_algo==2)% Univariate Kalman Filter + no_correlation_flag = 1; + if length(H)==1 & H == 0 + H = zeros(nobs,1); + else + if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal... + H = diag(H); + else + no_correlation_flag = 0; + end + end + if no_correlation_flag + LIK = univariate_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations); + else + LIK = univariate_kalman_filter_corr(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations); + end +end +if (kalman_algo==3)% Multivariate Diffuse Kalman Filter + if no_missing_data_flag + LIK = diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol, ... + riccati_tol); + else + LIK = missing_observations_diffuse_kalman_filter(ST,R1,Q,H,Pinf, ... + Pstar,Y,start,Z,kalman_tol,riccati_tol,... + data_index,number_of_observations,... + no_more_missing_observations); + end + if isinf(LIK) + kalman_algo = 4; + end +end +if (kalman_algo==4)% Univariate Diffuse Kalman Filter + no_correlation_flag = 1; + if length(H)==1 & H == 0 + H = zeros(nobs,1); + else + if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal... + H = diag(H); + else + no_correlation_flag = 0; + end + end + if no_correlation_flag + LIK = univariate_diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y, ... + start,Z,kalman_tol,riccati_tol,data_index,... + number_of_observations,no_more_missing_observations); + else + LIK = univariate_diffuse_kalman_filter_corr(ST,R1,Q,H,Pinf,Pstar, ... + Y,start,Z,kalman_tol,riccati_tol,... + data_index,number_of_observations,... + no_more_missing_observations); + end +end +if imag(LIK) ~= 0 + likelihood = bayestopt_.penalty; +else + likelihood = LIK; +end +% ------------------------------------------------------------------------------ +% Adds prior if necessary +% ------------------------------------------------------------------------------ +lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4); +fval = (likelihood-lnprior); +options_.kalman_algo = kalman_algo; \ No newline at end of file diff --git a/matlab/DsgeLikelihood_hh.m b/matlab/DsgeLikelihood_hh.m index 11938eb645..13b9a51ff1 100644 --- a/matlab/DsgeLikelihood_hh.m +++ b/matlab/DsgeLikelihood_hh.m @@ -38,284 +38,283 @@ function [fval,llik,cost_flag,ys,trend_coeff,info] = DsgeLikelihood_hh(xparam1,g % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_ - fval = []; - ys = []; - trend_coeff = []; - llik = NaN; - cost_flag = 1; - nobs = size(options_.varobs,1); - %------------------------------------------------------------------------------ - % 1. Get the structural parameters & define penalties - %------------------------------------------------------------------------------ - if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb) - k = find(xparam1 < bayestopt_.lb); - fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2); - cost_flag = 0; - info = 41; - return; - end - if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub) - k = find(xparam1 > bayestopt_.ub); - fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2); - cost_flag = 0; - info = 42; - return; - end - Q = M_.Sigma_e; - H = M_.H; - for i=1:estim_params_.nvx +global bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_ +fval = []; +ys = []; +trend_coeff = []; +llik = NaN; +cost_flag = 1; +nobs = size(options_.varobs,1); +%------------------------------------------------------------------------------ +% 1. Get the structural parameters & define penalties +%------------------------------------------------------------------------------ +if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb) + k = find(xparam1 < bayestopt_.lb); + fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2); + cost_flag = 0; + info = 41; + return; +end +if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub) + k = find(xparam1 > bayestopt_.ub); + fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2); + cost_flag = 0; + info = 42; + return; +end +Q = M_.Sigma_e; +H = M_.H; +for i=1:estim_params_.nvx k =estim_params_.var_exo(i,1); Q(k,k) = xparam1(i)*xparam1(i); - end - offset = estim_params_.nvx; - if estim_params_.nvn +end +offset = estim_params_.nvx; +if estim_params_.nvn for i=1:estim_params_.nvn - k = estim_params_.var_endo(i,1); - H(k,k) = xparam1(i+offset)*xparam1(i+offset); + k = estim_params_.var_endo(i,1); + H(k,k) = xparam1(i+offset)*xparam1(i+offset); end offset = offset+estim_params_.nvn; - end - if estim_params_.ncx +end +if estim_params_.ncx for i=1:estim_params_.ncx - k1 =estim_params_.corrx(i,1); - k2 =estim_params_.corrx(i,2); - Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2)); - Q(k2,k1) = Q(k1,k2); + k1 =estim_params_.corrx(i,1); + k2 =estim_params_.corrx(i,2); + Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2)); + Q(k2,k1) = Q(k1,k2); end [CholQ,testQ] = chol(Q); if testQ %% The variance-covariance matrix of the structural innovations is not definite positive. - %% We have to compute the eigenvalues of this matrix in order to build the penalty. - a = diag(eig(Q)); - k = find(a < 0); - if k > 0 - fval = bayestopt_.penalty+sum(-a(k)); - cost_flag = 0; - info = 43; - return - end + %% We have to compute the eigenvalues of this matrix in order to build the penalty. + a = diag(eig(Q)); + k = find(a < 0); + if k > 0 + fval = bayestopt_.penalty+sum(-a(k)); + cost_flag = 0; + info = 43; + return + end end offset = offset+estim_params_.ncx; - end - if estim_params_.ncn +end +if estim_params_.ncn for i=1:estim_params_.ncn - k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1)); - k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2)); - H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2)); - H(k2,k1) = H(k1,k2); + k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1)); + k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2)); + H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2)); + H(k2,k1) = H(k1,k2); end [CholH,testH] = chol(H); if testH - a = diag(eig(H)); - k = find(a < 0); - if k > 0 - fval = bayestopt_.penalty+sum(-a(k)); - cost_flag = 0; - info = 44; - return - end + a = diag(eig(H)); + k = find(a < 0); + if k > 0 + fval = bayestopt_.penalty+sum(-a(k)); + cost_flag = 0; + info = 44; + return + end end offset = offset+estim_params_.ncn; - end - if estim_params_.np > 0 - M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end); - end - M_.Sigma_e = Q; - M_.H = H; - %------------------------------------------------------------------------------ - % 2. call model setup & reduction program - %------------------------------------------------------------------------------ - [T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,... - bayestopt_.restrict_columns,... - bayestopt_.restrict_aux); - if info(1) == 1 | info(1) == 2 | info(1) == 5 +end +if estim_params_.np > 0 + M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end); +end +M_.Sigma_e = Q; +M_.H = H; +%------------------------------------------------------------------------------ +% 2. call model setup & reduction program +%------------------------------------------------------------------------------ +[T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,... + bayestopt_.restrict_columns,... + bayestopt_.restrict_aux); +if info(1) == 1 | info(1) == 2 | info(1) == 5 fval = bayestopt_.penalty+1; cost_flag = 0; return - elseif info(1) == 3 | info(1) == 4 | info(1) == 20 +elseif info(1) == 3 | info(1) == 4 | info(1) == 20 fval = bayestopt_.penalty+info(2);%^2; % penalty power raised in DR1.m and resol already. GP July'08 cost_flag = 0; return - end - bayestopt_.mf = bayestopt_.mf1; - if ~options_.noconstant +end +bayestopt_.mf = bayestopt_.mf1; +if ~options_.noconstant if options_.loglinear == 1 - constant = log(SteadyState(bayestopt_.mfys)); + constant = log(SteadyState(bayestopt_.mfys)); else - constant = SteadyState(bayestopt_.mfys); + constant = SteadyState(bayestopt_.mfys); end - else +else constant = zeros(nobs,1); - end - if bayestopt_.with_trend == 1 +end +if bayestopt_.with_trend == 1 trend_coeff = zeros(nobs,1); t = options_.trend_coeffs; for i=1:length(t) - if ~isempty(t{i}) - trend_coeff(i) = evalin('base',t{i}); - end + if ~isempty(t{i}) + trend_coeff(i) = evalin('base',t{i}); + end end trend = repmat(constant,1,gend)+trend_coeff*[1:gend]; - else +else trend = repmat(constant,1,gend); - end - start = options_.presample+1; - np = size(T,1); - mf = bayestopt_.mf; - no_missing_data_flag = (number_of_observations==gend*nobs); - %------------------------------------------------------------------------------ - % 3. Initial condition of the Kalman filter - %------------------------------------------------------------------------------ - kalman_algo = options_.kalman_algo; - if options_.lik_init == 1 % Kalman filter - if kalman_algo ~= 2 - kalman_algo = 1; - end - Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold); - Pinf = []; - elseif options_.lik_init == 2 % Old Diffuse Kalman filter - if kalman_algo ~= 2 - kalman_algo = 1; - end - Pstar = options_.Harvey_scale_factor*eye(np); - Pinf = []; - elseif options_.lik_init == 3 % Diffuse Kalman filter - if kalman_algo ~= 4 - kalman_algo = 3; - end - [QT,ST] = schur(T); - e1 = abs(ordeig(ST)) > 2-options_.qz_criterium; - [QT,ST] = ordschur(QT,ST,e1); - k = find(abs(ordeig(ST)) > 2-options_.qz_criterium); - nk = length(k); - nk1 = nk+1; - Pinf = zeros(np,np); - Pinf(1:nk,1:nk) = eye(nk); - Pstar = zeros(np,np); - B = QT'*R*Q*R'*QT; - for i=np:-1:nk+2 - if ST(i,i-1) == 0 - if i == np - c = zeros(np-nk,1); - else - c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... - ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i); - end - q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i); - Pstar(nk1:i,i) = q\(B(nk1:i,i)+c); - Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; - else - if i == np - c = zeros(np-nk,1); - c1 = zeros(np-nk,1); - else - c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... - ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i)+... - ST(i,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1); - c1 = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i-1,i+1:end)')+... - ST(i-1,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1)+... - ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i); - end - q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);... - -ST(nk1:i,nk1:i)*ST(i-1,i) eye(i-nk)-ST(nk1:i,nk1:i)*ST(i-1,i-1)]; - z = q\[B(nk1:i,i)+c;B(nk1:i,i-1)+c1]; - Pstar(nk1:i,i) = z(1:(i-nk)); - Pstar(nk1:i,i-1) = z(i-nk+1:end); - Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; - Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)'; - i = i - 1; - end - end - if i == nk+2 - c = ST(nk+1,:)*(Pstar(:,nk+2:end)*ST(nk1,nk+2:end)')+ST(nk1,nk1)*ST(nk1,nk+2:end)*Pstar(nk+2:end,nk1); - Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1)); - end - Z = QT(mf,:); - R1 = QT'*R; - [QQ,RR,EE] = qr(Z*ST(:,1:nk),0); - k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8); - if length(k) > 0 - k1 = EE(:,k); - dd =ones(nk,1); - dd(k1) = zeros(length(k1),1); - Pinf(1:nk,1:nk) = diag(dd); - end - end - if kalman_algo == 2 - no_correlation_flag = 1; - if length(H)==1 - H = zeros(nobs,1); - else - if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal... - H = diag(H); - else - no_correlation_flag = 1; - end - end - end - kalman_tol = options_.kalman_tol; - riccati_tol = options_.riccati_tol; - mf = bayestopt_.mf1; - Y = data-trend; - %------------------------------------------------------------------------------ - % 4. Likelihood evaluation - %------------------------------------------------------------------------------ - if (kalman_algo==1)% Multivariate Kalman Filter - if no_missing_data_flag - [LIK, lik] = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol); - else - [LIK, lik] = ... - missing_observations_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol, ... - data_index,number_of_observations,no_more_missing_observations); - end - if isinf(LIK) - kalman_algo = 2; - end - end - if (kalman_algo==2)% Univariate Kalman Filter - if no_correlation_flag - [LIK, lik] = univariate_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations); - else - [LIK, lik] = univariate_kalman_filter_corr(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations); - end - end - if (kalman_algo==3)% Multivariate Diffuse Kalman Filter - if no_missing_data_flag - data1 = data - trend; - if any(any(H ~= 0)) - [LIK, lik] = DiffuseLikelihoodH1_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,start); - else - [LIK, lik] = DiffuseLikelihood1_Z(ST,Z,R1,Q,Pinf,Pstar,data1,start); - end - if isinf(LIK) - kalman_algo = 4; - end - else - error(['The diffuse filter is not yet implemented for models with missing observations']) - end - end - if (kalman_algo==4)% Univariate Diffuse Kalman Filter - data1 = data - trend; - if any(any(H ~= 0)) - if ~estim_params_.ncn - [LIK, lik] = DiffuseLikelihoodH3_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,trend,start); - else - [LIK, lik] = DiffuseLikelihoodH3corr_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,trend,start); - end - else - [LIK, lik] = DiffuseLikelihood3_Z(ST,Z,R1,Q,Pinf,Pstar,data1,start); - end - end - if imag(LIK) ~= 0 - likelihood = bayestopt_.penalty; - else - likelihood = LIK; - end - % ------------------------------------------------------------------------------ - % Adds prior if necessary - % ------------------------------------------------------------------------------ - lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4); - fval = (likelihood-lnprior); - options_.kalman_algo = kalman_algo; - llik=[-lnprior; lik(start:end)]; - \ No newline at end of file +end +start = options_.presample+1; +np = size(T,1); +mf = bayestopt_.mf; +no_missing_data_flag = (number_of_observations==gend*nobs); +%------------------------------------------------------------------------------ +% 3. Initial condition of the Kalman filter +%------------------------------------------------------------------------------ +kalman_algo = options_.kalman_algo; +if options_.lik_init == 1 % Kalman filter + if kalman_algo ~= 2 + kalman_algo = 1; + end + Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold); + Pinf = []; +elseif options_.lik_init == 2 % Old Diffuse Kalman filter + if kalman_algo ~= 2 + kalman_algo = 1; + end + Pstar = options_.Harvey_scale_factor*eye(np); + Pinf = []; +elseif options_.lik_init == 3 % Diffuse Kalman filter + if kalman_algo ~= 4 + kalman_algo = 3; + end + [QT,ST] = schur(T); + e1 = abs(ordeig(ST)) > 2-options_.qz_criterium; + [QT,ST] = ordschur(QT,ST,e1); + k = find(abs(ordeig(ST)) > 2-options_.qz_criterium); + nk = length(k); + nk1 = nk+1; + Pinf = zeros(np,np); + Pinf(1:nk,1:nk) = eye(nk); + Pstar = zeros(np,np); + B = QT'*R*Q*R'*QT; + for i=np:-1:nk+2 + if ST(i,i-1) == 0 + if i == np + c = zeros(np-nk,1); + else + c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... + ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i); + end + q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i); + Pstar(nk1:i,i) = q\(B(nk1:i,i)+c); + Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; + else + if i == np + c = zeros(np-nk,1); + c1 = zeros(np-nk,1); + else + c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... + ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i)+... + ST(i,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1); + c1 = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i-1,i+1:end)')+... + ST(i-1,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1)+... + ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i); + end + q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);... + -ST(nk1:i,nk1:i)*ST(i-1,i) eye(i-nk)-ST(nk1:i,nk1:i)*ST(i-1,i-1)]; + z = q\[B(nk1:i,i)+c;B(nk1:i,i-1)+c1]; + Pstar(nk1:i,i) = z(1:(i-nk)); + Pstar(nk1:i,i-1) = z(i-nk+1:end); + Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; + Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)'; + i = i - 1; + end + end + if i == nk+2 + c = ST(nk+1,:)*(Pstar(:,nk+2:end)*ST(nk1,nk+2:end)')+ST(nk1,nk1)*ST(nk1,nk+2:end)*Pstar(nk+2:end,nk1); + Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1)); + end + Z = QT(mf,:); + R1 = QT'*R; + [QQ,RR,EE] = qr(Z*ST(:,1:nk),0); + k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8); + if length(k) > 0 + k1 = EE(:,k); + dd =ones(nk,1); + dd(k1) = zeros(length(k1),1); + Pinf(1:nk,1:nk) = diag(dd); + end +end +if kalman_algo == 2 + no_correlation_flag = 1; + if length(H)==1 + H = zeros(nobs,1); + else + if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal... + H = diag(H); + else + no_correlation_flag = 1; + end + end +end +kalman_tol = options_.kalman_tol; +riccati_tol = options_.riccati_tol; +mf = bayestopt_.mf1; +Y = data-trend; +%------------------------------------------------------------------------------ +% 4. Likelihood evaluation +%------------------------------------------------------------------------------ +if (kalman_algo==1)% Multivariate Kalman Filter + if no_missing_data_flag + [LIK, lik] = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol); + else + [LIK, lik] = ... + missing_observations_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol, ... + data_index,number_of_observations,no_more_missing_observations); + end + if isinf(LIK) + kalman_algo = 2; + end +end +if (kalman_algo==2)% Univariate Kalman Filter + if no_correlation_flag + [LIK, lik] = univariate_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations); + else + [LIK, lik] = univariate_kalman_filter_corr(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations); + end +end +if (kalman_algo==3)% Multivariate Diffuse Kalman Filter + if no_missing_data_flag + data1 = data - trend; + if any(any(H ~= 0)) + [LIK, lik] = DiffuseLikelihoodH1_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,start); + else + [LIK, lik] = DiffuseLikelihood1_Z(ST,Z,R1,Q,Pinf,Pstar,data1,start); + end + if isinf(LIK) + kalman_algo = 4; + end + else + error(['The diffuse filter is not yet implemented for models with missing observations']) + end +end +if (kalman_algo==4)% Univariate Diffuse Kalman Filter + data1 = data - trend; + if any(any(H ~= 0)) + if ~estim_params_.ncn + [LIK, lik] = DiffuseLikelihoodH3_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,trend,start); + else + [LIK, lik] = DiffuseLikelihoodH3corr_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,trend,start); + end + else + [LIK, lik] = DiffuseLikelihood3_Z(ST,Z,R1,Q,Pinf,Pstar,data1,start); + end +end +if imag(LIK) ~= 0 + likelihood = bayestopt_.penalty; +else + likelihood = LIK; +end +% ------------------------------------------------------------------------------ +% Adds prior if necessary +% ------------------------------------------------------------------------------ +lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4); +fval = (likelihood-lnprior); +options_.kalman_algo = kalman_algo; +llik=[-lnprior; lik(start:end)]; diff --git a/matlab/DsgeSmoother.m b/matlab/DsgeSmoother.m index 3c62224a24..71bee48049 100644 --- a/matlab/DsgeSmoother.m +++ b/matlab/DsgeSmoother.m @@ -47,281 +47,281 @@ function [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T,R,P,PK,d, % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global bayestopt_ M_ oo_ estim_params_ options_ +global bayestopt_ M_ oo_ estim_params_ options_ - alphahat = []; - etahat = []; - epsilonhat = []; - ahat = []; - SteadyState = []; - trend_coeff = []; - aK = []; - T = []; - R = []; - P = []; - PK = []; - d = []; - decomp = []; - nobs = size(options_.varobs,1); - smpl = size(Y,2); +alphahat = []; +etahat = []; +epsilonhat = []; +ahat = []; +SteadyState = []; +trend_coeff = []; +aK = []; +T = []; +R = []; +P = []; +PK = []; +d = []; +decomp = []; +nobs = size(options_.varobs,1); +smpl = size(Y,2); - set_all_parameters(xparam1); +set_all_parameters(xparam1); - %------------------------------------------------------------------------------ - % 2. call model setup & reduction program - %------------------------------------------------------------------------------ - [T,R,SteadyState] = dynare_resolve; - bayestopt_.mf = bayestopt_.mf2; - if options_.noconstant - constant = zeros(nobs,1); - else - if options_.loglinear == 1 - constant = log(SteadyState(bayestopt_.mfys)); - else - constant = SteadyState(bayestopt_.mfys); - end - end - trend_coeff = zeros(nobs,1); - if bayestopt_.with_trend == 1 +%------------------------------------------------------------------------------ +% 2. call model setup & reduction program +%------------------------------------------------------------------------------ +[T,R,SteadyState] = dynare_resolve; +bayestopt_.mf = bayestopt_.mf2; +if options_.noconstant + constant = zeros(nobs,1); +else + if options_.loglinear == 1 + constant = log(SteadyState(bayestopt_.mfys)); + else + constant = SteadyState(bayestopt_.mfys); + end +end +trend_coeff = zeros(nobs,1); +if bayestopt_.with_trend == 1 trend_coeff = zeros(nobs,1); t = options_.trend_coeffs; for i=1:length(t) - if ~isempty(t{i}) - trend_coeff(i) = evalin('base',t{i}); - end + if ~isempty(t{i}) + trend_coeff(i) = evalin('base',t{i}); + end end trend = constant*ones(1,gend)+trend_coeff*(1:gend); - else +else trend = constant*ones(1,gend); - end - start = options_.presample+1; - np = size(T,1); - mf = bayestopt_.mf; - % ------------------------------------------------------------------------------ - % 3. Initial condition of the Kalman filter - % ------------------------------------------------------------------------------ - % - % C'est ici qu'il faut d�terminer Pinf et Pstar. Si le mod�le est stationnaire, - % alors il suffit de poser Pstar comme la solution de l'�uation de Lyapounov et - % Pinf=[]. - % - Q = M_.Sigma_e; - H = M_.H; - - kalman_algo = options_.kalman_algo; - if options_.lik_init == 1 % Kalman filter - if kalman_algo ~= 2 - kalman_algo = 1; - end - Pstar = lyapunov_symm(T,R*Q*transpose(R),options_.qz_criterium,options_.lyapunov_complex_threshold); - Pinf = []; - elseif options_.lik_init == 2 % Old Diffuse Kalman filter - if kalman_algo ~= 2 - kalman_algo = 1; - end - Pstar = options_.Harvey_scale_factor*eye(np); - Pinf = []; - elseif options_.lik_init == 3 % Diffuse Kalman filter - if kalman_algo ~= 4 - kalman_algo = 3; - end - [QT,ST] = schur(T); - e1 = abs(ordeig(ST)) > 2-options_.qz_criterium; - [QT,ST] = ordschur(QT,ST,e1); - k = find(abs(ordeig(ST)) > 2-options_.qz_criterium); - nk = length(k); - nk1 = nk+1; - Pinf = zeros(np,np); - Pinf(1:nk,1:nk) = eye(nk); - Pstar = zeros(np,np); - B = QT'*R*Q*R'*QT; - for i=np:-1:nk+2 - if ST(i,i-1) == 0 - if i == np - c = zeros(np-nk,1); - else - c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... - ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i); - end - q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i); - Pstar(nk1:i,i) = q\(B(nk1:i,i)+c); - Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; - else - if i == np - c = zeros(np-nk,1); - c1 = zeros(np-nk,1); - else - c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... - ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i)+... - ST(i,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1); - c1 = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i-1,i+1:end)')+... - ST(i-1,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1)+... - ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i); - end - q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);... - -ST(nk1:i,nk1:i)*ST(i-1,i) eye(i-nk)-ST(nk1:i,nk1:i)*ST(i-1,i-1)]; - z = q\[B(nk1:i,i)+c;B(nk1:i,i-1)+c1]; - Pstar(nk1:i,i) = z(1:(i-nk)); - Pstar(nk1:i,i-1) = z(i-nk+1:end); - Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; - Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)'; - i = i - 1; - end - end - if i == nk+2 - c = ST(nk+1,:)*(Pstar(:,nk+2:end)*ST(nk1,nk+2:end)')+ST(nk1,nk1)*ST(nk1,nk+2:end)*Pstar(nk+2:end,nk1); - Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1)); - end - - Z = QT(mf,:); - R1 = QT'*R; - [QQ,RR,EE] = qr(Z*ST(:,1:nk),0); - k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8); - if length(k) > 0 - k1 = EE(:,k); - dd =ones(nk,1); - dd(k1) = zeros(length(k1),1); - Pinf(1:nk,1:nk) = diag(dd); - end - end - % ----------------------------------------------------------------------------- - % 4. Kalman smoother - % ----------------------------------------------------------------------------- - if any(any(H ~= 0)) % should be replaced by a flag - if kalman_algo == 1 - [alphahat,epsilonhat,etahat,ahat,aK] = ... - DiffuseKalmanSmootherH1(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf); - if all(alphahat(:)==0) - kalman_algo = 2; - if ~estim_params_.ncn - [alphahat,epsilonhat,etahat,ahat,aK] = ... - DiffuseKalmanSmootherH3(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf); - else - [alphahat,epsilonhat,etahat,ahat,aK] = ... - DiffuseKalmanSmootherH3corr(T,R,Q,H,Pinf,Pstar,Y,trend, ... - nobs,np,smpl,mf); - end - end - elseif options_.kalman_algo == 2 - if ~estim_params_.ncn - [alphahat,epsilonhat,etahat,ahat,aK] = ... - DiffuseKalmanSmootherH3(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf); - else - [alphahat,epsilonhat,etahat,ahat,aK] = ... - DiffuseKalmanSmootherH3corr(T,R,Q,H,Pinf,Pstar,Y,trend, ... - nobs,np,smpl,mf); - end - elseif kalman_algo == 3 | kalman_algo == 4 - data1 = Y - trend; - if kalman_algo == 3 - [alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ... - DiffuseKalmanSmootherH1_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,nobs,np,smpl); - if all(alphahat(:)==0) - kalman_algo = 4; - if ~estim_params_.ncn - [alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ... - DiffuseKalmanSmootherH3_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,nobs,np,smpl); - else - [alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ... - DiffuseKalmanSmootherH3corr_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1, ... - nobs,np,smpl); - end - end - else - if ~estim_params_.ncn - [alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ... - DiffuseKalmanSmootherH3_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1, ... - nobs,np,smpl); - else - [alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ... - DiffuseKalmanSmootherH3corr_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1, ... - nobs,np,smpl); - end - end - alphahat = QT*alphahat; - ahat = QT*ahat; - nk = options_.nk; - for jnk=1:nk - aK(jnk,:,:) = QT*squeeze(aK(jnk,:,:)); - for i=1:size(PK,4) - PK(jnk,:,:,i) = QT*squeeze(PK(jnk,:,:,i))*QT'; - end - for i=1:size(decomp,4) - decomp(jnk,:,:,i) = QT*squeeze(decomp(jnk,:,:,i)); - end - end - for i=1:size(P,4) - P(:,:,i) = QT*squeeze(P(:,:,i))*QT'; - end - end - else - if kalman_algo == 1 - if missing_value - [alphahat,etahat,ahat,aK] = missing_DiffuseKalmanSmoother1(T,R,Q, ... - Pinf,Pstar,Y,trend,nobs,np,smpl,mf,data_index); - else - [alphahat,etahat,ahat,aK] = DiffuseKalmanSmoother1(T,R,Q, ... - Pinf,Pstar,Y,trend,nobs,np,smpl,mf); - end - if all(alphahat(:)==0) - kalman_algo = 2; - end - end - if kalman_algo == 2 - if missing_value - [alphahat,etahat,ahat,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmoother3(T,R,Q, ... - Pinf,Pstar,Y,trend,nobs,np,smpl,mf,data_index); - else - [alphahat,etahat,ahat,P,aK,PK,d,decomp] = DiffuseKalmanSmoother3(T,R,Q, ... - Pinf,Pstar,Y,trend,nobs,np,smpl,mf); - end - end - if kalman_algo == 3 - data1 = Y - trend; - if missing_value - [alphahat,etahat,ahat,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmoother1_Z(ST, ... - Z,R1,Q,Pinf,Pstar,data1,nobs,np,smpl,data_index); - else - [alphahat,etahat,ahat,P,aK,PK,d,decomp] = DiffuseKalmanSmoother1_Z(ST, ... - Z,R1,Q,Pinf,Pstar, ... - data1,nobs,np,smpl); - end - if all(alphahat(:)==0) - options_.kalman_algo = 4; - end - end - if kalman_algo == 4 - data1 = Y - trend; - if missing_value - [alphahat,etahat,ahat,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmoother3_Z(ST, ... - Z,R1,Q,Pinf,Pstar,data1,nobs,np,smpl,data_index); - else - [alphahat,etahat,ahat,P,aK,PK,d,decomp] = DiffuseKalmanSmoother3_Z(ST, ... - Z,R1,Q,Pinf,Pstar, ... - data1,nobs,np,smpl); - end - end - if kalman_algo == 3 | kalman_algo == 4 - alphahat = QT*alphahat; - ahat = QT*ahat; - nk = options_.nk; +end +start = options_.presample+1; +np = size(T,1); +mf = bayestopt_.mf; +% ------------------------------------------------------------------------------ +% 3. Initial condition of the Kalman filter +% ------------------------------------------------------------------------------ +% +% C'est ici qu'il faut d�terminer Pinf et Pstar. Si le mod�le est stationnaire, +% alors il suffit de poser Pstar comme la solution de l'�uation de Lyapounov et +% Pinf=[]. +% +Q = M_.Sigma_e; +H = M_.H; + +kalman_algo = options_.kalman_algo; +if options_.lik_init == 1 % Kalman filter + if kalman_algo ~= 2 + kalman_algo = 1; + end + Pstar = lyapunov_symm(T,R*Q*transpose(R),options_.qz_criterium,options_.lyapunov_complex_threshold); + Pinf = []; +elseif options_.lik_init == 2 % Old Diffuse Kalman filter + if kalman_algo ~= 2 + kalman_algo = 1; + end + Pstar = options_.Harvey_scale_factor*eye(np); + Pinf = []; +elseif options_.lik_init == 3 % Diffuse Kalman filter + if kalman_algo ~= 4 + kalman_algo = 3; + end + [QT,ST] = schur(T); + e1 = abs(ordeig(ST)) > 2-options_.qz_criterium; + [QT,ST] = ordschur(QT,ST,e1); + k = find(abs(ordeig(ST)) > 2-options_.qz_criterium); + nk = length(k); + nk1 = nk+1; + Pinf = zeros(np,np); + Pinf(1:nk,1:nk) = eye(nk); + Pstar = zeros(np,np); + B = QT'*R*Q*R'*QT; + for i=np:-1:nk+2 + if ST(i,i-1) == 0 + if i == np + c = zeros(np-nk,1); + else + c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... + ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i); + end + q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i); + Pstar(nk1:i,i) = q\(B(nk1:i,i)+c); + Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; + else + if i == np + c = zeros(np-nk,1); + c1 = zeros(np-nk,1); + else + c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... + ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i)+... + ST(i,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1); + c1 = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i-1,i+1:end)')+... + ST(i-1,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1)+... + ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i); + end + q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);... + -ST(nk1:i,nk1:i)*ST(i-1,i) eye(i-nk)-ST(nk1:i,nk1:i)*ST(i-1,i-1)]; + z = q\[B(nk1:i,i)+c;B(nk1:i,i-1)+c1]; + Pstar(nk1:i,i) = z(1:(i-nk)); + Pstar(nk1:i,i-1) = z(i-nk+1:end); + Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; + Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)'; + i = i - 1; + end + end + if i == nk+2 + c = ST(nk+1,:)*(Pstar(:,nk+2:end)*ST(nk1,nk+2:end)')+ST(nk1,nk1)*ST(nk1,nk+2:end)*Pstar(nk+2:end,nk1); + Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1)); + end + + Z = QT(mf,:); + R1 = QT'*R; + [QQ,RR,EE] = qr(Z*ST(:,1:nk),0); + k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8); + if length(k) > 0 + k1 = EE(:,k); + dd =ones(nk,1); + dd(k1) = zeros(length(k1),1); + Pinf(1:nk,1:nk) = diag(dd); + end +end +% ----------------------------------------------------------------------------- +% 4. Kalman smoother +% ----------------------------------------------------------------------------- +if any(any(H ~= 0)) % should be replaced by a flag + if kalman_algo == 1 + [alphahat,epsilonhat,etahat,ahat,aK] = ... + DiffuseKalmanSmootherH1(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf); + if all(alphahat(:)==0) + kalman_algo = 2; + if ~estim_params_.ncn + [alphahat,epsilonhat,etahat,ahat,aK] = ... + DiffuseKalmanSmootherH3(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf); + else + [alphahat,epsilonhat,etahat,ahat,aK] = ... + DiffuseKalmanSmootherH3corr(T,R,Q,H,Pinf,Pstar,Y,trend, ... + nobs,np,smpl,mf); + end + end + elseif options_.kalman_algo == 2 + if ~estim_params_.ncn + [alphahat,epsilonhat,etahat,ahat,aK] = ... + DiffuseKalmanSmootherH3(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf); + else + [alphahat,epsilonhat,etahat,ahat,aK] = ... + DiffuseKalmanSmootherH3corr(T,R,Q,H,Pinf,Pstar,Y,trend, ... + nobs,np,smpl,mf); + end + elseif kalman_algo == 3 | kalman_algo == 4 + data1 = Y - trend; + if kalman_algo == 3 + [alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ... + DiffuseKalmanSmootherH1_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,nobs,np,smpl); + if all(alphahat(:)==0) + kalman_algo = 4; + if ~estim_params_.ncn + [alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ... + DiffuseKalmanSmootherH3_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1,nobs,np,smpl); + else + [alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ... + DiffuseKalmanSmootherH3corr_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1, ... + nobs,np,smpl); + end + end + else + if ~estim_params_.ncn + [alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ... + DiffuseKalmanSmootherH3_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1, ... + nobs,np,smpl); + else + [alphahat,epsilonhat,etahat,ahat,P,aK,PK,d,decomp] = ... + DiffuseKalmanSmootherH3corr_Z(ST,Z,R1,Q,H,Pinf,Pstar,data1, ... + nobs,np,smpl); + end + end + alphahat = QT*alphahat; + ahat = QT*ahat; + nk = options_.nk; + for jnk=1:nk + aK(jnk,:,:) = QT*squeeze(aK(jnk,:,:)); + for i=1:size(PK,4) + PK(jnk,:,:,i) = QT*squeeze(PK(jnk,:,:,i))*QT'; + end + for i=1:size(decomp,4) + decomp(jnk,:,:,i) = QT*squeeze(decomp(jnk,:,:,i)); + end + end + for i=1:size(P,4) + P(:,:,i) = QT*squeeze(P(:,:,i))*QT'; + end + end +else + if kalman_algo == 1 + if missing_value + [alphahat,etahat,ahat,aK] = missing_DiffuseKalmanSmoother1(T,R,Q, ... + Pinf,Pstar,Y,trend,nobs,np,smpl,mf,data_index); + else + [alphahat,etahat,ahat,aK] = DiffuseKalmanSmoother1(T,R,Q, ... + Pinf,Pstar,Y,trend,nobs,np,smpl,mf); + end + if all(alphahat(:)==0) + kalman_algo = 2; + end + end + if kalman_algo == 2 + if missing_value + [alphahat,etahat,ahat,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmoother3(T,R,Q, ... + Pinf,Pstar,Y,trend,nobs,np,smpl,mf,data_index); + else + [alphahat,etahat,ahat,P,aK,PK,d,decomp] = DiffuseKalmanSmoother3(T,R,Q, ... + Pinf,Pstar,Y,trend,nobs,np,smpl,mf); + end + end + if kalman_algo == 3 + data1 = Y - trend; + if missing_value + [alphahat,etahat,ahat,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmoother1_Z(ST, ... + Z,R1,Q,Pinf,Pstar,data1,nobs,np,smpl,data_index); + else + [alphahat,etahat,ahat,P,aK,PK,d,decomp] = DiffuseKalmanSmoother1_Z(ST, ... + Z,R1,Q,Pinf,Pstar, ... + data1,nobs,np,smpl); + end + if all(alphahat(:)==0) + options_.kalman_algo = 4; + end + end + if kalman_algo == 4 + data1 = Y - trend; + if missing_value + [alphahat,etahat,ahat,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmoother3_Z(ST, ... + Z,R1,Q,Pinf,Pstar,data1,nobs,np,smpl,data_index); + else + [alphahat,etahat,ahat,P,aK,PK,d,decomp] = DiffuseKalmanSmoother3_Z(ST, ... + Z,R1,Q,Pinf,Pstar, ... + data1,nobs,np,smpl); + end + end + if kalman_algo == 3 | kalman_algo == 4 + alphahat = QT*alphahat; + ahat = QT*ahat; + nk = options_.nk; % $$$ if M_.exo_nbr<2 % Fix the crash of Dynare when the estimated model has only one structural shock (problem with % $$$ % the squeeze function, that does not affect 2D arrays). % $$$ size_decomp = 0; % $$$ else % $$$ size_decomp = size(decomp,4); % $$$ end - for jnk=1:nk - aK(jnk,:,:) = QT*squeeze(aK(jnk,:,:)); - for i=1:size(PK,4) - PK(jnk,:,:,i) = QT*dynare_squeeze(PK(jnk,:,:,i))*QT'; - end - for i=1:size(decomp,4) - decomp(jnk,:,:,i) = QT*dynare_squeeze(decomp(jnk,:,:,i)); - end - end - for i=1:size(P,4) - P(:,:,i) = QT*dynare_squeeze(P(:,:,i))*QT'; - end - end - end + for jnk=1:nk + aK(jnk,:,:) = QT*squeeze(aK(jnk,:,:)); + for i=1:size(PK,4) + PK(jnk,:,:,i) = QT*dynare_squeeze(PK(jnk,:,:,i))*QT'; + end + for i=1:size(decomp,4) + decomp(jnk,:,:,i) = QT*dynare_squeeze(decomp(jnk,:,:,i)); + end + end + for i=1:size(P,4) + P(:,:,i) = QT*dynare_squeeze(P(:,:,i))*QT'; + end + end +end diff --git a/matlab/DsgeVarLikelihood.m b/matlab/DsgeVarLikelihood.m index 3c636dedb0..48b5e08dd9 100644 --- a/matlab/DsgeVarLikelihood.m +++ b/matlab/DsgeVarLikelihood.m @@ -146,15 +146,15 @@ 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; + 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); + GYX(:,(i-1)*NumberOfObservedVariables+1:i*NumberOfObservedVariables) = ... + TheoreticalAutoCovarianceOfTheObservedVariables(:,:,i+1); end if ~options_.noconstant GYX(:,end) = constant'; @@ -181,41 +181,41 @@ assignin('base','GXX',GXX); assignin('base','GYX',GYX); if ~isinf(dsge_prior_weight) - tmp0 = dsge_prior_weight*gend*TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1) + mYY ; - tmp1 = dsge_prior_weight*gend*GYX + mYX; - tmp2 = inv(dsge_prior_weight*gend*GXX+mXX); - SIGMAu = tmp0 - tmp1*tmp2*tmp1'; clear('tmp0'); - if ~ispd(SIGMAu) - v = diag(SIGMAu); - k = find(v<0); - fval = bayestopt_.penalty + sum(v(k).^2); - info = 52; - cost_flag = 0; - return; - end - SIGMAu = SIGMAu / (gend*(1+dsge_prior_weight)); - PHI = tmp2*tmp1'; clear('tmp1'); - prodlng1 = sum(gammaln(.5*((1+dsge_prior_weight)*gend- ... - NumberOfObservedVariables*NumberOfLags ... - +1-(1:NumberOfObservedVariables)'))); - prodlng2 = sum(gammaln(.5*(dsge_prior_weight*gend- ... - NumberOfObservedVariables*NumberOfLags ... - +1-(1:NumberOfObservedVariables)'))); - lik = .5*NumberOfObservedVariables*log(det(dsge_prior_weight*gend*GXX+mXX)) ... - + .5*((dsge_prior_weight+1)*gend-NumberOfParameters)*log(det((dsge_prior_weight+1)*gend*SIGMAu)) ... - - .5*NumberOfObservedVariables*log(det(dsge_prior_weight*gend*GXX)) ... - - .5*(dsge_prior_weight*gend-NumberOfParameters)*log(det(dsge_prior_weight*gend*(GYY-GYX*inv(GXX)*GYX'))) ... - + .5*NumberOfObservedVariables*gend*log(2*pi) ... - - .5*log(2)*NumberOfObservedVariables*((dsge_prior_weight+1)*gend-NumberOfParameters) ... - + .5*log(2)*NumberOfObservedVariables*(dsge_prior_weight*gend-NumberOfParameters) ... - - prodlng1 + prodlng2; + tmp0 = dsge_prior_weight*gend*TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1) + mYY ; + tmp1 = dsge_prior_weight*gend*GYX + mYX; + tmp2 = inv(dsge_prior_weight*gend*GXX+mXX); + SIGMAu = tmp0 - tmp1*tmp2*tmp1'; clear('tmp0'); + if ~ispd(SIGMAu) + v = diag(SIGMAu); + k = find(v<0); + fval = bayestopt_.penalty + sum(v(k).^2); + info = 52; + cost_flag = 0; + return; + end + SIGMAu = SIGMAu / (gend*(1+dsge_prior_weight)); + PHI = tmp2*tmp1'; clear('tmp1'); + prodlng1 = sum(gammaln(.5*((1+dsge_prior_weight)*gend- ... + NumberOfObservedVariables*NumberOfLags ... + +1-(1:NumberOfObservedVariables)'))); + prodlng2 = sum(gammaln(.5*(dsge_prior_weight*gend- ... + NumberOfObservedVariables*NumberOfLags ... + +1-(1:NumberOfObservedVariables)'))); + lik = .5*NumberOfObservedVariables*log(det(dsge_prior_weight*gend*GXX+mXX)) ... + + .5*((dsge_prior_weight+1)*gend-NumberOfParameters)*log(det((dsge_prior_weight+1)*gend*SIGMAu)) ... + - .5*NumberOfObservedVariables*log(det(dsge_prior_weight*gend*GXX)) ... + - .5*(dsge_prior_weight*gend-NumberOfParameters)*log(det(dsge_prior_weight*gend*(GYY-GYX*inv(GXX)*GYX'))) ... + + .5*NumberOfObservedVariables*gend*log(2*pi) ... + - .5*log(2)*NumberOfObservedVariables*((dsge_prior_weight+1)*gend-NumberOfParameters) ... + + .5*log(2)*NumberOfObservedVariables*(dsge_prior_weight*gend-NumberOfParameters) ... + - prodlng1 + prodlng2; else - iGXX = inv(GXX); - SIGMAu = GYY - GYX*iGXX*transpose(GYX); - PHI = iGXX*transpose(GYX); - lik = gend * ( log(det(SIGMAu)) + NumberOfObservedVariables*log(2*pi) + ... - trace(inv(SIGMAu)*(mYY - transpose(mYX*PHI) - mYX*PHI + transpose(PHI)*mXX*PHI)/gend)); - lik = .5*lik;% Minus likelihood + iGXX = inv(GXX); + SIGMAu = GYY - GYX*iGXX*transpose(GYX); + PHI = iGXX*transpose(GYX); + lik = gend * ( log(det(SIGMAu)) + NumberOfObservedVariables*log(2*pi) + ... + trace(inv(SIGMAu)*(mYY - transpose(mYX*PHI) - mYX*PHI + transpose(PHI)*mXX*PHI)/gend)); + lik = .5*lik;% Minus likelihood end lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4); diff --git a/matlab/GetAllPosteriorDraws.m b/matlab/GetAllPosteriorDraws.m index 0b2f69e4be..e8277cff8f 100644 --- a/matlab/GetAllPosteriorDraws.m +++ b/matlab/GetAllPosteriorDraws.m @@ -1,91 +1,91 @@ -function Draws = GetAllPosteriorDraws(column, FirstMhFile, FirstLine, TotalNumberOfMhFile, NumberOfDraws, blck) - -% function Draws = GetAllPosteriorDraws(column,FirstMhFile,FirstLine,TotalNumberOfMhFile,NumberOfDraws) -% Gets all posterior draws -% -% INPUTS -% column: column -% FirstMhFile: first mh file -% FirstLine: first line -% TotalNumberOfMhFile: total number of mh file -% NumberOfDraws: number of draws - -% OUTPUTS -% Draws: draws from posterior distribution -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2005-2008 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 <http://www.gnu.org/licenses/>. - -global M_ options_ - -nblck = options_.mh_nblck; - -iline = FirstLine; -linee = 1; -DirectoryName = CheckPath('metropolis'); - -if nblck>1 && nargin<6 - Draws = zeros(NumberOfDraws*nblck,1); - iline0=iline; - if column>0 - for blck = 1:nblck - iline=iline0; - for file = FirstMhFile:TotalNumberOfMhFile - load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'x2') - NumberOfLines = size(x2(iline:end,:),1); - Draws(linee:linee+NumberOfLines-1) = x2(iline:end,column); - linee = linee+NumberOfLines; - iline = 1; - end - end - else - for blck = 1:nblck - iline=iline0; - for file = FirstMhFile:TotalNumberOfMhFile - load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'logpo2') - NumberOfLines = size(logpo2(iline:end),1); - Draws(linee:linee+NumberOfLines-1) = logpo2(iline:end); - linee = linee+NumberOfLines; - iline = 1; - end - end - end -else - if nblck==1 - blck=1; - end - if column>0 - for file = FirstMhFile:TotalNumberOfMhFile - load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'x2') - NumberOfLines = size(x2(iline:end,:),1); - Draws(linee:linee+NumberOfLines-1) = x2(iline:end,column); - linee = linee+NumberOfLines; - iline = 1; - end - else - for file = FirstMhFile:TotalNumberOfMhFile - load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'logpo2') - NumberOfLines = size(logpo2(iline:end,:),1); - Draws(linee:linee+NumberOfLines-1) = logpo2(iline:end); - linee = linee+NumberOfLines; - iline = 1; - end - end +function Draws = GetAllPosteriorDraws(column, FirstMhFile, FirstLine, TotalNumberOfMhFile, NumberOfDraws, blck) + +% function Draws = GetAllPosteriorDraws(column,FirstMhFile,FirstLine,TotalNumberOfMhFile,NumberOfDraws) +% Gets all posterior draws +% +% INPUTS +% column: column +% FirstMhFile: first mh file +% FirstLine: first line +% TotalNumberOfMhFile: total number of mh file +% NumberOfDraws: number of draws + +% OUTPUTS +% Draws: draws from posterior distribution +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2005-2008 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 <http://www.gnu.org/licenses/>. + +global M_ options_ + +nblck = options_.mh_nblck; + +iline = FirstLine; +linee = 1; +DirectoryName = CheckPath('metropolis'); + +if nblck>1 && nargin<6 + Draws = zeros(NumberOfDraws*nblck,1); + iline0=iline; + if column>0 + for blck = 1:nblck + iline=iline0; + for file = FirstMhFile:TotalNumberOfMhFile + load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'x2') + NumberOfLines = size(x2(iline:end,:),1); + Draws(linee:linee+NumberOfLines-1) = x2(iline:end,column); + linee = linee+NumberOfLines; + iline = 1; + end + end + else + for blck = 1:nblck + iline=iline0; + for file = FirstMhFile:TotalNumberOfMhFile + load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'logpo2') + NumberOfLines = size(logpo2(iline:end),1); + Draws(linee:linee+NumberOfLines-1) = logpo2(iline:end); + linee = linee+NumberOfLines; + iline = 1; + end + end + end +else + if nblck==1 + blck=1; + end + if column>0 + for file = FirstMhFile:TotalNumberOfMhFile + load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'x2') + NumberOfLines = size(x2(iline:end,:),1); + Draws(linee:linee+NumberOfLines-1) = x2(iline:end,column); + linee = linee+NumberOfLines; + iline = 1; + end + else + for file = FirstMhFile:TotalNumberOfMhFile + load([DirectoryName '/' M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'logpo2') + NumberOfLines = size(logpo2(iline:end,:),1); + Draws(linee:linee+NumberOfLines-1) = logpo2(iline:end); + linee = linee+NumberOfLines; + iline = 1; + end + end end \ No newline at end of file diff --git a/matlab/GetOneDraw.m b/matlab/GetOneDraw.m index 199dd08923..08b43994e6 100644 --- a/matlab/GetOneDraw.m +++ b/matlab/GetOneDraw.m @@ -1,39 +1,39 @@ -function [xparams, logpost] = GetOneDraw(type) - -% function [xparams, logpost] = GetOneDraw(type) -% draws one row from metropolis -% -% INPUTS -% type: posterior -% prior -% -% OUTPUTS -% xparams: vector of estimated parameters (drawn from posterior distribution) -% logpost: log of the posterior density relative to this row -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2005-2008 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 <http://www.gnu.org/licenses/>. - - switch type - case 'posterior' - [xparams, logpost] = metropolis_draw(0); - case 'prior' - xparams = prior_draw(0); - end \ No newline at end of file +function [xparams, logpost] = GetOneDraw(type) + +% function [xparams, logpost] = GetOneDraw(type) +% draws one row from metropolis +% +% INPUTS +% type: posterior +% prior +% +% OUTPUTS +% xparams: vector of estimated parameters (drawn from posterior distribution) +% logpost: log of the posterior density relative to this row +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2005-2008 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 <http://www.gnu.org/licenses/>. + +switch type + case 'posterior' + [xparams, logpost] = metropolis_draw(0); + case 'prior' + xparams = prior_draw(0); +end \ No newline at end of file diff --git a/matlab/GetPosteriorParametersStatistics.m b/matlab/GetPosteriorParametersStatistics.m index 7ac1777081..d1398883df 100644 --- a/matlab/GetPosteriorParametersStatistics.m +++ b/matlab/GetPosteriorParametersStatistics.m @@ -307,57 +307,57 @@ end %% subfunctions: % function fid = TeXBegin(directory,fname,fnum,title) - TeXfile = [directory '/' fname '_Posterior_Mean_' int2str(fnum) '.TeX']; - fidTeX = fopen(TeXfile,'w'); - fprintf(fidTeX,'%% TeX-table generated by Dynare.\n'); - fprintf(fidTeX,['%% RESULTS FROM METROPOLIS HASTINGS (' title ')\n']); - fprintf(fidTeX,['%% ' datestr(now,0)]); - fprintf(fidTeX,' \n'); - fprintf(fidTeX,' \n'); - fprintf(fidTeX,'\\begin{table}\n'); - fprintf(fidTeX,'\\centering\n'); - fprintf(fidTeX,'\\begin{tabular}{l|lcccccc} \n'); - fprintf(fidTeX,'\\hline\\hline \\\\ \n'); - fprintf(fidTeX,[' & Prior distribution & Prior mean & Prior ' ... - 's.d. & Posterior mean & Posterior s.d. & HPD inf & HPD sup\\\\ \n']); - fprintf(fidTeX,'\\hline \\\\ \n'); - fid = fidTeX; +TeXfile = [directory '/' fname '_Posterior_Mean_' int2str(fnum) '.TeX']; +fidTeX = fopen(TeXfile,'w'); +fprintf(fidTeX,'%% TeX-table generated by Dynare.\n'); +fprintf(fidTeX,['%% RESULTS FROM METROPOLIS HASTINGS (' title ')\n']); +fprintf(fidTeX,['%% ' datestr(now,0)]); +fprintf(fidTeX,' \n'); +fprintf(fidTeX,' \n'); +fprintf(fidTeX,'\\begin{table}\n'); +fprintf(fidTeX,'\\centering\n'); +fprintf(fidTeX,'\\begin{tabular}{l|lcccccc} \n'); +fprintf(fidTeX,'\\hline\\hline \\\\ \n'); +fprintf(fidTeX,[' & Prior distribution & Prior mean & Prior ' ... + 's.d. & Posterior mean & Posterior s.d. & HPD inf & HPD sup\\\\ \n']); +fprintf(fidTeX,'\\hline \\\\ \n'); +fid = fidTeX; + - function TeXCore(fid,name,shape,priormean,priorstd,postmean,poststd,hpd) - fprintf(fid,['$%s$ & %s & %7.3f & %6.4f & %7.3f& %6.4f & %7.4f & %7.4f \\\\ \n'],... - name,... - shape,... - priormean,... - priorstd,... - postmean,... - poststd,... - hpd(1),... - hpd(2)); - +fprintf(fid,['$%s$ & %s & %7.3f & %6.4f & %7.3f& %6.4f & %7.4f & %7.4f \\\\ \n'],... + name,... + shape,... + priormean,... + priorstd,... + postmean,... + poststd,... + hpd(1),... + hpd(2)); + function TeXEnd(fid,fnum,title) - fprintf(fid,'\\hline\\hline \n'); - fprintf(fid,'\\end{tabular}\n '); - fprintf(fid,['\\caption{Results from Metropolis-Hastings (' title ')}\n ']); - fprintf(fid,['\\label{Table:MHPosterior:' int2str(fnum) '}\n']); - fprintf(fid,'\\end{table}\n'); - fprintf(fid,'%% End of TeX file.\n'); - fclose(fid); - - +fprintf(fid,'\\hline\\hline \n'); +fprintf(fid,'\\end{tabular}\n '); +fprintf(fid,['\\caption{Results from Metropolis-Hastings (' title ')}\n ']); +fprintf(fid,['\\label{Table:MHPosterior:' int2str(fnum) '}\n']); +fprintf(fid,'\\end{table}\n'); +fprintf(fid,'%% End of TeX file.\n'); +fclose(fid); + + function oo = Filloo(oo,name,type,postmean,hpdinterval,postmedian,postvar,postdecile,density) - eval(['oo.posterior_mean.' type '.' name ' = postmean;']); - eval(['oo.posterior_hpdinf.' type '.' name ' = hpdinterval(1);']); - eval(['oo.posterior_hpdsup.' type '.' name ' = hpdinterval(2);']); - eval(['oo.posterior_median.' type '.' name ' = postmedian;']); - eval(['oo.posterior_variance.' type '.' name ' = postvar;']); - eval(['oo.posterior_deciles.' type '.' name ' = postdecile;']); - eval(['oo.posterior_density.' type '.' name ' = density;']); - +eval(['oo.posterior_mean.' type '.' name ' = postmean;']); +eval(['oo.posterior_hpdinf.' type '.' name ' = hpdinterval(1);']); +eval(['oo.posterior_hpdsup.' type '.' name ' = hpdinterval(2);']); +eval(['oo.posterior_median.' type '.' name ' = postmedian;']); +eval(['oo.posterior_variance.' type '.' name ' = postvar;']); +eval(['oo.posterior_deciles.' type '.' name ' = postdecile;']); +eval(['oo.posterior_density.' type '.' name ' = density;']); + function [post_mean,hpd_interval,post_var] = Extractoo(oo,name,type) - hpd_interval = zeros(2,1); - eval(['post_mean = oo.posterior_mean.' type '.' name ';']); - eval(['hpd_interval(1) = oo.posterior_hpdinf.' type '.' name ';']); - eval(['hpd_interval(2) = oo.posterior_hpdsup.' type '.' name ';']); - eval(['post_var = oo.posterior_variance.' type '.' name ';']); \ No newline at end of file +hpd_interval = zeros(2,1); +eval(['post_mean = oo.posterior_mean.' type '.' name ';']); +eval(['hpd_interval(1) = oo.posterior_hpdinf.' type '.' name ';']); +eval(['hpd_interval(2) = oo.posterior_hpdsup.' type '.' name ';']); +eval(['post_var = oo.posterior_variance.' type '.' name ';']); \ No newline at end of file diff --git a/matlab/MakeAllFigures.m b/matlab/MakeAllFigures.m index c1ebb7ccd4..e5317bab8f 100644 --- a/matlab/MakeAllFigures.m +++ b/matlab/MakeAllFigures.m @@ -1,169 +1,169 @@ -function MakeAllFigures(NumberOfPlots,Caption,FigureProperties,Info) - -% Copyright (C) 2005 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 <http://www.gnu.org/licenses/>. - -global M_ options_ - -FigHandle = figure('Name',FigureProperties.Name); - -NAMES = cell(NumberOfPlots,1); -if options_.TeX - TeXNAMES = cell(NumberOfPlots,1); -end - -if NumberOfPlots == 9 - nr = 3; - nc = 3; -elseif NumberOfPlots == 8 - nr = 3; - nc = 3; -elseif NumberOfPlots == 7 - nr = 3; - nc = 3; -elseif NumberOfPlots == 6 - nr = 2; - nc = 3; -elseif NumberOfPlots == 5 - nr = 3; - nc = 2; -elseif NumberOfPlots == 4 - nr = 2; - nc = 2; -elseif NumberOfPlots == 3 - nr = 2; - nc = 2; -elseif NumberOfPlots == 2 - nr = 1; - nc = 2; -elseif NumberOfPlots == 1 - nr = 1; - nc = 1; -end - -for plt = 1:NumberOfPlots - eval(['NumberOfCurves = Info.Box' int2str(plt) '.Number;']) - NumberOfObservations = zeros(2,1); - x = cell(NumberOfCurves,1); - y = cell(NumberOfCurves,1); - PltType = cell(NumberofCurves,1); - top = NaN(NumberOfCurves,1); - bottom = NaN(NumberOfCurves,1); - binf = NaN(NumberOfCurves,1); - bsup = NaN(NumberOfCurves,1); - for curve = 1:NumberOfCurves - eval(['x{' curve '} = Info.Box' int2str(plt) '.Curve' int2str(curve) '.xdata;']) - eval(['y{' curve '} = Info.Box' int2str(plt) '.Curve' int2str(curve) '.ydata;']) - eval(['name = Info.Box' int2str(plt) '.Curve' int2str(curve) '.variablename;']) - eval(['PltType{' curve '} = Info.Box' int2str(plt) '.Curve' int2str(curve) '.type']); - if length(x{curve})-length(y{curve}) - disp('MakeFigure :: The number of observations in x doesn''t match with ') - disp(['the number of observation in y for ' name ]) - return - end - if Info.PlotProperties.CutTop - top(curve) = max(y{curve}); - else Info.PlotProperties.CutBottom - bottom(curve) = min(y{curve}); - end - binf(curve) = min(x{curve}); - bsup(curve) = max(x{curve}); - end - ymax = max(top); - ymin = min(bottom); - xmin = min(binf); - xmax = max(bsup); - if isnan(ymin(plt)) - ymin = 0; - end - eval(['NAMES{' int2str(plt) '} = Info.Box' int2str(plt) '.name;']) - if options_.TeX - eval(['TeXNAMES{' int2str(plt) '} = Info.Box' int2str(plt) '.texname;']) - end - subplot(nr,nc,plt) - hold on - for curve = 1:NumberOfCurves - hh = plot(x{curve},y{curve}); - if strcmpi(PltType{curve},'PriorDensity') - set(hh,'Color',[0.7 0.7 0.7],'LineStyle','-','LineWidth',2) - % - % - elseif strcmpi(PltType{curve},'DensityEstimate') - set(hh,'Color','k','LineStyle','-','LineWidth',2) - % - % - elseif strcmpi(PltType{curve},'ModeEstimate') - set(hh,'Color','g','LineStyle','--','LineWidth',2) - % - % - elseif strcmpi(PltType{curve},'SmoothVariable') - set(hh,'Color','k','LineStyle','-','LineWidth',2) - % - % - elseif strcmpi(PltType{curve},'Deciles') - set(hh,'Color','g','LineStyle','-','LineWidth',1) - % - % - elseif strcmpi(PltType{curve},'Forecasts') - set(hh,'Color','','LineStyle','-','LineWidth',2) - % - % - elseif strcmpi(PltType{curve},'ForecastsHPD') - set(hh,'Color','k','LineStyle','-','LineWidth',1) - % - % - elseif strcmpi(PltType{curve},'ForecastsDeciles') - set(hh,'Color','g','LineStyle','-','LineWidth',1) - % - % - elseif strcmpi(PltType{curve},'DiagnosticWithin') - set(hh,'Color','b','LineStyle','-','LineWidth',2) - % - % - elseif strcmpi(PltType{curve},'DiagnosticPooled') - set(hh,'Color','r','LineStyle','-','LineWidth',2) - % - % - end - end - axis([xmin xmax ymin ymax]) - title(NAMES{plt}) - drawnow - hold off -end - -if Info.SaveFormat.Eps - if isempty(Info.SaveFormat.Name) - eval(['print -depsc2 ' M_.fname Info.SaveFormat.GenericName int2str(Info.SaveFormat.Number) '.eps']); - else - eval(['print -depsc2 ' M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name '.eps']); - end -end -if Info.SaveFormat.Pdf && ~exist('OCTAVE_VERSION') - if isempty(Info.SaveFormat.Name) - eval(['print -dpdf ' M_.fname Info.SaveFormat.GenericName int2str(Info.SaveFormat.Number)]); - else - eval(['print -dpdf ' M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name]); - end -end -if Info.SaveFormat.Fig && ~exist('OCTAVE_VERSION') - if isempty(Info.SaveFormat.Name) - saveas(FigHandle,[M_.fname Info.SaveFormat.GenericName int2str(Info.SaveFormat.Number) '.fig']); - else - saveas(FigHandle,[M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name '.fig']); - end +function MakeAllFigures(NumberOfPlots,Caption,FigureProperties,Info) + +% Copyright (C) 2005 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 <http://www.gnu.org/licenses/>. + +global M_ options_ + +FigHandle = figure('Name',FigureProperties.Name); + +NAMES = cell(NumberOfPlots,1); +if options_.TeX + TeXNAMES = cell(NumberOfPlots,1); +end + +if NumberOfPlots == 9 + nr = 3; + nc = 3; +elseif NumberOfPlots == 8 + nr = 3; + nc = 3; +elseif NumberOfPlots == 7 + nr = 3; + nc = 3; +elseif NumberOfPlots == 6 + nr = 2; + nc = 3; +elseif NumberOfPlots == 5 + nr = 3; + nc = 2; +elseif NumberOfPlots == 4 + nr = 2; + nc = 2; +elseif NumberOfPlots == 3 + nr = 2; + nc = 2; +elseif NumberOfPlots == 2 + nr = 1; + nc = 2; +elseif NumberOfPlots == 1 + nr = 1; + nc = 1; +end + +for plt = 1:NumberOfPlots + eval(['NumberOfCurves = Info.Box' int2str(plt) '.Number;']) + NumberOfObservations = zeros(2,1); + x = cell(NumberOfCurves,1); + y = cell(NumberOfCurves,1); + PltType = cell(NumberofCurves,1); + top = NaN(NumberOfCurves,1); + bottom = NaN(NumberOfCurves,1); + binf = NaN(NumberOfCurves,1); + bsup = NaN(NumberOfCurves,1); + for curve = 1:NumberOfCurves + eval(['x{' curve '} = Info.Box' int2str(plt) '.Curve' int2str(curve) '.xdata;']) + eval(['y{' curve '} = Info.Box' int2str(plt) '.Curve' int2str(curve) '.ydata;']) + eval(['name = Info.Box' int2str(plt) '.Curve' int2str(curve) '.variablename;']) + eval(['PltType{' curve '} = Info.Box' int2str(plt) '.Curve' int2str(curve) '.type']); + if length(x{curve})-length(y{curve}) + disp('MakeFigure :: The number of observations in x doesn''t match with ') + disp(['the number of observation in y for ' name ]) + return + end + if Info.PlotProperties.CutTop + top(curve) = max(y{curve}); + else Info.PlotProperties.CutBottom + bottom(curve) = min(y{curve}); + end + binf(curve) = min(x{curve}); + bsup(curve) = max(x{curve}); + end + ymax = max(top); + ymin = min(bottom); + xmin = min(binf); + xmax = max(bsup); + if isnan(ymin(plt)) + ymin = 0; + end + eval(['NAMES{' int2str(plt) '} = Info.Box' int2str(plt) '.name;']) + if options_.TeX + eval(['TeXNAMES{' int2str(plt) '} = Info.Box' int2str(plt) '.texname;']) + end + subplot(nr,nc,plt) + hold on + for curve = 1:NumberOfCurves + hh = plot(x{curve},y{curve}); + if strcmpi(PltType{curve},'PriorDensity') + set(hh,'Color',[0.7 0.7 0.7],'LineStyle','-','LineWidth',2) + % + % + elseif strcmpi(PltType{curve},'DensityEstimate') + set(hh,'Color','k','LineStyle','-','LineWidth',2) + % + % + elseif strcmpi(PltType{curve},'ModeEstimate') + set(hh,'Color','g','LineStyle','--','LineWidth',2) + % + % + elseif strcmpi(PltType{curve},'SmoothVariable') + set(hh,'Color','k','LineStyle','-','LineWidth',2) + % + % + elseif strcmpi(PltType{curve},'Deciles') + set(hh,'Color','g','LineStyle','-','LineWidth',1) + % + % + elseif strcmpi(PltType{curve},'Forecasts') + set(hh,'Color','','LineStyle','-','LineWidth',2) + % + % + elseif strcmpi(PltType{curve},'ForecastsHPD') + set(hh,'Color','k','LineStyle','-','LineWidth',1) + % + % + elseif strcmpi(PltType{curve},'ForecastsDeciles') + set(hh,'Color','g','LineStyle','-','LineWidth',1) + % + % + elseif strcmpi(PltType{curve},'DiagnosticWithin') + set(hh,'Color','b','LineStyle','-','LineWidth',2) + % + % + elseif strcmpi(PltType{curve},'DiagnosticPooled') + set(hh,'Color','r','LineStyle','-','LineWidth',2) + % + % + end + end + axis([xmin xmax ymin ymax]) + title(NAMES{plt}) + drawnow + hold off +end + +if Info.SaveFormat.Eps + if isempty(Info.SaveFormat.Name) + eval(['print -depsc2 ' M_.fname Info.SaveFormat.GenericName int2str(Info.SaveFormat.Number) '.eps']); + else + eval(['print -depsc2 ' M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name '.eps']); + end +end +if Info.SaveFormat.Pdf && ~exist('OCTAVE_VERSION') + if isempty(Info.SaveFormat.Name) + eval(['print -dpdf ' M_.fname Info.SaveFormat.GenericName int2str(Info.SaveFormat.Number)]); + else + eval(['print -dpdf ' M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name]); + end +end +if Info.SaveFormat.Fig && ~exist('OCTAVE_VERSION') + if isempty(Info.SaveFormat.Name) + saveas(FigHandle,[M_.fname Info.SaveFormat.GenericName int2str(Info.SaveFormat.Number) '.fig']); + else + saveas(FigHandle,[M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name '.fig']); + end end \ No newline at end of file diff --git a/matlab/McMCDiagnostics_core.m b/matlab/McMCDiagnostics_core.m index 6f377a0f43..097700c104 100644 --- a/matlab/McMCDiagnostics_core.m +++ b/matlab/McMCDiagnostics_core.m @@ -1,94 +1,94 @@ -function myoutput = McMCDiagnostics_core(myinputs,fpar,npar,whoiam, ThisMatlab) -% Core functionality for MCMC Diagnostics, which can be parallelized - -% Copyright (C) 2005-2009 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 <http://www.gnu.org/licenses/>. - -if nargin<4, - whoiam=0; -end -struct2local(myinputs); - -if ~exist('MhDirectoryName'), - MhDirectoryName = CheckPath('metropolis'); -end - -ALPHA = 0.2; % increase too much with the number of simulations. -tmp = zeros(NumberOfDraws*nblck,3); -UDIAG = zeros(NumberOfLines,6,npar-fpar+1); - -if whoiam - waitbarString = ['Please wait... McMCDiagnostics (' int2str(fpar) 'of' int2str(npar) ')...']; - if Parallel(ThisMatlab).Local, - waitbarTitle=['Local ']; - else - waitbarTitle=[Parallel(ThisMatlab).PcName]; - end - fMessageStatus(0,whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab), MasterName, DyMo); -end -for j=fpar:npar, - fprintf(' Parameter %d... ',j); - for b = 1:nblck - startline = 0; - for n = 1:NumberOfMcFilesPerBlock - %load([MhDirectoryName '/' mcfiles(n,1,b).name],'x2'); - load([MhDirectoryName '/' M_.fname '_mh',int2str(n),'_blck' int2str(b) ... - '.mat'],'x2'); - nx2 = size(x2,1); - tmp((b-1)*NumberOfDraws+startline+(1:nx2),1) = x2(:,j); - % clear x2; - startline = startline + nx2; - end -% $$$ %load([MhDirectoryName '/' mcfiles(NumberOfMcFilesPerBlock,1,b).name],'x2'); -% $$$ load([MhDirectoryName '/' M_.fname '_mh',int2str(NumberOfMcFilesPerBlock),'_blck' int2str(b) '.mat'],'x2'); -% $$$ tmp((b-1)*NumberOfDraws+startline+1:(b-1)*NumberOfDraws+MAX_nruns*(LastFileNumber-1)+LastLineNumber,1) = x2(:,j); -% $$$ clear x2; -% $$$ startline = startline + LastLineNumber; - end - tmp(:,2) = kron(transpose(1:nblck),ones(NumberOfDraws,1)); - tmp(:,3) = kron(ones(nblck,1),time'); - tmp = sortrows(tmp,1); - ligne = 0; - for iter = Origin:StepSize:NumberOfDraws - ligne = ligne+1; - linea = ceil(0.5*iter); - n = iter-linea+1; - cinf = round(n*ALPHA/2); - csup = round(n*(1-ALPHA/2)); - CINF = round(nblck*n*ALPHA/2); - CSUP = round(nblck*n*(1-ALPHA/2)); - temp = tmp(find((tmp(:,3)>=linea) & (tmp(:,3)<=iter)),1:2); - UDIAG(ligne,1,j-fpar+1) = temp(CSUP,1)-temp(CINF,1); - moyenne = mean(temp(:,1));%% Pooled mean. - UDIAG(ligne,3,j-fpar+1) = sum((temp(:,1)-moyenne).^2)/(nblck*n-1); - UDIAG(ligne,5,j-fpar+1) = sum(abs(temp(:,1)-moyenne).^3)/(nblck*n-1); - for i=1:nblck - pmet = temp(find(temp(:,2)==i)); - UDIAG(ligne,2,j-fpar+1) = UDIAG(ligne,2,j-fpar+1) + pmet(csup,1)-pmet(cinf,1); - moyenne = mean(pmet,1); %% Within mean. - UDIAG(ligne,4,j-fpar+1) = UDIAG(ligne,4,j-fpar+1) + sum((pmet(:,1)-moyenne).^2)/(n-1); - UDIAG(ligne,6,j-fpar+1) = UDIAG(ligne,6,j-fpar+1) + sum(abs(pmet(:,1)-moyenne).^3)/(n-1); - end - end - fprintf('Done! \n'); - if whoiam, - waitbarString = [ 'Parameter ' int2str(j) '/' int2str(npar) ' done.']; - fMessageStatus((j-fpar+1)/(npar-fpar+1),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab), MasterName, DyMo) - end -end - +function myoutput = McMCDiagnostics_core(myinputs,fpar,npar,whoiam, ThisMatlab) +% Core functionality for MCMC Diagnostics, which can be parallelized + +% Copyright (C) 2005-2009 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 <http://www.gnu.org/licenses/>. + +if nargin<4, + whoiam=0; +end +struct2local(myinputs); + +if ~exist('MhDirectoryName'), + MhDirectoryName = CheckPath('metropolis'); +end + +ALPHA = 0.2; % increase too much with the number of simulations. +tmp = zeros(NumberOfDraws*nblck,3); +UDIAG = zeros(NumberOfLines,6,npar-fpar+1); + +if whoiam + waitbarString = ['Please wait... McMCDiagnostics (' int2str(fpar) 'of' int2str(npar) ')...']; + if Parallel(ThisMatlab).Local, + waitbarTitle=['Local ']; + else + waitbarTitle=[Parallel(ThisMatlab).PcName]; + end + fMessageStatus(0,whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab), MasterName, DyMo); +end +for j=fpar:npar, + fprintf(' Parameter %d... ',j); + for b = 1:nblck + startline = 0; + for n = 1:NumberOfMcFilesPerBlock + %load([MhDirectoryName '/' mcfiles(n,1,b).name],'x2'); + load([MhDirectoryName '/' M_.fname '_mh',int2str(n),'_blck' int2str(b) ... + '.mat'],'x2'); + nx2 = size(x2,1); + tmp((b-1)*NumberOfDraws+startline+(1:nx2),1) = x2(:,j); + % clear x2; + startline = startline + nx2; + end +% $$$ %load([MhDirectoryName '/' mcfiles(NumberOfMcFilesPerBlock,1,b).name],'x2'); +% $$$ load([MhDirectoryName '/' M_.fname '_mh',int2str(NumberOfMcFilesPerBlock),'_blck' int2str(b) '.mat'],'x2'); +% $$$ tmp((b-1)*NumberOfDraws+startline+1:(b-1)*NumberOfDraws+MAX_nruns*(LastFileNumber-1)+LastLineNumber,1) = x2(:,j); +% $$$ clear x2; +% $$$ startline = startline + LastLineNumber; + end + tmp(:,2) = kron(transpose(1:nblck),ones(NumberOfDraws,1)); + tmp(:,3) = kron(ones(nblck,1),time'); + tmp = sortrows(tmp,1); + ligne = 0; + for iter = Origin:StepSize:NumberOfDraws + ligne = ligne+1; + linea = ceil(0.5*iter); + n = iter-linea+1; + cinf = round(n*ALPHA/2); + csup = round(n*(1-ALPHA/2)); + CINF = round(nblck*n*ALPHA/2); + CSUP = round(nblck*n*(1-ALPHA/2)); + temp = tmp(find((tmp(:,3)>=linea) & (tmp(:,3)<=iter)),1:2); + UDIAG(ligne,1,j-fpar+1) = temp(CSUP,1)-temp(CINF,1); + moyenne = mean(temp(:,1));%% Pooled mean. + UDIAG(ligne,3,j-fpar+1) = sum((temp(:,1)-moyenne).^2)/(nblck*n-1); + UDIAG(ligne,5,j-fpar+1) = sum(abs(temp(:,1)-moyenne).^3)/(nblck*n-1); + for i=1:nblck + pmet = temp(find(temp(:,2)==i)); + UDIAG(ligne,2,j-fpar+1) = UDIAG(ligne,2,j-fpar+1) + pmet(csup,1)-pmet(cinf,1); + moyenne = mean(pmet,1); %% Within mean. + UDIAG(ligne,4,j-fpar+1) = UDIAG(ligne,4,j-fpar+1) + sum((pmet(:,1)-moyenne).^2)/(n-1); + UDIAG(ligne,6,j-fpar+1) = UDIAG(ligne,6,j-fpar+1) + sum(abs(pmet(:,1)-moyenne).^3)/(n-1); + end + end + fprintf('Done! \n'); + if whoiam, + waitbarString = [ 'Parameter ' int2str(j) '/' int2str(npar) ' done.']; + fMessageStatus((j-fpar+1)/(npar-fpar+1),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab), MasterName, DyMo) + end +end + myoutput.UDIAG = UDIAG; \ No newline at end of file diff --git a/matlab/PlotPosteriorDistributions.m b/matlab/PlotPosteriorDistributions.m index be3136c57d..bbcef6c210 100644 --- a/matlab/PlotPosteriorDistributions.m +++ b/matlab/PlotPosteriorDistributions.m @@ -1,189 +1,189 @@ -function oo_ = PlotPosteriorDistributions(estim_params_, M_, options_, bayestopt_, oo_) - -% function PlotPosteriorDistributions() -% plots posterior distributions -% -% INPUTS -% estim_params_ [structure] -% M_ [structure] -% options_ [structure] -% bayestopt_ [structure] -% oo_ [structure] -% -% OUTPUTS -% oo_ [structure] -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2005-2008 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 <http://www.gnu.org/licenses/>. - -OutputDirectoryName = CheckPath('Output'); - -TeX = options_.TeX; -nblck = options_.mh_nblck; -nvx = estim_params_.nvx; -nvn = estim_params_.nvn; -ncx = estim_params_.ncx; -ncn = estim_params_.ncn; -np = estim_params_.np ; -npar = nvx+nvn+ncx+ncn+np; - -MaxNumberOfPlotPerFigure = 9;% The square root must be an integer! -nn = sqrt(MaxNumberOfPlotPerFigure); - -figurename = 'Priors and posteriors'; - -if TeX - fidTeX = fopen([OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors.TeX'],'w'); - fprintf(fidTeX,'%% TeX eps-loader file generated by PlotPosteriorDistributions.m (Dynare).\n'); - fprintf(fidTeX,['%% ' datestr(now,0) '\n']); - fprintf(fidTeX,' \n'); -end - -figunumber = 0; -subplotnum = 0; - -for i=1:npar - subplotnum = subplotnum+1; - if subplotnum == 1 - figunumber = figunumber+1; - if options_.nograph - hfig = figure('Name',figurename,'Visible','off'); - else - hfig = figure('Name',figurename); - end - end - if subplotnum == 1 - if TeX - TeXNAMES = []; - end - NAMES = []; - end - [nam,texnam] = get_the_name(i,TeX); - NAMES = strvcat(NAMES,nam); - if TeX - TeXNAMES = strvcat(TeXNAMES,texnam); - end - [x2,f2,abscissa,dens,binf2,bsup2] = draw_prior_density(i,bayestopt_); - top2 = max(f2); - if i <= nvx - name = deblank(M_.exo_names(estim_params_.var_exo(i,1),:)); - eval(['x1 = oo_.posterior_density.shocks_std.' name '(:,1);']) - eval(['f1 = oo_.posterior_density.shocks_std.' name '(:,2);']) - eval(['oo_.prior_density.shocks_std.' name '(:,1) = x2;']) - eval(['oo_.prior_density.shocks_std.' name '(:,2) = f2;']) - if options_.posterior_mode_estimation - eval(['pmod = oo_.posterior_mode.shocks_std.' name ';']) - end - elseif i <= nvx+nvn - name = deblank(options_.varobs(estim_params_.var_endo(i-nvx,1),:)); - eval(['x1 = oo_.posterior_density.measurement_errors_std.' name '(:,1);']) - eval(['f1 = oo_.posterior_density.measurement_errors_std.' name '(:,2);']) - eval(['oo_.prior_density.mearsurement_errors_std.' name '(:,1) = x2;']) - eval(['oo_.prior_density.measurement_errors_std.' name '(:,2) = f2;']) - if options_.posterior_mode_estimation - eval(['pmod = oo_.posterior_mode.measurement_errors_std.' name ';']) - end - elseif i <= nvx+nvn+ncx - j = i - (nvx+nvn); - k1 = estim_params_.corrx(j,1); - k2 = estim_params_.corrx(j,2); - name = [deblank(M_.exo_names(k1,:)) '_' deblank(M_.exo_names(k2,:))]; - eval(['x1 = oo_.posterior_density.shocks_corr.' name '(:,1);']) - eval(['f1 = oo_.posterior_density.shocks_corr.' name '(:,2);']) - eval(['oo_.prior_density.shocks_corr.' name '(:,1) = x2;']) - eval(['oo_.prior_density.shocks_corr.' name '(:,2) = f2;']) - if options_.posterior_mode_estimation - eval(['pmod = oo_.posterior_mode.shocks_corr.' name ';']) - end - elseif i <= nvx+nvn+ncx+ncn - j = i - (nvx+nvn+ncx); - k1 = estim_params_.corrn(j,1); - k2 = estim_params_.corrn(j,2); - name = [deblank(M_.endo_names(k1,:)) '_' deblank(M_.endo_names(k2,:))]; - eval(['x1 = oo_.posterior_density.measurement_errors_corr.' name '(:,1);']) - eval(['f1 = oo_.posterior_density.measurement_errors_corr.' name '(:,2);']) - eval(['oo_.prior_density.mearsurement_errors_corr.' name '(:,1) = x2;']) - eval(['oo_.prior_density.measurement_errors_corr.' name '(:,2) = f2;']) - if options_.posterior_mode_estimation - eval(['pmod = oo_.posterior_mode.measurement_errors_corr.' name ';']) - end - else - j = i - (nvx+nvn+ncx+ncn); - name = deblank(M_.param_names(estim_params_.param_vals(j,1),:)); - eval(['x1 = oo_.posterior_density.parameters.' name '(:,1);']) - eval(['f1 = oo_.posterior_density.parameters.' name '(:,2);']) - eval(['oo_.prior_density.parameters.' name '(:,1) = x2;']) - eval(['oo_.prior_density.parameters.' name '(:,2) = f2;']) - if options_.posterior_mode_estimation - eval(['pmod = oo_.posterior_mode.parameters.' name ';']) - end - end - top1 = max(f1); - top0 = max([top1;top2]); - binf1 = x1(1); - bsup1 = x1(end); - borneinf = min(binf1,binf2); - bornesup = max(bsup1,bsup2); - subplot(nn,nn,subplotnum) - hh = plot(x2,f2,'-k','linewidth',2); - set(hh,'color',[0.7 0.7 0.7]); - hold on; - plot(x1,f1,'-k','linewidth',2); - if options_.posterior_mode_estimation - plot( [pmod pmod], [0.0 1.1*top0], '--g', 'linewidth', 2); - end - box on; - axis([borneinf bornesup 0 1.1*top0]); - title(nam,'Interpreter','none'); - hold off; - drawnow - if subplotnum == MaxNumberOfPlotPerFigure | i == npar; - eval(['print -depsc2 ' OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber) '.eps']); - if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber)]); - end - if options_.nograph, - set(hfig,'Visible','on'); - end - if ~exist('OCTAVE_VERSION') - saveas(hfig,[OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber) '.fig']); - end - if TeX - fprintf(fidTeX,'\\begin{figure}[H]\n'); - for j = 1:size(NAMES,1) - fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(j,:)),deblank(TeXNAMES(j,:))); - end - fprintf(fidTeX,'\\centering\n'); - fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_PriorsAndPosteriors%s}\n',M_.fname,int2str(figunumber)); - fprintf(fidTeX,'\\caption{Priors and posteriors.}'); - fprintf(fidTeX,'\\label{Fig:PriorsAndPosteriors:%s}\n',int2str(figunumber)); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,' \n'); - if i == npar - fprintf(fidTeX,'%% End of TeX file.\n'); - fclose(fidTeX); - end - end - if options_.nograph, - close(hfig), - end - subplotnum = 0; - end +function oo_ = PlotPosteriorDistributions(estim_params_, M_, options_, bayestopt_, oo_) + +% function PlotPosteriorDistributions() +% plots posterior distributions +% +% INPUTS +% estim_params_ [structure] +% M_ [structure] +% options_ [structure] +% bayestopt_ [structure] +% oo_ [structure] +% +% OUTPUTS +% oo_ [structure] +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2005-2008 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 <http://www.gnu.org/licenses/>. + +OutputDirectoryName = CheckPath('Output'); + +TeX = options_.TeX; +nblck = options_.mh_nblck; +nvx = estim_params_.nvx; +nvn = estim_params_.nvn; +ncx = estim_params_.ncx; +ncn = estim_params_.ncn; +np = estim_params_.np ; +npar = nvx+nvn+ncx+ncn+np; + +MaxNumberOfPlotPerFigure = 9;% The square root must be an integer! +nn = sqrt(MaxNumberOfPlotPerFigure); + +figurename = 'Priors and posteriors'; + +if TeX + fidTeX = fopen([OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors.TeX'],'w'); + fprintf(fidTeX,'%% TeX eps-loader file generated by PlotPosteriorDistributions.m (Dynare).\n'); + fprintf(fidTeX,['%% ' datestr(now,0) '\n']); + fprintf(fidTeX,' \n'); +end + +figunumber = 0; +subplotnum = 0; + +for i=1:npar + subplotnum = subplotnum+1; + if subplotnum == 1 + figunumber = figunumber+1; + if options_.nograph + hfig = figure('Name',figurename,'Visible','off'); + else + hfig = figure('Name',figurename); + end + end + if subplotnum == 1 + if TeX + TeXNAMES = []; + end + NAMES = []; + end + [nam,texnam] = get_the_name(i,TeX); + NAMES = strvcat(NAMES,nam); + if TeX + TeXNAMES = strvcat(TeXNAMES,texnam); + end + [x2,f2,abscissa,dens,binf2,bsup2] = draw_prior_density(i,bayestopt_); + top2 = max(f2); + if i <= nvx + name = deblank(M_.exo_names(estim_params_.var_exo(i,1),:)); + eval(['x1 = oo_.posterior_density.shocks_std.' name '(:,1);']) + eval(['f1 = oo_.posterior_density.shocks_std.' name '(:,2);']) + eval(['oo_.prior_density.shocks_std.' name '(:,1) = x2;']) + eval(['oo_.prior_density.shocks_std.' name '(:,2) = f2;']) + if options_.posterior_mode_estimation + eval(['pmod = oo_.posterior_mode.shocks_std.' name ';']) + end + elseif i <= nvx+nvn + name = deblank(options_.varobs(estim_params_.var_endo(i-nvx,1),:)); + eval(['x1 = oo_.posterior_density.measurement_errors_std.' name '(:,1);']) + eval(['f1 = oo_.posterior_density.measurement_errors_std.' name '(:,2);']) + eval(['oo_.prior_density.mearsurement_errors_std.' name '(:,1) = x2;']) + eval(['oo_.prior_density.measurement_errors_std.' name '(:,2) = f2;']) + if options_.posterior_mode_estimation + eval(['pmod = oo_.posterior_mode.measurement_errors_std.' name ';']) + end + elseif i <= nvx+nvn+ncx + j = i - (nvx+nvn); + k1 = estim_params_.corrx(j,1); + k2 = estim_params_.corrx(j,2); + name = [deblank(M_.exo_names(k1,:)) '_' deblank(M_.exo_names(k2,:))]; + eval(['x1 = oo_.posterior_density.shocks_corr.' name '(:,1);']) + eval(['f1 = oo_.posterior_density.shocks_corr.' name '(:,2);']) + eval(['oo_.prior_density.shocks_corr.' name '(:,1) = x2;']) + eval(['oo_.prior_density.shocks_corr.' name '(:,2) = f2;']) + if options_.posterior_mode_estimation + eval(['pmod = oo_.posterior_mode.shocks_corr.' name ';']) + end + elseif i <= nvx+nvn+ncx+ncn + j = i - (nvx+nvn+ncx); + k1 = estim_params_.corrn(j,1); + k2 = estim_params_.corrn(j,2); + name = [deblank(M_.endo_names(k1,:)) '_' deblank(M_.endo_names(k2,:))]; + eval(['x1 = oo_.posterior_density.measurement_errors_corr.' name '(:,1);']) + eval(['f1 = oo_.posterior_density.measurement_errors_corr.' name '(:,2);']) + eval(['oo_.prior_density.mearsurement_errors_corr.' name '(:,1) = x2;']) + eval(['oo_.prior_density.measurement_errors_corr.' name '(:,2) = f2;']) + if options_.posterior_mode_estimation + eval(['pmod = oo_.posterior_mode.measurement_errors_corr.' name ';']) + end + else + j = i - (nvx+nvn+ncx+ncn); + name = deblank(M_.param_names(estim_params_.param_vals(j,1),:)); + eval(['x1 = oo_.posterior_density.parameters.' name '(:,1);']) + eval(['f1 = oo_.posterior_density.parameters.' name '(:,2);']) + eval(['oo_.prior_density.parameters.' name '(:,1) = x2;']) + eval(['oo_.prior_density.parameters.' name '(:,2) = f2;']) + if options_.posterior_mode_estimation + eval(['pmod = oo_.posterior_mode.parameters.' name ';']) + end + end + top1 = max(f1); + top0 = max([top1;top2]); + binf1 = x1(1); + bsup1 = x1(end); + borneinf = min(binf1,binf2); + bornesup = max(bsup1,bsup2); + subplot(nn,nn,subplotnum) + hh = plot(x2,f2,'-k','linewidth',2); + set(hh,'color',[0.7 0.7 0.7]); + hold on; + plot(x1,f1,'-k','linewidth',2); + if options_.posterior_mode_estimation + plot( [pmod pmod], [0.0 1.1*top0], '--g', 'linewidth', 2); + end + box on; + axis([borneinf bornesup 0 1.1*top0]); + title(nam,'Interpreter','none'); + hold off; + drawnow + if subplotnum == MaxNumberOfPlotPerFigure | i == npar; + eval(['print -depsc2 ' OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber) '.eps']); + if ~exist('OCTAVE_VERSION') + eval(['print -dpdf ' OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber)]); + end + if options_.nograph, + set(hfig,'Visible','on'); + end + if ~exist('OCTAVE_VERSION') + saveas(hfig,[OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber) '.fig']); + end + if TeX + fprintf(fidTeX,'\\begin{figure}[H]\n'); + for j = 1:size(NAMES,1) + fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(j,:)),deblank(TeXNAMES(j,:))); + end + fprintf(fidTeX,'\\centering\n'); + fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_PriorsAndPosteriors%s}\n',M_.fname,int2str(figunumber)); + fprintf(fidTeX,'\\caption{Priors and posteriors.}'); + fprintf(fidTeX,'\\label{Fig:PriorsAndPosteriors:%s}\n',int2str(figunumber)); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,' \n'); + if i == npar + fprintf(fidTeX,'%% End of TeX file.\n'); + fclose(fidTeX); + end + end + if options_.nograph, + close(hfig), + end + subplotnum = 0; + end end \ No newline at end of file diff --git a/matlab/PosteriorFilterSmootherAndForecast.m b/matlab/PosteriorFilterSmootherAndForecast.m index 5b7f5e31d4..421612eb2d 100644 --- a/matlab/PosteriorFilterSmootherAndForecast.m +++ b/matlab/PosteriorFilterSmootherAndForecast.m @@ -1,273 +1,273 @@ -function PosteriorFilterSmootherAndForecast(Y,gend, type,data_index) - -% function PosteriorFilterSmootherAndForecast(Y,gend, type) -% Computes posterior filter smoother and forecasts -% -% INPUTS -% Y: data -% gend: number of observations -% type: posterior -% prior -% gsa -% -% OUTPUTS -% none -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2005-2008 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 <http://www.gnu.org/licenses/>. - -global options_ estim_params_ oo_ M_ bayestopt_ - -nvx = estim_params_.nvx; -nvn = estim_params_.nvn; -ncx = estim_params_.ncx; -ncn = estim_params_.ncn; -np = estim_params_.np ; -npar = nvx+nvn+ncx+ncn+np; -offset = npar-np; -naK = length(options_.filter_step_ahead); -%% -MaxNumberOfPlotPerFigure = 4;% The square root must be an integer! -MaxNumberOfBytes=options_.MaxNumberOfBytes; -endo_nbr=M_.endo_nbr; -exo_nbr=M_.exo_nbr; -nvobs = size(options_.varobs,1); -nn = sqrt(MaxNumberOfPlotPerFigure); -iendo = 1:endo_nbr; -i_last_obs = gend+(1-M_.maximum_endo_lag:0); -horizon = options_.forecast; -maxlag = M_.maximum_endo_lag; -%% -CheckPath('Plots/'); -DirectoryName = CheckPath('metropolis'); -load([ DirectoryName '/' M_.fname '_mh_history.mat']) -FirstMhFile = record.KeepedDraws.FirstMhFile; -FirstLine = record.KeepedDraws.FirstLine; -TotalNumberOfMhFiles = sum(record.MhDraws(:,2)); LastMhFile = TotalNumberOfMhFiles; -TotalNumberOfMhDraws = sum(record.MhDraws(:,1)); -NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws); -clear record; -B = min(1200, round(0.25*NumberOfDraws)); -B = 200; -%% -MAX_nruns = min(B,ceil(options_.MaxNumberOfBytes/(npar+2)/8)); -MAX_nsmoo = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*gend)/8)); -MAX_ninno = min(B,ceil(MaxNumberOfBytes/(exo_nbr*gend)/8)); -MAX_nerro = min(B,ceil(MaxNumberOfBytes/(size(options_.varobs,1)*gend)/8)); -if naK - MAX_naK = min(B,ceil(MaxNumberOfBytes/(size(options_.varobs,1)* ... - length(options_.filter_step_ahead)*gend)/8)); -end -if horizon - MAX_nforc1 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/8)); - MAX_nforc2 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/ ... - 8)); - IdObs = bayestopt_.mfys; - -end - -%% -varlist = options_.varlist; -if isempty(varlist) - varlist = M_.endo_names; - SelecVariables = transpose(1:M_.endo_nbr); - nvar = M_.endo_nbr; -else - nvar = size(varlist,1); - SelecVariables = []; - for i=1:nvar - if ~isempty(strmatch(varlist(i,:),M_.endo_names,'exact')) - SelecVariables = [SelecVariables;strmatch(varlist(i,:),M_.endo_names,'exact')]; - end - end -end - -irun1 = 1; -irun2 = 1; -irun3 = 1; -irun4 = 1; -irun5 = 1; -irun6 = 1; -irun7 = 1; -ifil1 = 0; -ifil2 = 0; -ifil3 = 0; -ifil4 = 0; -ifil5 = 0; -ifil6 = 0; -ifil7 = 0; - -h = waitbar(0,'Bayesian smoother...'); - -stock_param = zeros(MAX_nruns, npar); -stock_logpo = zeros(MAX_nruns,1); -stock_ys = zeros(MAX_nruns,endo_nbr); -if options_.smoother - stock_smooth = zeros(endo_nbr,gend,MAX_nsmoo); - stock_innov = zeros(exo_nbr,gend,B); - stock_error = zeros(nvobs,gend,MAX_nerro); -end -if options_.filter_step_ahead - stock_filter = zeros(naK,endo_nbr,gend+options_.filter_step_ahead(end),MAX_naK); -end -if options_.forecast - stock_forcst_mean = zeros(endo_nbr,horizon+maxlag,MAX_nforc1); - stock_forcst_total = zeros(endo_nbr,horizon+maxlag,MAX_nforc2); -end - -for b=1:B - %deep = GetOneDraw(NumberOfDraws,FirstMhFile,LastMhFile,FirstLine,MAX_nruns,DirectoryName); - [deep, logpo] = GetOneDraw(type); - set_all_parameters(deep); - dr = resol(oo_.steady_state,0); - [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK] = ... - DsgeSmoother(deep,gend,Y,data_index); - - if options_.loglinear - stock_smooth(dr.order_var,:,irun1) = alphahat(1:endo_nbr,:)+ ... - repmat(log(dr.ys(dr.order_var)),1,gend); - else - stock_smooth(dr.order_var,:,irun1) = alphahat(1:endo_nbr,:)+ ... - repmat(dr.ys(dr.order_var),1,gend); - end - if nvx - stock_innov(:,:,irun2) = etahat; - end - if nvn - stock_error(:,:,irun3) = epsilonhat; - end - if naK - stock_filter(:,dr.order_var,:,irun4) = aK(options_.filter_step_ahead,1:endo_nbr,:); - end - stock_param(irun5,:) = deep; - stock_logpo(irun5,1) = logpo; - stock_ys(irun5,:) = SteadyState'; - - if horizon - yyyy = alphahat(iendo,i_last_obs); - yf = forcst2a(yyyy,dr,zeros(horizon,exo_nbr)); - if options_.prefilter == 1 - yf(:,IdObs) = yf(:,IdObs)+repmat(bayestopt_.mean_varobs', ... - horizon+maxlag,1); - end - yf(:,IdObs) = yf(:,IdObs)+(gend+[1-maxlag:horizon]')*trend_coeff'; - if options_.loglinear == 1 - yf = yf+repmat(log(SteadyState'),horizon+maxlag,1); -% yf = exp(yf); - else - yf = yf+repmat(SteadyState',horizon+maxlag,1); - end - yf1 = forcst2(yyyy,horizon,dr,1); - if options_.prefilter == 1 - yf1(:,IdObs,:) = yf1(:,IdObs,:)+ ... - repmat(bayestopt_.mean_varobs',[horizon+maxlag,1,1]); - end - yf1(:,IdObs,:) = yf1(:,IdObs,:)+repmat((gend+[1-maxlag:horizon]')* ... - trend_coeff',[1,1,1]); - if options_.loglinear == 1 - yf1 = yf1 + repmat(log(SteadyState'),[horizon+maxlag,1,1]); -% yf1 = exp(yf1); - else - yf1 = yf1 + repmat(SteadyState',[horizon+maxlag,1,1]); - end - - stock_forcst_mean(:,:,irun6) = yf'; - stock_forcst_total(:,:,irun7) = yf1'; - end - - irun1 = irun1 + 1; - irun2 = irun2 + 1; - irun3 = irun3 + 1; - irun4 = irun4 + 1; - irun5 = irun5 + 1; - irun6 = irun6 + 1; - irun7 = irun7 + 1; - - if irun1 > MAX_nsmoo | b == B - stock = stock_smooth(:,:,1:irun1-1); - ifil1 = ifil1 + 1; - save([DirectoryName '/' M_.fname '_smooth' int2str(ifil1) '.mat'],'stock'); - irun1 = 1; - end - - if nvx & (irun2 > MAX_ninno | b == B) - stock = stock_innov(:,:,1:irun2-1); - ifil2 = ifil2 + 1; - save([DirectoryName '/' M_.fname '_inno' int2str(ifil2) '.mat'],'stock'); - irun2 = 1; - end - - if nvn & (irun3 > MAX_error | b == B) - stock = stock_error(:,:,1:irun3-1); - ifil3 = ifil3 + 1; - save([DirectoryName '/' M_.fname '_error' int2str(ifil3) '.mat'],'stock'); - irun3 = 1; - end - - if naK & (irun4 > MAX_naK | b == B) - stock = stock_filter(:,:,:,1:irun4-1); - ifil4 = ifil4 + 1; - save([DirectoryName '/' M_.fname '_filter' int2str(ifil4) '.mat'],'stock'); - irun4 = 1; - end - - if irun5 > MAX_nruns | b == B - stock = stock_param(1:irun5-1,:); - ifil5 = ifil5 + 1; - save([DirectoryName '/' M_.fname '_param' int2str(ifil5) '.mat'],'stock','stock_logpo','stock_ys'); - irun5 = 1; - end - - if horizon & (irun6 > MAX_nforc1 | b == B) - stock = stock_forcst_mean(:,:,1:irun6-1); - ifil6 = ifil6 + 1; - save([DirectoryName '/' M_.fname '_forc_mean' int2str(ifil6) '.mat'],'stock'); - irun6 = 1; - end - - if horizon & (irun7 > MAX_nforc2 | b == B) - stock = stock_forcst_total(:,:,1:irun7-1); - ifil7 = ifil7 + 1; - save([DirectoryName '/' M_.fname '_forc_total' int2str(ifil7) '.mat'],'stock'); - irun7 = 1; - end - - waitbar(b/B,h); -end -close(h) - -stock_gend=gend; -stock_data=Y; -save([DirectoryName '/' M_.fname '_data.mat'],'stock_gend','stock_data'); - -if options_.smoother - pm3(endo_nbr,gend,ifil1,B,'Smoothed variables',... - M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,... - 'names2','smooth',[M_.fname '/metropolis'],'_smooth') -end - -if options_.forecast - pm3(endo_nbr,horizon+maxlag,ifil6,B,'Forecasted variables (mean)',... - M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,... - 'names2','smooth',[M_.fname '/metropolis'],'_forc_mean') - pm3(endo_nbr,horizon+maxlag,ifil6,B,'Forecasted variables (total)',... - M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,... - 'names2','smooth',[M_.fname '/metropolis'],'_forc_total') -end +function PosteriorFilterSmootherAndForecast(Y,gend, type,data_index) + +% function PosteriorFilterSmootherAndForecast(Y,gend, type) +% Computes posterior filter smoother and forecasts +% +% INPUTS +% Y: data +% gend: number of observations +% type: posterior +% prior +% gsa +% +% OUTPUTS +% none +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2005-2008 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 <http://www.gnu.org/licenses/>. + +global options_ estim_params_ oo_ M_ bayestopt_ + +nvx = estim_params_.nvx; +nvn = estim_params_.nvn; +ncx = estim_params_.ncx; +ncn = estim_params_.ncn; +np = estim_params_.np ; +npar = nvx+nvn+ncx+ncn+np; +offset = npar-np; +naK = length(options_.filter_step_ahead); +%% +MaxNumberOfPlotPerFigure = 4;% The square root must be an integer! +MaxNumberOfBytes=options_.MaxNumberOfBytes; +endo_nbr=M_.endo_nbr; +exo_nbr=M_.exo_nbr; +nvobs = size(options_.varobs,1); +nn = sqrt(MaxNumberOfPlotPerFigure); +iendo = 1:endo_nbr; +i_last_obs = gend+(1-M_.maximum_endo_lag:0); +horizon = options_.forecast; +maxlag = M_.maximum_endo_lag; +%% +CheckPath('Plots/'); +DirectoryName = CheckPath('metropolis'); +load([ DirectoryName '/' M_.fname '_mh_history.mat']) +FirstMhFile = record.KeepedDraws.FirstMhFile; +FirstLine = record.KeepedDraws.FirstLine; +TotalNumberOfMhFiles = sum(record.MhDraws(:,2)); LastMhFile = TotalNumberOfMhFiles; +TotalNumberOfMhDraws = sum(record.MhDraws(:,1)); +NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws); +clear record; +B = min(1200, round(0.25*NumberOfDraws)); +B = 200; +%% +MAX_nruns = min(B,ceil(options_.MaxNumberOfBytes/(npar+2)/8)); +MAX_nsmoo = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*gend)/8)); +MAX_ninno = min(B,ceil(MaxNumberOfBytes/(exo_nbr*gend)/8)); +MAX_nerro = min(B,ceil(MaxNumberOfBytes/(size(options_.varobs,1)*gend)/8)); +if naK + MAX_naK = min(B,ceil(MaxNumberOfBytes/(size(options_.varobs,1)* ... + length(options_.filter_step_ahead)*gend)/8)); +end +if horizon + MAX_nforc1 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/8)); + MAX_nforc2 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/ ... + 8)); + IdObs = bayestopt_.mfys; + +end + +%% +varlist = options_.varlist; +if isempty(varlist) + varlist = M_.endo_names; + SelecVariables = transpose(1:M_.endo_nbr); + nvar = M_.endo_nbr; +else + nvar = size(varlist,1); + SelecVariables = []; + for i=1:nvar + if ~isempty(strmatch(varlist(i,:),M_.endo_names,'exact')) + SelecVariables = [SelecVariables;strmatch(varlist(i,:),M_.endo_names,'exact')]; + end + end +end + +irun1 = 1; +irun2 = 1; +irun3 = 1; +irun4 = 1; +irun5 = 1; +irun6 = 1; +irun7 = 1; +ifil1 = 0; +ifil2 = 0; +ifil3 = 0; +ifil4 = 0; +ifil5 = 0; +ifil6 = 0; +ifil7 = 0; + +h = waitbar(0,'Bayesian smoother...'); + +stock_param = zeros(MAX_nruns, npar); +stock_logpo = zeros(MAX_nruns,1); +stock_ys = zeros(MAX_nruns,endo_nbr); +if options_.smoother + stock_smooth = zeros(endo_nbr,gend,MAX_nsmoo); + stock_innov = zeros(exo_nbr,gend,B); + stock_error = zeros(nvobs,gend,MAX_nerro); +end +if options_.filter_step_ahead + stock_filter = zeros(naK,endo_nbr,gend+options_.filter_step_ahead(end),MAX_naK); +end +if options_.forecast + stock_forcst_mean = zeros(endo_nbr,horizon+maxlag,MAX_nforc1); + stock_forcst_total = zeros(endo_nbr,horizon+maxlag,MAX_nforc2); +end + +for b=1:B + %deep = GetOneDraw(NumberOfDraws,FirstMhFile,LastMhFile,FirstLine,MAX_nruns,DirectoryName); + [deep, logpo] = GetOneDraw(type); + set_all_parameters(deep); + dr = resol(oo_.steady_state,0); + [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK] = ... + DsgeSmoother(deep,gend,Y,data_index); + + if options_.loglinear + stock_smooth(dr.order_var,:,irun1) = alphahat(1:endo_nbr,:)+ ... + repmat(log(dr.ys(dr.order_var)),1,gend); + else + stock_smooth(dr.order_var,:,irun1) = alphahat(1:endo_nbr,:)+ ... + repmat(dr.ys(dr.order_var),1,gend); + end + if nvx + stock_innov(:,:,irun2) = etahat; + end + if nvn + stock_error(:,:,irun3) = epsilonhat; + end + if naK + stock_filter(:,dr.order_var,:,irun4) = aK(options_.filter_step_ahead,1:endo_nbr,:); + end + stock_param(irun5,:) = deep; + stock_logpo(irun5,1) = logpo; + stock_ys(irun5,:) = SteadyState'; + + if horizon + yyyy = alphahat(iendo,i_last_obs); + yf = forcst2a(yyyy,dr,zeros(horizon,exo_nbr)); + if options_.prefilter == 1 + yf(:,IdObs) = yf(:,IdObs)+repmat(bayestopt_.mean_varobs', ... + horizon+maxlag,1); + end + yf(:,IdObs) = yf(:,IdObs)+(gend+[1-maxlag:horizon]')*trend_coeff'; + if options_.loglinear == 1 + yf = yf+repmat(log(SteadyState'),horizon+maxlag,1); + % yf = exp(yf); + else + yf = yf+repmat(SteadyState',horizon+maxlag,1); + end + yf1 = forcst2(yyyy,horizon,dr,1); + if options_.prefilter == 1 + yf1(:,IdObs,:) = yf1(:,IdObs,:)+ ... + repmat(bayestopt_.mean_varobs',[horizon+maxlag,1,1]); + end + yf1(:,IdObs,:) = yf1(:,IdObs,:)+repmat((gend+[1-maxlag:horizon]')* ... + trend_coeff',[1,1,1]); + if options_.loglinear == 1 + yf1 = yf1 + repmat(log(SteadyState'),[horizon+maxlag,1,1]); + % yf1 = exp(yf1); + else + yf1 = yf1 + repmat(SteadyState',[horizon+maxlag,1,1]); + end + + stock_forcst_mean(:,:,irun6) = yf'; + stock_forcst_total(:,:,irun7) = yf1'; + end + + irun1 = irun1 + 1; + irun2 = irun2 + 1; + irun3 = irun3 + 1; + irun4 = irun4 + 1; + irun5 = irun5 + 1; + irun6 = irun6 + 1; + irun7 = irun7 + 1; + + if irun1 > MAX_nsmoo | b == B + stock = stock_smooth(:,:,1:irun1-1); + ifil1 = ifil1 + 1; + save([DirectoryName '/' M_.fname '_smooth' int2str(ifil1) '.mat'],'stock'); + irun1 = 1; + end + + if nvx & (irun2 > MAX_ninno | b == B) + stock = stock_innov(:,:,1:irun2-1); + ifil2 = ifil2 + 1; + save([DirectoryName '/' M_.fname '_inno' int2str(ifil2) '.mat'],'stock'); + irun2 = 1; + end + + if nvn & (irun3 > MAX_error | b == B) + stock = stock_error(:,:,1:irun3-1); + ifil3 = ifil3 + 1; + save([DirectoryName '/' M_.fname '_error' int2str(ifil3) '.mat'],'stock'); + irun3 = 1; + end + + if naK & (irun4 > MAX_naK | b == B) + stock = stock_filter(:,:,:,1:irun4-1); + ifil4 = ifil4 + 1; + save([DirectoryName '/' M_.fname '_filter' int2str(ifil4) '.mat'],'stock'); + irun4 = 1; + end + + if irun5 > MAX_nruns | b == B + stock = stock_param(1:irun5-1,:); + ifil5 = ifil5 + 1; + save([DirectoryName '/' M_.fname '_param' int2str(ifil5) '.mat'],'stock','stock_logpo','stock_ys'); + irun5 = 1; + end + + if horizon & (irun6 > MAX_nforc1 | b == B) + stock = stock_forcst_mean(:,:,1:irun6-1); + ifil6 = ifil6 + 1; + save([DirectoryName '/' M_.fname '_forc_mean' int2str(ifil6) '.mat'],'stock'); + irun6 = 1; + end + + if horizon & (irun7 > MAX_nforc2 | b == B) + stock = stock_forcst_total(:,:,1:irun7-1); + ifil7 = ifil7 + 1; + save([DirectoryName '/' M_.fname '_forc_total' int2str(ifil7) '.mat'],'stock'); + irun7 = 1; + end + + waitbar(b/B,h); +end +close(h) + +stock_gend=gend; +stock_data=Y; +save([DirectoryName '/' M_.fname '_data.mat'],'stock_gend','stock_data'); + +if options_.smoother + pm3(endo_nbr,gend,ifil1,B,'Smoothed variables',... + M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,... + 'names2','smooth',[M_.fname '/metropolis'],'_smooth') +end + +if options_.forecast + pm3(endo_nbr,horizon+maxlag,ifil6,B,'Forecasted variables (mean)',... + M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,... + 'names2','smooth',[M_.fname '/metropolis'],'_forc_mean') + pm3(endo_nbr,horizon+maxlag,ifil6,B,'Forecasted variables (total)',... + M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,... + 'names2','smooth',[M_.fname '/metropolis'],'_forc_total') +end diff --git a/matlab/PosteriorIRF.m b/matlab/PosteriorIRF.m index 9935143337..96219952d5 100644 --- a/matlab/PosteriorIRF.m +++ b/matlab/PosteriorIRF.m @@ -71,27 +71,27 @@ else end DirectoryName = CheckPath('Output'); if strcmpi(type,'posterior') - MhDirectoryName = CheckPath('metropolis'); + MhDirectoryName = CheckPath('metropolis'); elseif strcmpi(type,'gsa') - MhDirectoryName = CheckPath('GSA'); + MhDirectoryName = CheckPath('GSA'); else - MhDirectoryName = CheckPath('prior'); + MhDirectoryName = CheckPath('prior'); end if strcmpi(type,'posterior') - load([ MhDirectoryName '/' M_.fname '_mh_history.mat']) - TotalNumberOfMhDraws = sum(record.MhDraws(:,1)); - NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws); + load([ MhDirectoryName '/' M_.fname '_mh_history.mat']) + TotalNumberOfMhDraws = sum(record.MhDraws(:,1)); + NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws); elseif strcmpi(type,'gsa') - load([ MhDirectoryName '/' M_.fname '_prior.mat'],'lpmat0','lpmat','istable') - x=[lpmat0(istable,:) lpmat(istable,:)]; - clear lpmat istable - NumberOfDraws=size(x,1); - B=NumberOfDraws; options_.B = B; + load([ MhDirectoryName '/' M_.fname '_prior.mat'],'lpmat0','lpmat','istable') + x=[lpmat0(istable,:) lpmat(istable,:)]; + clear lpmat istable + NumberOfDraws=size(x,1); + B=NumberOfDraws; options_.B = B; else% type = 'prior' - NumberOfDraws = 500; + NumberOfDraws = 500; end if ~strcmpi(type,'gsa') - B = min([round(.5*NumberOfDraws),500]); options_.B = B; + B = min([round(.5*NumberOfDraws),500]); options_.B = B; end try delete([MhDirectoryName '/' M_.fname '_irf_dsge*.mat']) catch disp('No _IRFs (dsge) files to be deleted!') @@ -106,22 +106,22 @@ NumberOfIRFfiles_dsge = 1; NumberOfIRFfiles_dsgevar = 1; ifil2 = 1; if strcmpi(type,'posterior') - h = waitbar(0,'Bayesian (posterior) IRFs...'); + h = waitbar(0,'Bayesian (posterior) IRFs...'); elseif strcmpi(type,'gsa') - h = waitbar(0,'GSA (prior) IRFs...'); + h = waitbar(0,'GSA (prior) IRFs...'); else - h = waitbar(0,'Bayesian (prior) IRFs...'); + h = waitbar(0,'Bayesian (prior) IRFs...'); end % Create arrays if B <= MAX_nruns - stock_param = zeros(B, npar); + stock_param = zeros(B, npar); else - stock_param = zeros(MAX_nruns, npar); + stock_param = zeros(MAX_nruns, npar); end if B >= MAX_nirfs_dsge - stock_irf_dsge = zeros(options_.irf,nvar,M_.exo_nbr,MAX_nirfs_dsge); + stock_irf_dsge = zeros(options_.irf,nvar,M_.exo_nbr,MAX_nirfs_dsge); else - stock_irf_dsge = zeros(options_.irf,nvar,M_.exo_nbr,B); + stock_irf_dsge = zeros(options_.irf,nvar,M_.exo_nbr,B); end if MAX_nirfs_dsgevar if B >= MAX_nirfs_dsgevar @@ -204,14 +204,14 @@ while b<=B SIGMA_inv_upper_chol); % draw from the conditional posterior of PHI PHI_draw = rand_matrix_normal(NumberOfParametersPerEquation,nvobs, PHI, ... - chol(SIGMAu_draw)', chol(iXX)'); + chol(SIGMAu_draw)', chol(iXX)'); Companion_matrix(1:nvobs,:) = transpose(PHI_draw(1:NumberOfLagsTimesNvobs,:)); % Check for stationarity explosive_var = any(abs(eig(Companion_matrix))>1.000000001); end % Get the mean % $$$ if options_.noconstant - mu = zeros(1,nvobs); + mu = zeros(1,nvobs); % $$$ else % $$$ AA = eye(nvobs); % $$$ for lag=1:NumberOfLags @@ -219,7 +219,7 @@ while b<=B % $$$ end % $$$ mu = transpose(AA\transpose(PHI_draw(end,:))); % $$$ end - % Get rotation +% Get rotation if dsge_prior_weight > 0 Atheta(oo_.dr.order_var,M_.exo_names_orig_ord) = oo_.dr.ghu*sqrt(M_.Sigma_e); A0 = Atheta(bayestopt_.mfys,:); @@ -282,7 +282,7 @@ while b<=B waitbar(b/B,h); end if nosaddle - disp(['PosteriorIRF :: Percentage of discarded posterior draws = ' num2str(nosaddle/(B+nosaddle))]) + disp(['PosteriorIRF :: Percentage of discarded posterior draws = ' num2str(nosaddle/(B+nosaddle))]) end close(h); @@ -292,7 +292,7 @@ if MAX_nirfs_dsgevar end if strcmpi(type,'gsa') - return + return end IRF_DSGEs = dir([MhDirectoryName '/' M_.fname '_IRF_DSGEs*.mat']); @@ -310,10 +310,10 @@ DistribIRF = zeros(options_.irf,9,nvar,M_.exo_nbr); HPDIRF = zeros(options_.irf,2,nvar,M_.exo_nbr); if options_.TeX - varlist_TeX = []; - for i=1:nvar - varlist_TeX = strvcat(varlist_TeX,M_.endo_names_tex(IndxVariables(i),:)); - end + varlist_TeX = []; + for i=1:nvar + varlist_TeX = strvcat(varlist_TeX,M_.endo_names_tex(IndxVariables(i),:)); + end end fprintf('MH: Posterior (dsge) IRFs...\n'); @@ -321,31 +321,31 @@ tit(M_.exo_names_orig_ord,:) = M_.exo_names; kdx = 0; for file = 1:NumberOfIRFfiles_dsge - load([MhDirectoryName '/' M_.fname '_IRF_DSGEs' int2str(file) '.mat']); - for i = 1:M_.exo_nbr - for j = 1:nvar - for k = 1:size(STOCK_IRF_DSGE,1) - kk = k+kdx; - [MeanIRF(kk,j,i),MedianIRF(kk,j,i),VarIRF(kk,j,i),HPDIRF(kk,:,j,i),... - DistribIRF(kk,:,j,i)] = posterior_moments(squeeze(STOCK_IRF_DSGE(k,j,i,:)),0,options_.mh_conf_sig); + load([MhDirectoryName '/' M_.fname '_IRF_DSGEs' int2str(file) '.mat']); + for i = 1:M_.exo_nbr + for j = 1:nvar + for k = 1:size(STOCK_IRF_DSGE,1) + kk = k+kdx; + [MeanIRF(kk,j,i),MedianIRF(kk,j,i),VarIRF(kk,j,i),HPDIRF(kk,:,j,i),... + DistribIRF(kk,:,j,i)] = posterior_moments(squeeze(STOCK_IRF_DSGE(k,j,i,:)),0,options_.mh_conf_sig); + end end end - end - kdx = kdx + size(STOCK_IRF_DSGE,1); + kdx = kdx + size(STOCK_IRF_DSGE,1); end clear STOCK_IRF_DSGE; for i = 1:M_.exo_nbr - for j = 1:nvar - name = [deblank(M_.endo_names(IndxVariables(j),:)) '_' deblank(tit(i,:))]; - eval(['oo_.PosteriorIRF.dsge.Mean.' name ' = MeanIRF(:,j,i);']); - eval(['oo_.PosteriorIRF.dsge.Median.' name ' = MedianIRF(:,j,i);']); - eval(['oo_.PosteriorIRF.dsge.Var.' name ' = VarIRF(:,j,i);']); - eval(['oo_.PosteriorIRF.dsge.Distribution.' name ' = DistribIRF(:,:,j,i);']); - eval(['oo_.PosteriorIRF.dsge.HPDinf.' name ' = HPDIRF(:,1,j,i);']); - eval(['oo_.PosteriorIRF.dsge.HPDsup.' name ' = HPDIRF(:,2,j,i);']); - end + for j = 1:nvar + name = [deblank(M_.endo_names(IndxVariables(j),:)) '_' deblank(tit(i,:))]; + eval(['oo_.PosteriorIRF.dsge.Mean.' name ' = MeanIRF(:,j,i);']); + eval(['oo_.PosteriorIRF.dsge.Median.' name ' = MedianIRF(:,j,i);']); + eval(['oo_.PosteriorIRF.dsge.Var.' name ' = VarIRF(:,j,i);']); + eval(['oo_.PosteriorIRF.dsge.Distribution.' name ' = DistribIRF(:,:,j,i);']); + eval(['oo_.PosteriorIRF.dsge.HPDinf.' name ' = HPDIRF(:,1,j,i);']); + eval(['oo_.PosteriorIRF.dsge.HPDsup.' name ' = HPDIRF(:,2,j,i);']); + end end @@ -389,111 +389,111 @@ end %% Finally I build the plots. %% if options_.TeX - fidTeX = fopen([DirectoryName '/' M_.fname '_BayesianIRF.TeX'],'w'); - fprintf(fidTeX,'%% TeX eps-loader file generated by PosteriorIRF.m (Dynare).\n'); - fprintf(fidTeX,['%% ' datestr(now,0) '\n']); - fprintf(fidTeX,' \n'); - titTeX(M_.exo_names_orig_ord,:) = M_.exo_names_tex; + fidTeX = fopen([DirectoryName '/' M_.fname '_BayesianIRF.TeX'],'w'); + fprintf(fidTeX,'%% TeX eps-loader file generated by PosteriorIRF.m (Dynare).\n'); + fprintf(fidTeX,['%% ' datestr(now,0) '\n']); + fprintf(fidTeX,' \n'); + titTeX(M_.exo_names_orig_ord,:) = M_.exo_names_tex; end %% subplotnum = 0; for i=1:M_.exo_nbr - NAMES = []; - if options_.TeX - TEXNAMES = []; - end - figunumber = 0; - for j=1:nvar - if max(abs(MeanIRF(:,j,i))) > 10^(-6) - subplotnum = subplotnum+1; - if options_.nograph - if subplotnum == 1 & options_.relative_irf - hh = figure('Name',['Relative response to orthogonalized shock to ' tit(i,:)],'Visible','off'); - elseif subplotnum == 1 & ~options_.relative_irf - hh = figure('Name',['Orthogonalized shock to ' tit(i,:)],'Visible','off'); - end - else - if subplotnum == 1 & options_.relative_irf - hh = figure('Name',['Relative response to orthogonalized shock to ' tit(i,:)]); - elseif subplotnum == 1 & ~options_.relative_irf - hh = figure('Name',['Orthogonalized shock to ' tit(i,:)]); - end - end - set(0,'CurrentFigure',hh) - subplot(nn,nn,subplotnum); - if ~MAX_nirfs_dsgevar - h1 = area(1:options_.irf,HPDIRF(:,2,j,i)); - set(h1,'FaceColor',[.9 .9 .9]); - set(h1,'BaseValue',min(HPDIRF(:,1,j,i))); - hold on - h2 = area(1:options_.irf,HPDIRF(:,1,j,i),'FaceColor',[1 1 1],'BaseValue',min(HPDIRF(:,1,j,i))); - set(h2,'FaceColor',[1 1 1]); - set(h2,'BaseValue',min(HPDIRF(:,1,j,i))); - plot(1:options_.irf,MeanIRF(:,j,i),'-k','linewidth',3) - % plot([1 options_.irf],[0 0],'-r','linewidth',0.5); - box on - axis tight - xlim([1 options_.irf]); - hold off - else - h1 = area(1:options_.irf,HPDIRF(:,2,j,i)); - set(h1,'FaceColor',[.9 .9 .9]); - set(h1,'BaseValue',min([min(HPDIRF(:,1,j,i)),min(HPDIRFdsgevar(:,1,j,i))])); - hold on; - h2 = area(1:options_.irf,HPDIRF(:,1,j,i)); - set(h2,'FaceColor',[1 1 1]); - set(h2,'BaseValue',min([min(HPDIRF(:,1,j,i)),min(HPDIRFdsgevar(:,1,j,i))])); - plot(1:options_.irf,MeanIRF(:,j,i),'-k','linewidth',3) - % plot([1 options_.irf],[0 0],'-r','linewidth',0.5); - plot(1:options_.irf,MeanIRFdsgevar(:,j,i),'--k','linewidth',2) - plot(1:options_.irf,HPDIRFdsgevar(:,1,j,i),'--k','linewidth',1) - plot(1:options_.irf,HPDIRFdsgevar(:,2,j,i),'--k','linewidth',1) - box on - axis tight - xlim([1 options_.irf]); - hold off - end - name = deblank(varlist(j,:)); - NAMES = strvcat(NAMES,name); - if options_.TeX - texname = deblank(varlist_TeX(j,:)); - TEXNAMES = strvcat(TEXNAMES,['$' texname '$']); - end - title(name,'Interpreter','none') + NAMES = []; + if options_.TeX + TEXNAMES = []; end - if subplotnum == MaxNumberOfPlotPerFigure | (j == nvar & subplotnum> 0) - figunumber = figunumber+1; - set(hh,'visible','on') - eval(['print -depsc2 ' DirectoryName '/' M_.fname '_Bayesian_IRF_' deblank(tit(i,:)) '_' int2str(figunumber) '.eps']); - if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' DirectoryName '/' M_.fname '_Bayesian_IRF_' deblank(tit(i,:)) '_' int2str(figunumber)]); - saveas(hh,[DirectoryName '/' M_.fname '_Bayesian_IRF_' deblank(tit(i,:)) '_' int2str(figunumber) '.fig']); - end - set(hh,'visible','off') - if options_.nograph, close(hh), end - if options_.TeX - fprintf(fidTeX,'\\begin{figure}[H]\n'); - for jj = 1:size(TEXNAMES,1) - fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{%s}\n'],deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:))); - end - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_Bayesian_IRF_%s}\n',M_.fname,deblank(tit(i,:))); - if options_.relative_irf - fprintf(fidTeX,['\\caption{Bayesian relative IRF.}']); - else - fprintf(fidTeX,'\\caption{Bayesian IRF.}'); + figunumber = 0; + for j=1:nvar + if max(abs(MeanIRF(:,j,i))) > 10^(-6) + subplotnum = subplotnum+1; + if options_.nograph + if subplotnum == 1 & options_.relative_irf + hh = figure('Name',['Relative response to orthogonalized shock to ' tit(i,:)],'Visible','off'); + elseif subplotnum == 1 & ~options_.relative_irf + hh = figure('Name',['Orthogonalized shock to ' tit(i,:)],'Visible','off'); + end + else + if subplotnum == 1 & options_.relative_irf + hh = figure('Name',['Relative response to orthogonalized shock to ' tit(i,:)]); + elseif subplotnum == 1 & ~options_.relative_irf + hh = figure('Name',['Orthogonalized shock to ' tit(i,:)]); + end + end + set(0,'CurrentFigure',hh) + subplot(nn,nn,subplotnum); + if ~MAX_nirfs_dsgevar + h1 = area(1:options_.irf,HPDIRF(:,2,j,i)); + set(h1,'FaceColor',[.9 .9 .9]); + set(h1,'BaseValue',min(HPDIRF(:,1,j,i))); + hold on + h2 = area(1:options_.irf,HPDIRF(:,1,j,i),'FaceColor',[1 1 1],'BaseValue',min(HPDIRF(:,1,j,i))); + set(h2,'FaceColor',[1 1 1]); + set(h2,'BaseValue',min(HPDIRF(:,1,j,i))); + plot(1:options_.irf,MeanIRF(:,j,i),'-k','linewidth',3) + % plot([1 options_.irf],[0 0],'-r','linewidth',0.5); + box on + axis tight + xlim([1 options_.irf]); + hold off + else + h1 = area(1:options_.irf,HPDIRF(:,2,j,i)); + set(h1,'FaceColor',[.9 .9 .9]); + set(h1,'BaseValue',min([min(HPDIRF(:,1,j,i)),min(HPDIRFdsgevar(:,1,j,i))])); + hold on; + h2 = area(1:options_.irf,HPDIRF(:,1,j,i)); + set(h2,'FaceColor',[1 1 1]); + set(h2,'BaseValue',min([min(HPDIRF(:,1,j,i)),min(HPDIRFdsgevar(:,1,j,i))])); + plot(1:options_.irf,MeanIRF(:,j,i),'-k','linewidth',3) + % plot([1 options_.irf],[0 0],'-r','linewidth',0.5); + plot(1:options_.irf,MeanIRFdsgevar(:,j,i),'--k','linewidth',2) + plot(1:options_.irf,HPDIRFdsgevar(:,1,j,i),'--k','linewidth',1) + plot(1:options_.irf,HPDIRFdsgevar(:,2,j,i),'--k','linewidth',1) + box on + axis tight + xlim([1 options_.irf]); + hold off + end + name = deblank(varlist(j,:)); + NAMES = strvcat(NAMES,name); + if options_.TeX + texname = deblank(varlist_TeX(j,:)); + TEXNAMES = strvcat(TEXNAMES,['$' texname '$']); + end + title(name,'Interpreter','none') end - fprintf(fidTeX,'\\label{Fig:BayesianIRF:%s}\n',deblank(tit(i,:))); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,' \n'); - end - subplotnum = 0; - end - end% loop over selected endo_var + if subplotnum == MaxNumberOfPlotPerFigure | (j == nvar & subplotnum> 0) + figunumber = figunumber+1; + set(hh,'visible','on') + eval(['print -depsc2 ' DirectoryName '/' M_.fname '_Bayesian_IRF_' deblank(tit(i,:)) '_' int2str(figunumber) '.eps']); + if ~exist('OCTAVE_VERSION') + eval(['print -dpdf ' DirectoryName '/' M_.fname '_Bayesian_IRF_' deblank(tit(i,:)) '_' int2str(figunumber)]); + saveas(hh,[DirectoryName '/' M_.fname '_Bayesian_IRF_' deblank(tit(i,:)) '_' int2str(figunumber) '.fig']); + end + set(hh,'visible','off') + if options_.nograph, close(hh), end + if options_.TeX + fprintf(fidTeX,'\\begin{figure}[H]\n'); + for jj = 1:size(TEXNAMES,1) + fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{%s}\n'],deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:))); + end + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_Bayesian_IRF_%s}\n',M_.fname,deblank(tit(i,:))); + if options_.relative_irf + fprintf(fidTeX,['\\caption{Bayesian relative IRF.}']); + else + fprintf(fidTeX,'\\caption{Bayesian IRF.}'); + end + fprintf(fidTeX,'\\label{Fig:BayesianIRF:%s}\n',deblank(tit(i,:))); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,' \n'); + end + subplotnum = 0; + end + end% loop over selected endo_var end% loop over exo_var %% if options_.TeX - fprintf(fidTeX,'%% End of TeX file.\n'); - fclose(fidTeX); + fprintf(fidTeX,'%% End of TeX file.\n'); + fclose(fidTeX); end fprintf('MH: Posterior IRFs, done!\n'); \ No newline at end of file diff --git a/matlab/ReshapeMatFiles.m b/matlab/ReshapeMatFiles.m index de33a7ac9c..4ecbbaeb66 100644 --- a/matlab/ReshapeMatFiles.m +++ b/matlab/ReshapeMatFiles.m @@ -1,183 +1,183 @@ -function ReshapeMatFiles(type, type2) -% function ReshapeMatFiles(type, type2) -% Reshapes and sorts (along the mcmc simulations) the mat files generated by DYNARE. -% 4D-arrays are splitted along the first dimension. -% 3D-arrays are splitted along the second dimension. -% -% INPUTS: -% type: statistics type in the repertory: -% dgse -% irf_bvardsge -% smooth -% filter -% error -% innov -% forcst -% forcst1 -% type2: analysis type: -% posterior -% gsa -% prior -% -% OUTPUTS: -% none -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2003-2007 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 <http://www.gnu.org/licenses/>. - - global M_ options_ - -if nargin==1, - MhDirectoryName = [ CheckPath('metropolis') '/' ]; -else - if strcmpi(type2,'posterior') - MhDirectoryName = [CheckPath('metropolis') '/' ]; -elseif strcmpi(type2,'gsa') -if options_.opt_gsa.morris==1, - MhDirectoryName = [CheckPath('GSA\SCREEN') '/' ]; -elseif options_.opt_gsa.morris==2, - MhDirectoryName = [CheckPath('GSA\IDENTIF') '/' ]; -else - MhDirectoryName = [CheckPath('GSA') '/' ]; -end -else - MhDirectoryName = [CheckPath('prior') '/' ]; -end -end - switch type - case 'irf_dsge' - CAPtype = 'IRF_DSGE'; - TYPEsize = [ options_.irf , size(options_.varlist,1) , M_.exo_nbr ]; - TYPEarray = 4; - case 'irf_bvardsge' - CAPtype = 'IRF_BVARDSGE'; - TYPEsize = [ options_.irf , size(options_.varobs,1) , M_.exo_nbr ]; - TYPEarray = 4; - case 'smooth' - CAPtype = 'SMOOTH'; - TYPEsize = [ M_.endo_nbr , options_.nobs ]; - TYPEarray = 3; - case 'filter' - CAPtype = 'FILTER'; - TYPEsize = [ M_.endo_nbr , options_.nobs + 1 ];% TO BE CHECKED! - TYPEarray = 3; - case 'error' - CAPtype = 'ERROR'; - TYPEsize = [ size(options_.varobs,1) , options_.nobs ]; - TYPEarray = 3; - case 'innov' - CAPtype = 'INNOV'; - TYPEsize = [ M_.exo_nbr , options_.nobs ]; - TYPEarray = 3; - case 'forcst' - CAPtype = 'FORCST'; - TYPEsize = [ M_.endo_nbr , options_.forecast ]; - TYPEarray = 3; - case 'forcst1' - CAPtype = 'FORCST1'; - TYPEsize = [ M_.endo_nbr , options_.forecast ]; - TYPEarray = 3; - otherwise - disp('ReshapeMatFiles :: Unknown argument!') - return - end - - TYPEfiles = dir([MhDirectoryName M_.fname '_' type '*.mat']); - NumberOfTYPEfiles = length(TYPEfiles); - B = options_.B; - - switch TYPEarray - case 4 - if NumberOfTYPEfiles > 1 - NumberOfPeriodsPerTYPEfiles = ceil(TYPEsize(1)/NumberOfTYPEfiles); - foffset = NumberOfTYPEfiles-floor(TYPEsize(1)/NumberOfPeriodsPerTYPEfiles); - reste = TYPEsize(1)-NumberOfPeriodsPerTYPEfiles*(NumberOfTYPEfiles-foffset); - idx = 0; - jdx = 0; - for f1=1:NumberOfTYPEfiles-foffset - eval(['STOCK_' CAPtype ' = zeros(NumberOfPeriodsPerTYPEfiles,TYPEsize(2),TYPEsize(3),B);']) - for f2 = 1:NumberOfTYPEfiles - load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']); - eval(['STOCK_' CAPtype '(:,:,:,idx+1:idx+size(stock_' type ',4))=stock_' ... - type '(jdx+1:jdx+NumberOfPeriodsPerTYPEfiles,:,:,:);']) - eval(['idx = idx + size(stock_' type ',4);']) - end - %eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',4);']) - save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(f1) '.mat'],['STOCK_' CAPtype]); - jdx = jdx + NumberOfPeriodsPerTYPEfiles; - idx = 0; - end - if reste - eval(['STOCK_' CAPtype ' = zeros(reste,TYPEsize(2),TYPEsize(3),B);']) - for f2 = 1:NumberOfTYPEfiles - load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']); - eval(['STOCK_' CAPtype '(:,:,:,idx+1:idx+size(stock_' type ',4))=stock_' type '(jdx+1:jdx+reste,:,:,:);']) - eval(['idx = idx + size(stock_' type ',4);']) - end - %eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',4);']) - save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(NumberOfTYPEfiles-foffset+1) '.mat'],['STOCK_' CAPtype]); - end - else - load([MhDirectoryName M_.fname '_' type '1.mat']); - %eval(['STOCK_' CAPtype ' = sort(stock_' type ',4);']) - eval(['STOCK_' CAPtype ' = stock_' type ';']) - save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(1) '.mat'],['STOCK_' CAPtype ]); - end - % Original file format may be useful in some cases... - % for file = 1:NumberOfTYPEfiles - % delete([MhDirectoryName M_.fname '_' type int2str(file) '.mat']) - % end - case 3 - if NumberOfTYPEfiles>1 - NumberOfPeriodsPerTYPEfiles = ceil( TYPEsize(2)/NumberOfTYPEfiles ); - reste = TYPEsize(2)-NumberOfPeriodsPerTYPEfiles*(NumberOfTYPEfiles-1); - idx = 0; - jdx = 0; - for f1=1:NumberOfTYPEfiles-1 - eval(['STOCK_' CAPtype ' = zeros(TYPEsize(1),NumberOfPeriodsPerTYPEfiles,B);']) - for f2 = 1:NumberOfTYPEfiles - load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']); - eval(['STOCK_' CAPtype '(:,:,idx+1:idx+size(stock_ ' type ',3))=stock_' type '(:,jdx+1:jdx+NumberOfPeriodsPerTYPEfiles,:);']) - eval(['idx = idx + size(stock_' type ',3);']) - end - %eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',3);']) - save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(f1) '.mat'],['STOCK_' CAPtype]); - jdx = jdx + NumberOfPeriodsPerTYPEfiles; - idx = 0; - end - eval(['STOCK_' CAPtype ' = zeros(TYPEsize(1),reste,B);']) - for f2 = 1:NumberOfTYPEfiles - load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']); - eval(['STOCK_' CAPtype '(:,:,idx+1:idx+size(stock_' type ',3))=stock_' type '(:,jdx+1:jdx+reste,:);']) - eval(['idx = idx + size(stock_' type ',3);']) - end - %eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',3);']) - save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(NumberOfTYPEfiles) '.mat'],['STOCK_' CAPtype]); - else - load([MhDirectoryName M_.fname '_' type '1.mat']); - %eval(['STOCK_' CAPtype ' = sort(stock_' type ',3);']) - eval(['STOCK_' CAPtype ' = stock_' type ';']) - save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(1) '.mat'],['STOCK_' CAPtype ]); - end - % Original file format may be useful in some cases... - % for file = 1:NumberOfTYPEfiles - % delete([MhDirectoryName M_.fname '_' type int2str(file) '.mat']) - % end - end \ No newline at end of file +function ReshapeMatFiles(type, type2) +% function ReshapeMatFiles(type, type2) +% Reshapes and sorts (along the mcmc simulations) the mat files generated by DYNARE. +% 4D-arrays are splitted along the first dimension. +% 3D-arrays are splitted along the second dimension. +% +% INPUTS: +% type: statistics type in the repertory: +% dgse +% irf_bvardsge +% smooth +% filter +% error +% innov +% forcst +% forcst1 +% type2: analysis type: +% posterior +% gsa +% prior +% +% OUTPUTS: +% none +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2003-2007 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 <http://www.gnu.org/licenses/>. + +global M_ options_ + +if nargin==1, + MhDirectoryName = [ CheckPath('metropolis') '/' ]; +else + if strcmpi(type2,'posterior') + MhDirectoryName = [CheckPath('metropolis') '/' ]; + elseif strcmpi(type2,'gsa') + if options_.opt_gsa.morris==1, + MhDirectoryName = [CheckPath('GSA\SCREEN') '/' ]; + elseif options_.opt_gsa.morris==2, + MhDirectoryName = [CheckPath('GSA\IDENTIF') '/' ]; + else + MhDirectoryName = [CheckPath('GSA') '/' ]; + end + else + MhDirectoryName = [CheckPath('prior') '/' ]; + end +end +switch type + case 'irf_dsge' + CAPtype = 'IRF_DSGE'; + TYPEsize = [ options_.irf , size(options_.varlist,1) , M_.exo_nbr ]; + TYPEarray = 4; + case 'irf_bvardsge' + CAPtype = 'IRF_BVARDSGE'; + TYPEsize = [ options_.irf , size(options_.varobs,1) , M_.exo_nbr ]; + TYPEarray = 4; + case 'smooth' + CAPtype = 'SMOOTH'; + TYPEsize = [ M_.endo_nbr , options_.nobs ]; + TYPEarray = 3; + case 'filter' + CAPtype = 'FILTER'; + TYPEsize = [ M_.endo_nbr , options_.nobs + 1 ];% TO BE CHECKED! + TYPEarray = 3; + case 'error' + CAPtype = 'ERROR'; + TYPEsize = [ size(options_.varobs,1) , options_.nobs ]; + TYPEarray = 3; + case 'innov' + CAPtype = 'INNOV'; + TYPEsize = [ M_.exo_nbr , options_.nobs ]; + TYPEarray = 3; + case 'forcst' + CAPtype = 'FORCST'; + TYPEsize = [ M_.endo_nbr , options_.forecast ]; + TYPEarray = 3; + case 'forcst1' + CAPtype = 'FORCST1'; + TYPEsize = [ M_.endo_nbr , options_.forecast ]; + TYPEarray = 3; + otherwise + disp('ReshapeMatFiles :: Unknown argument!') + return +end + +TYPEfiles = dir([MhDirectoryName M_.fname '_' type '*.mat']); +NumberOfTYPEfiles = length(TYPEfiles); +B = options_.B; + +switch TYPEarray + case 4 + if NumberOfTYPEfiles > 1 + NumberOfPeriodsPerTYPEfiles = ceil(TYPEsize(1)/NumberOfTYPEfiles); + foffset = NumberOfTYPEfiles-floor(TYPEsize(1)/NumberOfPeriodsPerTYPEfiles); + reste = TYPEsize(1)-NumberOfPeriodsPerTYPEfiles*(NumberOfTYPEfiles-foffset); + idx = 0; + jdx = 0; + for f1=1:NumberOfTYPEfiles-foffset + eval(['STOCK_' CAPtype ' = zeros(NumberOfPeriodsPerTYPEfiles,TYPEsize(2),TYPEsize(3),B);']) + for f2 = 1:NumberOfTYPEfiles + load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']); + eval(['STOCK_' CAPtype '(:,:,:,idx+1:idx+size(stock_' type ',4))=stock_' ... + type '(jdx+1:jdx+NumberOfPeriodsPerTYPEfiles,:,:,:);']) + eval(['idx = idx + size(stock_' type ',4);']) + end + %eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',4);']) + save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(f1) '.mat'],['STOCK_' CAPtype]); + jdx = jdx + NumberOfPeriodsPerTYPEfiles; + idx = 0; + end + if reste + eval(['STOCK_' CAPtype ' = zeros(reste,TYPEsize(2),TYPEsize(3),B);']) + for f2 = 1:NumberOfTYPEfiles + load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']); + eval(['STOCK_' CAPtype '(:,:,:,idx+1:idx+size(stock_' type ',4))=stock_' type '(jdx+1:jdx+reste,:,:,:);']) + eval(['idx = idx + size(stock_' type ',4);']) + end + %eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',4);']) + save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(NumberOfTYPEfiles-foffset+1) '.mat'],['STOCK_' CAPtype]); + end + else + load([MhDirectoryName M_.fname '_' type '1.mat']); + %eval(['STOCK_' CAPtype ' = sort(stock_' type ',4);']) + eval(['STOCK_' CAPtype ' = stock_' type ';']) + save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(1) '.mat'],['STOCK_' CAPtype ]); + end + % Original file format may be useful in some cases... + % for file = 1:NumberOfTYPEfiles + % delete([MhDirectoryName M_.fname '_' type int2str(file) '.mat']) + % end + case 3 + if NumberOfTYPEfiles>1 + NumberOfPeriodsPerTYPEfiles = ceil( TYPEsize(2)/NumberOfTYPEfiles ); + reste = TYPEsize(2)-NumberOfPeriodsPerTYPEfiles*(NumberOfTYPEfiles-1); + idx = 0; + jdx = 0; + for f1=1:NumberOfTYPEfiles-1 + eval(['STOCK_' CAPtype ' = zeros(TYPEsize(1),NumberOfPeriodsPerTYPEfiles,B);']) + for f2 = 1:NumberOfTYPEfiles + load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']); + eval(['STOCK_' CAPtype '(:,:,idx+1:idx+size(stock_ ' type ',3))=stock_' type '(:,jdx+1:jdx+NumberOfPeriodsPerTYPEfiles,:);']) + eval(['idx = idx + size(stock_' type ',3);']) + end + %eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',3);']) + save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(f1) '.mat'],['STOCK_' CAPtype]); + jdx = jdx + NumberOfPeriodsPerTYPEfiles; + idx = 0; + end + eval(['STOCK_' CAPtype ' = zeros(TYPEsize(1),reste,B);']) + for f2 = 1:NumberOfTYPEfiles + load([MhDirectoryName M_.fname '_' type int2str(f2) '.mat']); + eval(['STOCK_' CAPtype '(:,:,idx+1:idx+size(stock_' type ',3))=stock_' type '(:,jdx+1:jdx+reste,:);']) + eval(['idx = idx + size(stock_' type ',3);']) + end + %eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',3);']) + save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(NumberOfTYPEfiles) '.mat'],['STOCK_' CAPtype]); + else + load([MhDirectoryName M_.fname '_' type '1.mat']); + %eval(['STOCK_' CAPtype ' = sort(stock_' type ',3);']) + eval(['STOCK_' CAPtype ' = stock_' type ';']) + save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(1) '.mat'],['STOCK_' CAPtype ]); + end + % Original file format may be useful in some cases... + % for file = 1:NumberOfTYPEfiles + % delete([MhDirectoryName M_.fname '_' type int2str(file) '.mat']) + % end +end \ No newline at end of file diff --git a/matlab/UnivariateSpectralDensity.m b/matlab/UnivariateSpectralDensity.m index 671b258203..2ecc826e06 100644 --- a/matlab/UnivariateSpectralDensity.m +++ b/matlab/UnivariateSpectralDensity.m @@ -1,179 +1,179 @@ -function [omega,f] = UnivariateSpectralDensity(dr,var_list) -% This function computes the theoretical spectral density of each -% endogenous variable declared in var_list. Results are stored in -% oo_ and may be plotted. -% -% Adapted from th_autocovariances.m. - -% Copyright (C) 2006-2009 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 <http://www.gnu.org/licenses/>. - -global options_ oo_ M_ - - -omega = []; f = []; - -if options_.order > 1 - disp('UnivariateSpectralDensity :: I Cannot compute the theoretical spectral density') - disp('with a second order approximation of the DSGE model!') - disp('Set order = 1.') - return -end - -pltinfo = 1;%options_.SpectralDensity.Th.plot; -cutoff = 150;%options_.SpectralDensity.Th.cutoff; -sdl = 0.01;%options_.SepctralDensity.Th.sdl; -omega = (0:sdl:pi)'; -GridSize = length(omega); -exo_names_orig_ord = M_.exo_names_orig_ord; -if exist('OCTAVE_VERSION') - warning('off', 'Octave:divide-by-zero') -else - warning off MATLAB:dividebyzero -end -if nargin<2 - var_list = []; -end -if size(var_list,1) == 0 - var_list = M_.endo_names(1:M_.orig_endo_nbr, :); -end -nvar = size(var_list,1); - ivar=zeros(nvar,1); - for i=1:nvar - i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact'); - if isempty(i_tmp) - error (['One of the variable specified does not exist']) ; - else - ivar(i) = i_tmp; - end - end -f = zeros(nvar,GridSize); -ghx = dr.ghx; -ghu = dr.ghu; -npred = dr.npred; -nstatic = dr.nstatic; -kstate = dr.kstate; -order = dr.order_var; -iv(order) = [1:length(order)]; -nx = size(ghx,2); -ikx = [nstatic+1:nstatic+npred]; -A = zeros(nx,nx); -k0 = kstate(find(kstate(:,2) <= M_.maximum_lag+1),:); -i0 = find(k0(:,2) == M_.maximum_lag+1); -i00 = i0; -n0 = length(i0); -A(i0,:) = ghx(ikx,:); -AS = ghx(:,i0); -ghu1 = zeros(nx,M_.exo_nbr); -ghu1(i0,:) = ghu(ikx,:); -for i=M_.maximum_lag:-1:2 - i1 = find(k0(:,2) == i); - n1 = size(i1,1); - j1 = zeros(n1,1); - j2 = j1; - for k1 = 1:n1 - j1(k1) = find(k0(i00,1)==k0(i1(k1),1)); - j2(k1) = find(k0(i0,1)==k0(i1(k1),1)); - end - AS(:,j1) = AS(:,j1)+ghx(:,i1); - i0 = i1; -end -Gamma = zeros(nvar,cutoff+1); -[A,B] = kalman_transition_matrix(dr,ikx',1:nx,dr.transition_auxiliary_variables,M_.exo_nbr); -[vx, u] = lyapunov_symm(A,B*M_.Sigma_e*B',options_.qz_criterium,options_.lyapunov_complex_threshold); -iky = iv(ivar); -if ~isempty(u) - iky = iky(find(any(abs(ghx(iky,:)*u) < options_.Schur_vec_tol,2))); - ivar = dr.order_var(iky); -end -aa = ghx(iky,:); -bb = ghu(iky,:); - -if options_.hp_filter == 0 - tmp = aa*vx*aa'+ bb*M_.Sigma_e*bb'; - k = find(abs(tmp) < 1e-12); - tmp(k) = 0; - Gamma(:,1) = diag(tmp); - vxy = (A*vx*aa'+ghu1*M_.Sigma_e*bb'); - tmp = aa*vxy; - k = find(abs(tmp) < 1e-12); - tmp(k) = 0; - Gamma(:,2) = diag(tmp); - for i=2:cutoff - vxy = A*vxy; - tmp = aa*vxy; - k = find(abs(tmp) < 1e-12); - tmp(k) = 0; - Gamma(:,i+1) = diag(tmp); - end -else - iky = iv(ivar); - aa = ghx(iky,:); - bb = ghu(iky,:); - lambda = options_.hp_filter; - ngrid = options_.hp_ngrid; - freqs = 0 : ((2*pi)/ngrid) : (2*pi*(1 - .5/ngrid)); - tpos = exp( sqrt(-1)*freqs); - tneg = exp(-sqrt(-1)*freqs); - hp1 = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2); - mathp_col = []; - IA = eye(size(A,1)); - IE = eye(M_.exo_nbr); - for ig = 1:ngrid - f_omega =(1/(2*pi))*( [inv(IA-A*tneg(ig))*ghu1;IE]... - *M_.Sigma_e*[ghu1'*inv(IA-A'*tpos(ig)) IE]); % state variables - g_omega = [aa*tneg(ig) bb]*f_omega*[aa'*tpos(ig); bb']; % selected variables - f_hp = hp1(ig)^2*g_omega; % spectral density of selected filtered series - mathp_col = [mathp_col ; (f_hp(:))']; % store as matrix row - % for ifft - end; - imathp_col = real(ifft(mathp_col))*(2*pi); - tmp = reshape(imathp_col(1,:),nvar,nvar); - k = find(abs(tmp)<1e-12); - tmp(k) = 0; - Gamma(:,1) = diag(tmp); - sy = sqrt(Gamma(:,1)); - sy = sy *sy'; - for i=1:cutoff-1 - tmp = reshape(imathp_col(i+1,:),nvar,nvar)./sy; - k = find(abs(tmp) < 1e-12); - tmp(k) = 0; - Gamma(:,i+1) = diag(tmp); - end -end - -H = 1:cutoff; -for i=1:nvar - f(i,:) = Gamma(i,1)/(2*pi) + Gamma(i,H+1)*cos(H'*omega')/pi; -end - -if exist('OCTAVE_VERSION') - warning('on', 'Octave:divide-by-zero') -else - warning on MATLAB:dividebyzero -end - -if pltinfo - for i= 1:nvar - figure('Name',['Spectral Density of ' deblank(M_.endo_names(ivar(i),:)) '.']) - plot(omega,f(i,:),'-k','linewidth',2) - xlabel('0 \leq \omega \leq \pi') - ylabel('f(\omega)') - box on - axis tight - end +function [omega,f] = UnivariateSpectralDensity(dr,var_list) +% This function computes the theoretical spectral density of each +% endogenous variable declared in var_list. Results are stored in +% oo_ and may be plotted. +% +% Adapted from th_autocovariances.m. + +% Copyright (C) 2006-2009 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 <http://www.gnu.org/licenses/>. + +global options_ oo_ M_ + + +omega = []; f = []; + +if options_.order > 1 + disp('UnivariateSpectralDensity :: I Cannot compute the theoretical spectral density') + disp('with a second order approximation of the DSGE model!') + disp('Set order = 1.') + return +end + +pltinfo = 1;%options_.SpectralDensity.Th.plot; +cutoff = 150;%options_.SpectralDensity.Th.cutoff; +sdl = 0.01;%options_.SepctralDensity.Th.sdl; +omega = (0:sdl:pi)'; +GridSize = length(omega); +exo_names_orig_ord = M_.exo_names_orig_ord; +if exist('OCTAVE_VERSION') + warning('off', 'Octave:divide-by-zero') +else + warning off MATLAB:dividebyzero +end +if nargin<2 + var_list = []; +end +if size(var_list,1) == 0 + var_list = M_.endo_names(1:M_.orig_endo_nbr, :); +end +nvar = size(var_list,1); +ivar=zeros(nvar,1); +for i=1:nvar + i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact'); + if isempty(i_tmp) + error (['One of the variable specified does not exist']) ; + else + ivar(i) = i_tmp; + end +end +f = zeros(nvar,GridSize); +ghx = dr.ghx; +ghu = dr.ghu; +npred = dr.npred; +nstatic = dr.nstatic; +kstate = dr.kstate; +order = dr.order_var; +iv(order) = [1:length(order)]; +nx = size(ghx,2); +ikx = [nstatic+1:nstatic+npred]; +A = zeros(nx,nx); +k0 = kstate(find(kstate(:,2) <= M_.maximum_lag+1),:); +i0 = find(k0(:,2) == M_.maximum_lag+1); +i00 = i0; +n0 = length(i0); +A(i0,:) = ghx(ikx,:); +AS = ghx(:,i0); +ghu1 = zeros(nx,M_.exo_nbr); +ghu1(i0,:) = ghu(ikx,:); +for i=M_.maximum_lag:-1:2 + i1 = find(k0(:,2) == i); + n1 = size(i1,1); + j1 = zeros(n1,1); + j2 = j1; + for k1 = 1:n1 + j1(k1) = find(k0(i00,1)==k0(i1(k1),1)); + j2(k1) = find(k0(i0,1)==k0(i1(k1),1)); + end + AS(:,j1) = AS(:,j1)+ghx(:,i1); + i0 = i1; +end +Gamma = zeros(nvar,cutoff+1); +[A,B] = kalman_transition_matrix(dr,ikx',1:nx,dr.transition_auxiliary_variables,M_.exo_nbr); +[vx, u] = lyapunov_symm(A,B*M_.Sigma_e*B',options_.qz_criterium,options_.lyapunov_complex_threshold); +iky = iv(ivar); +if ~isempty(u) + iky = iky(find(any(abs(ghx(iky,:)*u) < options_.Schur_vec_tol,2))); + ivar = dr.order_var(iky); +end +aa = ghx(iky,:); +bb = ghu(iky,:); + +if options_.hp_filter == 0 + tmp = aa*vx*aa'+ bb*M_.Sigma_e*bb'; + k = find(abs(tmp) < 1e-12); + tmp(k) = 0; + Gamma(:,1) = diag(tmp); + vxy = (A*vx*aa'+ghu1*M_.Sigma_e*bb'); + tmp = aa*vxy; + k = find(abs(tmp) < 1e-12); + tmp(k) = 0; + Gamma(:,2) = diag(tmp); + for i=2:cutoff + vxy = A*vxy; + tmp = aa*vxy; + k = find(abs(tmp) < 1e-12); + tmp(k) = 0; + Gamma(:,i+1) = diag(tmp); + end +else + iky = iv(ivar); + aa = ghx(iky,:); + bb = ghu(iky,:); + lambda = options_.hp_filter; + ngrid = options_.hp_ngrid; + freqs = 0 : ((2*pi)/ngrid) : (2*pi*(1 - .5/ngrid)); + tpos = exp( sqrt(-1)*freqs); + tneg = exp(-sqrt(-1)*freqs); + hp1 = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2); + mathp_col = []; + IA = eye(size(A,1)); + IE = eye(M_.exo_nbr); + for ig = 1:ngrid + f_omega =(1/(2*pi))*( [inv(IA-A*tneg(ig))*ghu1;IE]... + *M_.Sigma_e*[ghu1'*inv(IA-A'*tpos(ig)) IE]); % state variables + g_omega = [aa*tneg(ig) bb]*f_omega*[aa'*tpos(ig); bb']; % selected variables + f_hp = hp1(ig)^2*g_omega; % spectral density of selected filtered series + mathp_col = [mathp_col ; (f_hp(:))']; % store as matrix row + % for ifft + end; + imathp_col = real(ifft(mathp_col))*(2*pi); + tmp = reshape(imathp_col(1,:),nvar,nvar); + k = find(abs(tmp)<1e-12); + tmp(k) = 0; + Gamma(:,1) = diag(tmp); + sy = sqrt(Gamma(:,1)); + sy = sy *sy'; + for i=1:cutoff-1 + tmp = reshape(imathp_col(i+1,:),nvar,nvar)./sy; + k = find(abs(tmp) < 1e-12); + tmp(k) = 0; + Gamma(:,i+1) = diag(tmp); + end +end + +H = 1:cutoff; +for i=1:nvar + f(i,:) = Gamma(i,1)/(2*pi) + Gamma(i,H+1)*cos(H'*omega')/pi; +end + +if exist('OCTAVE_VERSION') + warning('on', 'Octave:divide-by-zero') +else + warning on MATLAB:dividebyzero +end + +if pltinfo + for i= 1:nvar + figure('Name',['Spectral Density of ' deblank(M_.endo_names(ivar(i),:)) '.']) + plot(omega,f(i,:),'-k','linewidth',2) + xlabel('0 \leq \omega \leq \pi') + ylabel('f(\omega)') + box on + axis tight + end end \ No newline at end of file diff --git a/matlab/add_auxiliary_variables_to_steadystate.m b/matlab/add_auxiliary_variables_to_steadystate.m index f010d12d11..a88460876b 100644 --- a/matlab/add_auxiliary_variables_to_steadystate.m +++ b/matlab/add_auxiliary_variables_to_steadystate.m @@ -1,7 +1,7 @@ function ys1 = add_auxiliary_variables_to_steadystate(ys,aux_vars,fname, ... - exo_steady_state, exo_det_steady_state,params) + exo_steady_state, exo_det_steady_state,params) % Add auxiliary variables to the steady state vector - + % Copyright (C) 2009 Dynare Team % % This file is part of Dynare. @@ -18,29 +18,28 @@ function ys1 = add_auxiliary_variables_to_steadystate(ys,aux_vars,fname, ... % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - n = length(aux_vars); - ys1 = [ys;zeros(n,1)]; - k = size(ys,1)+1; - aux_lead_nbr = 0; - for i=1:n - if aux_vars(i).type == 1 - ys1(k) = ys(aux_vars(i).orig_index); - elseif aux_vars(i).type == 0 - aux_lead_nbr = aux_lead_nbr + 1; - end - k = k+1; + +n = length(aux_vars); +ys1 = [ys;zeros(n,1)]; +k = size(ys,1)+1; +aux_lead_nbr = 0; +for i=1:n + if aux_vars(i).type == 1 + ys1(k) = ys(aux_vars(i).orig_index); + elseif aux_vars(i).type == 0 + aux_lead_nbr = aux_lead_nbr + 1; end - - for i=1:aux_lead_nbr+1; - res = feval([fname '_static'],ys1,... - [exo_steady_state; ... - exo_det_steady_state],params); - for j=1:n - if aux_vars(j).type == 0 - el = aux_vars(j).endo_index; - ys1(el) = ys1(el)-res(el); - end + k = k+1; +end + +for i=1:aux_lead_nbr+1; + res = feval([fname '_static'],ys1,... + [exo_steady_state; ... + exo_det_steady_state],params); + for j=1:n + if aux_vars(j).type == 0 + el = aux_vars(j).endo_index; + ys1(el) = ys1(el)-res(el); end end - \ No newline at end of file +end diff --git a/matlab/autoregressive_process_specification.m b/matlab/autoregressive_process_specification.m index ec1cbc90de..7cc34db27d 100644 --- a/matlab/autoregressive_process_specification.m +++ b/matlab/autoregressive_process_specification.m @@ -59,28 +59,28 @@ function [InnovationVariance,AutoregressiveParameters] = autoregressive_process_ % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - AutoregressiveParameters = NaN(p,1); - InnovationVariance = NaN; - switch p - case 1 - AutoregressiveParameters = Rho(1); - case 2 - tmp = (Rho(2)-1)/(Rho(1)*Rho(1)-1); - AutoregressiveParameters(1) = Rho(1)*tmp; - AutoregressiveParameters(2) = 1-tmp; - case 3 - t1 = 1/(Rho(2)-2*Rho(1)*Rho(1)+1); - t2 = (1.5*Rho(1)-2*Rho(1)*Rho(1)*Rho(1)+.5*Rho(3))*t1; - t3 = .5*(Rho(1)- Rho(3))/(Rho(2)-1); - AutoregressiveParameters(1) = t2-t3-Rho(1); - AutoregressiveParameters(2) = (Rho(2)*Rho(2)-Rho(3)*Rho(1)-Rho(1)*Rho(1)+Rho(2))*t1 ; - AutoregressiveParameters(3) = t3-Rho(1)+t2; - otherwise - AutocorrelationMatrix = eye(p); - for i=1:p-1 - AutocorrelationMatrix = AutocorrelationMatrix + diag(Rho(i)*ones(p-i,1),i); - AutocorrelationMatrix = AutocorrelationMatrix + diag(Rho(i)*ones(p-i,1),-i); - end - AutoregressiveParameters = AutocorrelationMatrix\Rho; +AutoregressiveParameters = NaN(p,1); +InnovationVariance = NaN; +switch p + case 1 + AutoregressiveParameters = Rho(1); + case 2 + tmp = (Rho(2)-1)/(Rho(1)*Rho(1)-1); + AutoregressiveParameters(1) = Rho(1)*tmp; + AutoregressiveParameters(2) = 1-tmp; + case 3 + t1 = 1/(Rho(2)-2*Rho(1)*Rho(1)+1); + t2 = (1.5*Rho(1)-2*Rho(1)*Rho(1)*Rho(1)+.5*Rho(3))*t1; + t3 = .5*(Rho(1)- Rho(3))/(Rho(2)-1); + AutoregressiveParameters(1) = t2-t3-Rho(1); + AutoregressiveParameters(2) = (Rho(2)*Rho(2)-Rho(3)*Rho(1)-Rho(1)*Rho(1)+Rho(2))*t1 ; + AutoregressiveParameters(3) = t3-Rho(1)+t2; + otherwise + AutocorrelationMatrix = eye(p); + for i=1:p-1 + AutocorrelationMatrix = AutocorrelationMatrix + diag(Rho(i)*ones(p-i,1),i); + AutocorrelationMatrix = AutocorrelationMatrix + diag(Rho(i)*ones(p-i,1),-i); end - InnovationVariance = Variance * (1-AutoregressiveParameters'*Rho); \ No newline at end of file + AutoregressiveParameters = AutocorrelationMatrix\Rho; +end +InnovationVariance = Variance * (1-AutoregressiveParameters'*Rho); \ No newline at end of file diff --git a/matlab/bfgsi.m b/matlab/bfgsi.m index 0f3c1b4265..84e4813c8e 100644 --- a/matlab/bfgsi.m +++ b/matlab/bfgsi.m @@ -25,20 +25,20 @@ function H = bfgsi(H0,dg,dx) % along with Dynare. If not, see <http://www.gnu.org/licenses/>. if size(dg,2)>1 - dg=dg'; + dg=dg'; end if size(dx,2)>1 - dx=dx'; + dx=dx'; end Hdg = H0*dg; dgdx = dg'*dx; if (abs(dgdx) >1e-12) - H = H0 + (1+(dg'*Hdg)/dgdx)*(dx*dx')/dgdx - (dx*Hdg'+Hdg*dx')/dgdx; + H = H0 + (1+(dg'*Hdg)/dgdx)*(dx*dx')/dgdx - (dx*Hdg'+Hdg*dx')/dgdx; else - disp('bfgs update failed.') - disp(['|dg| = ' num2str(sqrt(dg'*dg)) '|dx| = ' num2str(sqrt(dx'*dx))]); - disp(['dg''*dx = ' num2str(dgdx)]) - disp(['|H*dg| = ' num2str(Hdg'*Hdg)]) - H=H0; + disp('bfgs update failed.') + disp(['|dg| = ' num2str(sqrt(dg'*dg)) '|dx| = ' num2str(sqrt(dx'*dx))]); + disp(['dg''*dx = ' num2str(dgdx)]) + disp(['|H*dg| = ' num2str(Hdg'*Hdg)]) + H=H0; end save H.dat H diff --git a/matlab/bicgstab_.m b/matlab/bicgstab_.m index 43e8b019f9..30aeef2953 100644 --- a/matlab/bicgstab_.m +++ b/matlab/bicgstab_.m @@ -17,20 +17,20 @@ function [x,status]=bicgstab_(func,b,x,tole,kmax,varargin) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - status = 0; - r=b-feval(func,x,varargin{:}); - rh_0 = r; - rh = r; - rho_0 = 1; - alpha = 1; - w = 1; - v = 0; - p = 0; - k = 0; - rho_1 = rh_0'*r; - tolr = tole*norm(b); - - while norm(r) > tolr & k < kmax +status = 0; +r=b-feval(func,x,varargin{:}); +rh_0 = r; +rh = r; +rho_0 = 1; +alpha = 1; +w = 1; +v = 0; +p = 0; +k = 0; +rho_1 = rh_0'*r; +tolr = tole*norm(b); + +while norm(r) > tolr & k < kmax k = k+1; beta = (rho_1/rho_0)*(alpha/w); p = r+beta*(p-w*v); @@ -43,8 +43,8 @@ function [x,status]=bicgstab_(func,b,x,tole,kmax,varargin) rho_1 = -w*(rh_0'*t); x = x+alpha*p+w*r; r = r-w*t; - end +end if k == kmax - status = 1; - warning(sprintf('BICSTABN didn''t converge after %d iterations: norm(r) = %g',kmax,norm(r))); + status = 1; + warning(sprintf('BICSTABN didn''t converge after %d iterations: norm(r) = %g',kmax,norm(r))); end \ No newline at end of file diff --git a/matlab/bksup1.m b/matlab/bksup1.m index 61fc00da77..2fa21290ff 100644 --- a/matlab/bksup1.m +++ b/matlab/bksup1.m @@ -36,9 +36,9 @@ irf = iyf+(options_.periods-1)*ny ; icf = [1:size(iyf,2)] ; for i = 2:options_.periods - c(ir,jcf) = c(ir,jcf)-c(ir,icf)*c(irf,jcf) ; - ir = ir-ny ; - irf = irf-ny ; + c(ir,jcf) = c(ir,jcf)-c(ir,icf)*c(irf,jcf) ; + ir = ir-ny ; + irf = irf-ny ; end d = c(:,jcf) ; diff --git a/matlab/bksupk.m b/matlab/bksupk.m index bc13cb4f68..cd949a7b1c 100644 --- a/matlab/bksupk.m +++ b/matlab/bksupk.m @@ -49,28 +49,28 @@ ir = ir-ny ; i = 2 ; while i <= M_.maximum_lead | i <= options_.periods - irf1 = selif(irf,irf<=options_.periods*ny) ; + irf1 = selif(irf,irf<=options_.periods*ny) ; - ofs = (((options_.periods-i)*ny+1)-1)*jcf*8 ; - junk = fseek(fid,ofs,-1) ; - c = fread(fid,[jcf,ny],'float64')' ; + ofs = (((options_.periods-i)*ny+1)-1)*jcf*8 ; + junk = fseek(fid,ofs,-1) ; + c = fread(fid,[jcf,ny],'float64')' ; - d1(ir) = c(:,jcf) - c(:,1:size(irf1,1))*d1(irf1) ; - ir = ir - ny ; - irf = irf - ny ; - i = i + 1 ; + d1(ir) = c(:,jcf) - c(:,1:size(irf1,1))*d1(irf1) ; + ir = ir - ny ; + irf = irf - ny ; + i = i + 1 ; end while i <= options_.periods - ofs = (((options_.periods-i)*ny+1)-1)*jcf*8 ; - junk = fseek(fid,ofs,-1) ; - c = fread(fid,[jcf,ny],'float64')' ; + ofs = (((options_.periods-i)*ny+1)-1)*jcf*8 ; + junk = fseek(fid,ofs,-1) ; + c = fread(fid,[jcf,ny],'float64')' ; - d1(ir) = c(:,jcf)-c(:,icf)*d1(irf) ; - ir = ir-ny ; - irf = irf-ny ; - i = i+1; + d1(ir) = c(:,jcf)-c(:,icf)*d1(irf) ; + ir = ir-ny ; + irf = irf-ny ; + i = i+1; end return ; diff --git a/matlab/block_mfs_steadystate.m b/matlab/block_mfs_steadystate.m index f1c7de4df4..172cb0f21f 100644 --- a/matlab/block_mfs_steadystate.m +++ b/matlab/block_mfs_steadystate.m @@ -19,12 +19,12 @@ function [r, g1] = block_mfs_steadystate(y, b) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ oo_ - - ss = oo_.steady_state; - indx = M_.blocksMFS{b}; - - ss(indx) = y; - x = [oo_.exo_steady_state; oo_.exo_det_steady_state]; +global M_ oo_ - eval(['[r,g1] = ' M_.fname '_static(b, ss, x, M_.params);']); +ss = oo_.steady_state; +indx = M_.blocksMFS{b}; + +ss(indx) = y; +x = [oo_.exo_steady_state; oo_.exo_det_steady_state]; + +eval(['[r,g1] = ' M_.fname '_static(b, ss, x, M_.params);']); diff --git a/matlab/bseastr.m b/matlab/bseastr.m index 0dcb5a4249..fd618da567 100644 --- a/matlab/bseastr.m +++ b/matlab/bseastr.m @@ -23,26 +23,26 @@ s1=upper(deblank(s1)); s2=upper(deblank(s2)); for im = 1:m - key = s1(im,:) ; - h = size(s2,1) ; - l = 1 ; - while l <= h - mid = round((h+l)/2) ; - temp = s2(mid,:) ; - if ~ strcmp(key,temp) - for i = 1:min(length(key),length(temp)) - if temp(i) > key(i) - h = mid - 1 ; - break - else - l = mid + 1 ; - break - end - end - else - x(im) = mid ; - break - end - end + key = s1(im,:) ; + h = size(s2,1) ; + l = 1 ; + while l <= h + mid = round((h+l)/2) ; + temp = s2(mid,:) ; + if ~ strcmp(key,temp) + for i = 1:min(length(key),length(temp)) + if temp(i) > key(i) + h = mid - 1 ; + break + else + l = mid + 1 ; + break + end + end + else + x(im) = mid ; + break + end + end end diff --git a/matlab/bvar_density.m b/matlab/bvar_density.m index e74bb57bbc..e0eeadba4d 100644 --- a/matlab/bvar_density.m +++ b/matlab/bvar_density.m @@ -29,21 +29,21 @@ function bvar_density(maxnlags) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - for nlags = 1:maxnlags - [ny, nx, posterior, prior] = bvar_toolbox(nlags); - - posterior_int = matrictint(posterior.S, posterior.df, posterior.XXi); - prior_int = matrictint(prior.S, prior.df, prior.XXi); - - lik_nobs = posterior.df - prior.df; - - log_dnsty = posterior_int - prior_int - 0.5*ny*lik_nobs*log(2*pi); - - disp(' ') - fprintf('The marginal log density of the BVAR(%g) model is equal to %10.4f\n', ... - nlags, log_dnsty); - disp(' ') - end +for nlags = 1:maxnlags + [ny, nx, posterior, prior] = bvar_toolbox(nlags); + + posterior_int = matrictint(posterior.S, posterior.df, posterior.XXi); + prior_int = matrictint(prior.S, prior.df, prior.XXi); + + lik_nobs = posterior.df - prior.df; + + log_dnsty = posterior_int - prior_int - 0.5*ny*lik_nobs*log(2*pi); + + disp(' ') + fprintf('The marginal log density of the BVAR(%g) model is equal to %10.4f\n', ... + nlags, log_dnsty); + disp(' ') +end function w = matrictint(S, df, XXi) @@ -64,31 +64,31 @@ function w = matrictint(S, df, XXi) % Original file downloaded from: % http://sims.princeton.edu/yftp/VARtools/matlab/matrictint.m - - k=size(XXi,1); - ny=size(S,1); - [cx,p]=chol(XXi); - [cs,q]=chol(S); - if any(diag(cx)<100*eps) - error('singular XXi') - end - if any(diag(cs<100*eps)) - error('singular S') - end +k=size(XXi,1); +ny=size(S,1); +[cx,p]=chol(XXi); +[cs,q]=chol(S); - % Matrix-normal component - w1 = 0.5*k*ny*log(2*pi)+ny*sum(log(diag(cx))); - - % Inverse-Wishart component - w2 = -df*sum(log(diag(cs))) + 0.5*df*ny*log(2) + ny*(ny-1)*0.25*log(pi) + ggammaln(ny, df); - - w = w1 + w2; +if any(diag(cx)<100*eps) + error('singular XXi') +end +if any(diag(cs<100*eps)) + error('singular S') +end + +% Matrix-normal component +w1 = 0.5*k*ny*log(2*pi)+ny*sum(log(diag(cx))); + +% Inverse-Wishart component +w2 = -df*sum(log(diag(cs))) + 0.5*df*ny*log(2) + ny*(ny-1)*0.25*log(pi) + ggammaln(ny, df); + +w = w1 + w2; function lgg = ggammaln(m, df) - if df <= (m-1) - error('too few df in ggammaln') - else - garg = 0.5*(df+(0:-1:1-m)); - lgg = sum(gammaln(garg)); - end +if df <= (m-1) + error('too few df in ggammaln') +else + garg = 0.5*(df+(0:-1:1-m)); + lgg = sum(gammaln(garg)); +end diff --git a/matlab/bvar_forecast.m b/matlab/bvar_forecast.m index aad3406bf8..f455d40a14 100644 --- a/matlab/bvar_forecast.m +++ b/matlab/bvar_forecast.m @@ -28,158 +28,158 @@ function bvar_forecast(nlags) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global options_ oo_ M_ - - options_ = set_default_option(options_, 'bvar_replic', 2000); - if options_.forecast == 0 - error('bvar_forecast: you must specify "forecast" option') - end - [ny, nx, posterior, prior, forecast_data] = bvar_toolbox(nlags); +global options_ oo_ M_ + +options_ = set_default_option(options_, 'bvar_replic', 2000); +if options_.forecast == 0 + error('bvar_forecast: you must specify "forecast" option') +end +[ny, nx, posterior, prior, forecast_data] = bvar_toolbox(nlags); + +sims_no_shock = NaN(options_.forecast, ny, options_.bvar_replic); +sims_with_shocks = NaN(options_.forecast, ny, options_.bvar_replic); + +S_inv_upper_chol = chol(inv(posterior.S)); - sims_no_shock = NaN(options_.forecast, ny, options_.bvar_replic); - sims_with_shocks = NaN(options_.forecast, ny, options_.bvar_replic); +% Option 'lower' of chol() not available in old versions of +% Matlab, so using transpose +XXi_lower_chol = chol(posterior.XXi)'; + +k = ny*nlags+nx; + +% Declaration of the companion matrix +Companion_matrix = diag(ones(ny*(nlags-1),1),-ny); + +% Number of explosive VAR models sampled +p = 0; +% Loop counter initialization +d = 0; +while d <= options_.bvar_replic - S_inv_upper_chol = chol(inv(posterior.S)); + Sigma = rand_inverse_wishart(ny, posterior.df, S_inv_upper_chol); % Option 'lower' of chol() not available in old versions of % Matlab, so using transpose - XXi_lower_chol = chol(posterior.XXi)'; - - k = ny*nlags+nx; - - % Declaration of the companion matrix - Companion_matrix = diag(ones(ny*(nlags-1),1),-ny); - - % Number of explosive VAR models sampled - p = 0; - % Loop counter initialization - d = 0; - while d <= options_.bvar_replic - - Sigma = rand_inverse_wishart(ny, posterior.df, S_inv_upper_chol); - - % Option 'lower' of chol() not available in old versions of - % Matlab, so using transpose - Sigma_lower_chol = chol(Sigma)'; - - Phi = rand_matrix_normal(k, ny, posterior.PhiHat, Sigma_lower_chol, XXi_lower_chol); - - % All the eigenvalues of the companion matrix have to be on or inside the unit circle - Companion_matrix(1:ny,:) = Phi(1:ny*nlags,:)'; - test = (abs(eig(Companion_matrix))); - if any(test>1.0000000000001) - p = p+1; - end - d = d+1; - - % Without shocks - lags_data = forecast_data.initval; - for t = 1:options_.forecast - X = [ reshape(flipdim(lags_data, 1)', 1, ny*nlags) forecast_data.xdata(t, :) ]; - y = X * Phi; - lags_data(1:end-1,:) = lags_data(2:end, :); - lags_data(end,:) = y; - sims_no_shock(t, :, d) = y; - end + Sigma_lower_chol = chol(Sigma)'; + + Phi = rand_matrix_normal(k, ny, posterior.PhiHat, Sigma_lower_chol, XXi_lower_chol); - % With shocks - lags_data = forecast_data.initval; - for t = 1:options_.forecast - X = [ reshape(flipdim(lags_data, 1)', 1, ny*nlags) forecast_data.xdata(t, :) ]; - shock = (Sigma_lower_chol * randn(ny, 1))'; - y = X * Phi + shock; - lags_data(1:end-1,:) = lags_data(2:end, :); - lags_data(end,:) = y; - sims_with_shocks(t, :, d) = y; - end + % All the eigenvalues of the companion matrix have to be on or inside the unit circle + Companion_matrix(1:ny,:) = Phi(1:ny*nlags,:)'; + test = (abs(eig(Companion_matrix))); + if any(test>1.0000000000001) + p = p+1; end + d = d+1; - if p > 0 - disp(' ') - disp(['Some of the VAR models sampled from the posterior distribution']) - disp(['were found to be explosive (' num2str(p/options_.bvar_replic) ' percent).']) - disp(' ') + % Without shocks + lags_data = forecast_data.initval; + for t = 1:options_.forecast + X = [ reshape(flipdim(lags_data, 1)', 1, ny*nlags) forecast_data.xdata(t, :) ]; + y = X * Phi; + lags_data(1:end-1,:) = lags_data(2:end, :); + lags_data(end,:) = y; + sims_no_shock(t, :, d) = y; end - % Plot graphs - sims_no_shock_mean = mean(sims_no_shock, 3); - - sort_idx = round((0.5 + [-options_.conf_sig, options_.conf_sig, 0]/2) * options_.bvar_replic); - - sims_no_shock_sort = sort(sims_no_shock, 3); - sims_no_shock_down_conf = sims_no_shock_sort(:, :, sort_idx(1)); - sims_no_shock_up_conf = sims_no_shock_sort(:, :, sort_idx(2)); - sims_no_shock_median = sims_no_shock_sort(:, :, sort_idx(3)); - - sims_with_shocks_sort = sort(sims_with_shocks, 3); - sims_with_shocks_down_conf = sims_with_shocks_sort(:, :, sort_idx(1)); - sims_with_shocks_up_conf = sims_with_shocks_sort(:, :, sort_idx(2)); + % With shocks + lags_data = forecast_data.initval; + for t = 1:options_.forecast + X = [ reshape(flipdim(lags_data, 1)', 1, ny*nlags) forecast_data.xdata(t, :) ]; + shock = (Sigma_lower_chol * randn(ny, 1))'; + y = X * Phi + shock; + lags_data(1:end-1,:) = lags_data(2:end, :); + lags_data(end,:) = y; + sims_with_shocks(t, :, d) = y; + end +end + +if p > 0 + disp(' ') + disp(['Some of the VAR models sampled from the posterior distribution']) + disp(['were found to be explosive (' num2str(p/options_.bvar_replic) ' percent).']) + disp(' ') +end - dynare_graph_init(sprintf('BVAR forecasts (nlags = %d)', nlags), ny, {'b-' 'g-' 'g-' 'r-' 'r-'}); +% Plot graphs +sims_no_shock_mean = mean(sims_no_shock, 3); + +sort_idx = round((0.5 + [-options_.conf_sig, options_.conf_sig, 0]/2) * options_.bvar_replic); + +sims_no_shock_sort = sort(sims_no_shock, 3); +sims_no_shock_down_conf = sims_no_shock_sort(:, :, sort_idx(1)); +sims_no_shock_up_conf = sims_no_shock_sort(:, :, sort_idx(2)); +sims_no_shock_median = sims_no_shock_sort(:, :, sort_idx(3)); + +sims_with_shocks_sort = sort(sims_with_shocks, 3); +sims_with_shocks_down_conf = sims_with_shocks_sort(:, :, sort_idx(1)); +sims_with_shocks_up_conf = sims_with_shocks_sort(:, :, sort_idx(2)); + +dynare_graph_init(sprintf('BVAR forecasts (nlags = %d)', nlags), ny, {'b-' 'g-' 'g-' 'r-' 'r-'}); + +for i = 1:ny + dynare_graph([ sims_no_shock_median(:, i) ... + sims_no_shock_up_conf(:, i) sims_no_shock_down_conf(:, i) ... + sims_with_shocks_up_conf(:, i) sims_with_shocks_down_conf(:, i) ], ... + options_.varobs(i, :)); +end + +dynare_graph_close; + + +% Compute RMSE + +if ~isempty(forecast_data.realized_val) - for i = 1:ny - dynare_graph([ sims_no_shock_median(:, i) ... - sims_no_shock_up_conf(:, i) sims_no_shock_down_conf(:, i) ... - sims_with_shocks_up_conf(:, i) sims_with_shocks_down_conf(:, i) ], ... - options_.varobs(i, :)); + sq_err_cumul = zeros(1, ny); + + lags_data = forecast_data.initval; + for t = 1:size(forecast_data.realized_val, 1) + X = [ reshape(flipdim(lags_data, 1)', 1, ny*nlags) forecast_data.realized_xdata(t, :) ]; + y = X * posterior.PhiHat; + lags_data(1:end-1,:) = lags_data(2:end, :); + lags_data(end,:) = y; + sq_err_cumul = sq_err_cumul + (y - forecast_data.realized_val(t, :)) .^ 2; end - dynare_graph_close; - + rmse = sqrt(sq_err_cumul / size(sq_err_cumul, 1)); - % Compute RMSE + fprintf('RMSE of BVAR(%d):\n', nlags); - if ~isempty(forecast_data.realized_val) - - sq_err_cumul = zeros(1, ny); - - lags_data = forecast_data.initval; - for t = 1:size(forecast_data.realized_val, 1) - X = [ reshape(flipdim(lags_data, 1)', 1, ny*nlags) forecast_data.realized_xdata(t, :) ]; - y = X * posterior.PhiHat; - lags_data(1:end-1,:) = lags_data(2:end, :); - lags_data(end,:) = y; - sq_err_cumul = sq_err_cumul + (y - forecast_data.realized_val(t, :)) .^ 2; - end - - rmse = sqrt(sq_err_cumul / size(sq_err_cumul, 1)); - - fprintf('RMSE of BVAR(%d):\n', nlags); - - for i = 1:size(options_.varobs, 1) - fprintf('%s: %10.4f\n', options_.varobs(i, :), rmse(i)); - end - end + for i = 1:size(options_.varobs, 1) + fprintf('%s: %10.4f\n', options_.varobs(i, :), rmse(i)); + end +end - % Store results +% Store results - DirectoryName = [ M_.fname '/bvar_forecast' ]; - if ~isdir(DirectoryName) - if ~isdir(M_.fname) - mkdir(M_.fname); - end - mkdir(DirectoryName); +DirectoryName = [ M_.fname '/bvar_forecast' ]; +if ~isdir(DirectoryName) + if ~isdir(M_.fname) + mkdir(M_.fname); end - save([ DirectoryName '/simulations.mat'], 'sims_no_shock', 'sims_with_shocks'); + mkdir(DirectoryName); +end +save([ DirectoryName '/simulations.mat'], 'sims_no_shock', 'sims_with_shocks'); - for i = 1:size(options_.varobs, 1) - name = options_.varobs(i, :); - - sims = squeeze(sims_with_shocks(:,i,:)); - eval(['oo_.bvar.forecast.with_shocks.Mean.' name ' = mean(sims, 2);']); - eval(['oo_.bvar.forecast.with_shocks.Median.' name ' = median(sims, 2);']); - eval(['oo_.bvar.forecast.with_shocks.Var.' name ' = var(sims, 0, 2);']); - eval(['oo_.bvar.forecast.with_shocks.HPDsup.' name ' = sims_with_shocks_up_conf(:,i);']); - eval(['oo_.bvar.forecast.with_shocks.HPDinf.' name ' = sims_with_shocks_down_conf(:,i);']); - - sims = squeeze(sims_no_shock(:,i,:)); - eval(['oo_.bvar.forecast.no_shock.Mean.' name ' = sims_no_shock_mean(:,i);']); - eval(['oo_.bvar.forecast.no_shock.Median.' name ' = sims_no_shock_median(:,i);']); - eval(['oo_.bvar.forecast.no_shock.Var.' name ' = var(sims, 0, 2);']); - eval(['oo_.bvar.forecast.no_shock.HPDsup.' name ' = sims_no_shock_up_conf(:,i);']); - eval(['oo_.bvar.forecast.no_shock.HPDinf.' name ' = sims_no_shock_down_conf(:,i);']); - - if exist('rmse') - eval(['oo_.bvar.forecast.rmse.' name ' = rmse(i);']); - end +for i = 1:size(options_.varobs, 1) + name = options_.varobs(i, :); + + sims = squeeze(sims_with_shocks(:,i,:)); + eval(['oo_.bvar.forecast.with_shocks.Mean.' name ' = mean(sims, 2);']); + eval(['oo_.bvar.forecast.with_shocks.Median.' name ' = median(sims, 2);']); + eval(['oo_.bvar.forecast.with_shocks.Var.' name ' = var(sims, 0, 2);']); + eval(['oo_.bvar.forecast.with_shocks.HPDsup.' name ' = sims_with_shocks_up_conf(:,i);']); + eval(['oo_.bvar.forecast.with_shocks.HPDinf.' name ' = sims_with_shocks_down_conf(:,i);']); + + sims = squeeze(sims_no_shock(:,i,:)); + eval(['oo_.bvar.forecast.no_shock.Mean.' name ' = sims_no_shock_mean(:,i);']); + eval(['oo_.bvar.forecast.no_shock.Median.' name ' = sims_no_shock_median(:,i);']); + eval(['oo_.bvar.forecast.no_shock.Var.' name ' = var(sims, 0, 2);']); + eval(['oo_.bvar.forecast.no_shock.HPDsup.' name ' = sims_no_shock_up_conf(:,i);']); + eval(['oo_.bvar.forecast.no_shock.HPDinf.' name ' = sims_no_shock_down_conf(:,i);']); + + if exist('rmse') + eval(['oo_.bvar.forecast.rmse.' name ' = rmse(i);']); end +end diff --git a/matlab/bvar_irf.m b/matlab/bvar_irf.m index cee8e15597..a588762502 100644 --- a/matlab/bvar_irf.m +++ b/matlab/bvar_irf.m @@ -28,125 +28,125 @@ function bvar_irf(nlags,identification) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global options_ oo_ M_ - - if nargin==1 - identification = 'Cholesky'; - end - - options_ = set_default_option(options_, 'bvar_replic', 2000); +global options_ oo_ M_ - [ny, nx, posterior, prior] = bvar_toolbox(nlags); - - S_inv_upper_chol = chol(inv(posterior.S)); +if nargin==1 + identification = 'Cholesky'; +end - % Option 'lower' of chol() not available in old versions of - % Matlab, so using transpose - XXi_lower_chol = chol(posterior.XXi)'; - - k = ny*nlags+nx; - - % Declaration of the companion matrix - Companion_matrix = diag(ones(ny*(nlags-1),1),-ny); +options_ = set_default_option(options_, 'bvar_replic', 2000); + +[ny, nx, posterior, prior] = bvar_toolbox(nlags); + +S_inv_upper_chol = chol(inv(posterior.S)); + +% Option 'lower' of chol() not available in old versions of +% Matlab, so using transpose +XXi_lower_chol = chol(posterior.XXi)'; + +k = ny*nlags+nx; + +% Declaration of the companion matrix +Companion_matrix = diag(ones(ny*(nlags-1),1),-ny); + +% Number of explosive VAR models sampled +p = 0; + +% Initialize a four dimensional array. +sampled_irfs = NaN(ny, ny, options_.irf, options_.bvar_replic); + +for draw=1:options_.bvar_replic - % Number of explosive VAR models sampled - p = 0; + % Get a covariance matrix from an inverted Wishart distribution. + Sigma = rand_inverse_wishart(ny, posterior.df, S_inv_upper_chol); + Sigma_upper_chol = chol(Sigma); + Sigma_lower_chol = transpose(Sigma_upper_chol); - % Initialize a four dimensional array. - sampled_irfs = NaN(ny, ny, options_.irf, options_.bvar_replic); + % Get the Autoregressive matrices from a matrix variate distribution. + Phi = rand_matrix_normal(k, ny, posterior.PhiHat, Sigma_lower_chol, XXi_lower_chol); - for draw=1:options_.bvar_replic - - % Get a covariance matrix from an inverted Wishart distribution. - Sigma = rand_inverse_wishart(ny, posterior.df, S_inv_upper_chol); - Sigma_upper_chol = chol(Sigma); - Sigma_lower_chol = transpose(Sigma_upper_chol); - - % Get the Autoregressive matrices from a matrix variate distribution. - Phi = rand_matrix_normal(k, ny, posterior.PhiHat, Sigma_lower_chol, XXi_lower_chol); - - % Form the companion matrix. - Companion_matrix(1:ny,:) = transpose(Phi(1:ny*nlags,:)); - - % All the eigenvalues of the companion matrix have to be on or - % inside the unit circle to rule out explosive time series. - test = (abs(eig(Companion_matrix))); - if any(test>1.0000000000001) - p = p+1; - end - - if strcmpi(identification,'Cholesky') - StructuralMat = Sigma_lower_chol; - elseif strcmpi(identification,'SquareRoot') - StructuralMat = sqrtm(Sigma); - end - - % Build the IRFs... - lags_data = zeros(ny,ny*nlags) ; - sampled_irfs(:,:,1,draw) = Sigma_lower_chol ; - lags_data(:,1:ny) = Sigma_lower_chol ; - for t=2:options_.irf - sampled_irfs(:,:,t,draw) = lags_data(:,:)*Phi(1:ny*nlags,:) ; - lags_data(:,ny+1:end) = lags_data(:,1:end-ny) ; - lags_data(:,1:ny) = sampled_irfs(:,:,t,draw) ; - end - - end + % Form the companion matrix. + Companion_matrix(1:ny,:) = transpose(Phi(1:ny*nlags,:)); - if p > 0 - disp(' ') - disp(['Some of the VAR models sampled from the posterior distribution']) - disp(['were found to be explosive (' int2str(p) ' samples).']) - disp(' ') + % All the eigenvalues of the companion matrix have to be on or + % inside the unit circle to rule out explosive time series. + test = (abs(eig(Companion_matrix))); + if any(test>1.0000000000001) + p = p+1; end - posterior_mean_irfs = mean(sampled_irfs,4); - posterior_variance_irfs = var(sampled_irfs, 1, 4); - - sorted_irfs = sort(sampled_irfs,4); - sort_idx = round((0.5 + [-options_.conf_sig, options_.conf_sig, .0]/2) * options_.bvar_replic); - - posterior_down_conf_irfs = sorted_irfs(:,:,:,sort_idx(1)); - posterior_up_conf_irfs = sorted_irfs(:,:,:,sort_idx(2)); - posterior_median_irfs = sorted_irfs(:,:,:,sort_idx(3)); + if strcmpi(identification,'Cholesky') + StructuralMat = Sigma_lower_chol; + elseif strcmpi(identification,'SquareRoot') + StructuralMat = sqrtm(Sigma); + end - number_of_columns = fix(sqrt(ny)); - number_of_rows = ceil(ny / number_of_columns) ; - - % Plots of the IRFs - for shock=1:ny - figure('Name',['Posterior BVAR Impulse Responses (shock in equation ' int2str(shock) ').']); - for variable=1:ny - subplot(number_of_rows,number_of_columns,variable); - h1 = area(1:options_.irf,squeeze(posterior_up_conf_irfs(shock,variable,:))); - set(h1,'BaseValue',min([min(posterior_up_conf_irfs(shock,variable,:)),min(posterior_down_conf_irfs(shock,variable,:))])) - set(h1,'FaceColor',[.9 .9 .9]) - hold on - h2 = area(1:options_.irf,squeeze(posterior_down_conf_irfs(shock,variable,:))); - set(h2,'BaseValue',min([min(posterior_up_conf_irfs(shock,variable,:)),min(posterior_down_conf_irfs(shock,variable,:))])) - set(h2,'FaceColor',[1 1 1]) - plot(1:options_.irf,squeeze(posterior_median_irfs(shock,variable,:)),'-k','linewidth',2) - axis tight - hold off - end + % Build the IRFs... + lags_data = zeros(ny,ny*nlags) ; + sampled_irfs(:,:,1,draw) = Sigma_lower_chol ; + lags_data(:,1:ny) = Sigma_lower_chol ; + for t=2:options_.irf + sampled_irfs(:,:,t,draw) = lags_data(:,:)*Phi(1:ny*nlags,:) ; + lags_data(:,ny+1:end) = lags_data(:,1:end-ny) ; + lags_data(:,1:ny) = sampled_irfs(:,:,t,draw) ; end - % Save intermediate results - DirectoryName = [ M_.fname '/bvar_irf' ]; - if ~isdir(DirectoryName) - mkdir('.',DirectoryName); +end + +if p > 0 + disp(' ') + disp(['Some of the VAR models sampled from the posterior distribution']) + disp(['were found to be explosive (' int2str(p) ' samples).']) + disp(' ') +end + +posterior_mean_irfs = mean(sampled_irfs,4); +posterior_variance_irfs = var(sampled_irfs, 1, 4); + +sorted_irfs = sort(sampled_irfs,4); +sort_idx = round((0.5 + [-options_.conf_sig, options_.conf_sig, .0]/2) * options_.bvar_replic); + +posterior_down_conf_irfs = sorted_irfs(:,:,:,sort_idx(1)); +posterior_up_conf_irfs = sorted_irfs(:,:,:,sort_idx(2)); +posterior_median_irfs = sorted_irfs(:,:,:,sort_idx(3)); + +number_of_columns = fix(sqrt(ny)); +number_of_rows = ceil(ny / number_of_columns) ; + +% Plots of the IRFs +for shock=1:ny + figure('Name',['Posterior BVAR Impulse Responses (shock in equation ' int2str(shock) ').']); + for variable=1:ny + subplot(number_of_rows,number_of_columns,variable); + h1 = area(1:options_.irf,squeeze(posterior_up_conf_irfs(shock,variable,:))); + set(h1,'BaseValue',min([min(posterior_up_conf_irfs(shock,variable,:)),min(posterior_down_conf_irfs(shock,variable,:))])) + set(h1,'FaceColor',[.9 .9 .9]) + hold on + h2 = area(1:options_.irf,squeeze(posterior_down_conf_irfs(shock,variable,:))); + set(h2,'BaseValue',min([min(posterior_up_conf_irfs(shock,variable,:)),min(posterior_down_conf_irfs(shock,variable,:))])) + set(h2,'FaceColor',[1 1 1]) + plot(1:options_.irf,squeeze(posterior_median_irfs(shock,variable,:)),'-k','linewidth',2) + axis tight + hold off + end +end + +% Save intermediate results +DirectoryName = [ M_.fname '/bvar_irf' ]; +if ~isdir(DirectoryName) + mkdir('.',DirectoryName); +end +save([ DirectoryName '/simulations.mat'], 'sampled_irfs'); + +% Save results in oo_ +for i=1:ny + shock_name = options_.varobs(i, :); + for j=1:ny + variable_name = options_.varobs(j, :); + eval(['oo_.bvar.irf.Mean.' variable_name '.' shock_name ' = posterior_mean_irfs(' int2str(j) ',' int2str(i) ',:);']) + eval(['oo_.bvar.irf.Median.' variable_name '.' shock_name ' = posterior_median_irfs(' int2str(j) ',' int2str(i) ',:);']) + eval(['oo_.bvar.irf.Var.' variable_name '.' shock_name ' = posterior_variance_irfs(' int2str(j) ',' int2str(i) ',:);']) + eval(['oo_.bvar.irf.Upper_bound.' variable_name '.' shock_name ' = posterior_up_conf_irfs(' int2str(j) ',' int2str(i) ',:);']) + eval(['oo_.bvar.irf.Lower_bound.' variable_name '.' shock_name ' = posterior_down_conf_irfs(' int2str(j) ',' int2str(i) ',:);']) end - save([ DirectoryName '/simulations.mat'], 'sampled_irfs'); - - % Save results in oo_ - for i=1:ny - shock_name = options_.varobs(i, :); - for j=1:ny - variable_name = options_.varobs(j, :); - eval(['oo_.bvar.irf.Mean.' variable_name '.' shock_name ' = posterior_mean_irfs(' int2str(j) ',' int2str(i) ',:);']) - eval(['oo_.bvar.irf.Median.' variable_name '.' shock_name ' = posterior_median_irfs(' int2str(j) ',' int2str(i) ',:);']) - eval(['oo_.bvar.irf.Var.' variable_name '.' shock_name ' = posterior_variance_irfs(' int2str(j) ',' int2str(i) ',:);']) - eval(['oo_.bvar.irf.Upper_bound.' variable_name '.' shock_name ' = posterior_up_conf_irfs(' int2str(j) ',' int2str(i) ',:);']) - eval(['oo_.bvar.irf.Lower_bound.' variable_name '.' shock_name ' = posterior_down_conf_irfs(' int2str(j) ',' int2str(i) ',:);']) - end - end \ No newline at end of file +end \ No newline at end of file diff --git a/matlab/bvar_toolbox.m b/matlab/bvar_toolbox.m index 6a0a4ddd45..f35deb7b04 100644 --- a/matlab/bvar_toolbox.m +++ b/matlab/bvar_toolbox.m @@ -40,7 +40,7 @@ function [ny, nx, posterior, prior, forecast_data] = bvar_toolbox(nlags) % This function uses the following Dynare options: % - datafile, first_obs, varobs, xls_sheet, xls_range, nobs, presample % - bvar_prior_{tau,decay,lambda,mu,omega,flat,train} - + % Copyright (C) 2003-2007 Christopher Sims % Copyright (C) 2007-2008 Dynare Team % @@ -59,105 +59,105 @@ function [ny, nx, posterior, prior, forecast_data] = bvar_toolbox(nlags) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global options_ - - % Load dataset - dataset = read_variables(options_.datafile, options_.varobs, [], options_.xls_sheet, options_.xls_range); - options_ = set_default_option(options_, 'nobs', size(dataset,1)-options_.first_obs+1); - - % Parameters for prior - options_ = set_default_option(options_, 'bvar_prior_tau', 3); - options_ = set_default_option(options_, 'bvar_prior_decay', 0.5); - options_ = set_default_option(options_, 'bvar_prior_lambda', 5); - options_ = set_default_option(options_, 'bvar_prior_mu', 2); - options_ = set_default_option(options_, 'bvar_prior_omega', 1); - options_ = set_default_option(options_, 'bvar_prior_flat', 0); - options_ = set_default_option(options_, 'bvar_prior_train', 0); - - if options_.first_obs + options_.presample <= nlags - error('first_obs+presample should be > nlags (for initializing the VAR)') - end +global options_ - train = options_.bvar_prior_train; - - if options_.first_obs + options_.presample - train <= nlags - error('first_obs+presample-train should be > nlags (for initializating the VAR)') - end +% Load dataset +dataset = read_variables(options_.datafile, options_.varobs, [], options_.xls_sheet, options_.xls_range); +options_ = set_default_option(options_, 'nobs', size(dataset,1)-options_.first_obs+1); - idx = options_.first_obs+options_.presample-train-nlags:options_.first_obs+options_.nobs-1; - - % Prepare dataset - if options_.loglinear & ~options_.logdata - dataset = log(dataset); - end - if options_.prefilter - dataset(idx,:) = dataset(idx,:) - ones(length(idx),1)*mean(dataset(idx,:)); - end - - mnprior.tight = options_.bvar_prior_tau; - mnprior.decay = options_.bvar_prior_decay; - - % Use only initializations lags for the variance prior - vprior.sig = std(dataset(options_.first_obs+options_.presample-nlags:options_.first_obs+options_.presample-1,:))'; - vprior.w = options_.bvar_prior_omega; - - lambda = options_.bvar_prior_lambda; - mu = options_.bvar_prior_mu; - flat = options_.bvar_prior_flat; - - ny = size(dataset, 2); - if options_.prefilter | options_.noconstant - nx = 0; - else - nx = 1; - end - - [ydum, xdum, pbreaks] = varprior(ny, nx, nlags, mnprior, vprior); - - ydata = dataset(idx, :); - T = size(ydata, 1); - xdata = ones(T,nx); - - % Posterior density - var = rfvar3([ydata; ydum], nlags, [xdata; xdum], [T; T+pbreaks], lambda, mu); - Tu = size(var.u, 1); - - posterior.df = Tu - ny*nlags - nx - flat*(ny+1); - posterior.S = var.u' * var.u; - posterior.XXi = var.xxi; - posterior.PhiHat = var.B; - - % Prior density - Tp = train + nlags; - if nx - xdata = xdata(1:Tp, :); +% Parameters for prior +options_ = set_default_option(options_, 'bvar_prior_tau', 3); +options_ = set_default_option(options_, 'bvar_prior_decay', 0.5); +options_ = set_default_option(options_, 'bvar_prior_lambda', 5); +options_ = set_default_option(options_, 'bvar_prior_mu', 2); +options_ = set_default_option(options_, 'bvar_prior_omega', 1); +options_ = set_default_option(options_, 'bvar_prior_flat', 0); +options_ = set_default_option(options_, 'bvar_prior_train', 0); + +if options_.first_obs + options_.presample <= nlags + error('first_obs+presample should be > nlags (for initializing the VAR)') +end + +train = options_.bvar_prior_train; + +if options_.first_obs + options_.presample - train <= nlags + error('first_obs+presample-train should be > nlags (for initializating the VAR)') +end + +idx = options_.first_obs+options_.presample-train-nlags:options_.first_obs+options_.nobs-1; + +% Prepare dataset +if options_.loglinear & ~options_.logdata + dataset = log(dataset); +end +if options_.prefilter + dataset(idx,:) = dataset(idx,:) - ones(length(idx),1)*mean(dataset(idx,:)); +end + +mnprior.tight = options_.bvar_prior_tau; +mnprior.decay = options_.bvar_prior_decay; + +% Use only initializations lags for the variance prior +vprior.sig = std(dataset(options_.first_obs+options_.presample-nlags:options_.first_obs+options_.presample-1,:))'; +vprior.w = options_.bvar_prior_omega; + +lambda = options_.bvar_prior_lambda; +mu = options_.bvar_prior_mu; +flat = options_.bvar_prior_flat; + +ny = size(dataset, 2); +if options_.prefilter | options_.noconstant + nx = 0; +else + nx = 1; +end + +[ydum, xdum, pbreaks] = varprior(ny, nx, nlags, mnprior, vprior); + +ydata = dataset(idx, :); +T = size(ydata, 1); +xdata = ones(T,nx); + +% Posterior density +var = rfvar3([ydata; ydum], nlags, [xdata; xdum], [T; T+pbreaks], lambda, mu); +Tu = size(var.u, 1); + +posterior.df = Tu - ny*nlags - nx - flat*(ny+1); +posterior.S = var.u' * var.u; +posterior.XXi = var.xxi; +posterior.PhiHat = var.B; + +% Prior density +Tp = train + nlags; +if nx + xdata = xdata(1:Tp, :); +else + xdata = []; +end +varp = rfvar3([ydata(1:Tp, :); ydum], nlags, [xdata; xdum], [Tp; Tp + pbreaks], lambda, mu); +Tup = size(varp.u, 1); + +prior.df = Tup - ny*nlags - nx - flat*(ny+1); +prior.S = varp.u' * varp.u; +prior.XXi = varp.xxi; +prior.PhiHat = varp.B; + +if prior.df < ny + error('Too few degrees of freedom in the inverse-Wishart part of prior distribution. You should increase training sample size.') +end + +% Add forecast informations +if nargout >= 5 + forecast_data.xdata = ones(options_.forecast, nx); + forecast_data.initval = ydata(end-nlags+1:end, :); + if options_.first_obs + options_.nobs <= size(dataset, 1) + forecast_data.realized_val = dataset(options_.first_obs+options_.nobs:end, :); + forecast_data.realized_xdata = ones(size(forecast_data.realized_val, 1), nx); else - xdata = []; - end - varp = rfvar3([ydata(1:Tp, :); ydum], nlags, [xdata; xdum], [Tp; Tp + pbreaks], lambda, mu); - Tup = size(varp.u, 1); - - prior.df = Tup - ny*nlags - nx - flat*(ny+1); - prior.S = varp.u' * varp.u; - prior.XXi = varp.xxi; - prior.PhiHat = varp.B; - - if prior.df < ny - error('Too few degrees of freedom in the inverse-Wishart part of prior distribution. You should increase training sample size.') - end - - % Add forecast informations - if nargout >= 5 - forecast_data.xdata = ones(options_.forecast, nx); - forecast_data.initval = ydata(end-nlags+1:end, :); - if options_.first_obs + options_.nobs <= size(dataset, 1) - forecast_data.realized_val = dataset(options_.first_obs+options_.nobs:end, :); - forecast_data.realized_xdata = ones(size(forecast_data.realized_val, 1), nx); - else - forecast_data.realized_val = []; - end + forecast_data.realized_val = []; end - +end + function [ydum,xdum,breaks]=varprior(nv,nx,lags,mnprior,vprior) %function [ydum,xdum,breaks]=varprior(nv,nx,lags,mnprior,vprior) @@ -185,41 +185,41 @@ function [ydum,xdum,breaks]=varprior(nv,nx,lags,mnprior,vprior) % Original file downloaded from: % http://sims.princeton.edu/yftp/VARtools/matlab/varprior.m - if ~isempty(mnprior) - xdum = zeros(lags+1,nx,lags,nv); - ydum = zeros(lags+1,nv,lags,nv); - for il = 1:lags - ydum(il+1,:,il,:) = il^mnprior.decay*diag(vprior.sig); - end - ydum(1,:,1,:) = diag(vprior.sig); - ydum = mnprior.tight*reshape(ydum,[lags+1,nv,lags*nv]); - ydum = flipdim(ydum,1); - xdum = mnprior.tight*reshape(xdum,[lags+1,nx,lags*nv]); - xdum = flipdim(xdum,1); - breaks = (lags+1)*[1:(nv*lags)]'; - lbreak = breaks(end); - else - ydum = []; - xdum = []; - breaks = []; - lbreak = 0; +if ~isempty(mnprior) + xdum = zeros(lags+1,nx,lags,nv); + ydum = zeros(lags+1,nv,lags,nv); + for il = 1:lags + ydum(il+1,:,il,:) = il^mnprior.decay*diag(vprior.sig); end - if ~isempty(vprior) & vprior.w>0 - ydum2 = zeros(lags+1,nv,nv); - xdum2 = zeros(lags+1,nx,nv); - ydum2(end,:,:) = diag(vprior.sig); - for i = 1:vprior.w - ydum = cat(3,ydum,ydum2); - xdum = cat(3,xdum,xdum2); - breaks = [breaks;(lags+1)*[1:nv]'+lbreak]; - lbreak = breaks(end); - end + ydum(1,:,1,:) = diag(vprior.sig); + ydum = mnprior.tight*reshape(ydum,[lags+1,nv,lags*nv]); + ydum = flipdim(ydum,1); + xdum = mnprior.tight*reshape(xdum,[lags+1,nx,lags*nv]); + xdum = flipdim(xdum,1); + breaks = (lags+1)*[1:(nv*lags)]'; + lbreak = breaks(end); +else + ydum = []; + xdum = []; + breaks = []; + lbreak = 0; +end +if ~isempty(vprior) & vprior.w>0 + ydum2 = zeros(lags+1,nv,nv); + xdum2 = zeros(lags+1,nx,nv); + ydum2(end,:,:) = diag(vprior.sig); + for i = 1:vprior.w + ydum = cat(3,ydum,ydum2); + xdum = cat(3,xdum,xdum2); + breaks = [breaks;(lags+1)*[1:nv]'+lbreak]; + lbreak = breaks(end); end - dimy = size(ydum); - ydum = reshape(permute(ydum,[1 3 2]),dimy(1)*dimy(3),nv); - xdum = reshape(permute(xdum,[1 3 2]),dimy(1)*dimy(3),nx); - breaks = breaks(1:(end-1)); - +end +dimy = size(ydum); +ydum = reshape(permute(ydum,[1 3 2]),dimy(1)*dimy(3),nv); +xdum = reshape(permute(xdum,[1 3 2]),dimy(1)*dimy(3),nx); +breaks = breaks(1:(end-1)); + function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu) %function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu) @@ -253,74 +253,74 @@ function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu) % Original file downloaded from: % http://sims.princeton.edu/yftp/VARtools/matlab/rfvar3.m - [T,nvar] = size(ydata); - nox = isempty(xdata); +[T,nvar] = size(ydata); +nox = isempty(xdata); +if ~nox + [T2,nx] = size(xdata); +else + T2 = T; + nx = 0; + xdata = zeros(T2,0); +end +% note that x must be same length as y, even though first part of x will not be used. +% This is so that the lags parameter can be changed without reshaping the xdata matrix. +if T2 ~= T, error('Mismatch of x and y data lengths'),end +if nargin < 4 + nbreaks = 0; + breaks = []; +else + nbreaks = length(breaks); +end +breaks = [0;breaks;T]; +smpl = []; +for nb = 1:nbreaks+1 + smpl = [smpl;[breaks(nb)+lags+1:breaks(nb+1)]']; +end +Tsmpl = size(smpl,1); +X = zeros(Tsmpl,nvar,lags); +for is = 1:length(smpl) + X(is,:,:) = ydata(smpl(is)-(1:lags),:)'; +end +X = [X(:,:) xdata(smpl,:)]; +y = ydata(smpl,:); +% Everything now set up with input data for y=Xb+e + +% Add persistence dummies +if lambda ~= 0 | mu > 0 + ybar = mean(ydata(1:lags,:),1); if ~nox - [T2,nx] = size(xdata); - else - T2 = T; - nx = 0; - xdata = zeros(T2,0); - end - % note that x must be same length as y, even though first part of x will not be used. - % This is so that the lags parameter can be changed without reshaping the xdata matrix. - if T2 ~= T, error('Mismatch of x and y data lengths'),end - if nargin < 4 - nbreaks = 0; - breaks = []; + xbar = mean(xdata(1:lags,:),1); else - nbreaks = length(breaks); - end - breaks = [0;breaks;T]; - smpl = []; - for nb = 1:nbreaks+1 - smpl = [smpl;[breaks(nb)+lags+1:breaks(nb+1)]']; - end - Tsmpl = size(smpl,1); - X = zeros(Tsmpl,nvar,lags); - for is = 1:length(smpl) - X(is,:,:) = ydata(smpl(is)-(1:lags),:)'; + xbar = []; end - X = [X(:,:) xdata(smpl,:)]; - y = ydata(smpl,:); - % Everything now set up with input data for y=Xb+e - - % Add persistence dummies - if lambda ~= 0 | mu > 0 - ybar = mean(ydata(1:lags,:),1); - if ~nox - xbar = mean(xdata(1:lags,:),1); + if lambda ~= 0 + if lambda>0 + xdum = lambda*[repmat(ybar,1,lags) xbar]; else - xbar = []; - end - if lambda ~= 0 - if lambda>0 - xdum = lambda*[repmat(ybar,1,lags) xbar]; - else - lambda = -lambda; - xdum = lambda*[repmat(ybar,1,lags) zeros(size(xbar))]; - end - ydum = zeros(1,nvar); - ydum(1,:) = lambda*ybar; - y = [y;ydum]; - X = [X;xdum]; - end - if mu>0 - xdum = [repmat(diag(ybar),1,lags) zeros(nvar,nx)]*mu; - ydum = mu*diag(ybar); - X = [X;xdum]; - y = [y;ydum]; + lambda = -lambda; + xdum = lambda*[repmat(ybar,1,lags) zeros(size(xbar))]; end + ydum = zeros(1,nvar); + ydum(1,:) = lambda*ybar; + y = [y;ydum]; + X = [X;xdum]; + end + if mu>0 + xdum = [repmat(diag(ybar),1,lags) zeros(nvar,nx)]*mu; + ydum = mu*diag(ybar); + X = [X;xdum]; + y = [y;ydum]; end - - % Compute OLS regression and residuals - [vl,d,vr] = svd(X,0); - di = 1./diag(d); - B = (vr.*repmat(di',nvar*lags+nx,1))*vl'*y; - u = y-X*B; - xxi = vr.*repmat(di',nvar*lags+nx,1); - xxi = xxi*xxi'; - - var.B = B; - var.u = u; - var.xxi = xxi; +end + +% Compute OLS regression and residuals +[vl,d,vr] = svd(X,0); +di = 1./diag(d); +B = (vr.*repmat(di',nvar*lags+nx,1))*vl'*y; +u = y-X*B; +xxi = vr.*repmat(di',nvar*lags+nx,1); +xxi = xxi*xxi'; + +var.B = B; +var.u = u; +var.xxi = xxi; diff --git a/matlab/calib.m b/matlab/calib.m index d0f8c4611d..08e21882d9 100644 --- a/matlab/calib.m +++ b/matlab/calib.m @@ -17,177 +17,177 @@ function M_.Sigma_e = calib(var_indices,targets,var_weights,nar,cova,M_.Sigma_e) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global oo_ M_ vx - - ncstr = 0; - ni = size(var_indices,1); - for i=1:nar+3 +global oo_ M_ vx + +ncstr = 0; +ni = size(var_indices,1); +for i=1:nar+3 ncstr = ncstr + size(var_indices{i},1); - end - if cova +end +if cova if ncstr < M_.exo_nbr*(M_.exo_nbr+1)/2 - error(['number of preset variances is smaller than number of shock' ... - ' variances and covariances to be estimated !']) + error(['number of preset variances is smaller than number of shock' ... + ' variances and covariances to be estimated !']) end - else +else if ncstr < M_.exo_nbr - error(['number of preset variances is smaller than number of shock' ... - ' variances to be estimated !']) + error(['number of preset variances is smaller than number of shock' ... + ' variances to be estimated !']) end - end - - % computes approximate solution at order 1 - dr = resol(oo_.steady_state,0,0,1); - - ghx = dr.ghx; - ghu = dr.ghu; - npred = dr.npred; - nstatic = dr.nstatic; - kstate = dr.kstate; - order = dr.order_var; - iv(order) = [1:M_.endo_nbr]; - iv = iv'; - nx = size(ghx,2); +end + +% computes approximate solution at order 1 +dr = resol(oo_.steady_state,0,0,1); + +ghx = dr.ghx; +ghu = dr.ghu; +npred = dr.npred; +nstatic = dr.nstatic; +kstate = dr.kstate; +order = dr.order_var; +iv(order) = [1:M_.endo_nbr]; +iv = iv'; +nx = size(ghx,2); - ikx = [nstatic+1:nstatic+npred]; - - A = zeros(nx,nx); - A(1:npred,:)=ghx(ikx,:); - offset_r = npred; - offset_c = 0; - i0 = find(kstate(:,2) == M_.maximum_lag+1); - n0 = size(i0,1); - for i=M_.maximum_lag:-1:2 +ikx = [nstatic+1:nstatic+npred]; + +A = zeros(nx,nx); +A(1:npred,:)=ghx(ikx,:); +offset_r = npred; +offset_c = 0; +i0 = find(kstate(:,2) == M_.maximum_lag+1); +n0 = size(i0,1); +for i=M_.maximum_lag:-1:2 i1 = find(kstate(:,2) == i); n1 = size(i1,1); j = zeros(n1,1); for j1 = 1:n1 - j(j1) = find(kstate(i0,1)==kstate(i1(j1),1)); + j(j1) = find(kstate(i0,1)==kstate(i1(j1),1)); end A(offset_r+1:offset_r+n1,offset_c+j)=eye(n1); offset_r = offset_r + n1; offset_c = offset_c + n0; i0 = i1; n0 = n1; - end - ghu1 = [ghu(ikx,:);zeros(nx-npred,M_.exo_nbr)]; +end +ghu1 = [ghu(ikx,:);zeros(nx-npred,M_.exo_nbr)]; % IA = speye(nx*nx)-kron(A,A); % kron_ghu = kron(ghu1,ghu1); - - % vx1 such that vec(sigma_x) = vx1 * vec(M_.Sigma_e) (predetermined vars) + +% vx1 such that vec(sigma_x) = vx1 * vec(M_.Sigma_e) (predetermined vars) vx1 = []; - % vx1 = IA\kron_ghu; - IA = []; - kron_ghu = []; - - % computes required variables and indices among required variables - iiy = []; - for i=1:nar+3 +% vx1 = IA\kron_ghu; +IA = []; +kron_ghu = []; + +% computes required variables and indices among required variables +iiy = []; +for i=1:nar+3 if i ~= 3 & ~isempty(var_indices{i}) - iiy = union(iiy, iv(var_indices{i}(:,1))); + iiy = union(iiy, iv(var_indices{i}(:,1))); end - end - if ~isempty(var_indices{2}) +end +if ~isempty(var_indices{2}) iiy = union(iiy, iv(var_indices{2}(:,2))); - end - ny = size(iiy,1); +end +ny = size(iiy,1); - for i=1:nar+3 +for i=1:nar+3 if i ~= 3 & ~isempty(var_indices{i}) - var_indices{i}(:,1) = indnv(iv(var_indices{i}(:,1)),iiy); + var_indices{i}(:,1) = indnv(iv(var_indices{i}(:,1)),iiy); end if i ~= 2 & i ~= 3 & ~isempty(var_indices{i}) - var_indices{i} = sub2ind([ny ny],var_indices{i},var_indices{i}); + var_indices{i} = sub2ind([ny ny],var_indices{i},var_indices{i}); end - end - if ~isempty(var_indices{2}) +end +if ~isempty(var_indices{2}) var_indices{2}(:,2) = indnv(iv(var_indices{2}(:,2)),iiy); var_indices{2} = sub2ind([ny ny],var_indices{2}(:,1),var_indices{2}(:,2)); - end - if ~isempty(var_indices{3}) +end +if ~isempty(var_indices{3}) var_indices{3} = sub2ind([M_.exo_nbr M_.exo_nbr],var_indices{3}(:,1),var_indices{3}(:,2)); - end - if isempty(M_.Sigma_e) +end +if isempty(M_.Sigma_e) M_.Sigma_e = 0.01*eye(M_.exo_nbr); b = 0.1*ghu1*ghu1'; - else +else b = ghu1*M_.Sigma_e*ghu1'; M_.Sigma_e = chol(M_.Sigma_e+1e-14*eye(M_.exo_nbr)); - end - options=optimset('LargeScale','on','MaxFunEvals',20000*ny,'TolX',1e-4, ... - 'TolFun',1e-4,'Display','Iter','MaxIter',10000); +end +options=optimset('LargeScale','on','MaxFunEvals',20000*ny,'TolX',1e-4, ... + 'TolFun',1e-4,'Display','Iter','MaxIter',10000); % [M_.Sigma_e,f]=fminunc(@calib_obj,M_.Sigma_e,options,A,ghu1,ghx(iiy,:),ghu(iiy,:),targets,var_weights,var_indices,nar); - [M_.Sigma_e,f]=fmincon(@calib_obj,diag(M_.Sigma_e).^2,-eye(M_.exo_nbr),zeros(M_.exo_nbr,1),[],[],[],[],[],options,A,ghu1,ghx(iiy,:),ghu(iiy,:),targets,var_weights,var_indices,nar); - M_.Sigma_e = diag(M_.Sigma_e); - - objective = calib_obj2(diag(M_.Sigma_e),A,ghu1,ghx(iiy,:),ghu(iiy,:),targets,var_weights,var_indices,nar); - disp('CALIBRATION') - disp('') - if ~isempty(var_indices{1}) +[M_.Sigma_e,f]=fmincon(@calib_obj,diag(M_.Sigma_e).^2,-eye(M_.exo_nbr),zeros(M_.exo_nbr,1),[],[],[],[],[],options,A,ghu1,ghx(iiy,:),ghu(iiy,:),targets,var_weights,var_indices,nar); +M_.Sigma_e = diag(M_.Sigma_e); + +objective = calib_obj2(diag(M_.Sigma_e),A,ghu1,ghx(iiy,:),ghu(iiy,:),targets,var_weights,var_indices,nar); +disp('CALIBRATION') +disp('') +if ~isempty(var_indices{1}) disp(sprintf('%16s %14s %14s %14s %14s','Std. Dev','Target','Obtained','Diff')); str = ' '; for i=1:size(var_indices{1},1) - [i1,i2] = ind2sub([ny ny],var_indices{1}(i)); - str = sprintf('%16s: %14.2f %14.2f %14.2f',M_.endo_names(order(iiy(i1)),:),targets{1}(i),objective{1}(i),objective{1}(i)-targets{1}(i)); - disp(str); + [i1,i2] = ind2sub([ny ny],var_indices{1}(i)); + str = sprintf('%16s: %14.2f %14.2f %14.2f',M_.endo_names(order(iiy(i1)),:),targets{1}(i),objective{1}(i),objective{1}(i)-targets{1}(i)); + disp(str); end - end - if ~isempty(var_indices{2}) +end +if ~isempty(var_indices{2}) disp(sprintf('%32s %14s %14s','Correlations','Target','Obtained','Diff')); str = ' '; for i=1:size(var_indices{2},1) - [i1,i2]=ind2sub([ny ny],var_indices{2}(i)); - str = sprintf('%16s,%16s: %14.2f %14.2f %14.2f',M_.endo_names(order(iiy(i1)),:), ... - M_.endo_names(order(iiy(i2)),:),targets{2}(i),objective{2}(i),objective{2}(i)-targets{2}(i)); - disp(str); + [i1,i2]=ind2sub([ny ny],var_indices{2}(i)); + str = sprintf('%16s,%16s: %14.2f %14.2f %14.2f',M_.endo_names(order(iiy(i1)),:), ... + M_.endo_names(order(iiy(i2)),:),targets{2}(i),objective{2}(i),objective{2}(i)-targets{2}(i)); + disp(str); end - end - if ~isempty(var_indices{3}) +end +if ~isempty(var_indices{3}) disp(sprintf('%32s %16s %16s','Constrained shocks (co)variances','Target','Obtained')); str = ' '; for i=1:size(var_indices{3},1) - [i1,i2]=ind2sub([M_.exo_nbr M_.exo_nbr],var_indices{3}(i)); - if i1 == i2 - str = sprintf('%32s: %16.4f %16.4f',M_.exo_name(order(i1),:), ... - targets{3}(i),objective{3}(i)); - else - str = sprintf('%16s,%16s: %16.4f %16.4f',M_.exo_name(order(i1),:), ... - M_.exo_name(order(i2), :),targets{3}(i),objective{3}(i)); - end - disp(str); + [i1,i2]=ind2sub([M_.exo_nbr M_.exo_nbr],var_indices{3}(i)); + if i1 == i2 + str = sprintf('%32s: %16.4f %16.4f',M_.exo_name(order(i1),:), ... + targets{3}(i),objective{3}(i)); + else + str = sprintf('%16s,%16s: %16.4f %16.4f',M_.exo_name(order(i1),:), ... + M_.exo_name(order(i2), :),targets{3}(i),objective{3}(i)); + end + disp(str); end - end - flag = 1; - for j=4:nar+3 +end +flag = 1; +for j=4:nar+3 if ~isempty(var_indices{j}) - if flag - disp(sprintf('%16s %16s %16s','Autocorrelations','Target','Obtained')); - str = ' '; - flag = 0; - end - for i=1:size(var_indices{j},1) - [i1,i2] = ind2sub([ny ny],var_indices{j}(i)); - str = sprintf('%16s(%d): %16.4f %16.4f',M_.endo_names(order(iiy(i1)),:), ... - j-3,targets{j}(i),objective{j}(i)); - disp(str); - end + if flag + disp(sprintf('%16s %16s %16s','Autocorrelations','Target','Obtained')); + str = ' '; + flag = 0; + end + for i=1:size(var_indices{j},1) + [i1,i2] = ind2sub([ny ny],var_indices{j}(i)); + str = sprintf('%16s(%d): %16.4f %16.4f',M_.endo_names(order(iiy(i1)),:), ... + j-3,targets{j}(i),objective{j}(i)); + disp(str); + end end - end - - disp(''); - disp('Calibrated variances') - str = ' '; - for i=1:M_.exo_nbr +end + +disp(''); +disp('Calibrated variances') +str = ' '; +for i=1:M_.exo_nbr str = [str sprintf('%16s',M_.exo_name(i,:))]; - end - disp(str); - disp(''); - str = ' '; - for i=1:M_.exo_nbr +end +disp(str); +disp(''); +str = ' '; +for i=1:M_.exo_nbr str = [str sprintf('%16f',M_.Sigma_e(i,i))]; - end - disp(str); - +end +disp(str); + + - - % 10/9/02 MJ \ No newline at end of file +% 10/9/02 MJ \ No newline at end of file diff --git a/matlab/calib_obj.m b/matlab/calib_obj.m index cd44b61eba..087406e588 100644 --- a/matlab/calib_obj.m +++ b/matlab/calib_obj.m @@ -19,67 +19,66 @@ function f=calib_obj(M_.Sigma_e,A,ghu1,ghx,ghu,targets,var_weights,iy,nar) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global vx fold options_ - - oo_.gamma_y = cell(nar+1,1); +global vx fold options_ + +oo_.gamma_y = cell(nar+1,1); % M_.Sigma_e = M_.Sigma_e'*M_.Sigma_e; - M_.Sigma_e=diag(M_.Sigma_e); - nx = size(ghx,2); - b=ghu1*M_.Sigma_e*ghu1'; - vx = []; - if isempty(vx) +M_.Sigma_e=diag(M_.Sigma_e); +nx = size(ghx,2); +b=ghu1*M_.Sigma_e*ghu1'; +vx = []; +if isempty(vx) vx = lyapunov_symm(A,b,options_.qz_criterium,options_.lyapunov_complex_threshold); - else +else [vx,status] = bicgstab_(@f_var,b(:),vx(:),1e-8,50,A,nx); if status - vx = lyapunov_symm(A,b,options_.qz_criterium,options_.lyapunov_complex_threshold); + vx = lyapunov_symm(A,b,options_.qz_criterium,options_.lyapunov_complex_threshold); else - vx=reshape(vx,nx,nx); + vx=reshape(vx,nx,nx); end - end - oo_.gamma_y{1} = ghx*vx*ghx'+ ghu*M_.Sigma_e*ghu'; - f = 0; - if ~isempty(targets{1}) +end +oo_.gamma_y{1} = ghx*vx*ghx'+ ghu*M_.Sigma_e*ghu'; +f = 0; +if ~isempty(targets{1}) e = targets{1}-sqrt(oo_.gamma_y{1}(iy{1})); f = e'*(var_weights{1}.*e); - end +end - sy = sqrt(diag(oo_.gamma_y{1})); - sy = sy *sy'; - if ~isempty(targets{2}) +sy = sqrt(diag(oo_.gamma_y{1})); +sy = sy *sy'; +if ~isempty(targets{2}) e = targets{2}-oo_.gamma_y{1}(iy{2})./(sy(iy{2})+1e-10); f = f+e'*(var_weights{2}.*e); - end - - if ~isempty(targets{3}) +end + +if ~isempty(targets{3}) e = targets{3}-sqrt(M_.Sigma_e(iy{3})); f = f+e'*(var_weights{3}.*e); - end - - % autocorrelations - if nar > 0 +end + +% autocorrelations +if nar > 0 vxy = (A*vx*ghx'+ghu1*M_.Sigma_e*ghu'); oo_.gamma_y{2} = ghx*vxy./(sy+1e-10); if ~isempty(targets{4}) - e = targets{4}-oo_.gamma_y{2}(iy{4}); - f = f+e'*(var_weights{4}.*e); + e = targets{4}-oo_.gamma_y{2}(iy{4}); + f = f+e'*(var_weights{4}.*e); end for i=2:nar - vxy = A*vxy; - oo_.gamma_y{i+1} = ghx*vxy./(sy+1e-10); - if ~isempty(targets{i+3}) - e = targets{i+3}-oo_.gamma_y{i+1}(iy{i+3}); - f = f+e'*(var_weights{i+3}.*e); - end + vxy = A*vxy; + oo_.gamma_y{i+1} = ghx*vxy./(sy+1e-10); + if ~isempty(targets{i+3}) + e = targets{i+3}-oo_.gamma_y{i+1}(iy{i+3}); + f = f+e'*(var_weights{i+3}.*e); + end end - end - if isempty(fold) | f < 2*fold +end +if isempty(fold) | f < 2*fold fold = f; vxold = vx; - end - % 11/04/02 MJ generalized for correlations, autocorrelations and - % constraints on M_.Sigma_e - % 01/25/03 MJ targets std. dev. instead of variances - \ No newline at end of file +end +% 11/04/02 MJ generalized for correlations, autocorrelations and +% constraints on M_.Sigma_e +% 01/25/03 MJ targets std. dev. instead of variances diff --git a/matlab/calib_obj2.m b/matlab/calib_obj2.m index 0e3e8a03ee..0d1f76b10e 100644 --- a/matlab/calib_obj2.m +++ b/matlab/calib_obj2.m @@ -19,46 +19,46 @@ function objective=calib_obj2(M_.Sigma_e,A,ghu1,ghx,ghu,targets,var_weights,iy,n % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global vx fold options_ - - objective = cell (nar+3); - oo_.gamma_y = cell(nar+1,1); - M_.Sigma_e=diag(M_.Sigma_e); - nx = size(ghx,2); - b=ghu1*M_.Sigma_e*ghu1'; - vx = lyapunov_symm(A,b,options_.qz_criterium,options_.lyapunov_complex_threshold); - oo_.gamma_y{1} = ghx*vx*ghx'+ ghu*M_.Sigma_e*ghu'; - if ~isempty(targets{1}) +global vx fold options_ + +objective = cell (nar+3); +oo_.gamma_y = cell(nar+1,1); +M_.Sigma_e=diag(M_.Sigma_e); +nx = size(ghx,2); +b=ghu1*M_.Sigma_e*ghu1'; +vx = lyapunov_symm(A,b,options_.qz_criterium,options_.lyapunov_complex_threshold); +oo_.gamma_y{1} = ghx*vx*ghx'+ ghu*M_.Sigma_e*ghu'; +if ~isempty(targets{1}) objective{1} = sqrt(oo_.gamma_y{1}(iy{1})); - end +end - sy = sqrt(diag(oo_.gamma_y{1})); - sy = sy *sy'; - if ~isempty(targets{2}) +sy = sqrt(diag(oo_.gamma_y{1})); +sy = sy *sy'; +if ~isempty(targets{2}) objective{2} = oo_.gamma_y{1}(iy{2})./(sy(iy{2})+1e-10); - end - - if ~isempty(targets{3}) +end + +if ~isempty(targets{3}) objective{3} = M_.Sigma_e(iy{3}); - end - - % autocorrelations - if nar > 0 +end + +% autocorrelations +if nar > 0 vxy = (A*vx*ghx'+ghu1*M_.Sigma_e*ghu'); oo_.gamma_y{2} = ghx*vxy./(sy+1e-10); if ~isempty(targets{4}) - objective{4} = oo_.gamma_y{2}(iy{4}); + objective{4} = oo_.gamma_y{2}(iy{4}); end for i=2:nar - vxy = A*vxy; - oo_.gamma_y{i+1} = ghx*vxy./(sy+1e-10); - if ~isempty(targets{i+3}) - objecitve{i+3} = oo_.gamma_y{i+1}(iy{i+3}); - end + vxy = A*vxy; + oo_.gamma_y{i+1} = ghx*vxy./(sy+1e-10); + if ~isempty(targets{i+3}) + objecitve{i+3} = oo_.gamma_y{i+1}(iy{i+3}); + end end - end +end - % 11/04/02 MJ generalized for correlations, autocorrelations and - % constraints on M_.Sigma_e \ No newline at end of file +% 11/04/02 MJ generalized for correlations, autocorrelations and +% constraints on M_.Sigma_e \ No newline at end of file diff --git a/matlab/check.m b/matlab/check.m index 181b20fecf..b7dd226caa 100644 --- a/matlab/check.m +++ b/matlab/check.m @@ -30,63 +30,63 @@ function result = check global M_ options_ oo_ - if options_.block || options_.bytecode - error('CHECK: incompatibility with "block" or "bytecode" option') - end +if options_.block || options_.bytecode + error('CHECK: incompatibility with "block" or "bytecode" option') +end - temp_options = options_; - tempex = oo_.exo_simul; - if ~options_.initval_file & M_.exo_nbr > 1 - oo_.exo_simul = ones(M_.maximum_lead+M_.maximum_lag+1,1)*oo_.exo_steady_state'; - end - - options_.order = 1; - - [dr, info] = resol(oo_.steady_state,1); - - oo_.dr = dr; - - if info(1) ~= 0 & info(1) ~= 3 & info(1) ~= 4 - print_info(info, options_.noprint); - end - - oo_.exo_simul = tempex; - - eigenvalues_ = dr.eigval; - nyf = nnz(dr.kstate(:,2)>M_.maximum_endo_lag+1); - [m_lambda,i]=sort(abs(eigenvalues_)); - n_explod = nnz(abs(eigenvalues_) > options_.qz_criterium); - - if options_.noprint == 0 - disp(' ') - disp('EIGENVALUES:') - disp(sprintf('%16s %16s %16s\n','Modulus','Real','Imaginary')) - z=[m_lambda real(eigenvalues_(i)) imag(eigenvalues_(i))]'; - disp(sprintf('%16.4g %16.4g %16.4g\n',z)) - options_ = set_default_option(options_,'qz_criterium',1.000001); - disp(sprintf('\nThere are %d eigenvalue(s) larger than 1 in modulus ', ... - n_explod)); - disp(sprintf('for %d forward-looking variable(s)',nyf)); - disp(' ') - if dr.rank == nyf & nyf == n_explod - disp('The rank condition is verified.') - else - disp('The rank conditions ISN''T verified!') - end - disp(' ') +temp_options = options_; +tempex = oo_.exo_simul; +if ~options_.initval_file & M_.exo_nbr > 1 + oo_.exo_simul = ones(M_.maximum_lead+M_.maximum_lag+1,1)*oo_.exo_steady_state'; +end + +options_.order = 1; + +[dr, info] = resol(oo_.steady_state,1); + +oo_.dr = dr; + +if info(1) ~= 0 & info(1) ~= 3 & info(1) ~= 4 + print_info(info, options_.noprint); +end + +oo_.exo_simul = tempex; + +eigenvalues_ = dr.eigval; +nyf = nnz(dr.kstate(:,2)>M_.maximum_endo_lag+1); +[m_lambda,i]=sort(abs(eigenvalues_)); +n_explod = nnz(abs(eigenvalues_) > options_.qz_criterium); + +if options_.noprint == 0 + disp(' ') + disp('EIGENVALUES:') + disp(sprintf('%16s %16s %16s\n','Modulus','Real','Imaginary')) + z=[m_lambda real(eigenvalues_(i)) imag(eigenvalues_(i))]'; + disp(sprintf('%16.4g %16.4g %16.4g\n',z)) + options_ = set_default_option(options_,'qz_criterium',1.000001); + disp(sprintf('\nThere are %d eigenvalue(s) larger than 1 in modulus ', ... + n_explod)); + disp(sprintf('for %d forward-looking variable(s)',nyf)); + disp(' ') + if dr.rank == nyf & nyf == n_explod + disp('The rank condition is verified.') + else + disp('The rank conditions ISN''T verified!') end - - options_ = temp_options; - - % 2/9/99 MJ: line 15, added test for absence of exogenous variable. - % 8/27/2000 MJ: change JACOB call. Added ...,1 to cumsum() - % 6/24/01 MJ: added count of abs(eigenvalues) > 1 - % 2/21/02 MJ: count eigenvalues > 1[+1e-5] - % 01/22/03 MJ: warning(warning_state) needs parentheses for Matlab 6.5 - % name conflicts with parameters - % 05/21/03 MJ: replace computation by dr1.m and add rank check - % 06/05/03 MJ: corrected bug when M_.maximum_lag > 0 - + disp(' ') +end + +options_ = temp_options; + +% 2/9/99 MJ: line 15, added test for absence of exogenous variable. +% 8/27/2000 MJ: change JACOB call. Added ...,1 to cumsum() +% 6/24/01 MJ: added count of abs(eigenvalues) > 1 +% 2/21/02 MJ: count eigenvalues > 1[+1e-5] +% 01/22/03 MJ: warning(warning_state) needs parentheses for Matlab 6.5 +% name conflicts with parameters +% 05/21/03 MJ: replace computation by dr1.m and add rank check +% 06/05/03 MJ: corrected bug when M_.maximum_lag > 0 + diff --git a/matlab/check_list_of_variables.m b/matlab/check_list_of_variables.m index 801110ce94..00ead8f426 100644 --- a/matlab/check_list_of_variables.m +++ b/matlab/check_list_of_variables.m @@ -31,127 +31,127 @@ function varlist = check_list_of_variables(options_, M_, varlist) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - msg = 0; - if options_.bvar_dsge && options_.bayesian_irf - if ~isempty(varlist) - for i=1:size(varlist,1) - idx = strmatch(deblank(varlist(i,:)),options_.varobs,'exact'); - if isempty(idx) - disp([varlist(i,:) ' is not an observed variable!']); - msg = 1; - end - end - if size(varlist,1)~=size(options_.varobs) - msg = 1; - end - if msg - disp(' ') - disp('Posterior IRFs will be computed for all observed variables.') - disp(' ') - end - end - varlist = options_.varobs; - return - end - - if isempty(varlist) - disp(' ') - disp(['You did not declare endogenous variables after the estimation command.']) - cas = []; - if options_.bayesian_irf - cas = 'Posterior IRFs'; - end - if options_.moments_varendo - if isempty(cas) - cas = 'Posterior moments'; - else - cas = [ cas , ', posterior moments']; +msg = 0; +if options_.bvar_dsge && options_.bayesian_irf + if ~isempty(varlist) + for i=1:size(varlist,1) + idx = strmatch(deblank(varlist(i,:)),options_.varobs,'exact'); + if isempty(idx) + disp([varlist(i,:) ' is not an observed variable!']); + msg = 1; end end - if options_.smoother - if isempty(cas) - cas = 'Posterior smoothed variables'; - else - cas = [ cas , ', posterior smoothed variables']; - end + if size(varlist,1)~=size(options_.varobs) + msg = 1; end - if options_.smoother - if isempty(cas) - cas = 'Posterior smoothed variables'; - else - cas = [ cas , ', posterior smoothed variables']; - end + if msg + disp(' ') + disp('Posterior IRFs will be computed for all observed variables.') + disp(' ') end - if ~isempty(options_.filter_step_ahead) - if isempty(cas) - cas = 'Posterior k-step ahead filtered variables'; - else - cas = [ cas , ', posterior k-step ahead filtered variables']; - end + end + varlist = options_.varobs; + return +end + +if isempty(varlist) + disp(' ') + disp(['You did not declare endogenous variables after the estimation command.']) + cas = []; + if options_.bayesian_irf + cas = 'Posterior IRFs'; + end + if options_.moments_varendo + if isempty(cas) + cas = 'Posterior moments'; + else + cas = [ cas , ', posterior moments']; end - if options_.forecast - if isempty(cas) - cas = 'Posterior forecasts'; - else - cas = [ cas , ' and posterior forecats']; - end + end + if options_.smoother + if isempty(cas) + cas = 'Posterior smoothed variables'; + else + cas = [ cas , ', posterior smoothed variables']; end - if ~isempty(cas) - string = [ cas , ' will be computed for the ' num2str(M_.endo_nbr) ' endogenous variables']; - string = [ string ' of your model, this can be very long....']; - format_text(string, 10) - choice = []; - while isempty(choice) - disp(' ') - disp(' ') - disp('Choose one of the following options:') - disp(' ') - disp(' [1] Consider all the endogenous variables.') - disp(' [2] Consider all the observed endogenous variables.') - disp(' [3] Stop Dynare and change the mod file.') - disp(' ') - choice = input('options [default is 1] = '); - if isempty(choice) - choice=1; - end - if choice==1 - varlist = M_.endo_names(1:M_.orig_endo_nbr, :); - elseif choice==2 - varlist = options_.varobs; - elseif choice==3 - varlist = NaN; - else - disp('') - disp('YOU HAVE TO ANSWER 1, 2 or 3!') - disp('') - end - end + end + if options_.smoother + if isempty(cas) + cas = 'Posterior smoothed variables'; + else + cas = [ cas , ', posterior smoothed variables']; end - if isnan(varlist) - edit([M_.fname '.mod']) + end + if ~isempty(options_.filter_step_ahead) + if isempty(cas) + cas = 'Posterior k-step ahead filtered variables'; + else + cas = [ cas , ', posterior k-step ahead filtered variables']; end - disp('') end - - - - function format_text(remain, max_number_of_words_per_line) - index = 0; - line_of_text = []; - while ~isempty(remain) - [token, remain] = strtok(remain); - index = index+1; - if isempty(line_of_text) - line_of_text = token; + if options_.forecast + if isempty(cas) + cas = 'Posterior forecasts'; else - line_of_text = [line_of_text , ' ' , token]; + cas = [ cas , ' and posterior forecats']; end - if index==max_number_of_words_per_line - disp(line_of_text) - index = 0; - line_of_text = []; + end + if ~isempty(cas) + string = [ cas , ' will be computed for the ' num2str(M_.endo_nbr) ' endogenous variables']; + string = [ string ' of your model, this can be very long....']; + format_text(string, 10) + choice = []; + while isempty(choice) + disp(' ') + disp(' ') + disp('Choose one of the following options:') + disp(' ') + disp(' [1] Consider all the endogenous variables.') + disp(' [2] Consider all the observed endogenous variables.') + disp(' [3] Stop Dynare and change the mod file.') + disp(' ') + choice = input('options [default is 1] = '); + if isempty(choice) + choice=1; + end + if choice==1 + varlist = M_.endo_names(1:M_.orig_endo_nbr, :); + elseif choice==2 + varlist = options_.varobs; + elseif choice==3 + varlist = NaN; + else + disp('') + disp('YOU HAVE TO ANSWER 1, 2 or 3!') + disp('') + end end end - if index<max_number_of_words_per_line + if isnan(varlist) + edit([M_.fname '.mod']) + end + disp('') +end + + + +function format_text(remain, max_number_of_words_per_line) +index = 0; +line_of_text = []; +while ~isempty(remain) + [token, remain] = strtok(remain); + index = index+1; + if isempty(line_of_text) + line_of_text = token; + else + line_of_text = [line_of_text , ' ' , token]; + end + if index==max_number_of_words_per_line disp(line_of_text) - end \ No newline at end of file + index = 0; + line_of_text = []; + end +end +if index<max_number_of_words_per_line + disp(line_of_text) +end \ No newline at end of file diff --git a/matlab/check_model.m b/matlab/check_model.m index b123a0c7a7..90e152394c 100644 --- a/matlab/check_model.m +++ b/matlab/check_model.m @@ -1,36 +1,36 @@ -function check_model() - -% Copyright (C) 2005-2006 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 <http://www.gnu.org/licenses/>. - - global M_ - - xlen = M_.maximum_exo_lag+M_.maximum_exo_lead + 1; - if ~ M_.lead_lag_incidence(M_.maximum_lag+1,:) > 0 - error ('RESOL: Error in model specification: some variables don"t appear as current') ; -end - -if xlen > 1 - error (['RESOL: stochastic exogenous variables must appear only at the' ... - ' current period. Use additional endogenous variables']) ; -end - -if (M_.exo_det_nbr > 0) & (M_.maximum_lag > 1 | M_.maximum_lead > 1) - error(['Exogenous deterministic variables are currently only allowed in' ... - ' models with leads and lags on only one period']) -end - +function check_model() + +% Copyright (C) 2005-2006 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 <http://www.gnu.org/licenses/>. + +global M_ + +xlen = M_.maximum_exo_lag+M_.maximum_exo_lead + 1; +if ~ M_.lead_lag_incidence(M_.maximum_lag+1,:) > 0 + error ('RESOL: Error in model specification: some variables don"t appear as current') ; +end + +if xlen > 1 + error (['RESOL: stochastic exogenous variables must appear only at the' ... + ' current period. Use additional endogenous variables']) ; +end + +if (M_.exo_det_nbr > 0) & (M_.maximum_lag > 1 | M_.maximum_lead > 1) + error(['Exogenous deterministic variables are currently only allowed in' ... + ' models with leads and lags on only one period']) +end + diff --git a/matlab/check_name.m b/matlab/check_name.m index 6a56076e68..f51416b1ac 100644 --- a/matlab/check_name.m +++ b/matlab/check_name.m @@ -17,4 +17,4 @@ function n = check_name(vartan,varname) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - n = strmatch(varname,vartan,'exact'); \ No newline at end of file +n = strmatch(varname,vartan,'exact'); \ No newline at end of file diff --git a/matlab/check_posterior_analysis_data.m b/matlab/check_posterior_analysis_data.m index 551375f36b..f895b22a24 100644 --- a/matlab/check_posterior_analysis_data.m +++ b/matlab/check_posterior_analysis_data.m @@ -16,85 +16,85 @@ function [info,description] = check_posterior_analysis_data(type,M_) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - info = 0; + +info = 0; +if nargout>1 + description = ''; +end + +%% Get informations about mcmc files. +if ~exist([ M_.dname '/metropolis'],'dir') + disp('check_posterior_analysis_data:: Can''t find any mcmc file!') + return +end +mhname = get_name_of_the_last_mh_file(M_); +mhdate = get_date_of_a_file(mhname); + +%% Get informations about _posterior_draws files. +drawsinfo = dir([ M_.dname '/metropolis/' M_.fname '_posterior_draws*.mat']); +if isempty(drawsinfo) + info = 1; % select_posterior_draws has to be called first. if nargout>1 - description = ''; + description = 'select_posterior_draws has to be called.'; end - - %% Get informations about mcmc files. - if ~exist([ M_.dname '/metropolis'],'dir') - disp('check_posterior_analysis_data:: Can''t find any mcmc file!') - return - end - mhname = get_name_of_the_last_mh_file(M_); - mhdate = get_date_of_a_file(mhname); - - %% Get informations about _posterior_draws files. - drawsinfo = dir([ M_.dname '/metropolis/' M_.fname '_posterior_draws*.mat']); - if isempty(drawsinfo) - info = 1; % select_posterior_draws has to be called first. + return +else + number_of_last_posterior_draws_file = length(drawsinfo); + pddate = get_date_of_a_file([ M_.dname '/metropolis/' M_.fname '_posterior_draws'... + int2str(number_of_last_posterior_draws_file) '.mat']); + if pddate<mhdate + info = 2; % _posterior_draws files have to be updated. if nargout>1 - description = 'select_posterior_draws has to be called.'; + description = 'posterior draws files have to be updated.'; end return else - number_of_last_posterior_draws_file = length(drawsinfo); - pddate = get_date_of_a_file([ M_.dname '/metropolis/' M_.fname '_posterior_draws'... - int2str(number_of_last_posterior_draws_file) '.mat']); - if pddate<mhdate - info = 2; % _posterior_draws files have to be updated. - if nargout>1 - description = 'posterior draws files have to be updated.'; - end - return - else - info = 3; % Ok! - if nargout>1 - description = 'posterior draws files are up to date.'; - end + info = 3; % Ok! + if nargout>1 + description = 'posterior draws files are up to date.'; end end - - %% Get informations about posterior data files. - switch type - case 'variance' - generic_post_data_file_name = 'Posterior2ndOrderMoments'; - case 'decomposition' - generic_post_data_file_name = 'PosteriorVarianceDecomposition'; - case 'correlation' - generic_post_data_file_name = 'PosteriorCorrelations'; - case 'conditional decomposition' - generic_post_data_file_name = 'PosteriorConditionalVarianceDecomposition'; - otherwise - disp('This feature is not yest implemented!') +end + +%% Get informations about posterior data files. +switch type + case 'variance' + generic_post_data_file_name = 'Posterior2ndOrderMoments'; + case 'decomposition' + generic_post_data_file_name = 'PosteriorVarianceDecomposition'; + case 'correlation' + generic_post_data_file_name = 'PosteriorCorrelations'; + case 'conditional decomposition' + generic_post_data_file_name = 'PosteriorConditionalVarianceDecomposition'; + otherwise + disp('This feature is not yest implemented!') +end +pdfinfo = dir([ M_.dname '/metropolis/' M_.fname '_' generic_post_data_file_name '*']); +if isempty(pdfinfo) + info = 4; % posterior draws have to be processed. + if nargout>1 + description = 'posterior draws files have to be processed.'; end - pdfinfo = dir([ M_.dname '/metropolis/' M_.fname '_' generic_post_data_file_name '*']); - if isempty(pdfinfo) - info = 4; % posterior draws have to be processed. + return +else + number_of_the_last_post_data_file = length(pdfinfo); + name_of_the_last_post_data_file = ... + [ './' M_.dname ... + '/metropolis/' ... + M_.fname '_' ... + generic_post_data_file_name ... + int2str(number_of_the_last_post_data_file) ... + '.mat' ]; + pdfdate = get_date_of_a_file(name_of_the_last_post_data_file); + if pdfdate<pddate + info = 5; % posterior data files have to be updated. if nargout>1 - description = 'posterior draws files have to be processed.'; - end - return + description = 'posterior data files have to be updated.'; + end else - number_of_the_last_post_data_file = length(pdfinfo); - name_of_the_last_post_data_file = ... - [ './' M_.dname ... - '/metropolis/' ... - M_.fname '_' ... - generic_post_data_file_name ... - int2str(number_of_the_last_post_data_file) ... - '.mat' ]; - pdfdate = get_date_of_a_file(name_of_the_last_post_data_file); - if pdfdate<pddate - info = 5; % posterior data files have to be updated. - if nargout>1 - description = 'posterior data files have to be updated.'; - end - else - info = 6; % Ok (nothing to do ;-) - if nargout>1 - description = 'There is nothing to do'; - end - end - end \ No newline at end of file + info = 6; % Ok (nothing to do ;-) + if nargout>1 + description = 'There is nothing to do'; + end + end +end \ No newline at end of file diff --git a/matlab/check_prior_analysis_data.m b/matlab/check_prior_analysis_data.m index a566707988..2afff80984 100644 --- a/matlab/check_prior_analysis_data.m +++ b/matlab/check_prior_analysis_data.m @@ -15,84 +15,84 @@ function [info,description] = check_prior_analysis_data(type,M_) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - info = 0; + +info = 0; +if nargout>1 + description = ''; +end + +%% Get informations about prior draws files. +if ~exist([ M_.dname '/prior/draws'],'dir') + disp('check_prior_analysis_data:: Can''t find any prior draws file!') + return +end + +prior_draws_info = dir([ M_.dname '/prior/draws/prior_draws*.mat']); +name_of_the_last_prior_draw_file = prior_draws_info(end).name; +date_of_the_last_prior_draw_file = prior_draws_info(end).datenum; + +%% Get informations about _posterior_draws files. +if isempty(prior_draws_info) + info = 1; if nargout>1 - description = ''; + description = 'prior_sampler has to be called.'; end - - %% Get informations about prior draws files. - if ~exist([ M_.dname '/prior/draws'],'dir') - disp('check_prior_analysis_data:: Can''t find any prior draws file!') - return - end - - prior_draws_info = dir([ M_.dname '/prior/draws/prior_draws*.mat']); - name_of_the_last_prior_draw_file = prior_draws_info(end).name; - date_of_the_last_prior_draw_file = prior_draws_info(end).datenum; - - %% Get informations about _posterior_draws files. - if isempty(prior_draws_info) - info = 1; + return +else + number_of_last_prior_draws_file = length(prior_draws_info); + date_of_the_prior_definition = get_date_of_a_file([ M_.dname '/prior/definition.mat']); + if date_of_the_prior_definition>date_of_the_last_prior_draw_file + info = 2; if nargout>1 - description = 'prior_sampler has to be called.'; + description = 'prior draws files have to be updated.'; end return else - number_of_last_prior_draws_file = length(prior_draws_info); - date_of_the_prior_definition = get_date_of_a_file([ M_.dname '/prior/definition.mat']); - if date_of_the_prior_definition>date_of_the_last_prior_draw_file - info = 2; - if nargout>1 - description = 'prior draws files have to be updated.'; - end - return - else - info = 3; % Nothing to do! - if nargout>1 - description = 'prior draws files are up to date.'; - end + info = 3; % Nothing to do! + if nargout>1 + description = 'prior draws files are up to date.'; end end - - %% Get informations about prior data files. - switch type - case 'variance' - generic_prior_data_file_name = 'Prior2ndOrderMoments'; - case 'decomposition' - generic_prior_data_file_name = 'PriorVarianceDecomposition'; - case 'correlation' - generic_prior_data_file_name = 'PriorCorrelations'; - case 'conditional decomposition' - generic_prior_data_file_name = 'PriorConditionalVarianceDecomposition'; - otherwise - disp(['This feature is not yet implemented!']) +end + +%% Get informations about prior data files. +switch type + case 'variance' + generic_prior_data_file_name = 'Prior2ndOrderMoments'; + case 'decomposition' + generic_prior_data_file_name = 'PriorVarianceDecomposition'; + case 'correlation' + generic_prior_data_file_name = 'PriorCorrelations'; + case 'conditional decomposition' + generic_prior_data_file_name = 'PriorConditionalVarianceDecomposition'; + otherwise + disp(['This feature is not yet implemented!']) +end +CheckPath('prior/moments'); +pdfinfo = dir([ M_.dname '/prior/' generic_prior_data_file_name '*']); +if isempty(pdfinfo) + info = 4; + if nargout>1 + description = 'prior draws files have to be processed.'; end - CheckPath('prior/moments'); - pdfinfo = dir([ M_.dname '/prior/' generic_prior_data_file_name '*']); - if isempty(pdfinfo) - info = 4; + return +else + number_of_the_last_prior_data_file = length(pdfinfo); + name_of_the_last_prior_data_file = pdinfo(end).name; + pdfdate = pdinfo(end).datenum; + % /!\ REMARK /!\ + % The user can change the model or the value of a calibrated + % parameter without changing the prior. In this case the (prior) + % moments should be computed. But this case cannot be detected!!! + if pdfdate<date_of_the_last_prior_draw_file + info = 5; % prior data files have to be updated. if nargout>1 - description = 'prior draws files have to be processed.'; + description = 'prior data files have to be updated.'; end - return else - number_of_the_last_prior_data_file = length(pdfinfo); - name_of_the_last_prior_data_file = pdinfo(end).name; - pdfdate = pdinfo(end).datenum; - % /!\ REMARK /!\ - % The user can change the model or the value of a calibrated - % parameter without changing the prior. In this case the (prior) - % moments should be computed. But this case cannot be detected!!! - if pdfdate<date_of_the_last_prior_draw_file - info = 5; % prior data files have to be updated. - if nargout>1 - description = 'prior data files have to be updated.'; - end - else - info = 6; % Ok (nothing to do ;-) - if nargout>1 - description = 'prior data files are up to date.'; - end + info = 6; % Ok (nothing to do ;-) + if nargout>1 + description = 'prior data files are up to date.'; end - end \ No newline at end of file + end +end \ No newline at end of file diff --git a/matlab/compute_mh_covariance_matrix.m b/matlab/compute_mh_covariance_matrix.m index 25f759b620..f785ef87a3 100644 --- a/matlab/compute_mh_covariance_matrix.m +++ b/matlab/compute_mh_covariance_matrix.m @@ -36,10 +36,10 @@ global M_ options_ estim_params_ n = estim_params_.np + ... - estim_params_.nvn+ ... - estim_params_.ncx+ ... - estim_params_.ncn+ ... - estim_params_.nvx; + estim_params_.nvn+ ... + estim_params_.ncx+ ... + estim_params_.ncn+ ... + estim_params_.nvx; nblck = options_.mh_nblck; MhDirectoryName = CheckPath('metropolis'); diff --git a/matlab/compute_model_moments.m b/matlab/compute_model_moments.m index 4cee165ef8..20260f254b 100644 --- a/matlab/compute_model_moments.m +++ b/matlab/compute_model_moments.m @@ -1,31 +1,31 @@ -function moments=compute_model_moments(dr,M_,options_) -% -% INPUTS -% dr: structure describing model solution -% M_: structure of Dynare options -% options_ -% -% OUTPUTS -% moments: a cell array containing requested moments -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. - - moments = th_autocovariances(dr,options_.varlist,M_,options_); +function moments=compute_model_moments(dr,M_,options_) +% +% INPUTS +% dr: structure describing model solution +% M_: structure of Dynare options +% options_ +% +% OUTPUTS +% moments: a cell array containing requested moments +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. + +moments = th_autocovariances(dr,options_.varlist,M_,options_); diff --git a/matlab/compute_moments_varendo.m b/matlab/compute_moments_varendo.m index c394ed6f01..0cb903e6a8 100644 --- a/matlab/compute_moments_varendo.m +++ b/matlab/compute_moments_varendo.m @@ -32,88 +32,88 @@ function oo_ = compute_moments_varendo(type,options_,M_,oo_,var_list_) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - if strcmpi(type,'posterior') - posterior = 1; - if nargin==4 - var_list_ = options_.varobs; - end - elseif strcmpi(type,'prior') - posterior = 0; - if nargin==4 - var_list_ = options_.prior_analysis_endo_var_list; - if isempty(var_list_) - options_.prior_analysis_var_list = options_.varobs; - end + +if strcmpi(type,'posterior') + posterior = 1; + if nargin==4 + var_list_ = options_.varobs; + end +elseif strcmpi(type,'prior') + posterior = 0; + if nargin==4 + var_list_ = options_.prior_analysis_endo_var_list; + if isempty(var_list_) + options_.prior_analysis_var_list = options_.varobs; end - else - disp('compute_moments_varendo:: Unknown type!') - error() end +else + disp('compute_moments_varendo:: Unknown type!') + error() +end - NumberOfEndogenousVariables = rows(var_list_); - NumberOfExogenousVariables = M_.exo_nbr; - list_of_exogenous_variables = M_.exo_names; - NumberOfLags = options_.ar; - Steps = options_.conditional_variance_decomposition; +NumberOfEndogenousVariables = rows(var_list_); +NumberOfExogenousVariables = M_.exo_nbr; +list_of_exogenous_variables = M_.exo_names; +NumberOfLags = options_.ar; +Steps = options_.conditional_variance_decomposition; - % COVARIANCE MATRIX. - if posterior - for i=1:NumberOfEndogenousVariables - for j=i:NumberOfEndogenousVariables - oo_ = posterior_analysis('variance',var_list_(i,:),var_list_(j,:),[],options_,M_,oo_); - end - end - else - for i=1:NumberOfEndogenousVariables - for j=i:NumberOfEndogenousVariables - oo_ = prior_analysis('variance',var_list_(i,:),var_list_(j,:),[],options_,M_,oo_); - end +% COVARIANCE MATRIX. +if posterior + for i=1:NumberOfEndogenousVariables + for j=i:NumberOfEndogenousVariables + oo_ = posterior_analysis('variance',var_list_(i,:),var_list_(j,:),[],options_,M_,oo_); end end - % CORRELATION FUNCTION. - if posterior - for h=NumberOfLags:-1:1 - for i=1:NumberOfEndogenousVariables - for j=1:NumberOfEndogenousVariables - oo_ = posterior_analysis('correlation',var_list_(i,:),var_list_(j,:),h,options_,M_,oo_); - end - end - end - else - for h=NumberOfLags:-1:1 - for i=1:NumberOfEndogenousVariables - for j=1:NumberOfEndogenousVariables - oo_ = prior_analysis('correlation',var_list_(i,:),var_list_(j,:),h,options_,M_,oo_); - end - end +else + for i=1:NumberOfEndogenousVariables + for j=i:NumberOfEndogenousVariables + oo_ = prior_analysis('variance',var_list_(i,:),var_list_(j,:),[],options_,M_,oo_); end end - % VARIANCE DECOMPOSITION. - if posterior +end +% CORRELATION FUNCTION. +if posterior + for h=NumberOfLags:-1:1 for i=1:NumberOfEndogenousVariables - for j=1:NumberOfExogenousVariables - oo_ = posterior_analysis('decomposition',var_list_(i,:),M_.exo_names(j,:),[],options_,M_,oo_); + for j=1:NumberOfEndogenousVariables + oo_ = posterior_analysis('correlation',var_list_(i,:),var_list_(j,:),h,options_,M_,oo_); end end - else - for i=1:NumberOfEndogenousVariables - for j=1:NumberOfExogenousVariables - oo_ = prior_analysis('decomposition',var_list_(i,:),M_.exo_names(j,:),[],options_,M_,oo_); - end - end end - % CONDITIONAL VARIANCE DECOMPOSITION. - if posterior +else + for h=NumberOfLags:-1:1 for i=1:NumberOfEndogenousVariables - for j=1:NumberOfExogenousVariables - oo_ = posterior_analysis('conditional decomposition',var_list_(i,:),M_.exo_names(j,:),Steps,options_,M_,oo_); + for j=1:NumberOfEndogenousVariables + oo_ = prior_analysis('correlation',var_list_(i,:),var_list_(j,:),h,options_,M_,oo_); end end - else - for i=1:NumberOfEndogenousVariables - for j=1:NumberOfExogenousVariables - oo_ = prior_analysis('conditional decomposition',var_list_(i,:),M_.exo_names(j,:),Steps,options_,M_,oo_); - end + end +end +% VARIANCE DECOMPOSITION. +if posterior + for i=1:NumberOfEndogenousVariables + for j=1:NumberOfExogenousVariables + oo_ = posterior_analysis('decomposition',var_list_(i,:),M_.exo_names(j,:),[],options_,M_,oo_); end - end \ No newline at end of file + end +else + for i=1:NumberOfEndogenousVariables + for j=1:NumberOfExogenousVariables + oo_ = prior_analysis('decomposition',var_list_(i,:),M_.exo_names(j,:),[],options_,M_,oo_); + end + end +end +% CONDITIONAL VARIANCE DECOMPOSITION. +if posterior + for i=1:NumberOfEndogenousVariables + for j=1:NumberOfExogenousVariables + oo_ = posterior_analysis('conditional decomposition',var_list_(i,:),M_.exo_names(j,:),Steps,options_,M_,oo_); + end + end +else + for i=1:NumberOfEndogenousVariables + for j=1:NumberOfExogenousVariables + oo_ = prior_analysis('conditional decomposition',var_list_(i,:),M_.exo_names(j,:),Steps,options_,M_,oo_); + end + end +end \ No newline at end of file diff --git a/matlab/conditional_variance_decomposition.m b/matlab/conditional_variance_decomposition.m index 1f86331062..c04c61e0c6 100644 --- a/matlab/conditional_variance_decomposition.m +++ b/matlab/conditional_variance_decomposition.m @@ -31,43 +31,43 @@ function PackedConditionalVarianceDecomposition = conditional_variance_decomposi % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - number_of_state_innovations = ... - StateSpaceModel.number_of_state_innovations; - transition_matrix = StateSpaceModel.transition_matrix; - number_of_state_equations = ... - StateSpaceModel.number_of_state_equations; - nSteps = length(Steps); - - ConditionalVariance = zeros(number_of_state_equations,number_of_state_equations); - ConditionalVariance = repmat(ConditionalVariance,[1 1 nSteps ... - number_of_state_innovations]); +number_of_state_innovations = ... + StateSpaceModel.number_of_state_innovations; +transition_matrix = StateSpaceModel.transition_matrix; +number_of_state_equations = ... + StateSpaceModel.number_of_state_equations; +nSteps = length(Steps); - if StateSpaceModel.sigma_e_is_diagonal - B = StateSpaceModel.impulse_matrix.* ... - repmat(sqrt(diag(StateSpaceModel.state_innovations_covariance_matrix)'),... - number_of_state_equations,1); - else - B = StateSpaceModel.impulse_matrix*chol(StateSpaceModel.state_innovations_covariance_matrix)'; - end - - for i=1:number_of_state_innovations - BB = B(:,i)*B(:,i)'; - V = zeros(number_of_state_equations,number_of_state_equations); - m = 1; - for h = 1:max(Steps) - V = transition_matrix*V*transition_matrix'+BB; - if h == Steps(m) - ConditionalVariance(:,:,m,i) = V; - m = m+1; - end +ConditionalVariance = zeros(number_of_state_equations,number_of_state_equations); +ConditionalVariance = repmat(ConditionalVariance,[1 1 nSteps ... + number_of_state_innovations]); + +if StateSpaceModel.sigma_e_is_diagonal + B = StateSpaceModel.impulse_matrix.* ... + repmat(sqrt(diag(StateSpaceModel.state_innovations_covariance_matrix)'),... + number_of_state_equations,1); +else + B = StateSpaceModel.impulse_matrix*chol(StateSpaceModel.state_innovations_covariance_matrix)'; +end + +for i=1:number_of_state_innovations + BB = B(:,i)*B(:,i)'; + V = zeros(number_of_state_equations,number_of_state_equations); + m = 1; + for h = 1:max(Steps) + V = transition_matrix*V*transition_matrix'+BB; + if h == Steps(m) + ConditionalVariance(:,:,m,i) = V; + m = m+1; end end - - ConditionalVariance = ConditionalVariance(SubsetOfVariables,SubsetOfVariables,:,:); - NumberOfVariables = length(SubsetOfVariables); - PackedConditionalVarianceDecomposition = zeros(NumberOfVariables*(NumberOfVariables+1)/2,length(Steps),StateSpaceModel.number_of_state_innovations); - for i=1:number_of_state_innovations - for h = 1:length(Steps) - PackedConditionalVarianceDecomposition(:,h,i) = vech(ConditionalVariance(:,:,h,i)); - end - end \ No newline at end of file +end + +ConditionalVariance = ConditionalVariance(SubsetOfVariables,SubsetOfVariables,:,:); +NumberOfVariables = length(SubsetOfVariables); +PackedConditionalVarianceDecomposition = zeros(NumberOfVariables*(NumberOfVariables+1)/2,length(Steps),StateSpaceModel.number_of_state_innovations); +for i=1:number_of_state_innovations + for h = 1:length(Steps) + PackedConditionalVarianceDecomposition(:,h,i) = vech(ConditionalVariance(:,:,h,i)); + end +end \ No newline at end of file diff --git a/matlab/conditional_variance_decomposition_mc_analysis.m b/matlab/conditional_variance_decomposition_mc_analysis.m index c0701c6927..0968535f94 100644 --- a/matlab/conditional_variance_decomposition_mc_analysis.m +++ b/matlab/conditional_variance_decomposition_mc_analysis.m @@ -19,78 +19,78 @@ function oo_ = conditional_variance_decomposition_mc_analysis(NumberOfSimulation % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if strcmpi(type,'posterior') - TYPE = 'Posterior'; - PATH = [dname '/metropolis/']; - else - TYPE = 'Prior'; - PATH = [dname '/prior/moments/']; - end +if strcmpi(type,'posterior') + TYPE = 'Posterior'; + PATH = [dname '/metropolis/']; +else + TYPE = 'Prior'; + PATH = [dname '/prior/moments/']; +end - indx = check_name(vartan,var); - if isempty(indx) - disp([ type '_analysis:: ' var ' is not a stationary endogenous variable!']) - return - end - endogenous_variable_index = sum(1:indx); - exogenous_variable_index = check_name(exonames,exo); - if isempty(exogenous_variable_index) - disp([ type '_analysis:: ' exo ' is not a declared exogenous variable!']) - return - end +indx = check_name(vartan,var); +if isempty(indx) + disp([ type '_analysis:: ' var ' is not a stationary endogenous variable!']) + return +end +endogenous_variable_index = sum(1:indx); +exogenous_variable_index = check_name(exonames,exo); +if isempty(exogenous_variable_index) + disp([ type '_analysis:: ' exo ' is not a declared exogenous variable!']) + return +end - name = [ var '.' exo ]; - if isfield(oo_, [ TYPE 'TheoreticalMoments' ]) - eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;']) - if isfield(temporary_structure,'dsge') - eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;']) - if isfield(temporary_structure,'ConditionalVarianceDecomposition') - eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.mean;']) - if isfield(temporary_structure,name) - if sum(Steps-temporary_structure.(name)(1,:)) == 0 - % Nothing (new) to do here... - return - end +name = [ var '.' exo ]; +if isfield(oo_, [ TYPE 'TheoreticalMoments' ]) + eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;']) + if isfield(temporary_structure,'dsge') + eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;']) + if isfield(temporary_structure,'ConditionalVarianceDecomposition') + eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.mean;']) + if isfield(temporary_structure,name) + if sum(Steps-temporary_structure.(name)(1,:)) == 0 + % Nothing (new) to do here... + return end end end end - - ListOfFiles = dir([ PATH fname '_' TYPE 'ConditionalVarianceDecomposition*.mat']); - i1 = 1; tmp = zeros(NumberOfSimulations,length(Steps)); - for file = 1:length(ListOfFiles) - load([ PATH ListOfFiles(file).name ]); - % 4D-array (endovar,time,exovar,simul) - i2 = i1 + size(Conditional_decomposition_array,4) - 1; - tmp(i1:i2,:) = transpose(dynare_squeeze(Conditional_decomposition_array(endogenous_variable_index,:,exogenous_variable_index,:))); - i1 = i2+1; - end +end - p_mean = NaN(2,length(Steps)); - p_mean(1,:) = Steps; - p_median = NaN(1,length(Steps)); - p_variance = NaN(1,length(Steps)); - p_deciles = NaN(9,length(Steps)); - p_density = NaN(2^9,2,length(Steps)); - p_hpdinf = NaN(1,length(Steps)); - p_hpdsup = NaN(1,length(Steps)); - for i=1:length(Steps) - if ~isconst(tmp(:,i)) - [pp_mean, pp_median, pp_var, hpd_interval, pp_deciles, pp_density] = ... - posterior_moments(tmp(:,i),1,mh_conf_sig); - p_mean(2,i) = pp_mean; - p_median(i) = pp_median; - p_variance(i) = pp_var; - p_deciles(:,i) = pp_deciles; - p_hpdinf(i) = hpd_interval(1); - p_hpdinf(i) = hpd_interval(2); - p_density(:,:,i) = pp_density; - end +ListOfFiles = dir([ PATH fname '_' TYPE 'ConditionalVarianceDecomposition*.mat']); +i1 = 1; tmp = zeros(NumberOfSimulations,length(Steps)); +for file = 1:length(ListOfFiles) + load([ PATH ListOfFiles(file).name ]); + % 4D-array (endovar,time,exovar,simul) + i2 = i1 + size(Conditional_decomposition_array,4) - 1; + tmp(i1:i2,:) = transpose(dynare_squeeze(Conditional_decomposition_array(endogenous_variable_index,:,exogenous_variable_index,:))); + i1 = i2+1; +end + +p_mean = NaN(2,length(Steps)); +p_mean(1,:) = Steps; +p_median = NaN(1,length(Steps)); +p_variance = NaN(1,length(Steps)); +p_deciles = NaN(9,length(Steps)); +p_density = NaN(2^9,2,length(Steps)); +p_hpdinf = NaN(1,length(Steps)); +p_hpdsup = NaN(1,length(Steps)); +for i=1:length(Steps) + if ~isconst(tmp(:,i)) + [pp_mean, pp_median, pp_var, hpd_interval, pp_deciles, pp_density] = ... + posterior_moments(tmp(:,i),1,mh_conf_sig); + p_mean(2,i) = pp_mean; + p_median(i) = pp_median; + p_variance(i) = pp_var; + p_deciles(:,i) = pp_deciles; + p_hpdinf(i) = hpd_interval(1); + p_hpdinf(i) = hpd_interval(2); + p_density(:,:,i) = pp_density; end - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.mean.' name ' = p_mean;']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.median.' name ' = p_median;']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.variance.' name ' = p_variance;']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.hpdinf.' name ' = p_hpdinf;']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.hpdsup.' name ' = p_hpdsup;']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.deciles.' name ' = p_deciles;']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.density.' name ' = p_density;']); \ No newline at end of file +end +eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.mean.' name ' = p_mean;']); +eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.median.' name ' = p_median;']); +eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.variance.' name ' = p_variance;']); +eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.hpdinf.' name ' = p_hpdinf;']); +eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.hpdsup.' name ' = p_hpdsup;']); +eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.deciles.' name ' = p_deciles;']); +eval(['oo_.' TYPE 'TheoreticalMoments.dsge.ConditionalVarianceDecomposition.density.' name ' = p_density;']); \ No newline at end of file diff --git a/matlab/correlation_mc_analysis.m b/matlab/correlation_mc_analysis.m index a82219ea54..6d66de9d9b 100644 --- a/matlab/correlation_mc_analysis.m +++ b/matlab/correlation_mc_analysis.m @@ -19,55 +19,52 @@ function oo_ = correlation_mc_analysis(SampleSize,type,dname,fname,vartan,nvar,v % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if strcmpi(type,'posterior') - TYPE = 'Posterior'; - PATH = [dname '/metropolis/']; - else - TYPE = 'Prior'; - PATH = [dname '/prior/moments/']; - end +if strcmpi(type,'posterior') + TYPE = 'Posterior'; + PATH = [dname '/metropolis/']; +else + TYPE = 'Prior'; + PATH = [dname '/prior/moments/']; +end - indx1 = check_name(vartan,var1); - if isempty(indx1) - disp([ type '_analysis:: ' var1 ' is not a stationary endogenous variable!']) +indx1 = check_name(vartan,var1); +if isempty(indx1) + disp([ type '_analysis:: ' var1 ' is not a stationary endogenous variable!']) + return +end +if ~isempty(var2) + indx2 = check_name(vartan,var2); + if isempty(indx2) + disp([ type '_analysis:: ' var2 ' is not a stationary endogenous variable!']) return end - if ~isempty(var2) - indx2 = check_name(vartan,var2); - if isempty(indx2) - disp([ type '_analysis:: ' var2 ' is not a stationary endogenous variable!']) - return - end - else - indx2 = indx1; - var2 = var1; - end +else + indx2 = indx1; + var2 = var1; +end - if isfield(oo_,[TYPE 'TheoreticalMoments']) - eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;']) - if isfield(temporary_structure,'dsge') - eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;']) - if isfield(temporary_structure,'correlation') - eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge.correlation.mean;']) - if isfield(temporary_structure,var1) - eval(['temporary_structure_1 = oo_.' TYPE 'TheoreticalMoments.dsge.correlation.mean.' var1 ';']) - if isfield(temporary_structure_1,var2) - eval(['temporary_structure_2 = temporary_structure_1.' var2 ';']) - l1 = length(temporary_structure_2); - if l1<nar - % INITIALIZATION: - oo_ = initialize_output_structure(var1,var2,nar,type,oo_); - delete([PATH fname '_' TYPE 'Correlations*']) - [nvar,vartan,NumberOfFiles] = ... - dsge_simulated_theoretical_correlation(SampleSize,nar,M_,options_,oo_,type); - else - if ~isnan(temporary_structure_2(nar)) - %Nothing to do. - return - end - end +if isfield(oo_,[TYPE 'TheoreticalMoments']) + eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;']) + if isfield(temporary_structure,'dsge') + eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;']) + if isfield(temporary_structure,'correlation') + eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge.correlation.mean;']) + if isfield(temporary_structure,var1) + eval(['temporary_structure_1 = oo_.' TYPE 'TheoreticalMoments.dsge.correlation.mean.' var1 ';']) + if isfield(temporary_structure_1,var2) + eval(['temporary_structure_2 = temporary_structure_1.' var2 ';']) + l1 = length(temporary_structure_2); + if l1<nar + % INITIALIZATION: + oo_ = initialize_output_structure(var1,var2,nar,type,oo_); + delete([PATH fname '_' TYPE 'Correlations*']) + [nvar,vartan,NumberOfFiles] = ... + dsge_simulated_theoretical_correlation(SampleSize,nar,M_,options_,oo_,type); else - oo_ = initialize_output_structure(var1,var2,nar,TYPE,oo_); + if ~isnan(temporary_structure_2(nar)) + %Nothing to do. + return + end end else oo_ = initialize_output_structure(var1,var2,nar,TYPE,oo_); @@ -81,72 +78,75 @@ function oo_ = correlation_mc_analysis(SampleSize,type,dname,fname,vartan,nvar,v else oo_ = initialize_output_structure(var1,var2,nar,TYPE,oo_); end - ListOfFiles = dir([ PATH fname '_' TYPE 'Correlations*.mat']); - i1 = 1; tmp = zeros(SampleSize,1); - for file = 1:length(ListOfFiles) - load([ PATH ListOfFiles(file).name ]); - i2 = i1 + rows(Correlation_array) - 1; - tmp(i1:i2) = Correlation_array(:,indx1,indx2,nar); - i1 = i2+1; - end - name = [ var1 '.' var2 ]; - if ~isconst(tmp) - [p_mean, p_median, p_var, hpd_interval, p_deciles, density] = ... - posterior_moments(tmp,1,mh_conf_sig); - if isfield(oo_,[ TYPE 'TheoreticalMoments']) - eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;']) - if isfield(temporary_structure,'dsge') - eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;']) - if isfield(temporary_structure,'correlation') - oo_ = fill_output_structure(var1,var2,TYPE,oo_,'mean',nar,p_mean); - oo_ = fill_output_structure(var1,var2,TYPE,oo_,'median',nar,p_median); - oo_ = fill_output_structure(var1,var2,TYPE,oo_,'variance',nar,p_var); - oo_ = fill_output_structure(var1,var2,TYPE,oo_,'hpdinf',nar,hpd_interval(1)); - oo_ = fill_output_structure(var1,var2,TYPE,oo_,'hpdsup',nar,hpd_interval(2)); - oo_ = fill_output_structure(var1,var2,TYPE,oo_,'deciles',nar,p_deciles); - oo_ = fill_output_structure(var1,var2,TYPE,oo_,'density',nar,density); - end +else + oo_ = initialize_output_structure(var1,var2,nar,TYPE,oo_); +end +ListOfFiles = dir([ PATH fname '_' TYPE 'Correlations*.mat']); +i1 = 1; tmp = zeros(SampleSize,1); +for file = 1:length(ListOfFiles) + load([ PATH ListOfFiles(file).name ]); + i2 = i1 + rows(Correlation_array) - 1; + tmp(i1:i2) = Correlation_array(:,indx1,indx2,nar); + i1 = i2+1; +end +name = [ var1 '.' var2 ]; +if ~isconst(tmp) + [p_mean, p_median, p_var, hpd_interval, p_deciles, density] = ... + posterior_moments(tmp,1,mh_conf_sig); + if isfield(oo_,[ TYPE 'TheoreticalMoments']) + eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;']) + if isfield(temporary_structure,'dsge') + eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;']) + if isfield(temporary_structure,'correlation') + oo_ = fill_output_structure(var1,var2,TYPE,oo_,'mean',nar,p_mean); + oo_ = fill_output_structure(var1,var2,TYPE,oo_,'median',nar,p_median); + oo_ = fill_output_structure(var1,var2,TYPE,oo_,'variance',nar,p_var); + oo_ = fill_output_structure(var1,var2,TYPE,oo_,'hpdinf',nar,hpd_interval(1)); + oo_ = fill_output_structure(var1,var2,TYPE,oo_,'hpdsup',nar,hpd_interval(2)); + oo_ = fill_output_structure(var1,var2,TYPE,oo_,'deciles',nar,p_deciles); + oo_ = fill_output_structure(var1,var2,TYPE,oo_,'density',nar,density); end end - else - if isfield(oo_,'PosteriorTheoreticalMoments') - eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;']) - if isfield(temporary_structure,'dsge') - eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;']) - if isfield(temporary_structure,'correlation') - oo_ = fill_output_structure(var1,var2,TYPE,oo_,'mean',nar,NaN); - oo_ = fill_output_structure(var1,var2,TYPE,oo_,'median',nar,NaN); - oo_ = fill_output_structure(var1,var2,TYPE,oo_,'variance',nar,NaN); - oo_ = fill_output_structure(var1,var2,TYPE,oo_,'hpdinf',nar,NaN); - oo_ = fill_output_structure(var1,var2,TYPE,oo_,'hpdsup',nar,NaN); - oo_ = fill_output_structure(var1,var2,TYPE,oo_,'deciles',nar,NaN); - oo_ = fill_output_structure(var1,var2,TYPE,oo_,'density',nar,NaN); - end + end +else + if isfield(oo_,'PosteriorTheoreticalMoments') + eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;']) + if isfield(temporary_structure,'dsge') + eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;']) + if isfield(temporary_structure,'correlation') + oo_ = fill_output_structure(var1,var2,TYPE,oo_,'mean',nar,NaN); + oo_ = fill_output_structure(var1,var2,TYPE,oo_,'median',nar,NaN); + oo_ = fill_output_structure(var1,var2,TYPE,oo_,'variance',nar,NaN); + oo_ = fill_output_structure(var1,var2,TYPE,oo_,'hpdinf',nar,NaN); + oo_ = fill_output_structure(var1,var2,TYPE,oo_,'hpdsup',nar,NaN); + oo_ = fill_output_structure(var1,var2,TYPE,oo_,'deciles',nar,NaN); + oo_ = fill_output_structure(var1,var2,TYPE,oo_,'density',nar,NaN); end end end - +end + function oo_ = initialize_output_structure(var1,var2,nar,type,oo_) - name = [ var1 '.' var2 ]; - eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.mean.' name ' = NaN(' int2str(nar) ',1);']); - eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.median.' name ' = NaN(' int2str(nar) ',1);']); - eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.variance.' name ' = NaN(' int2str(nar) ',1);']); - eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.hpdinf.' name ' = NaN(' int2str(nar) ',1);']); - eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.hpdsup.' name ' = NaN(' int2str(nar) ',1);']); - eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.deciles.' name ' = cell(' int2str(nar) ',1);']); - eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.density.' name ' = cell(' int2str(nar) ',1);']); - for i=1:nar - eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.density.' name '(' int2str(i) ',1) = {NaN};']); - eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.deciles.' name '(' int2str(i) ',1) = {NaN};']); - end - +name = [ var1 '.' var2 ]; +eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.mean.' name ' = NaN(' int2str(nar) ',1);']); +eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.median.' name ' = NaN(' int2str(nar) ',1);']); +eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.variance.' name ' = NaN(' int2str(nar) ',1);']); +eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.hpdinf.' name ' = NaN(' int2str(nar) ',1);']); +eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.hpdsup.' name ' = NaN(' int2str(nar) ',1);']); +eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.deciles.' name ' = cell(' int2str(nar) ',1);']); +eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.density.' name ' = cell(' int2str(nar) ',1);']); +for i=1:nar + eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.density.' name '(' int2str(i) ',1) = {NaN};']); + eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.deciles.' name '(' int2str(i) ',1) = {NaN};']); +end + function oo_ = fill_output_structure(var1,var2,type,oo_,moment,lag,result) - name = [ var1 '.' var2 ]; - switch moment - case {'mean','median','variance','hpdinf','hpdsup'} - eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.' moment '.' name '(' int2str(lag) ',1) = result;']); - case {'deciles','density'} - eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.' moment '.' name '(' int2str(lag) ',1) = {result};']); - otherwise - disp('fill_output_structure:: Unknown field!') - end \ No newline at end of file +name = [ var1 '.' var2 ]; +switch moment + case {'mean','median','variance','hpdinf','hpdsup'} + eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.' moment '.' name '(' int2str(lag) ',1) = result;']); + case {'deciles','density'} + eval(['oo_.' type 'TheoreticalMoments.dsge.correlation.' moment '.' name '(' int2str(lag) ',1) = {result};']); + otherwise + disp('fill_output_structure:: Unknown field!') +end \ No newline at end of file diff --git a/matlab/cosn.m b/matlab/cosn.m index d286c97fb5..7fad0f6b00 100644 --- a/matlab/cosn.m +++ b/matlab/cosn.m @@ -1,41 +1,41 @@ -function co = cosn(H); - -% function co = cosn(H); -% computes the cosine of the angle between the H(:,1) and its -% projection onto the span of H(:,2:end) -% -% Not the same as multiple correlation coefficient since the means are not -% zero -% -% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. - -y = H(:,1); -X = H(:,2:end); - -% y = H(:,1); -% X = H(:,2:end); - -yhat = X*(X\y); -if rank(yhat), - co = y'*yhat/sqrt((y'*y)*(yhat'*yhat)); -else - co=0; -end - - - +function co = cosn(H); + +% function co = cosn(H); +% computes the cosine of the angle between the H(:,1) and its +% projection onto the span of H(:,2:end) +% +% Not the same as multiple correlation coefficient since the means are not +% zero +% +% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. + +y = H(:,1); +X = H(:,2:end); + +% y = H(:,1); +% X = H(:,2:end); + +yhat = X*(X\y); +if rank(yhat), + co = y'*yhat/sqrt((y'*y)*(yhat'*yhat)); +else + co=0; +end + + + diff --git a/matlab/covariance_mc_analysis.m b/matlab/covariance_mc_analysis.m index f89d764454..5695943a10 100644 --- a/matlab/covariance_mc_analysis.m +++ b/matlab/covariance_mc_analysis.m @@ -19,80 +19,80 @@ function oo_ = covariance_mc_analysis(NumberOfSimulations,type,dname,fname,varta % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if strcmpi(type,'posterior') - TYPE = 'Posterior'; - PATH = [dname '/metropolis/']; - else - TYPE = 'Prior'; - PATH = [dname '/prior/moments/']; - end +if strcmpi(type,'posterior') + TYPE = 'Posterior'; + PATH = [dname '/metropolis/']; +else + TYPE = 'Prior'; + PATH = [dname '/prior/moments/']; +end - indx1 = check_name(vartan,var1); - if isempty(indx1) - disp([ type '_analysis:: ' var1 ' is not a stationary endogenous variable!']) +indx1 = check_name(vartan,var1); +if isempty(indx1) + disp([ type '_analysis:: ' var1 ' is not a stationary endogenous variable!']) + return +end +if ~isempty(var2) + indx2 = check_name(vartan,var2); + if isempty(indx2) + disp([ type '_analysis:: ' var2 ' is not a stationary endogenous variable!']) return end - if ~isempty(var2) - indx2 = check_name(vartan,var2); - if isempty(indx2) - disp([ type '_analysis:: ' var2 ' is not a stationary endogenous variable!']) - return - end - else - indx2 = indx1; - var2 = var1; - end +else + indx2 = indx1; + var2 = var1; +end - if isfield(oo_,[ TYPE 'TheoreticalMoments']) - eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;']) - if isfield(temporary_structure,'dsge') - eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;']) - if isfield(temporary_structure,'covariance') - eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean;']) - if isfield(temporary_structure,var1) - eval(['temporary_structure_1 = oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' var1 ';']) - if isfield(temporary_structure_1,var2) +if isfield(oo_,[ TYPE 'TheoreticalMoments']) + eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;']) + if isfield(temporary_structure,'dsge') + eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;']) + if isfield(temporary_structure,'covariance') + eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean;']) + if isfield(temporary_structure,var1) + eval(['temporary_structure_1 = oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' var1 ';']) + if isfield(temporary_structure_1,var2) + % Nothing to do (the covariance matrix is symmetric!). + return + end + else + if isfield(temporary_structure,var2) + eval(['temporary_structure_2 = oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' var2 ';']) + if isfield(temporary_structure_2,var1) % Nothing to do (the covariance matrix is symmetric!). return end - else - if isfield(temporary_structure,var2) - eval(['temporary_structure_2 = oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' var2 ';']) - if isfield(temporary_structure_2,var1) - % Nothing to do (the covariance matrix is symmetric!). - return - end - end end end end end +end - ListOfFiles = dir([ PATH fname '_' TYPE '2ndOrderMoments*.mat']); - i1 = 1; tmp = zeros(NumberOfSimulations,1); - for file = 1:length(ListOfFiles) - load([ PATH ListOfFiles(file).name ]); - i2 = i1 + rows(Covariance_matrix) - 1; - tmp(i1:i2) = Covariance_matrix(:,symmetric_matrix_index(indx1,indx2,nvar)); - i1 = i2+1; - end - name = [var1 '.' var2]; - if ~isconst(tmp) - [p_mean, p_median, p_var, hpd_interval, p_deciles, density] = ... - posterior_moments(tmp,1,mh_conf_sig); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' name ' = p_mean;']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.median.' name ' = p_median;']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.variance.' name ' = p_var;']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.hpdinf.' name ' = hpd_interval(1);']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.hpdsup.' name ' = hpd_interval(2);']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.deciles.' name ' = p_deciles;']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.density.' name ' = density;']); - else - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' name ' = NaN;']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.median.' name ' = NaN;']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.variance.' name ' = NaN;']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.hpdinf.' name ' = NaN;']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.hpdsup.' name ' = NaN;']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.deciles.' name ' = NaN;']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.density.' name ' = NaN;']); - end \ No newline at end of file +ListOfFiles = dir([ PATH fname '_' TYPE '2ndOrderMoments*.mat']); +i1 = 1; tmp = zeros(NumberOfSimulations,1); +for file = 1:length(ListOfFiles) + load([ PATH ListOfFiles(file).name ]); + i2 = i1 + rows(Covariance_matrix) - 1; + tmp(i1:i2) = Covariance_matrix(:,symmetric_matrix_index(indx1,indx2,nvar)); + i1 = i2+1; +end +name = [var1 '.' var2]; +if ~isconst(tmp) + [p_mean, p_median, p_var, hpd_interval, p_deciles, density] = ... + posterior_moments(tmp,1,mh_conf_sig); + eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' name ' = p_mean;']); + eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.median.' name ' = p_median;']); + eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.variance.' name ' = p_var;']); + eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.hpdinf.' name ' = hpd_interval(1);']); + eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.hpdsup.' name ' = hpd_interval(2);']); + eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.deciles.' name ' = p_deciles;']); + eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.density.' name ' = density;']); +else + eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.mean.' name ' = NaN;']); + eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.median.' name ' = NaN;']); + eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.variance.' name ' = NaN;']); + eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.hpdinf.' name ' = NaN;']); + eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.hpdsup.' name ' = NaN;']); + eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.deciles.' name ' = NaN;']); + eval(['oo_.' TYPE 'TheoreticalMoments.dsge.covariance.density.' name ' = NaN;']); +end \ No newline at end of file diff --git a/matlab/csminit.m b/matlab/csminit.m index f018e9fcfb..26c84c6b63 100644 --- a/matlab/csminit.m +++ b/matlab/csminit.m @@ -60,152 +60,152 @@ g = g0; gnorm = norm(g); % if (gnorm < 1.e-12) & ~badg % put ~badg 8/4/94 - retcode =1; - dxnorm=0; - % gradient convergence + retcode =1; + dxnorm=0; + % gradient convergence else - % with badg true, we don't try to match rate of improvement to directional - % derivative. We're satisfied just to get some improvement in f. - % - %if(badg) - % dx = -g*FCHANGE/(gnorm*gnorm); - % dxnorm = norm(dx); - % if dxnorm > 1e12 - % disp('Bad, small gradient problem.') - % dx = dx*FCHANGE/dxnorm; - % end - %else - % Gauss-Newton step; - %---------- Start of 7/19/93 mod --------------- - %[v d] = eig(H0); - %toc - %d=max(1e-10,abs(diag(d))); - %d=abs(diag(d)); - %dx = -(v.*(ones(size(v,1),1)*d'))*(v'*g); -% toc - dx = -H0*g; -% toc - dxnorm = norm(dx); - if dxnorm > 1e12 - disp('Near-singular H problem.') - dx = dx*FCHANGE/dxnorm; - end - dfhat = dx'*g0; - %end - % - % - if ~badg - % test for alignment of dx with gradient and fix if necessary - a = -dfhat/(gnorm*dxnorm); - if a<ANGLE - dx = dx - (ANGLE*dxnorm/gnorm+dfhat/(gnorm*gnorm))*g; - dfhat = dx'*g; - dxnorm = norm(dx); - disp(sprintf('Correct for low angle: %g',a)) - end - end - disp(sprintf('Predicted improvement: %18.9f',-dfhat/2)) - % - % Have OK dx, now adjust length of step (lambda) until min and - % max improvement rate criteria are met. - done=0; - factor=3; - shrink=1; - lambdaMin=0; - lambdaMax=inf; - lambdaPeak=0; - fPeak=f0; - lambdahat=0; - while ~done - if size(x0,2)>1 - dxtest=x0+dx'*lambda; - else - dxtest=x0+dx*lambda; - end - % home - f = feval(fcn,dxtest,varargin{:}); - %ARGLIST - %f = feval(fcn,dxtest,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13); - % f = feval(fcn,x0+dx*lambda,P1,P2,P3,P4,P5,P6,P7,P8); - disp(sprintf('lambda = %10.5g; f = %20.7f',lambda,f )) - %debug - %disp(sprintf('Improvement too great? f0-f: %g, criterion: %g',f0-f,-(1-THETA)*dfhat*lambda)) - if f<fhat - fhat=f; - xhat=dxtest; - lambdahat = lambda; - end - fcount=fcount+1; - shrinkSignal = (~badg & (f0-f < max([-THETA*dfhat*lambda 0]))) | (badg & (f0-f) < 0) ; - growSignal = ~badg & ( (lambda > 0) & (f0-f > -(1-THETA)*dfhat*lambda) ); - if shrinkSignal & ( (lambda>lambdaPeak) | (lambda<0) ) - if (lambda>0) & ((~shrink) | (lambda/factor <= lambdaPeak)) - shrink=1; - factor=factor^.6; - while lambda/factor <= lambdaPeak - factor=factor^.6; + % with badg true, we don't try to match rate of improvement to directional + % derivative. We're satisfied just to get some improvement in f. + % + %if(badg) + % dx = -g*FCHANGE/(gnorm*gnorm); + % dxnorm = norm(dx); + % if dxnorm > 1e12 + % disp('Bad, small gradient problem.') + % dx = dx*FCHANGE/dxnorm; + % end + %else + % Gauss-Newton step; + %---------- Start of 7/19/93 mod --------------- + %[v d] = eig(H0); + %toc + %d=max(1e-10,abs(diag(d))); + %d=abs(diag(d)); + %dx = -(v.*(ones(size(v,1),1)*d'))*(v'*g); + % toc + dx = -H0*g; + % toc + dxnorm = norm(dx); + if dxnorm > 1e12 + disp('Near-singular H problem.') + dx = dx*FCHANGE/dxnorm; + end + dfhat = dx'*g0; + %end + % + % + if ~badg + % test for alignment of dx with gradient and fix if necessary + a = -dfhat/(gnorm*dxnorm); + if a<ANGLE + dx = dx - (ANGLE*dxnorm/gnorm+dfhat/(gnorm*gnorm))*g; + dfhat = dx'*g; + dxnorm = norm(dx); + disp(sprintf('Correct for low angle: %g',a)) + end + end + disp(sprintf('Predicted improvement: %18.9f',-dfhat/2)) + % + % Have OK dx, now adjust length of step (lambda) until min and + % max improvement rate criteria are met. + done=0; + factor=3; + shrink=1; + lambdaMin=0; + lambdaMax=inf; + lambdaPeak=0; + fPeak=f0; + lambdahat=0; + while ~done + if size(x0,2)>1 + dxtest=x0+dx'*lambda; + else + dxtest=x0+dx*lambda; + end + % home + f = feval(fcn,dxtest,varargin{:}); + %ARGLIST + %f = feval(fcn,dxtest,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13); + % f = feval(fcn,x0+dx*lambda,P1,P2,P3,P4,P5,P6,P7,P8); + disp(sprintf('lambda = %10.5g; f = %20.7f',lambda,f )) + %debug + %disp(sprintf('Improvement too great? f0-f: %g, criterion: %g',f0-f,-(1-THETA)*dfhat*lambda)) + if f<fhat + fhat=f; + xhat=dxtest; + lambdahat = lambda; + end + fcount=fcount+1; + shrinkSignal = (~badg & (f0-f < max([-THETA*dfhat*lambda 0]))) | (badg & (f0-f) < 0) ; + growSignal = ~badg & ( (lambda > 0) & (f0-f > -(1-THETA)*dfhat*lambda) ); + if shrinkSignal & ( (lambda>lambdaPeak) | (lambda<0) ) + if (lambda>0) & ((~shrink) | (lambda/factor <= lambdaPeak)) + shrink=1; + factor=factor^.6; + while lambda/factor <= lambdaPeak + factor=factor^.6; + end + %if (abs(lambda)*(factor-1)*dxnorm < MINDX) | (abs(lambda)*(factor-1) < MINLAMB) + if abs(factor-1)<MINDFAC + if abs(lambda)<4 + retcode=2; + else + retcode=7; + end + done=1; + end end - %if (abs(lambda)*(factor-1)*dxnorm < MINDX) | (abs(lambda)*(factor-1) < MINLAMB) - if abs(factor-1)<MINDFAC - if abs(lambda)<4 - retcode=2; - else - retcode=7; - end - done=1; + if (lambda<lambdaMax) & (lambda>lambdaPeak) + lambdaMax=lambda; end - end - if (lambda<lambdaMax) & (lambda>lambdaPeak) - lambdaMax=lambda; - end - lambda=lambda/factor; - if abs(lambda) < MINLAMB - if (lambda > 0) & (f0 <= fhat) - % try going against gradient, which may be inaccurate - lambda = -lambda*factor^6 - else - if lambda < 0 - retcode = 6; - else - retcode = 3; - end - done = 1; + lambda=lambda/factor; + if abs(lambda) < MINLAMB + if (lambda > 0) & (f0 <= fhat) + % try going against gradient, which may be inaccurate + lambda = -lambda*factor^6 + else + if lambda < 0 + retcode = 6; + else + retcode = 3; + end + done = 1; + end + end + elseif (growSignal & lambda>0) | (shrinkSignal & ((lambda <= lambdaPeak) & (lambda>0))) + if shrink + shrink=0; + factor = factor^.6; + %if ( abs(lambda)*(factor-1)*dxnorm< MINDX ) | ( abs(lambda)*(factor-1)< MINLAMB) + if abs(factor-1)<MINDFAC + if abs(lambda)<4 + retcode=4; + else + retcode=7; + end + done=1; + end end - end - elseif (growSignal & lambda>0) | (shrinkSignal & ((lambda <= lambdaPeak) & (lambda>0))) - if shrink - shrink=0; - factor = factor^.6; - %if ( abs(lambda)*(factor-1)*dxnorm< MINDX ) | ( abs(lambda)*(factor-1)< MINLAMB) - if abs(factor-1)<MINDFAC - if abs(lambda)<4 - retcode=4; - else - retcode=7; - end - done=1; + if ( f<fPeak ) & (lambda>0) + fPeak=f; + lambdaPeak=lambda; + if lambdaMax<=lambdaPeak + lambdaMax=lambdaPeak*factor*factor; + end end - end - if ( f<fPeak ) & (lambda>0) - fPeak=f; - lambdaPeak=lambda; - if lambdaMax<=lambdaPeak - lambdaMax=lambdaPeak*factor*factor; + lambda=lambda*factor; + if abs(lambda) > 1e20; + retcode = 5; + done =1; + end + else + done=1; + if factor < 1.2 + retcode=7; + else + retcode=0; end - end - lambda=lambda*factor; - if abs(lambda) > 1e20; - retcode = 5; - done =1; - end - else - done=1; - if factor < 1.2 - retcode=7; - else - retcode=0; - end - end - end + end + end end disp(sprintf('Norm of dx %10.5g', dxnorm)) diff --git a/matlab/csminwel.m b/matlab/csminwel.m index 468c150ecd..b6866c031d 100644 --- a/matlab/csminwel.m +++ b/matlab/csminwel.m @@ -1,309 +1,309 @@ -function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel(fcn,x0,H0,grad,crit,nit,method,varargin) -%[fhat,xhat,ghat,Hhat,itct,fcount,retcodehat] = csminwel(fcn,x0,H0,grad,crit,nit,method,varargin) -% fcn: string naming the objective function to be minimized -% x0: initial value of the parameter vector -% H0: initial value for the inverse Hessian. Must be positive definite. -% grad: Either a string naming a function that calculates the gradient, or the null matrix. -% If it's null, the program calculates a numerical gradient. In this case fcn must -% be written so that it can take a matrix argument and produce a row vector of values. -% crit: Convergence criterion. Iteration will cease when it proves impossible to improve the -% function value by more than crit. -% nit: Maximum number of iterations. -% method: integer scalar, 2, 3 or 5 points formula. -% penalty: scalar double, size of the penality. -% varargin: A list of optional length of additional parameters that get handed off to fcn each -% time it is called. -% Note that if the program ends abnormally, it is possible to retrieve the current x, -% f, and H from the files g1.mat and H.mat that are written at each iteration and at each -% hessian update, respectively. (When the routine hits certain kinds of difficulty, it -% write g2.mat and g3.mat as well. If all were written at about the same time, any of them -% may be a decent starting point. One can also start from the one with best function value.) - -% Original file downloaded from: -% http://sims.princeton.edu/yftp/optimize/mfiles/csminwel.m - -% Copyright (C) 1993-2007 Christopher Sims -% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. - -global bayestopt_ -fh = []; -xh = []; -[nx,no]=size(x0); -nx=max(nx,no); -Verbose=1; -NumGrad= isempty(grad); -done=0; -itct=0; -fcount=0; -snit=100; -%tailstr = ')'; -%stailstr = []; -% Lines below make the number of Pi's optional. This is inefficient, though, and precludes -% use of the matlab compiler. Without them, we use feval and the number of Pi's must be -% changed with the editor for each application. Places where this is required are marked -% with ARGLIST comments -%for i=nargin-6:-1:1 -% tailstr=[ ',P' num2str(i) tailstr]; -% stailstr=[' P' num2str(i) stailstr]; -%end - -[f0,cost_flag] = feval(fcn,x0,varargin{:}); -if ~cost_flag - disp('Bad initial parameter.') - return -end - -if NumGrad - switch method - case 2 - [g,badg] = numgrad(fcn,x0, varargin{:}); - case 3 - [g,badg] = numgrad3(fcn,x0, varargin{:}); - case 5 - [g,badg] = numgrad5(fcn,x0, varargin{:}); - end -else - [g,badg] = feval(grad,x0,varargin{:}); -end -retcode3=101; -x=x0; -f=f0; -H=H0; -cliff=0; -while ~done - bayestopt_.penalty = f; - g1=[]; g2=[]; g3=[]; - %addition fj. 7/6/94 for control - disp('-----------------') - disp('-----------------') - %disp('f and x at the beginning of new iteration') - disp(sprintf('f at the beginning of new iteration, %20.10f',f)) - %-----------Comment out this line if the x vector is long---------------- - % disp([sprintf('x = ') sprintf('%15.8g %15.8g %15.8g %15.8g\n',x)]); - %------------------------- - itct=itct+1; - [f1 x1 fc retcode1] = csminit(fcn,x,f,g,badg,H,varargin{:}); - %ARGLIST - %[f1 x1 fc retcode1] = csminit(fcn,x,f,g,badg,H,P1,P2,P3,P4,P5,P6,P7,... - % P8,P9,P10,P11,P12,P13); - % itct=itct+1; - fcount = fcount+fc; - % erased on 8/4/94 - % if (retcode == 1) | (abs(f1-f) < crit) - % done=1; - % end - % if itct > nit - % done = 1; - % retcode = -retcode; - % end - if retcode1 ~= 1 - if retcode1==2 | retcode1==4 - wall1=1; badg1=1; - else - if NumGrad - switch method - case 2 - [g1 badg1] = numgrad(fcn, x1,varargin{:}); - case 3 - [g1 badg1] = numgrad3(fcn, x1,varargin{:}); - case 5 - [g1,badg1] = numgrad5(fcn,x0, varargin{:}); - end - else - [g1 badg1] = feval(grad,x1,varargin{:}); - end - wall1=badg1; - % g1 - save g1.mat g1 x1 f1 varargin; - %ARGLIST - %save g1 g1 x1 f1 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13; - end - if wall1 % & (~done) by Jinill - % Bad gradient or back and forth on step length. Possibly at - % cliff edge. Try perturbing search direction. - % - %fcliff=fh;xcliff=xh; - Hcliff=H+diag(diag(H).*rand(nx,1)); - disp('Cliff. Perturbing search direction.') - [f2 x2 fc retcode2] = csminit(fcn,x,f,g,badg,Hcliff,varargin{:}); - %ARGLIST - %[f2 x2 fc retcode2] = csminit(fcn,x,f,g,badg,Hcliff,P1,P2,P3,P4,... - % P5,P6,P7,P8,P9,P10,P11,P12,P13); - fcount = fcount+fc; % put by Jinill - if f2 < f - if retcode2==2 | retcode2==4 - wall2=1; badg2=1; - else - if NumGrad - switch method - case 2 - [g2 badg2] = numgrad(fcn, x2,varargin{:}); - case 3 - [g2 badg2] = numgrad3(fcn, x2,varargin{:}); - case 5 - [g2,badg2] = numgrad5(fcn,x0, varargin{:}); - end - else - [g2 badg2] = feval(grad,x2,varargin{:}); - end - wall2=badg2; - % g2 - badg2 - save g2.mat g2 x2 f2 varargin - %ARGLIST - %save g2 g2 x2 f2 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13; - end - if wall2 - disp('Cliff again. Try traversing') - if norm(x2-x1) < 1e-13 - f3=f; x3=x; badg3=1;retcode3=101; - else - gcliff=((f2-f1)/((norm(x2-x1))^2))*(x2-x1); - if(size(x0,2)>1), gcliff=gcliff', end - [f3 x3 fc retcode3] = csminit(fcn,x,f,gcliff,0,eye(nx),varargin{:}); - %ARGLIST - %[f3 x3 fc retcode3] = csminit(fcn,x,f,gcliff,0,eye(nx),P1,P2,P3,... - % P4,P5,P6,P7,P8,... - % P9,P10,P11,P12,P13); - fcount = fcount+fc; % put by Jinill - if retcode3==2 | retcode3==4 - wall3=1; badg3=1; - else - if NumGrad - switch method - case 2 - [g3 badg3] = numgrad(fcn, x3,varargin{:}); - case 3 - [g3 badg3] = numgrad3(fcn, x3,varargin{:}); - case 5 - [g3,badg3] = numgrad5(fcn,x0, varargin{:}); - end - else - [g3 badg3] = feval(grad,x3,varargin{:}); - end - wall3=badg3; - % g3 - save g3.mat g3 x3 f3 varargin; - %ARGLIST - %save g3 g3 x3 f3 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13; - end - end - else - f3=f; x3=x; badg3=1; retcode3=101; - end - else - f3=f; x3=x; badg3=1;retcode3=101; - end - else - % normal iteration, no walls, or else we're finished here. - f2=f; f3=f; badg2=1; badg3=1; retcode2=101; retcode3=101; - end - else - f2=f;f3=f;f1=f;retcode2=retcode1;retcode3=retcode1; - end - %how to pick gh and xh - if f3 < f - crit & badg3==0 & f3 < f2 & f3 < f1 - ih=3; - fh=f3;xh=x3;gh=g3;badgh=badg3;retcodeh=retcode3; - elseif f2 < f - crit & badg2==0 & f2 < f1 - ih=2; - fh=f2;xh=x2;gh=g2;badgh=badg2;retcodeh=retcode2; - elseif f1 < f - crit & badg1==0 - ih=1; - fh=f1;xh=x1;gh=g1;badgh=badg1;retcodeh=retcode1; - else - [fh,ih] = min([f1,f2,f3]); - %disp(sprintf('ih = %d',ih)) - %eval(['xh=x' num2str(ih) ';']) - switch ih - case 1 - xh=x1; - case 2 - xh=x2; - case 3 - xh=x3; - end %case - %eval(['gh=g' num2str(ih) ';']) - %eval(['retcodeh=retcode' num2str(ih) ';']) - retcodei=[retcode1,retcode2,retcode3]; - retcodeh=retcodei(ih); - if exist('gh') - nogh=isempty(gh); - else - nogh=1; - end - if nogh - if NumGrad - switch method - case 2 - [gh,badgh] = numgrad(fcn,xh,varargin{:}); - case 3 - [gh,badgh] = numgrad3(fcn,xh,varargin{:}); - case 5 - [gh,badgh] = numgrad5(fcn,xh,varargin{:}); - end - else - [gh badgh] = feval(grad, xh,varargin{:}); - end - end - badgh=1; - end - %end of picking - %ih - %fh - %xh - %gh - %badgh - stuck = (abs(fh-f) < crit); - if (~badg)&(~badgh)&(~stuck) - H = bfgsi(H,gh-g,xh-x); - end - if Verbose - disp('----') - disp(sprintf('Improvement on iteration %d = %18.9f',itct,f-fh)) - end - % if Verbose - if itct > nit - disp('iteration count termination') - done = 1; - elseif stuck - disp('improvement < crit termination') - done = 1; - end - rc=retcodeh; - if rc == 1 - disp('zero gradient') - elseif rc == 6 - disp('smallest step still improving too slow, reversed gradient') - elseif rc == 5 - disp('largest step still improving too fast') - elseif (rc == 4) | (rc==2) - disp('back and forth on step length never finished') - elseif rc == 3 - disp('smallest step still improving too slow') - elseif rc == 7 - disp('warning: possible inaccuracy in H matrix') - end - % end - f=fh; - x=xh; - g=gh; - badg=badgh; -end -% what about making an m-file of 10 lines including numgrad.m +function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel(fcn,x0,H0,grad,crit,nit,method,varargin) +%[fhat,xhat,ghat,Hhat,itct,fcount,retcodehat] = csminwel(fcn,x0,H0,grad,crit,nit,method,varargin) +% fcn: string naming the objective function to be minimized +% x0: initial value of the parameter vector +% H0: initial value for the inverse Hessian. Must be positive definite. +% grad: Either a string naming a function that calculates the gradient, or the null matrix. +% If it's null, the program calculates a numerical gradient. In this case fcn must +% be written so that it can take a matrix argument and produce a row vector of values. +% crit: Convergence criterion. Iteration will cease when it proves impossible to improve the +% function value by more than crit. +% nit: Maximum number of iterations. +% method: integer scalar, 2, 3 or 5 points formula. +% penalty: scalar double, size of the penality. +% varargin: A list of optional length of additional parameters that get handed off to fcn each +% time it is called. +% Note that if the program ends abnormally, it is possible to retrieve the current x, +% f, and H from the files g1.mat and H.mat that are written at each iteration and at each +% hessian update, respectively. (When the routine hits certain kinds of difficulty, it +% write g2.mat and g3.mat as well. If all were written at about the same time, any of them +% may be a decent starting point. One can also start from the one with best function value.) + +% Original file downloaded from: +% http://sims.princeton.edu/yftp/optimize/mfiles/csminwel.m + +% Copyright (C) 1993-2007 Christopher Sims +% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. + +global bayestopt_ +fh = []; +xh = []; +[nx,no]=size(x0); +nx=max(nx,no); +Verbose=1; +NumGrad= isempty(grad); +done=0; +itct=0; +fcount=0; +snit=100; +%tailstr = ')'; +%stailstr = []; +% Lines below make the number of Pi's optional. This is inefficient, though, and precludes +% use of the matlab compiler. Without them, we use feval and the number of Pi's must be +% changed with the editor for each application. Places where this is required are marked +% with ARGLIST comments +%for i=nargin-6:-1:1 +% tailstr=[ ',P' num2str(i) tailstr]; +% stailstr=[' P' num2str(i) stailstr]; +%end + +[f0,cost_flag] = feval(fcn,x0,varargin{:}); +if ~cost_flag + disp('Bad initial parameter.') + return +end + +if NumGrad + switch method + case 2 + [g,badg] = numgrad(fcn,x0, varargin{:}); + case 3 + [g,badg] = numgrad3(fcn,x0, varargin{:}); + case 5 + [g,badg] = numgrad5(fcn,x0, varargin{:}); + end +else + [g,badg] = feval(grad,x0,varargin{:}); +end +retcode3=101; +x=x0; +f=f0; +H=H0; +cliff=0; +while ~done + bayestopt_.penalty = f; + g1=[]; g2=[]; g3=[]; + %addition fj. 7/6/94 for control + disp('-----------------') + disp('-----------------') + %disp('f and x at the beginning of new iteration') + disp(sprintf('f at the beginning of new iteration, %20.10f',f)) + %-----------Comment out this line if the x vector is long---------------- + % disp([sprintf('x = ') sprintf('%15.8g %15.8g %15.8g %15.8g\n',x)]); + %------------------------- + itct=itct+1; + [f1 x1 fc retcode1] = csminit(fcn,x,f,g,badg,H,varargin{:}); + %ARGLIST + %[f1 x1 fc retcode1] = csminit(fcn,x,f,g,badg,H,P1,P2,P3,P4,P5,P6,P7,... + % P8,P9,P10,P11,P12,P13); + % itct=itct+1; + fcount = fcount+fc; + % erased on 8/4/94 + % if (retcode == 1) | (abs(f1-f) < crit) + % done=1; + % end + % if itct > nit + % done = 1; + % retcode = -retcode; + % end + if retcode1 ~= 1 + if retcode1==2 | retcode1==4 + wall1=1; badg1=1; + else + if NumGrad + switch method + case 2 + [g1 badg1] = numgrad(fcn, x1,varargin{:}); + case 3 + [g1 badg1] = numgrad3(fcn, x1,varargin{:}); + case 5 + [g1,badg1] = numgrad5(fcn,x0, varargin{:}); + end + else + [g1 badg1] = feval(grad,x1,varargin{:}); + end + wall1=badg1; + % g1 + save g1.mat g1 x1 f1 varargin; + %ARGLIST + %save g1 g1 x1 f1 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13; + end + if wall1 % & (~done) by Jinill + % Bad gradient or back and forth on step length. Possibly at + % cliff edge. Try perturbing search direction. + % + %fcliff=fh;xcliff=xh; + Hcliff=H+diag(diag(H).*rand(nx,1)); + disp('Cliff. Perturbing search direction.') + [f2 x2 fc retcode2] = csminit(fcn,x,f,g,badg,Hcliff,varargin{:}); + %ARGLIST + %[f2 x2 fc retcode2] = csminit(fcn,x,f,g,badg,Hcliff,P1,P2,P3,P4,... + % P5,P6,P7,P8,P9,P10,P11,P12,P13); + fcount = fcount+fc; % put by Jinill + if f2 < f + if retcode2==2 | retcode2==4 + wall2=1; badg2=1; + else + if NumGrad + switch method + case 2 + [g2 badg2] = numgrad(fcn, x2,varargin{:}); + case 3 + [g2 badg2] = numgrad3(fcn, x2,varargin{:}); + case 5 + [g2,badg2] = numgrad5(fcn,x0, varargin{:}); + end + else + [g2 badg2] = feval(grad,x2,varargin{:}); + end + wall2=badg2; + % g2 + badg2 + save g2.mat g2 x2 f2 varargin + %ARGLIST + %save g2 g2 x2 f2 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13; + end + if wall2 + disp('Cliff again. Try traversing') + if norm(x2-x1) < 1e-13 + f3=f; x3=x; badg3=1;retcode3=101; + else + gcliff=((f2-f1)/((norm(x2-x1))^2))*(x2-x1); + if(size(x0,2)>1), gcliff=gcliff', end + [f3 x3 fc retcode3] = csminit(fcn,x,f,gcliff,0,eye(nx),varargin{:}); + %ARGLIST + %[f3 x3 fc retcode3] = csminit(fcn,x,f,gcliff,0,eye(nx),P1,P2,P3,... + % P4,P5,P6,P7,P8,... + % P9,P10,P11,P12,P13); + fcount = fcount+fc; % put by Jinill + if retcode3==2 | retcode3==4 + wall3=1; badg3=1; + else + if NumGrad + switch method + case 2 + [g3 badg3] = numgrad(fcn, x3,varargin{:}); + case 3 + [g3 badg3] = numgrad3(fcn, x3,varargin{:}); + case 5 + [g3,badg3] = numgrad5(fcn,x0, varargin{:}); + end + else + [g3 badg3] = feval(grad,x3,varargin{:}); + end + wall3=badg3; + % g3 + save g3.mat g3 x3 f3 varargin; + %ARGLIST + %save g3 g3 x3 f3 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13; + end + end + else + f3=f; x3=x; badg3=1; retcode3=101; + end + else + f3=f; x3=x; badg3=1;retcode3=101; + end + else + % normal iteration, no walls, or else we're finished here. + f2=f; f3=f; badg2=1; badg3=1; retcode2=101; retcode3=101; + end + else + f2=f;f3=f;f1=f;retcode2=retcode1;retcode3=retcode1; + end + %how to pick gh and xh + if f3 < f - crit & badg3==0 & f3 < f2 & f3 < f1 + ih=3; + fh=f3;xh=x3;gh=g3;badgh=badg3;retcodeh=retcode3; + elseif f2 < f - crit & badg2==0 & f2 < f1 + ih=2; + fh=f2;xh=x2;gh=g2;badgh=badg2;retcodeh=retcode2; + elseif f1 < f - crit & badg1==0 + ih=1; + fh=f1;xh=x1;gh=g1;badgh=badg1;retcodeh=retcode1; + else + [fh,ih] = min([f1,f2,f3]); + %disp(sprintf('ih = %d',ih)) + %eval(['xh=x' num2str(ih) ';']) + switch ih + case 1 + xh=x1; + case 2 + xh=x2; + case 3 + xh=x3; + end %case + %eval(['gh=g' num2str(ih) ';']) + %eval(['retcodeh=retcode' num2str(ih) ';']) + retcodei=[retcode1,retcode2,retcode3]; + retcodeh=retcodei(ih); + if exist('gh') + nogh=isempty(gh); + else + nogh=1; + end + if nogh + if NumGrad + switch method + case 2 + [gh,badgh] = numgrad(fcn,xh,varargin{:}); + case 3 + [gh,badgh] = numgrad3(fcn,xh,varargin{:}); + case 5 + [gh,badgh] = numgrad5(fcn,xh,varargin{:}); + end + else + [gh badgh] = feval(grad, xh,varargin{:}); + end + end + badgh=1; + end + %end of picking + %ih + %fh + %xh + %gh + %badgh + stuck = (abs(fh-f) < crit); + if (~badg)&(~badgh)&(~stuck) + H = bfgsi(H,gh-g,xh-x); + end + if Verbose + disp('----') + disp(sprintf('Improvement on iteration %d = %18.9f',itct,f-fh)) + end + % if Verbose + if itct > nit + disp('iteration count termination') + done = 1; + elseif stuck + disp('improvement < crit termination') + done = 1; + end + rc=retcodeh; + if rc == 1 + disp('zero gradient') + elseif rc == 6 + disp('smallest step still improving too slow, reversed gradient') + elseif rc == 5 + disp('largest step still improving too fast') + elseif (rc == 4) | (rc==2) + disp('back and forth on step length never finished') + elseif rc == 3 + disp('smallest step still improving too slow') + elseif rc == 7 + disp('warning: possible inaccuracy in H matrix') + end + % end + f=fh; + x=xh; + g=gh; + badg=badgh; +end +% what about making an m-file of 10 lines including numgrad.m % since it appears three times in csminwel.m \ No newline at end of file diff --git a/matlab/csolve.m b/matlab/csolve.m index 40be2d8db0..ae78b26cf7 100644 --- a/matlab/csolve.m +++ b/matlab/csolve.m @@ -49,121 +49,121 @@ alpha=1e-3; %--------------------------------------- %------------ verbose ---------------- verbose=0;% if this is set to zero, all screen output is suppressed -%------------------------------------- -%------------ analyticg -------------- + %------------------------------------- + %------------ analyticg -------------- analyticg=1-isempty(gradfun); %if the grad argument is [], numerical derivatives are used. -%------------------------------------- + %------------------------------------- nv=length(x); tvec=delta*eye(nv); done=0; if isempty(varargin) - f0=feval(FUN,x); + f0=feval(FUN,x); else - f0=feval(FUN,x,varargin{:}); + f0=feval(FUN,x,varargin{:}); end af0=sum(abs(f0)); af00=af0; itct=0; while ~done -% disp([af00-af0 crit*max(1,af0)]) - if itct>3 & af00-af0<crit*max(1,af0) & rem(itct,2)==1 - randomize=1; - else - if ~analyticg + % disp([af00-af0 crit*max(1,af0)]) + if itct>3 & af00-af0<crit*max(1,af0) & rem(itct,2)==1 + randomize=1; + else + if ~analyticg % $$$ if isempty(varargin) % $$$ grad = (feval(FUN,x*ones(1,nv)+tvec)-f0*ones(1,nv))/delta; % $$$ else % $$$ grad = (feval(FUN,x*ones(1,nv)+tvec,varargin{:})-f0*ones(1,nv))/delta; % $$$ end - grad = zeros(nv,nv); - for i=1:nv - grad(:,i) = (feval(FUN,x+tvec(:,i),varargin{:})-f0)/delta; - end - else % use analytic gradient - % grad=feval(gradfun,x,varargin{:}); - [f0,grad] = feval(gradfun,x,varargin{:}); - end - if isreal(grad) - if rcond(grad)<1e-12 - grad=grad+tvec; - end - dx0=-grad\f0; - randomize=0; - else - if(verbose),disp('gradient imaginary'),end - randomize=1; - end - end - if randomize - if(verbose),fprintf(1,'\n Random Search'),end - dx0=norm(x)./randn(size(x)); - end - lambda=1; - lambdamin=1; - fmin=f0; - xmin=x; - afmin=af0; - dxSize=norm(dx0); - factor=.6; - shrink=1; - subDone=0; - while ~subDone - dx=lambda*dx0; - f=feval(FUN,x+dx,varargin{:}); - af=sum(abs(f)); - if af<afmin - afmin=af; - fmin=f; - lambdamin=lambda; - xmin=x+dx; - end - if ((lambda >0) & (af0-af < alpha*lambda*af0)) | ((lambda<0) & (af0-af < 0) ) - if ~shrink - factor=factor^.6; - shrink=1; - end - if abs(lambda*(1-factor))*dxSize > .1*delta; - lambda = factor*lambda; - elseif (lambda > 0) & (factor==.6) %i.e., we've only been shrinking - lambda=-.3; - else % - subDone=1; - if lambda > 0 - if factor==.6 - rc = 2; - else - rc = 1; - end - else - rc=3; + grad = zeros(nv,nv); + for i=1:nv + grad(:,i) = (feval(FUN,x+tvec(:,i),varargin{:})-f0)/delta; + end + else % use analytic gradient + % grad=feval(gradfun,x,varargin{:}); + [f0,grad] = feval(gradfun,x,varargin{:}); + end + if isreal(grad) + if rcond(grad)<1e-12 + grad=grad+tvec; end - end - elseif (lambda >0) & (af-af0 > (1-alpha)*lambda*af0) - if shrink - factor=factor^.6; - shrink=0; - end - lambda=lambda/factor; - else % good value found - subDone=1; - rc=0; - end - end % while ~subDone - itct=itct+1; - if(verbose) - fprintf(1,'\nitct %d, af %g, lambda %g, rc %g',itct,afmin,lambdamin,rc) - fprintf(1,'\n x %10g %10g %10g %10g',xmin); - fprintf(1,'\n f %10g %10g %10g %10g',fmin); - end - x=xmin; - f0=fmin; - af00=af0; - af0=afmin; - if itct >= itmax - done=1; - rc=4; - elseif af0<crit; - done=1; - rc=0; - end + dx0=-grad\f0; + randomize=0; + else + if(verbose),disp('gradient imaginary'),end + randomize=1; + end + end + if randomize + if(verbose),fprintf(1,'\n Random Search'),end + dx0=norm(x)./randn(size(x)); + end + lambda=1; + lambdamin=1; + fmin=f0; + xmin=x; + afmin=af0; + dxSize=norm(dx0); + factor=.6; + shrink=1; + subDone=0; + while ~subDone + dx=lambda*dx0; + f=feval(FUN,x+dx,varargin{:}); + af=sum(abs(f)); + if af<afmin + afmin=af; + fmin=f; + lambdamin=lambda; + xmin=x+dx; + end + if ((lambda >0) & (af0-af < alpha*lambda*af0)) | ((lambda<0) & (af0-af < 0) ) + if ~shrink + factor=factor^.6; + shrink=1; + end + if abs(lambda*(1-factor))*dxSize > .1*delta; + lambda = factor*lambda; + elseif (lambda > 0) & (factor==.6) %i.e., we've only been shrinking + lambda=-.3; + else % + subDone=1; + if lambda > 0 + if factor==.6 + rc = 2; + else + rc = 1; + end + else + rc=3; + end + end + elseif (lambda >0) & (af-af0 > (1-alpha)*lambda*af0) + if shrink + factor=factor^.6; + shrink=0; + end + lambda=lambda/factor; + else % good value found + subDone=1; + rc=0; + end + end % while ~subDone + itct=itct+1; + if(verbose) + fprintf(1,'\nitct %d, af %g, lambda %g, rc %g',itct,afmin,lambdamin,rc) + fprintf(1,'\n x %10g %10g %10g %10g',xmin); + fprintf(1,'\n f %10g %10g %10g %10g',fmin); + end + x=xmin; + f0=fmin; + af00=af0; + af0=afmin; + if itct >= itmax + done=1; + rc=4; + elseif af0<crit; + done=1; + rc=0; + end end diff --git a/matlab/datatomfile.m b/matlab/datatomfile.m index a320f1e2a3..6b35e4ead6 100644 --- a/matlab/datatomfile.m +++ b/matlab/datatomfile.m @@ -1,63 +1,63 @@ -function datatomfile (s,var_list) -% function datatomfile (s,var_list) -% This optional command saves the simulation results in a text file. The name of each -% variable preceeds the corresponding results. This command must follow SIMUL. -% -% INPUTS -% s: data file name -% var_list: vector of selected endogenous variables -% -% OUTPUTS -% none -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2001-2009 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 <http://www.gnu.org/licenses/>. - -global M_ oo_ - -sm=[s,'.m']; -fid=fopen(sm,'w') ; - -if size(var_list,1) == 0 - var_list = M_.endo_names(1:M_.orig_endo_nbr,:); -end -n = size(var_list,1); - ivar=zeros(n,1); - for i=1:n - i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact'); - if isempty(i_tmp) - error (['One of the specified variables does not exist']) ; - else - ivar(i) = i_tmp; - end - end - - - -for i = 1:n - fprintf(fid,[M_.endo_names(ivar(i),:), '=['],'\n') ; - fprintf(fid,'\n') ; - fprintf(fid,'%15.8g\n',oo_.endo_simul(ivar(i),:)') ; - fprintf(fid,'\n') ; - fprintf(fid,'];\n') ; - fprintf(fid,'\n') ; -end -fclose(fid) ; - +function datatomfile (s,var_list) +% function datatomfile (s,var_list) +% This optional command saves the simulation results in a text file. The name of each +% variable preceeds the corresponding results. This command must follow SIMUL. +% +% INPUTS +% s: data file name +% var_list: vector of selected endogenous variables +% +% OUTPUTS +% none +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2001-2009 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 <http://www.gnu.org/licenses/>. + +global M_ oo_ + +sm=[s,'.m']; +fid=fopen(sm,'w') ; + +if size(var_list,1) == 0 + var_list = M_.endo_names(1:M_.orig_endo_nbr,:); +end +n = size(var_list,1); +ivar=zeros(n,1); +for i=1:n + i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact'); + if isempty(i_tmp) + error (['One of the specified variables does not exist']) ; + else + ivar(i) = i_tmp; + end +end + + + +for i = 1:n + fprintf(fid,[M_.endo_names(ivar(i),:), '=['],'\n') ; + fprintf(fid,'\n') ; + fprintf(fid,'%15.8g\n',oo_.endo_simul(ivar(i),:)') ; + fprintf(fid,'\n') ; + fprintf(fid,'];\n') ; + fprintf(fid,'\n') ; +end +fclose(fid) ; + diff --git a/matlab/dcompare.m b/matlab/dcompare.m index 2cc14748b6..e1c184532a 100644 --- a/matlab/dcompare.m +++ b/matlab/dcompare.m @@ -24,27 +24,27 @@ ftest(s1,0) ; i = [lag1(1):size(x,2)-lag1(2)+1]' ; if size(options_.smpl,1) == 1 - error(['DSAMPLE not specified.']) ; + error(['DSAMPLE not specified.']) ; end if options_.smpl(3) > 0 - if options_.smpl(3) == 2 - if options_.smpl(1)<0 | options_.smpl(2)>size(x,2)-lag1(2) - error ('Wrong sample.') ; - end - i = [options_.smpl(1)+lag1(1):options_.smpl(2)+lag1(1)]' ; - elseif options_.smpl(3) == 1 - if options_.smpl(1)>size(x,2)-lag1(2) - error ('Wrong sample.') ; - end - i = [lag1(1):options_.smpl(1)+lag1(1)]' ; - end + if options_.smpl(3) == 2 + if options_.smpl(1)<0 | options_.smpl(2)>size(x,2)-lag1(2) + error ('Wrong sample.') ; + end + i = [options_.smpl(1)+lag1(1):options_.smpl(2)+lag1(1)]' ; + elseif options_.smpl(3) == 1 + if options_.smpl(1)>size(x,2)-lag1(2) + error ('Wrong sample.') ; + end + i = [lag1(1):options_.smpl(1)+lag1(1)]' ; + end end j = bseastr(nvx,nvy) ; if stop - return ; + return ; end z = mean(mean(abs(x(j,i)-y(j,i)))) ; diff --git a/matlab/diag_vech.m b/matlab/diag_vech.m index be5c1d003a..6b444b10e1 100644 --- a/matlab/diag_vech.m +++ b/matlab/diag_vech.m @@ -25,7 +25,7 @@ function d = diag_vech(Vector) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - m = length(Vector); - n = (sqrt(1+8*m)-1)/2; - k = cumsum(1:n); - d = Vector(k); +m = length(Vector); +n = (sqrt(1+8*m)-1)/2; +k = cumsum(1:n); +d = Vector(k); diff --git a/matlab/disp_dr.m b/matlab/disp_dr.m index 22050118e6..32d5143528 100644 --- a/matlab/disp_dr.m +++ b/matlab/disp_dr.m @@ -6,7 +6,7 @@ function disp_dr(dr,order,var_list) % order [int]: order of approximation % var_list [char array]: list of endogenous variables for which the % decision rules should be printed - + % Copyright (C) 2001-2009 Dynare Team % % This file is part of Dynare. @@ -24,190 +24,190 @@ function disp_dr(dr,order,var_list) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ - - nx =size(dr.ghx,2); - nu =size(dr.ghu,2); - k = find(dr.kstate(:,2) <= M_.maximum_lag+1); - klag = dr.kstate(k,[1 2]); - - k1 = dr.order_var; - - if size(var_list,1) == 0 - var_list = M_.endo_names(1:M_.orig_endo_nbr, :); - end +global M_ - nvar = size(var_list,1); +nx =size(dr.ghx,2); +nu =size(dr.ghu,2); +k = find(dr.kstate(:,2) <= M_.maximum_lag+1); +klag = dr.kstate(k,[1 2]); - ivar=zeros(nvar,1); - for i=1:nvar - i_tmp = strmatch(var_list(i,:),M_.endo_names(k1,:),'exact'); - if isempty(i_tmp) +k1 = dr.order_var; + +if size(var_list,1) == 0 + var_list = M_.endo_names(1:M_.orig_endo_nbr, :); +end + +nvar = size(var_list,1); + +ivar=zeros(nvar,1); +for i=1:nvar + i_tmp = strmatch(var_list(i,:),M_.endo_names(k1,:),'exact'); + if isempty(i_tmp) disp(var_list(i,:)); error (['One of the variable specified does not exist']) ; - else + else ivar(i) = i_tmp; - end end +end - disp('POLICY AND TRANSITION FUNCTIONS') - % variable names - str = ' '; - for i=1:nvar +disp('POLICY AND TRANSITION FUNCTIONS') +% variable names +str = ' '; +for i=1:nvar str = [str sprintf('%16s',M_.endo_names(k1(ivar(i)),:))]; - end - disp(str); - % - % constant - % - str = 'Constant '; - flag = 0; - for i=1:nvar +end +disp(str); +% +% constant +% +str = 'Constant '; +flag = 0; +for i=1:nvar x = dr.ys(k1(ivar(i))); if order > 1 - x = x + dr.ghs2(ivar(i))/2; + x = x + dr.ghs2(ivar(i))/2; end if abs(x) > 1e-6 - flag = 1; - str = [str sprintf('%16.6f',x)]; + flag = 1; + str = [str sprintf('%16.6f',x)]; else - str = [str ' 0']; + str = [str ' 0']; end - end - if flag +end +if flag disp(str) - end - if order > 1 +end +if order > 1 str = '(correction) '; flag = 0; for i=1:nvar - x = dr.ghs2(ivar(i))/2; - if abs(x) > 1e-6 - flag = 1; - str = [str sprintf('%16.6f',x)]; - else - str = [str ' 0']; - end + x = dr.ghs2(ivar(i))/2; + if abs(x) > 1e-6 + flag = 1; + str = [str sprintf('%16.6f',x)]; + else + str = [str ' 0']; + end end if flag - disp(str) + disp(str) end - end - % - % ghx - % - for k=1:nx +end +% +% ghx +% +for k=1:nx flag = 0; str1 = subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2); str = sprintf('%-20s',str1); for i=1:nvar - x = dr.ghx(ivar(i),k); - if abs(x) > 1e-6 - flag = 1; - str = [str sprintf('%16.6f',x)]; - else - str = [str ' 0']; - end + x = dr.ghx(ivar(i),k); + if abs(x) > 1e-6 + flag = 1; + str = [str sprintf('%16.6f',x)]; + else + str = [str ' 0']; + end end if flag - disp(str) + disp(str) end - end - % - % ghu - % - for k=1:nu +end +% +% ghu +% +for k=1:nu flag = 0; str = sprintf('%-20s',M_.exo_names(k,:)); for i=1:nvar - x = dr.ghu(ivar(i),k); - if abs(x) > 1e-6 - flag = 1; - str = [str sprintf('%16.6f',x)]; - else - str = [str ' 0']; - end + x = dr.ghu(ivar(i),k); + if abs(x) > 1e-6 + flag = 1; + str = [str sprintf('%16.6f',x)]; + else + str = [str ' 0']; + end end if flag - disp(str) + disp(str) end - end +end - if order > 1 +if order > 1 % ghxx for k = 1:nx - for j = 1:k - flag = 0; - str1 = sprintf('%s,%s',subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2), ... - subst_auxvar(k1(klag(j,1)),klag(j,2)-M_.maximum_lag-2)); - str = sprintf('%-20s',str1); - for i=1:nvar - if k == j - x = dr.ghxx(ivar(i),(k-1)*nx+j)/2; - else - x = dr.ghxx(ivar(i),(k-1)*nx+j); - end - if abs(x) > 1e-6 - flag = 1; - str = [str sprintf('%16.6f',x)]; - else - str = [str ' 0']; - end - end - if flag - disp(str) - end - end + for j = 1:k + flag = 0; + str1 = sprintf('%s,%s',subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2), ... + subst_auxvar(k1(klag(j,1)),klag(j,2)-M_.maximum_lag-2)); + str = sprintf('%-20s',str1); + for i=1:nvar + if k == j + x = dr.ghxx(ivar(i),(k-1)*nx+j)/2; + else + x = dr.ghxx(ivar(i),(k-1)*nx+j); + end + if abs(x) > 1e-6 + flag = 1; + str = [str sprintf('%16.6f',x)]; + else + str = [str ' 0']; + end + end + if flag + disp(str) + end + end end % % ghuu % for k = 1:nu - for j = 1:k - flag = 0; - str = sprintf('%-20s',[M_.exo_names(k,:) ',' M_.exo_names(j,:)] ); - for i=1:nvar - if k == j - x = dr.ghuu(ivar(i),(k-1)*nu+j)/2; - else - x = dr.ghuu(ivar(i),(k-1)*nu+j); - end - if abs(x) > 1e-6 - flag = 1; - str = [str sprintf('%16.6f',x)]; - else - str = [str ' 0']; - end - end - if flag - disp(str) - end - end + for j = 1:k + flag = 0; + str = sprintf('%-20s',[M_.exo_names(k,:) ',' M_.exo_names(j,:)] ); + for i=1:nvar + if k == j + x = dr.ghuu(ivar(i),(k-1)*nu+j)/2; + else + x = dr.ghuu(ivar(i),(k-1)*nu+j); + end + if abs(x) > 1e-6 + flag = 1; + str = [str sprintf('%16.6f',x)]; + else + str = [str ' 0']; + end + end + if flag + disp(str) + end + end end % % ghxu % for k = 1:nx - for j = 1:nu - flag = 0; - str1 = sprintf('%s,%s',subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2), ... - M_.exo_names(j,:)); - str = sprintf('%-20s',str1); - for i=1:nvar - x = dr.ghxu(ivar(i),(k-1)*nu+j); - if abs(x) > 1e-6 - flag = 1; - str = [str sprintf('%16.6f',x)]; - else - str = [str ' 0']; - end - end - if flag - disp(str) - end - end + for j = 1:nu + flag = 0; + str1 = sprintf('%s,%s',subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2), ... + M_.exo_names(j,:)); + str = sprintf('%-20s',str1); + for i=1:nvar + x = dr.ghxu(ivar(i),(k-1)*nu+j); + if abs(x) > 1e-6 + flag = 1; + str = [str sprintf('%16.6f',x)]; + else + str = [str ' 0']; + end + end + if flag + disp(str) + end + end end - end +end end % Given the index of an endogenous (possibly an auxiliary var), and a @@ -215,25 +215,25 @@ end % In the case of auxiliary vars for lags, replace by the original variable % name, and compute the lead/lag accordingly. function str = subst_auxvar(aux_index, aux_lead_lag) - global M_ - - if aux_index <= M_.orig_endo_nbr - str = sprintf('%s(%d)', deblank(M_.endo_names(aux_index,:)), aux_lead_lag); - return - end - for i = 1:length(M_.aux_vars) - if M_.aux_vars(i).endo_index == aux_index - switch M_.aux_vars(i).type - case 1 - orig_name = deblank(M_.endo_names(M_.aux_vars(i).orig_index, :)); - case 3 - orig_name = deblank(M_.exo_names(M_.aux_vars(i).orig_index, :)); - otherwise - error(sprintf('Invalid auxiliary type: %s', M_.endo_names(aux_index, :))) - end - str = sprintf('%s(%d)', orig_name, M_.aux_vars(i).orig_lead_lag+aux_lead_lag); - return +global M_ + +if aux_index <= M_.orig_endo_nbr + str = sprintf('%s(%d)', deblank(M_.endo_names(aux_index,:)), aux_lead_lag); + return +end +for i = 1:length(M_.aux_vars) + if M_.aux_vars(i).endo_index == aux_index + switch M_.aux_vars(i).type + case 1 + orig_name = deblank(M_.endo_names(M_.aux_vars(i).orig_index, :)); + case 3 + orig_name = deblank(M_.exo_names(M_.aux_vars(i).orig_index, :)); + otherwise + error(sprintf('Invalid auxiliary type: %s', M_.endo_names(aux_index, :))) end + str = sprintf('%s(%d)', orig_name, M_.aux_vars(i).orig_lead_lag+aux_lead_lag); + return end - error(sprintf('Could not find aux var: %s', M_.endo_names(aux_index, :))) +end +error(sprintf('Could not find aux var: %s', M_.endo_names(aux_index, :))) end diff --git a/matlab/disp_dr_sparse.m b/matlab/disp_dr_sparse.m index 859f0e1781..f41fb396ff 100644 --- a/matlab/disp_dr_sparse.m +++ b/matlab/disp_dr_sparse.m @@ -25,209 +25,209 @@ function disp_dr_sparse(dr,order,var_list) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ - nx = 0; - nu = 0; - k = []; - klag = []; - k1 = []; - nspred = 0; - for i=1:length(M_.block_structure.block) - nspred = nspred + M_.block_structure.block(i).dr.nspred; - end; - ghu = zeros(M_.endo_nbr, M_.exo_nbr*(M_.maximum_exo_lag+M_.maximum_exo_lead+1)); - ghx = zeros(M_.endo_nbr, nspred); - for i=1:length(M_.block_structure.block) - nx = nx + size(M_.block_structure.block(i).dr.ghx,2); -% M_.block_structure.block(i).dr.ghx -% M_.block_structure.block(i).equation -% M_.block_structure.block(i).variable - ghx(M_.block_structure.block(i).equation, M_.block_structure.block(i).variable(find(M_.block_structure.block(i).lead_lag_incidence(1: M_.block_structure.block(i).maximum_endo_lag,:))) ) = M_.block_structure.block(i).dr.ghx; - if(M_.block_structure.block(i).exo_nbr) +global M_ +nx = 0; +nu = 0; +k = []; +klag = []; +k1 = []; +nspred = 0; +for i=1:length(M_.block_structure.block) + nspred = nspred + M_.block_structure.block(i).dr.nspred; +end; +ghu = zeros(M_.endo_nbr, M_.exo_nbr*(M_.maximum_exo_lag+M_.maximum_exo_lead+1)); +ghx = zeros(M_.endo_nbr, nspred); +for i=1:length(M_.block_structure.block) + nx = nx + size(M_.block_structure.block(i).dr.ghx,2); + % M_.block_structure.block(i).dr.ghx + % M_.block_structure.block(i).equation + % M_.block_structure.block(i).variable + ghx(M_.block_structure.block(i).equation, M_.block_structure.block(i).variable(find(M_.block_structure.block(i).lead_lag_incidence(1: M_.block_structure.block(i).maximum_endo_lag,:))) ) = M_.block_structure.block(i).dr.ghx; + if(M_.block_structure.block(i).exo_nbr) nu = nu + size(M_.block_structure.block(i).dr.ghu,2); ghu(M_.block_structure.block(i).equation, M_.block_structure.block(i).exogenous) = M_.block_structure.block(i).dr.ghu; - end - k_tmp = find(M_.block_structure.block(i).dr.kstate(:,2) <= M_.block_structure.block(i).maximum_lag+1); - k = [k ; k_tmp]; - klag = [klag ; M_.block_structure.block(i).dr.kstate(k_tmp,[1 2])]; - k1 = [k1 ; M_.block_structure.block(i).variable(M_.block_structure.block(i).dr.order_var)']; - end + end + k_tmp = find(M_.block_structure.block(i).dr.kstate(:,2) <= M_.block_structure.block(i).maximum_lag+1); + k = [k ; k_tmp]; + klag = [klag ; M_.block_structure.block(i).dr.kstate(k_tmp,[1 2])]; + k1 = [k1 ; M_.block_structure.block(i).variable(M_.block_structure.block(i).dr.order_var)']; +end - if size(var_list,1) == 0 - var_list = M_.endo_names(1:M_.orig_endo_nbr, :); - end +if size(var_list,1) == 0 + var_list = M_.endo_names(1:M_.orig_endo_nbr, :); +end - nvar = size(var_list,1); +nvar = size(var_list,1); - ivar=zeros(nvar,1); - for i=1:nvar - i_tmp = strmatch(var_list(i,:),M_.endo_names(k1,:),'exact'); - if isempty(i_tmp) +ivar=zeros(nvar,1); +for i=1:nvar + i_tmp = strmatch(var_list(i,:),M_.endo_names(k1,:),'exact'); + if isempty(i_tmp) disp(var_list(i,:)); error (['One of the variable specified does not exist']) ; - else + else ivar(i) = i_tmp; - end end +end - disp('POLICY AND TRANSITION FUNCTIONS') - % variable names - str = ' '; - for i=1:nvar +disp('POLICY AND TRANSITION FUNCTIONS') +% variable names +str = ' '; +for i=1:nvar str = [str sprintf('%16s',M_.endo_names(k1(ivar(i)),:))]; - end - disp(str); - % - % constant - % - str = 'Constant '; - flag = 0; - for i=1:nvar +end +disp(str); +% +% constant +% +str = 'Constant '; +flag = 0; +for i=1:nvar x = dr.ys(k1(ivar(i))); if order > 1 - x = x + dr.ghs2(ivar(i))/2; + x = x + dr.ghs2(ivar(i))/2; end if abs(x) > 1e-6 - flag = 1; - str = [str sprintf('%16.6f',x)]; + flag = 1; + str = [str sprintf('%16.6f',x)]; else - str = [str ' 0']; + str = [str ' 0']; end - end - if flag +end +if flag disp(str) - end - if order > 1 +end +if order > 1 str = '(correction) '; flag = 0; for i=1:nvar - x = dr.ghs2(ivar(i))/2; - if abs(x) > 1e-6 - flag = 1; - str = [str sprintf('%16.6f',x)]; - else - str = [str ' 0']; - end + x = dr.ghs2(ivar(i))/2; + if abs(x) > 1e-6 + flag = 1; + str = [str sprintf('%16.6f',x)]; + else + str = [str ' 0']; + end end if flag - disp(str) + disp(str) end - end - % - % ghx - % - for k=1:nx +end +% +% ghx +% +for k=1:nx flag = 0; str1 = subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2); str = sprintf('%-20s',str1); for i=1:nvar - x = ghx(ivar(i),k); - if abs(x) > 1e-6 - flag = 1; - str = [str sprintf('%16.6f',x)]; - else - str = [str ' 0']; - end + x = ghx(ivar(i),k); + if abs(x) > 1e-6 + flag = 1; + str = [str sprintf('%16.6f',x)]; + else + str = [str ' 0']; + end end if flag - disp(str) + disp(str) end - end - % - % ghu - % - for k=1:nu +end +% +% ghu +% +for k=1:nu flag = 0; str = sprintf('%-20s',M_.exo_names(k,:)); for i=1:nvar - x = ghu(ivar(i),k); - if abs(x) > 1e-6 - flag = 1; - str = [str sprintf('%16.6f',x)]; - else - str = [str ' 0']; - end + x = ghu(ivar(i),k); + if abs(x) > 1e-6 + flag = 1; + str = [str sprintf('%16.6f',x)]; + else + str = [str ' 0']; + end end if flag - disp(str) + disp(str) end - end +end - if order > 1 +if order > 1 % ghxx for k = 1:nx - for j = 1:k - flag = 0; - str1 = sprintf('%s,%s',subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2), ... - subst_auxvar(k1(klag(j,1)),klag(j,2)-M_.maximum_lag-2)); - str = sprintf('%-20s',str1); - for i=1:nvar - if k == j - x = dr.ghxx(ivar(i),(k-1)*nx+j)/2; - else - x = dr.ghxx(ivar(i),(k-1)*nx+j); - end - if abs(x) > 1e-6 - flag = 1; - str = [str sprintf('%16.6f',x)]; - else - str = [str ' 0']; - end - end - if flag - disp(str) - end - end + for j = 1:k + flag = 0; + str1 = sprintf('%s,%s',subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2), ... + subst_auxvar(k1(klag(j,1)),klag(j,2)-M_.maximum_lag-2)); + str = sprintf('%-20s',str1); + for i=1:nvar + if k == j + x = dr.ghxx(ivar(i),(k-1)*nx+j)/2; + else + x = dr.ghxx(ivar(i),(k-1)*nx+j); + end + if abs(x) > 1e-6 + flag = 1; + str = [str sprintf('%16.6f',x)]; + else + str = [str ' 0']; + end + end + if flag + disp(str) + end + end end % % ghuu % for k = 1:nu - for j = 1:k - flag = 0; - str = sprintf('%-20s',[M_.exo_names(k,:) ',' M_.exo_names(j,:)] ); - for i=1:nvar - if k == j - x = dr.ghuu(ivar(i),(k-1)*nu+j)/2; - else - x = dr.ghuu(ivar(i),(k-1)*nu+j); - end - if abs(x) > 1e-6 - flag = 1; - str = [str sprintf('%16.6f',x)]; - else - str = [str ' 0']; - end - end - if flag - disp(str) - end - end + for j = 1:k + flag = 0; + str = sprintf('%-20s',[M_.exo_names(k,:) ',' M_.exo_names(j,:)] ); + for i=1:nvar + if k == j + x = dr.ghuu(ivar(i),(k-1)*nu+j)/2; + else + x = dr.ghuu(ivar(i),(k-1)*nu+j); + end + if abs(x) > 1e-6 + flag = 1; + str = [str sprintf('%16.6f',x)]; + else + str = [str ' 0']; + end + end + if flag + disp(str) + end + end end % % ghxu % for k = 1:nx - for j = 1:nu - flag = 0; - str1 = sprintf('%s,%s',subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2), ... - M_.exo_names(j,:)); - str = sprintf('%-20s',str1); - for i=1:nvar - x = dr.ghxu(ivar(i),(k-1)*nu+j); - if abs(x) > 1e-6 - flag = 1; - str = [str sprintf('%16.6f',x)]; - else - str = [str ' 0']; - end - end - if flag - disp(str) - end - end + for j = 1:nu + flag = 0; + str1 = sprintf('%s,%s',subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2), ... + M_.exo_names(j,:)); + str = sprintf('%-20s',str1); + for i=1:nvar + x = dr.ghxu(ivar(i),(k-1)*nu+j); + if abs(x) > 1e-6 + flag = 1; + str = [str sprintf('%16.6f',x)]; + else + str = [str ' 0']; + end + end + if flag + disp(str) + end + end end - end +end end % Given the index of an endogenous (possibly an auxiliary var), and a @@ -235,25 +235,25 @@ end % In the case of auxiliary vars for lags, replace by the original variable % name, and compute the lead/lag accordingly. function str = subst_auxvar(aux_index, aux_lead_lag) - global M_ - - if aux_index <= M_.orig_endo_nbr - str = sprintf('%s(%d)', deblank(M_.endo_names(aux_index,:)), aux_lead_lag); - return - end - for i = 1:length(M_.aux_vars) - if M_.aux_vars(i).endo_index == aux_index - switch M_.aux_vars(i).type - case 1 - orig_name = deblank(M_.endo_names(M_.aux_vars(i).orig_index, :)); - case 3 - orig_name = deblank(M_.exo_names(M_.aux_vars(i).orig_index, :)); - otherwise - error(sprintf('Invalid auxiliary type: %s', M_.endo_names(aux_index, :))) - end - str = sprintf('%s(%d)', orig_name, M_.aux_vars(i).orig_lead_lag+aux_lead_lag); - return +global M_ + +if aux_index <= M_.orig_endo_nbr + str = sprintf('%s(%d)', deblank(M_.endo_names(aux_index,:)), aux_lead_lag); + return +end +for i = 1:length(M_.aux_vars) + if M_.aux_vars(i).endo_index == aux_index + switch M_.aux_vars(i).type + case 1 + orig_name = deblank(M_.endo_names(M_.aux_vars(i).orig_index, :)); + case 3 + orig_name = deblank(M_.exo_names(M_.aux_vars(i).orig_index, :)); + otherwise + error(sprintf('Invalid auxiliary type: %s', M_.endo_names(aux_index, :))) end + str = sprintf('%s(%d)', orig_name, M_.aux_vars(i).orig_lead_lag+aux_lead_lag); + return end - error(sprintf('Could not find aux var: %s', M_.endo_names(aux_index, :))) +end +error(sprintf('Could not find aux var: %s', M_.endo_names(aux_index, :))) end diff --git a/matlab/disp_identification.m b/matlab/disp_identification.m index d2b0368438..fa8d3a79ae 100644 --- a/matlab/disp_identification.m +++ b/matlab/disp_identification.m @@ -1,107 +1,107 @@ -function disp_identification(pdraws, idemodel, idemoments, disp_pcorr) - -% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. - -global bayestopt_ - -if nargin<4 | isempty(disp_pcorr), - disp_pcorr=0; -end - -[SampleSize, npar] = size(pdraws); -jok = 0; -jokP = 0; -jokJ = 0; -jokPJ = 0; -if ~any(any(idemodel.ind==0)) - disp(['All parameters are identified in the model in the MC sample (rank of H).' ]), - disp(' ') -end -if ~any(any(idemoments.ind==0)) - disp(['All parameters are identified by J moments in the MC sample (rank of J)' ]), -end -for j=1:npar, - if any(idemodel.ind(j,:)==0), - pno = 100*length(find(idemodel.ind(j,:)==0))/SampleSize; - disp(['Parameter ',bayestopt_.name{j},' is not identified in the model for ',num2str(pno),'% of MC runs!' ]) - disp(' ') - end - if any(idemoments.ind(j,:)==0), - pno = 100*length(find(idemoments.ind(j,:)==0))/SampleSize; - disp(['Parameter ',bayestopt_.name{j},' is not identified by J moments for ',num2str(pno),'% of MC runs!' ]) - disp(' ') - end - if any(idemodel.ind(j,:)==1), - iok = find(idemodel.ind(j,:)==1); - jok = jok+1; - kok(jok) = j; - mmin(jok,1) = min(idemodel.Mco(j,iok)); - mmean(jok,1) = mean(idemodel.Mco(j,iok)); - mmax(jok,1) = max(idemodel.Mco(j,iok)); - [ipmax, jpmax] = find(abs(squeeze(idemodel.Pco(j,[1:j-1,j+1:end],iok)))>0.95); - if ~isempty(ipmax) - jokP = jokP+1; - kokP(jokP) = j; - ipmax(find(ipmax>=j))=ipmax(find(ipmax>=j))+1; - [N,X]=hist(ipmax,[1:npar]); - jpM(jokP)={find(N)}; - NPM(jokP)={N(find(N))./SampleSize.*100}; - pmeanM(jokP)={mean(squeeze(idemodel.Pco(j,find(N),iok))')}; - pminM(jokP)={min(squeeze(idemodel.Pco(j,find(N),iok))')}; - pmaxM(jokP)={max(squeeze(idemodel.Pco(j,find(N),iok))')}; - end - end - if any(idemoments.ind(j,:)==1), - iok = find(idemoments.ind(j,:)==1); - jokJ = jokJ+1; - kokJ(jokJ) = j; - mminJ(jokJ,1) = min(idemoments.Mco(j,iok)); - mmeanJ(jokJ,1) = mean(idemoments.Mco(j,iok)); - mmaxJ(jokJ,1) = max(idemoments.Mco(j,iok)); - [ipmax, jpmax] = find(abs(squeeze(idemoments.Pco(j,[1:j-1,j+1:end],iok)))>0.95); - if ~isempty(ipmax) - jokPJ = jokPJ+1; - kokPJ(jokPJ) = j; - ipmax(find(ipmax>=j))=ipmax(find(ipmax>=j))+1; - [N,X]=hist(ipmax,[1:npar]); - jpJ(jokPJ)={find(N)}; - NPJ(jokPJ)={N(find(N))./SampleSize.*100}; - pmeanJ(jokPJ)={mean(squeeze(idemoments.Pco(j,find(N),iok))')}; - pminJ(jokPJ)={min(squeeze(idemoments.Pco(j,find(N),iok))')}; - pmaxJ(jokPJ)={max(squeeze(idemoments.Pco(j,find(N),iok))')}; - end - end -end - -dyntable('Multi collinearity in the model:',strvcat('param','min','mean','max'), ... - strvcat(bayestopt_.name(kok)),[mmin, mmean, mmax],10,10,6); - -dyntable('Multi collinearity for moments in J:',strvcat('param','min','mean','max'), ... - strvcat(bayestopt_.name(kokJ)),[mminJ, mmeanJ, mmaxJ],10,10,6); - -if disp_pcorr, -for j=1:length(kokP), -dyntable([bayestopt_.name{kokP(j)},' pairwise correlations in the model'],strvcat(' ','min','mean','max'), ... - strvcat(bayestopt_.name{jpM{j}}),[pminM{j}' pmeanM{j}' pmaxM{j}'],10,10,3); -end - -for j=1:length(kokPJ), -dyntable([bayestopt_.name{kokPJ(j)},' pairwise correlations in J moments'],strvcat(' ','min','mean','max'), ... - strvcat(bayestopt_.name{jpJ{j}}),[pminJ{j}' pmeanJ{j}' pmaxJ{j}'],10,10,3); -end -end +function disp_identification(pdraws, idemodel, idemoments, disp_pcorr) + +% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. + +global bayestopt_ + +if nargin<4 | isempty(disp_pcorr), + disp_pcorr=0; +end + +[SampleSize, npar] = size(pdraws); +jok = 0; +jokP = 0; +jokJ = 0; +jokPJ = 0; +if ~any(any(idemodel.ind==0)) + disp(['All parameters are identified in the model in the MC sample (rank of H).' ]), + disp(' ') +end +if ~any(any(idemoments.ind==0)) + disp(['All parameters are identified by J moments in the MC sample (rank of J)' ]), +end +for j=1:npar, + if any(idemodel.ind(j,:)==0), + pno = 100*length(find(idemodel.ind(j,:)==0))/SampleSize; + disp(['Parameter ',bayestopt_.name{j},' is not identified in the model for ',num2str(pno),'% of MC runs!' ]) + disp(' ') + end + if any(idemoments.ind(j,:)==0), + pno = 100*length(find(idemoments.ind(j,:)==0))/SampleSize; + disp(['Parameter ',bayestopt_.name{j},' is not identified by J moments for ',num2str(pno),'% of MC runs!' ]) + disp(' ') + end + if any(idemodel.ind(j,:)==1), + iok = find(idemodel.ind(j,:)==1); + jok = jok+1; + kok(jok) = j; + mmin(jok,1) = min(idemodel.Mco(j,iok)); + mmean(jok,1) = mean(idemodel.Mco(j,iok)); + mmax(jok,1) = max(idemodel.Mco(j,iok)); + [ipmax, jpmax] = find(abs(squeeze(idemodel.Pco(j,[1:j-1,j+1:end],iok)))>0.95); + if ~isempty(ipmax) + jokP = jokP+1; + kokP(jokP) = j; + ipmax(find(ipmax>=j))=ipmax(find(ipmax>=j))+1; + [N,X]=hist(ipmax,[1:npar]); + jpM(jokP)={find(N)}; + NPM(jokP)={N(find(N))./SampleSize.*100}; + pmeanM(jokP)={mean(squeeze(idemodel.Pco(j,find(N),iok))')}; + pminM(jokP)={min(squeeze(idemodel.Pco(j,find(N),iok))')}; + pmaxM(jokP)={max(squeeze(idemodel.Pco(j,find(N),iok))')}; + end + end + if any(idemoments.ind(j,:)==1), + iok = find(idemoments.ind(j,:)==1); + jokJ = jokJ+1; + kokJ(jokJ) = j; + mminJ(jokJ,1) = min(idemoments.Mco(j,iok)); + mmeanJ(jokJ,1) = mean(idemoments.Mco(j,iok)); + mmaxJ(jokJ,1) = max(idemoments.Mco(j,iok)); + [ipmax, jpmax] = find(abs(squeeze(idemoments.Pco(j,[1:j-1,j+1:end],iok)))>0.95); + if ~isempty(ipmax) + jokPJ = jokPJ+1; + kokPJ(jokPJ) = j; + ipmax(find(ipmax>=j))=ipmax(find(ipmax>=j))+1; + [N,X]=hist(ipmax,[1:npar]); + jpJ(jokPJ)={find(N)}; + NPJ(jokPJ)={N(find(N))./SampleSize.*100}; + pmeanJ(jokPJ)={mean(squeeze(idemoments.Pco(j,find(N),iok))')}; + pminJ(jokPJ)={min(squeeze(idemoments.Pco(j,find(N),iok))')}; + pmaxJ(jokPJ)={max(squeeze(idemoments.Pco(j,find(N),iok))')}; + end + end +end + +dyntable('Multi collinearity in the model:',strvcat('param','min','mean','max'), ... + strvcat(bayestopt_.name(kok)),[mmin, mmean, mmax],10,10,6); + +dyntable('Multi collinearity for moments in J:',strvcat('param','min','mean','max'), ... + strvcat(bayestopt_.name(kokJ)),[mminJ, mmeanJ, mmaxJ],10,10,6); + +if disp_pcorr, + for j=1:length(kokP), + dyntable([bayestopt_.name{kokP(j)},' pairwise correlations in the model'],strvcat(' ','min','mean','max'), ... + strvcat(bayestopt_.name{jpM{j}}),[pminM{j}' pmeanM{j}' pmaxM{j}'],10,10,3); + end + + for j=1:length(kokPJ), + dyntable([bayestopt_.name{kokPJ(j)},' pairwise correlations in J moments'],strvcat(' ','min','mean','max'), ... + strvcat(bayestopt_.name{jpJ{j}}),[pminJ{j}' pmeanJ{j}' pmaxJ{j}'],10,10,3); + end +end diff --git a/matlab/disp_model_summary.m b/matlab/disp_model_summary.m index b09c3adc46..0ee14f5056 100644 --- a/matlab/disp_model_summary.m +++ b/matlab/disp_model_summary.m @@ -24,19 +24,19 @@ function disp_model_summary(M,dr) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - disp(' ') - disp('MODEL SUMMARY') - disp(' ') - disp([' Number of variables: ' int2str(M.endo_nbr)]) - disp([' Number of stochastic shocks: ' int2str(M.exo_nbr)]) - disp([' Number of state variables: ' ... - int2str(length(find(dr.kstate(:,2) <= M.maximum_lag+1)))]) - disp([' Number of jumpers: ' ... - int2str(length(find(dr.kstate(:,2) == M.maximum_lag+2)))]) - disp([' Number of static variables: ' int2str(dr.nstatic)]) - my_title='MATRIX OF COVARIANCE OF EXOGENOUS SHOCKS'; - labels = deblank(M.exo_names); - headers = strvcat('Variables',labels); - lh = size(labels,2)+2; - dyntable(my_title,headers,labels,M.Sigma_e,lh,10,6); +disp(' ') +disp('MODEL SUMMARY') +disp(' ') +disp([' Number of variables: ' int2str(M.endo_nbr)]) +disp([' Number of stochastic shocks: ' int2str(M.exo_nbr)]) +disp([' Number of state variables: ' ... + int2str(length(find(dr.kstate(:,2) <= M.maximum_lag+1)))]) +disp([' Number of jumpers: ' ... + int2str(length(find(dr.kstate(:,2) == M.maximum_lag+2)))]) +disp([' Number of static variables: ' int2str(dr.nstatic)]) +my_title='MATRIX OF COVARIANCE OF EXOGENOUS SHOCKS'; +labels = deblank(M.exo_names); +headers = strvcat('Variables',labels); +lh = size(labels,2)+2; +dyntable(my_title,headers,labels,M.Sigma_e,lh,10,6); diff --git a/matlab/disp_moments.m b/matlab/disp_moments.m index 7341308617..dedc4c1d70 100644 --- a/matlab/disp_moments.m +++ b/matlab/disp_moments.m @@ -18,81 +18,81 @@ function disp_moments(y,var_list) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ options_ oo_ - - warning_old_state = warning; - warning off +global M_ options_ oo_ - if options_.hp_filter - error('STOCH_SIMUL: HP filter is not yet implemented for empirical moments') - end - - if size(var_list,1) == 0 - var_list = M_.endo_names(1:M_.orig_endo_nbr, :); - end - - nvar = size(var_list,1); - ivar=zeros(nvar,1); - for i=1:nvar - i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact'); - if isempty(i_tmp) +warning_old_state = warning; +warning off + +if options_.hp_filter + error('STOCH_SIMUL: HP filter is not yet implemented for empirical moments') +end + +if size(var_list,1) == 0 + var_list = M_.endo_names(1:M_.orig_endo_nbr, :); +end + +nvar = size(var_list,1); +ivar=zeros(nvar,1); +for i=1:nvar + i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact'); + if isempty(i_tmp) error (['One of the variable specified does not exist']) ; - else + else ivar(i) = i_tmp; - end end +end + +y = y(ivar,options_.drop+M_.maximum_lag+1:end)'; - y = y(ivar,options_.drop+M_.maximum_lag+1:end)'; - - m = mean(y); - y = y - repmat(m,size(y,1),1); - s2 = mean(y.*y); - s = sqrt(s2); - oo_.mean = transpose(m); - oo_.var = y'*y/size(y,1); +m = mean(y); +y = y - repmat(m,size(y,1),1); +s2 = mean(y.*y); +s = sqrt(s2); +oo_.mean = transpose(m); +oo_.var = y'*y/size(y,1); - labels = deblank(M_.endo_names(ivar,:)); - - if options_.nomoments == 0 +labels = deblank(M_.endo_names(ivar,:)); + +if options_.nomoments == 0 z = [ m' s' s2' (mean(y.^3)./s2.^1.5)' (mean(y.^4)./(s2.*s2)-3)' ]; - + title='MOMENTS OF SIMULATED VARIABLES'; if options_.hp_filter - title = [title ' (HP filter, lambda = ' ... - int2str(options_.hp_filter) ')']; + title = [title ' (HP filter, lambda = ' ... + int2str(options_.hp_filter) ')']; end headers=strvcat('VARIABLE','MEAN','STD. DEV.','VARIANCE','SKEWNESS', ... 'KURTOSIS'); dyntable(title,headers,labels,z,size(labels,2)+2,16,6); - end - - if options_.nocorr == 0 +end + +if options_.nocorr == 0 corr = (y'*y/size(y,1))./(s'*s); title = 'CORRELATION OF SIMULATED VARIABLES'; if options_.hp_filter - title = [title ' (HP filter, lambda = ' ... - int2str(options_.hp_filter) ')']; + title = [title ' (HP filter, lambda = ' ... + int2str(options_.hp_filter) ')']; end headers = strvcat('VARIABLE',M_.endo_names(ivar,:)); dyntable(title,headers,labels,corr,size(labels,2)+2,8,4); - end - - ar = options_.ar; - options_ = set_default_option(options_,'ar',5); - ar = options_.ar; - if ar > 0 +end + +ar = options_.ar; +options_ = set_default_option(options_,'ar',5); +ar = options_.ar; +if ar > 0 autocorr = []; for i=1:ar - oo_.autocorr{i} = y(ar+1:end,:)'*y(ar+1-i:end-i,:)./((size(y,1)-ar)*s'*s); - autocorr = [ autocorr diag(oo_.autocorr{i}) ]; + oo_.autocorr{i} = y(ar+1:end,:)'*y(ar+1-i:end-i,:)./((size(y,1)-ar)*s'*s); + autocorr = [ autocorr diag(oo_.autocorr{i}) ]; end title = 'AUTOCORRELATION OF SIMULATED VARIABLES'; if options_.hp_filter - title = [title ' (HP filter, lambda = ' ... - int2str(options_.hp_filter) ')']; + title = [title ' (HP filter, lambda = ' ... + int2str(options_.hp_filter) ')']; end headers = strvcat('VARIABLE',int2str([1:ar]')); dyntable(title,headers,labels,autocorr,size(labels,2)+2,8,4); - end - - warning(warning_old_state); +end + +warning(warning_old_state); diff --git a/matlab/disp_th_moments.m b/matlab/disp_th_moments.m index 1775360df6..40996030d9 100644 --- a/matlab/disp_th_moments.m +++ b/matlab/disp_th_moments.m @@ -1,6 +1,6 @@ function disp_th_moments(dr,var_list) % Display theoretical moments of variables - + % Copyright (C) 2001-2009 Dynare Team % % This file is part of Dynare. @@ -18,62 +18,62 @@ function disp_th_moments(dr,var_list) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ oo_ options_ - - if size(var_list,1) == 0 - var_list = M_.endo_names(1:M_.orig_endo_nbr, :); - end - nvar = size(var_list,1); - ivar=zeros(nvar,1); - for i=1:nvar - i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact'); - if isempty(i_tmp) +global M_ oo_ options_ + +if size(var_list,1) == 0 + var_list = M_.endo_names(1:M_.orig_endo_nbr, :); +end +nvar = size(var_list,1); +ivar=zeros(nvar,1); +for i=1:nvar + i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact'); + if isempty(i_tmp) error (['One of the variable specified does not exist']) ; - else + else ivar(i) = i_tmp; - end end - - [oo_.gamma_y,stationary_vars] = th_autocovariances(dr,ivar,M_,options_); - m = dr.ys(ivar); - non_stationary_vars = setdiff(1:length(ivar),stationary_vars); - ivar1 = intersect(non_stationary_vars,ivar); - m(ivar1) = NaN; +end + +[oo_.gamma_y,stationary_vars] = th_autocovariances(dr,ivar,M_,options_); +m = dr.ys(ivar); +non_stationary_vars = setdiff(1:length(ivar),stationary_vars); +ivar1 = intersect(non_stationary_vars,ivar); +m(ivar1) = NaN; + - - i1 = find(abs(diag(oo_.gamma_y{1})) > 1e-12); - s2 = diag(oo_.gamma_y{1}); - sd = sqrt(s2); - if options_.order == 2 +i1 = find(abs(diag(oo_.gamma_y{1})) > 1e-12); +s2 = diag(oo_.gamma_y{1}); +sd = sqrt(s2); +if options_.order == 2 m = m+oo_.gamma_y{options_.ar+3}; - end - - z = [ m sd s2 ]; - oo_.mean = m; - oo_.var = oo_.gamma_y{1}; - - if options_.nomoments == 0 +end + +z = [ m sd s2 ]; +oo_.mean = m; +oo_.var = oo_.gamma_y{1}; + +if options_.nomoments == 0 title='THEORETICAL MOMENTS'; if options_.hp_filter - title = [title ' (HP filter, lambda = ' int2str(options_.hp_filter) ')']; + title = [title ' (HP filter, lambda = ' int2str(options_.hp_filter) ')']; end headers=strvcat('VARIABLE','MEAN','STD. DEV.','VARIANCE'); labels = deblank(M_.endo_names(ivar,:)); lh = size(labels,2)+2; dyntable(title,headers,labels,z,lh,11,4); if M_.exo_nbr > 1 - disp(' ') - title='VARIANCE DECOMPOSITION (in percent)'; - if options_.hp_filter - title = [title ' (HP filter, lambda = ' ... - int2str(options_.hp_filter) ')']; - end - headers = M_.exo_names; - headers(M_.exo_names_orig_ord,:) = headers; - headers = strvcat(' ',headers); - lh = size(deblank(M_.endo_names(ivar(stationary_vars),:)),2)+2; - dyntable(title,headers,deblank(M_.endo_names(ivar(stationary_vars), ... - :)),100*oo_.gamma_y{options_.ar+2}(stationary_vars,:),lh,8,2); + disp(' ') + title='VARIANCE DECOMPOSITION (in percent)'; + if options_.hp_filter + title = [title ' (HP filter, lambda = ' ... + int2str(options_.hp_filter) ')']; + end + headers = M_.exo_names; + headers(M_.exo_names_orig_ord,:) = headers; + headers = strvcat(' ',headers); + lh = size(deblank(M_.endo_names(ivar(stationary_vars),:)),2)+2; + dyntable(title,headers,deblank(M_.endo_names(ivar(stationary_vars), ... + :)),100*oo_.gamma_y{options_.ar+2}(stationary_vars,:),lh,8,2); end conditional_variance_steps = options_.conditional_variance_decomposition; @@ -82,34 +82,34 @@ function disp_th_moments(dr,var_list) ivar,dr,M_, ... options_,oo_); end - end - - if options_.nocorr == 0 +end + +if options_.nocorr == 0 disp(' ') title='MATRIX OF CORRELATIONS'; if options_.hp_filter - title = [title ' (HP filter, lambda = ' int2str(options_.hp_filter) ')']; + title = [title ' (HP filter, lambda = ' int2str(options_.hp_filter) ')']; end labels = deblank(M_.endo_names(ivar(i1),:)); headers = strvcat('Variables',labels); corr = oo_.gamma_y{1}(i1,i1)./(sd(i1)*sd(i1)'); lh = size(labels,2)+2; dyntable(title,headers,labels,corr,lh,8,4); - end - - if options_.ar > 0 +end + +if options_.ar > 0 disp(' ') title='COEFFICIENTS OF AUTOCORRELATION'; if options_.hp_filter - title = [title ' (HP filter, lambda = ' int2str(options_.hp_filter) ')']; + title = [title ' (HP filter, lambda = ' int2str(options_.hp_filter) ')']; end labels = deblank(M_.endo_names(ivar(i1),:)); headers = strvcat('Order ',int2str([1:options_.ar]')); z=[]; for i=1:options_.ar - oo_.autocorr{i} = oo_.gamma_y{i+1}; - z(:,i) = diag(oo_.gamma_y{i+1}(i1,i1)); + oo_.autocorr{i} = oo_.gamma_y{i+1}; + z(:,i) = diag(oo_.gamma_y{i+1}(i1,i1)); end lh = size(labels,2)+2; dyntable(title,headers,labels,z,lh,8,4); - end +end diff --git a/matlab/display_conditional_variance_decomposition.m b/matlab/display_conditional_variance_decomposition.m index 32faf26355..5fd17383c6 100644 --- a/matlab/display_conditional_variance_decomposition.m +++ b/matlab/display_conditional_variance_decomposition.m @@ -32,45 +32,45 @@ function oo_ = display_conditional_variance_decomposition(Steps, SubsetOfVariabl % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - endo_nbr = M_.endo_nbr; - exo_nbr = M_.exo_nbr; - StateSpaceModel.number_of_state_equations = M_.endo_nbr; - StateSpaceModel.number_of_state_innovations = exo_nbr; - StateSpaceModel.sigma_e_is_diagonal = M_.sigma_e_is_diagonal; - - iv = (1:endo_nbr)'; - ic = dr.nstatic+(1:dr.npred)'; - - [StateSpaceModel.transition_matrix,StateSpaceModel.impulse_matrix] = kalman_transition_matrix(dr,iv,ic,[],exo_nbr); - StateSpaceModel.state_innovations_covariance_matrix = M_.Sigma_e; - conditional_decomposition_array = conditional_variance_decomposition(StateSpaceModel,Steps,dr.inv_order_var(SubsetOfVariables )); +endo_nbr = M_.endo_nbr; +exo_nbr = M_.exo_nbr; +StateSpaceModel.number_of_state_equations = M_.endo_nbr; +StateSpaceModel.number_of_state_innovations = exo_nbr; +StateSpaceModel.sigma_e_is_diagonal = M_.sigma_e_is_diagonal; - if options_.noprint == 0 - disp(' ') - disp('CONDITIONAL VARIANCE DECOMPOSITION (in percent)') - end - - vardec_i = zeros(length(SubsetOfVariables),exo_nbr); +iv = (1:endo_nbr)'; +ic = dr.nstatic+(1:dr.npred)'; + +[StateSpaceModel.transition_matrix,StateSpaceModel.impulse_matrix] = kalman_transition_matrix(dr,iv,ic,[],exo_nbr); +StateSpaceModel.state_innovations_covariance_matrix = M_.Sigma_e; + +conditional_decomposition_array = conditional_variance_decomposition(StateSpaceModel,Steps,dr.inv_order_var(SubsetOfVariables )); + +if options_.noprint == 0 + disp(' ') + disp('CONDITIONAL VARIANCE DECOMPOSITION (in percent)') +end + +vardec_i = zeros(length(SubsetOfVariables),exo_nbr); + +for i=1:length(Steps) + disp(['Period ' int2str(Steps(i)) ':']) - for i=1:length(Steps) - disp(['Period ' int2str(Steps(i)) ':']) - - for j=1:exo_nbr - vardec_i(:,j) = diag_vech(conditional_decomposition_array(:, ... - i,j)); - end - vardec_i = 100*vardec_i./repmat(sum(vardec_i,2),1,exo_nbr); - if options_.noprint == 0 - headers = M_.exo_names; - headers(M_.exo_names_orig_ord,:) = headers; - headers = strvcat(' ',headers); - lh = size(deblank(M_.endo_names(SubsetOfVariables,:)),2)+2; - dyntable('',headers,... - deblank(M_.endo_names(SubsetOfVariables,:)),... - vardec_i,lh,8,2); - end + for j=1:exo_nbr + vardec_i(:,j) = diag_vech(conditional_decomposition_array(:, ... + i,j)); end - - oo_.conditional_variance_decomposition = conditional_decomposition_array; \ No newline at end of file + vardec_i = 100*vardec_i./repmat(sum(vardec_i,2),1,exo_nbr); + if options_.noprint == 0 + headers = M_.exo_names; + headers(M_.exo_names_orig_ord,:) = headers; + headers = strvcat(' ',headers); + lh = size(deblank(M_.endo_names(SubsetOfVariables,:)),2)+2; + dyntable('',headers,... + deblank(M_.endo_names(SubsetOfVariables,:)),... + vardec_i,lh,8,2); + end +end + +oo_.conditional_variance_decomposition = conditional_decomposition_array; \ No newline at end of file diff --git a/matlab/distributions/compute_prior_mode.m b/matlab/distributions/compute_prior_mode.m index 061b128581..50df6a1687 100644 --- a/matlab/distributions/compute_prior_mode.m +++ b/matlab/distributions/compute_prior_mode.m @@ -38,50 +38,50 @@ function m = compute_prior_mode(hyperparameters,shape) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - m = NaN ; - switch shape - case 1 - if (hyperparameters(1)>1 && hyperparameters(2)>1) - m = (hyperparameters(1)-1)/(hyperparameters(1)+hyperparameters(2)-2) ; - elseif (hyperparameters(1)<1 && hyperparameters(2)<1) - m = [ 0 ; 1 ] ; - elseif ( hyperparameters(1)<1 && hyperparameters(2)>1-eps ) || ( abs(hyperparameters(1)-1)<2*eps && hyperparameters(2)>1 ) - m = 0; - elseif ( hyperparameters(1)>1 && hyperparameters(2)<1+eps ) || ( abs(hyperparameters(1)-1)<2*eps && hyperparameters(2)<1 ) - m = 1; - elseif ( abs(hyperparameters(1)-1)<2*eps && abs(hyperparameters(2)-1)<2*eps )% Uniform distribution! - m = .5 ; - end - if length(hyperparameters)==4 - m = m*(hyperparameters(4)-hyperparameters(3)) + hyperparameters(3) ; - end - case 2 - if hyperparameters(1)<1 - m = 0; - else - m = (hyperparameters(1)-1)*hyperparameters(2); - end - if length(hyperparameters)>2 - m = m + hyperparameters(3); - end - case 3 - m = hyperparameters(1); - case 4 - % s = hyperparameters(1) - % nu = hyperparameters(2) - m = 1/sqrt((hyperparameters(2)+1)/hyperparameters(1));%sqrt((hyperparameters(2)-1)/hyperparameters(1)) - if length(hyperparameters)>2 - m = m + hyperparameters(3); - end - case 5 - m = .5*(hyperparameters(2)-hyperparameters(1)) ; - case 6 - % s = hyperparameters(1) - % nu = hyperparameters(2) - m = hyperparameters(1)/(hyperparameters(2)+2) ; - if length(hyperparameters)>2 - m = m + hyperparameters(3) ; - end - otherwise - error('Unknown prior shape!') - end \ No newline at end of file +m = NaN ; +switch shape + case 1 + if (hyperparameters(1)>1 && hyperparameters(2)>1) + m = (hyperparameters(1)-1)/(hyperparameters(1)+hyperparameters(2)-2) ; + elseif (hyperparameters(1)<1 && hyperparameters(2)<1) + m = [ 0 ; 1 ] ; + elseif ( hyperparameters(1)<1 && hyperparameters(2)>1-eps ) || ( abs(hyperparameters(1)-1)<2*eps && hyperparameters(2)>1 ) + m = 0; + elseif ( hyperparameters(1)>1 && hyperparameters(2)<1+eps ) || ( abs(hyperparameters(1)-1)<2*eps && hyperparameters(2)<1 ) + m = 1; + elseif ( abs(hyperparameters(1)-1)<2*eps && abs(hyperparameters(2)-1)<2*eps )% Uniform distribution! + m = .5 ; + end + if length(hyperparameters)==4 + m = m*(hyperparameters(4)-hyperparameters(3)) + hyperparameters(3) ; + end + case 2 + if hyperparameters(1)<1 + m = 0; + else + m = (hyperparameters(1)-1)*hyperparameters(2); + end + if length(hyperparameters)>2 + m = m + hyperparameters(3); + end + case 3 + m = hyperparameters(1); + case 4 + % s = hyperparameters(1) + % nu = hyperparameters(2) + m = 1/sqrt((hyperparameters(2)+1)/hyperparameters(1));%sqrt((hyperparameters(2)-1)/hyperparameters(1)) + if length(hyperparameters)>2 + m = m + hyperparameters(3); + end + case 5 + m = .5*(hyperparameters(2)-hyperparameters(1)) ; + case 6 + % s = hyperparameters(1) + % nu = hyperparameters(2) + m = hyperparameters(1)/(hyperparameters(2)+2) ; + if length(hyperparameters)>2 + m = m + hyperparameters(3) ; + end + otherwise + error('Unknown prior shape!') +end \ No newline at end of file diff --git a/matlab/distributions/inverse_gamma_specification.m b/matlab/distributions/inverse_gamma_specification.m index f2b8585955..dbe4a1e614 100644 --- a/matlab/distributions/inverse_gamma_specification.m +++ b/matlab/distributions/inverse_gamma_specification.m @@ -38,37 +38,37 @@ sigma2 = sigma^2; mu2 = mu^2; if type == 2; % Inverse Gamma 2 - nu = 2*(2+mu2/sigma2); - s = 2*mu*(1+mu2/sigma2); + nu = 2*(2+mu2/sigma2); + s = 2*mu*(1+mu2/sigma2); elseif type == 1; % Inverse Gamma 1 if sigma2 < Inf; - nu = sqrt(2*(2+mu2/sigma2)); - nu2 = 2*nu; - nu1 = 2; - err = 2*mu2*gamma(nu/2)^2-(sigma2+mu2)*(nu-2)*gamma((nu-1)/2)^2; - while abs(nu2-nu1) > 1e-12 - if err > 0 - nu1 = nu; - if nu < nu2 - nu = nu2; - else - nu = 2*nu; - nu2 = nu; - end - else - nu2 = nu; - end - nu = (nu1+nu2)/2; - err = 2*mu2*gamma(nu/2)^2-(sigma2+mu2)*(nu-2)*gamma((nu-1)/2)^2; - end - s = (sigma2+mu2)*(nu-2); + nu = sqrt(2*(2+mu2/sigma2)); + nu2 = 2*nu; + nu1 = 2; + err = 2*mu2*gamma(nu/2)^2-(sigma2+mu2)*(nu-2)*gamma((nu-1)/2)^2; + while abs(nu2-nu1) > 1e-12 + if err > 0 + nu1 = nu; + if nu < nu2 + nu = nu2; + else + nu = 2*nu; + nu2 = nu; + end + else + nu2 = nu; + end + nu = (nu1+nu2)/2; + err = 2*mu2*gamma(nu/2)^2-(sigma2+mu2)*(nu-2)*gamma((nu-1)/2)^2; + end + s = (sigma2+mu2)*(nu-2); else; nu = 2; s = 2*mu2/pi; end; else; - s = -1; - nu = -1; + s = -1; + nu = -1; end; % 01/18/2004 MJ replaced fsolve with secant diff --git a/matlab/distributions/mode_and_variance_to_mean.m b/matlab/distributions/mode_and_variance_to_mean.m index 31e9a4b8a1..a69f0cdbe2 100644 --- a/matlab/distributions/mode_and_variance_to_mean.m +++ b/matlab/distributions/mode_and_variance_to_mean.m @@ -34,156 +34,156 @@ function [mu, parameters] = mode_and_variance_to_mean(m,s2,distribution,lower_bo % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - % Check input aruments. - if ~(nargin==3 || nargin==5 || nargin==4 ) - error('mode_and_variance_to mean:: 3 or 5 input arguments are needed!') +% Check input aruments. +if ~(nargin==3 || nargin==5 || nargin==4 ) + error('mode_and_variance_to mean:: 3 or 5 input arguments are needed!') +end + +% Set defaults bounds. +if nargin==3 + switch distribution + case 1 + lower_bound = 0; + upper_bound = Inf; + case 3 + lower_bound = 0; + upper_bound = Inf; + case 2 + lower_bound = 0; + upper_bound = Inf; + case 4 + lower_bound = 0; + upper_bound = 1; + otherwise + error('Unknown distribution!') end - - % Set defaults bounds. - if nargin==3 - switch distribution - case 1 - lower_bound = 0; - upper_bound = Inf; - case 3 - lower_bound = 0; - upper_bound = Inf; - case 2 - lower_bound = 0; - upper_bound = Inf; - case 4 - lower_bound = 0; - upper_bound = 1; - otherwise - error('Unknown distribution!') - end +end +if nargin==4 + switch distribution + case 1 + upper_bound = Inf; + case 3 + upper_bound = Inf; + case 2 + upper_bound = Inf; + case 4 + upper_bound = 1; + otherwise + error('Unknown distribution!') end - if nargin==4 - switch distribution - case 1 - upper_bound = Inf; - case 3 - upper_bound = Inf; - case 2 - upper_bound = Inf; - case 4 - upper_bound = 1; - otherwise - error('Unknown distribution!') - end +end + + +if (distribution==1)% Gamma distribution + if m<lower_bound + error('The mode has to be greater than the lower bound!') end - - - if (distribution==1)% Gamma distribution - if m<lower_bound - error('The mode has to be greater than the lower bound!') - end - if (m-lower_bound)<1e-12 - error('The gamma distribution should be specified with the mean and variance.') - end - m = m - lower_bound ; - beta = -.5*m*(1-sqrt(1+4*s2/(m*m))) ; - alpha = (m+beta)/beta ; - parameters(1) = alpha; - parameters(2) = beta; - mu = alpha*beta + lower_bound ; - return + if (m-lower_bound)<1e-12 + error('The gamma distribution should be specified with the mean and variance.') + end + m = m - lower_bound ; + beta = -.5*m*(1-sqrt(1+4*s2/(m*m))) ; + alpha = (m+beta)/beta ; + parameters(1) = alpha; + parameters(2) = beta; + mu = alpha*beta + lower_bound ; + return +end + +if (distribution==2)% Inverse Gamma - 2 distribution + if m<lower_bound+2*eps + error('The mode has to be greater than the lower bound!') end - - if (distribution==2)% Inverse Gamma - 2 distribution - if m<lower_bound+2*eps - error('The mode has to be greater than the lower bound!') - end - m = m - lower_bound ; - if isinf(s2) - nu = 4; - s = 2*m; - else - delta = 2*(m*m/s2); - poly = [ 1 , -(8+delta) , 20-4*delta , -(16+4*delta) ]; - all_roots = roots(poly); - real_roots = all_roots(find(abs(imag(all_roots))<2*eps)); - nu = real_roots(find(real_roots>2)); - s = m*(nu+2); - end - parameters(1) = nu; - parameters(2) = s; - mu = s/(nu-2) + lower_bound; - return + m = m - lower_bound ; + if isinf(s2) + nu = 4; + s = 2*m; + else + delta = 2*(m*m/s2); + poly = [ 1 , -(8+delta) , 20-4*delta , -(16+4*delta) ]; + all_roots = roots(poly); + real_roots = all_roots(find(abs(imag(all_roots))<2*eps)); + nu = real_roots(find(real_roots>2)); + s = m*(nu+2); end - - if (distribution==3)% Inverted Gamma 1 distribution - if m<lower_bound+2*eps - error('The mode has to be greater than the lower bound!') - end - m = m - lower_bound ; - if isinf(s2) - nu = 2; - s = 3*(m*m); - else - [mu, parameters] = mode_and_variance_to_mean(m,s2,2); - nu = sqrt(parameters(1)); - nu2 = 2*nu; - nu1 = 2; - err = s2/(m*m) - (nu+1)/(nu-2) + .5*(nu+1)*(gamma((nu-1)/2)/gamma(nu/2))^2; - while abs(nu2-nu1) > 1e-12 - if err < 0 - nu1 = nu; - if nu < nu2 - nu = nu2; - else - nu = 2*nu; - nu2 = nu; - end + parameters(1) = nu; + parameters(2) = s; + mu = s/(nu-2) + lower_bound; + return +end + +if (distribution==3)% Inverted Gamma 1 distribution + if m<lower_bound+2*eps + error('The mode has to be greater than the lower bound!') + end + m = m - lower_bound ; + if isinf(s2) + nu = 2; + s = 3*(m*m); + else + [mu, parameters] = mode_and_variance_to_mean(m,s2,2); + nu = sqrt(parameters(1)); + nu2 = 2*nu; + nu1 = 2; + err = s2/(m*m) - (nu+1)/(nu-2) + .5*(nu+1)*(gamma((nu-1)/2)/gamma(nu/2))^2; + while abs(nu2-nu1) > 1e-12 + if err < 0 + nu1 = nu; + if nu < nu2 + nu = nu2; else + nu = 2*nu; nu2 = nu; end - nu = (nu1+nu2)/2; - err = s2/(m*m) - (nu+1)/(nu-2) + .5*(nu+1)*(gamma((nu-1)/2)/gamma(nu/2))^2; + else + nu2 = nu; end - s = (nu+1)*(m*m) ; + nu = (nu1+nu2)/2; + err = s2/(m*m) - (nu+1)/(nu-2) + .5*(nu+1)*(gamma((nu-1)/2)/gamma(nu/2))^2; end - parameters(1) = nu; - parameters(2) = s; - mu = sqrt(.5*s)*gamma(.5*(nu-1))/gamma(.5*nu) + lower_bound ; - return + s = (nu+1)*(m*m) ; end - - if (distribution==4)% Beta distribution - if m<lower_bound - error('The mode has to be greater than the lower bound!') - end - if m>upper_bound - error('The mode has to be less than the upper bound!') - end - if (m-lower_bound)<1e-12 - error('The beta distribution should be specified with the mean and variance.') - end - if (upper_bound-m)<1e-12 - error('The beta distribution should be specified with the mean and variance.') - end - ll = upper_bound-lower_bound; - m = (m-lower_bound)/ll; - s2 = s2/(ll*ll); - delta = m^2/s2; - poly = NaN(1,4); - poly(1) = 1; - poly(2) = 7*m-(1-m)*delta-3; - poly(3) = 16*m^2-14*m+3-2*m*delta+delta; - poly(4) = 12*m^3-16*m^2+7*m-1; - all_roots = roots(poly); - real_roots = all_roots(find(abs(imag(all_roots))<2*eps)); - idx = find(real_roots>1); - if length(idx)>1 - error('Multiplicity of solutions for the beta distribution specification.') - elseif isempty(idx) - disp('No solution for the beta distribution specification. You should reduce the variance.') - error(); - end - alpha = real_roots(idx); - beta = ((1-m)*alpha+2*m-1)/m; - parameters(1) = alpha; - parameters(2) = beta; - mu = alpha/(alpha+beta)*(upper_bound-lower_bound)+lower_bound; - return - end \ No newline at end of file + parameters(1) = nu; + parameters(2) = s; + mu = sqrt(.5*s)*gamma(.5*(nu-1))/gamma(.5*nu) + lower_bound ; + return +end + +if (distribution==4)% Beta distribution + if m<lower_bound + error('The mode has to be greater than the lower bound!') + end + if m>upper_bound + error('The mode has to be less than the upper bound!') + end + if (m-lower_bound)<1e-12 + error('The beta distribution should be specified with the mean and variance.') + end + if (upper_bound-m)<1e-12 + error('The beta distribution should be specified with the mean and variance.') + end + ll = upper_bound-lower_bound; + m = (m-lower_bound)/ll; + s2 = s2/(ll*ll); + delta = m^2/s2; + poly = NaN(1,4); + poly(1) = 1; + poly(2) = 7*m-(1-m)*delta-3; + poly(3) = 16*m^2-14*m+3-2*m*delta+delta; + poly(4) = 12*m^3-16*m^2+7*m-1; + all_roots = roots(poly); + real_roots = all_roots(find(abs(imag(all_roots))<2*eps)); + idx = find(real_roots>1); + if length(idx)>1 + error('Multiplicity of solutions for the beta distribution specification.') + elseif isempty(idx) + disp('No solution for the beta distribution specification. You should reduce the variance.') + error(); + end + alpha = real_roots(idx); + beta = ((1-m)*alpha+2*m-1)/m; + parameters(1) = alpha; + parameters(2) = beta; + mu = alpha/(alpha+beta)*(upper_bound-lower_bound)+lower_bound; + return +end \ No newline at end of file diff --git a/matlab/distributions/multivariate_normal_pdf.m b/matlab/distributions/multivariate_normal_pdf.m index 66565f19d3..c00f64f3f5 100644 --- a/matlab/distributions/multivariate_normal_pdf.m +++ b/matlab/distributions/multivariate_normal_pdf.m @@ -31,6 +31,6 @@ function density = multivariate_normal_pdf(X,Mean,Sigma_upper_chol,n); % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - density = (2*pi)^(-.5*n) * ... - prod(diag(Sigma_upper_chol))^(-1) * ... - exp(-.5*(X-Mean)*(Sigma_upper_chol\(transpose(Sigma_upper_chol)\transpose(X-Mean)))); \ No newline at end of file +density = (2*pi)^(-.5*n) * ... + prod(diag(Sigma_upper_chol))^(-1) * ... + exp(-.5*(X-Mean)*(Sigma_upper_chol\(transpose(Sigma_upper_chol)\transpose(X-Mean)))); \ No newline at end of file diff --git a/matlab/distributions/multivariate_student_pdf.m b/matlab/distributions/multivariate_student_pdf.m index 1865b41aee..8e5ddb18b7 100644 --- a/matlab/distributions/multivariate_student_pdf.m +++ b/matlab/distributions/multivariate_student_pdf.m @@ -30,7 +30,7 @@ function density = multivariate_student_pdf(X,Mean,Sigma_upper_chol,df); % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - nn = length(X); - t1 = gamma( .5*(nn+df) ) / ( gamma( .5*nn ) * (df*pi)^(.5*nn) ) ; - t2 = t1 / prod(diag(Sigma_upper_chol)) ; - density = t2 / ( 1 + (X-Mean)*(Sigma_upper_chol\(transpose(Sigma_upper_chol)\transpose(X-Mean)))/df )^(.5*(nn+df)); \ No newline at end of file +nn = length(X); +t1 = gamma( .5*(nn+df) ) / ( gamma( .5*nn ) * (df*pi)^(.5*nn) ) ; +t2 = t1 / prod(diag(Sigma_upper_chol)) ; +density = t2 / ( 1 + (X-Mean)*(Sigma_upper_chol\(transpose(Sigma_upper_chol)\transpose(X-Mean)))/df )^(.5*(nn+df)); \ No newline at end of file diff --git a/matlab/distributions/rand_inverse_wishart.m b/matlab/distributions/rand_inverse_wishart.m index f6de993e00..da407ac25e 100644 --- a/matlab/distributions/rand_inverse_wishart.m +++ b/matlab/distributions/rand_inverse_wishart.m @@ -41,13 +41,13 @@ function G = rand_inverse_wishart(m, v, H_inv_upper_chol) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - X = randn(v, m) * H_inv_upper_chol; - - - % At this point, X'*X is Wishart distributed - % G = inv(X'*X); +X = randn(v, m) * H_inv_upper_chol; - % Rather compute inv(X'*X) using the SVD - [U,S,V] = svd(X, 0); - SSi = 1 ./ (diag(S) .^ 2); - G = (V .* repmat(SSi', m, 1)) * V'; \ No newline at end of file + +% At this point, X'*X is Wishart distributed +% G = inv(X'*X); + +% Rather compute inv(X'*X) using the SVD +[U,S,V] = svd(X, 0); +SSi = 1 ./ (diag(S) .^ 2); +G = (V .* repmat(SSi', m, 1)) * V'; \ No newline at end of file diff --git a/matlab/distributions/rand_matrix_normal.m b/matlab/distributions/rand_matrix_normal.m index 32aa4bafd9..b2b11306d0 100644 --- a/matlab/distributions/rand_matrix_normal.m +++ b/matlab/distributions/rand_matrix_normal.m @@ -37,7 +37,7 @@ function B = rand_matrix_normal(n, p, M, Omega_lower_chol, Sigma_lower_chol) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - B1 = randn(n * p, 1); - B2 = kron(Omega_lower_chol, Sigma_lower_chol) * B1; - B3 = reshape(B2, n, p); - B = B3 + M; +B1 = randn(n * p, 1); +B2 = kron(Omega_lower_chol, Sigma_lower_chol) * B1; +B3 = reshape(B2, n, p); +B = B3 + M; diff --git a/matlab/distributions/rand_multivariate_normal.m b/matlab/distributions/rand_multivariate_normal.m index bd70c51dfd..52cb6f50fa 100644 --- a/matlab/distributions/rand_multivariate_normal.m +++ b/matlab/distributions/rand_multivariate_normal.m @@ -31,4 +31,4 @@ function draw = rand_multivariate_normal(Mean,Sigma_upper_chol,n) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - draw = Mean + randn(1,n) * Sigma_upper_chol; +draw = Mean + randn(1,n) * Sigma_upper_chol; diff --git a/matlab/distributions/rand_multivariate_student.m b/matlab/distributions/rand_multivariate_student.m index cc4fc0e75a..7065d0a187 100644 --- a/matlab/distributions/rand_multivariate_student.m +++ b/matlab/distributions/rand_multivariate_student.m @@ -35,5 +35,5 @@ function draw = rand_multivariate_student(Mean,Sigma_upper_chol,df) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - n = length(Mean); - draw = Mean + randn(1,n) * Sigma_upper_chol * sqrt(df/sum(randn(df,1).^2)); +n = length(Mean); +draw = Mean + randn(1,n) * Sigma_upper_chol * sqrt(df/sum(randn(df,1).^2)); diff --git a/matlab/dr1.m b/matlab/dr1.m index 67b86d0c86..422ead5b56 100644 --- a/matlab/dr1.m +++ b/matlab/dr1.m @@ -49,17 +49,88 @@ function [dr,info,M_,options_,oo_] = dr1(dr,task,M_,options_,oo_) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - info = 0; - - if options_.k_order_solver; - dr = set_state_space(dr,M_); - [dr,info] = k_order_pert(dr,M_,options_,oo_); - oo_.dr = dr; - return; +info = 0; + +if options_.k_order_solver; + dr = set_state_space(dr,M_); + [dr,info] = k_order_pert(dr,M_,options_,oo_); + oo_.dr = dr; + return; +end + +xlen = M_.maximum_endo_lead + M_.maximum_endo_lag + 1; +klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1; +iyv = M_.lead_lag_incidence'; +iyv = iyv(:); +iyr0 = find(iyv) ; +it_ = M_.maximum_lag + 1 ; + +if M_.exo_nbr == 0 + oo_.exo_steady_state = [] ; +end + +% expanding system for Optimal Linear Regulator +if options_.ramsey_policy + if isfield(M_,'orig_model') + orig_model = M_.orig_model; + M_.endo_nbr = orig_model.endo_nbr; + M_.orig_endo_nbr = orig_model.orig_endo_nbr; + M_.aux_vars = orig_model.aux_vars; + M_.endo_names = orig_model.endo_names; + M_.lead_lag_incidence = orig_model.lead_lag_incidence; + M_.maximum_lead = orig_model.maximum_lead; + M_.maximum_endo_lead = orig_model.maximum_endo_lead; + M_.maximum_lag = orig_model.maximum_lag; + M_.maximum_endo_lag = orig_model.maximum_endo_lag; end - - xlen = M_.maximum_endo_lead + M_.maximum_endo_lag + 1; - klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1; + + if options_.steadystate_flag + k_inst = []; + instruments = options_.instruments; + for i = 1:size(instruments,1) + k_inst = [k_inst; strmatch(options_.instruments(i,:), ... + M_.endo_names,'exact')]; + end + ys = oo_.steady_state; + inst_val = dynare_solve('dyn_ramsey_static_', ... + oo_.steady_state(k_inst),0, ... + M_,options_,oo_,it_); + ys(k_inst) = inst_val; + [x,check] = feval([M_.fname '_steadystate'],... + ys,[oo_.exo_steady_state; ... + oo_.exo_det_steady_state]); + if size(x,1) < M_.endo_nbr + if length(M_.aux_vars) > 0 + x = add_auxiliary_variables_to_steadystate(x,M_.aux_vars,... + M_.fname,... + oo_.exo_steady_state,... + oo_.exo_det_steady_state,... + M_.params); + else + error([M_.fname '_steadystate.m doesn''t match the model']); + end + end + oo_.steady_state = x; + [junk,junk,multbar] = dyn_ramsey_static_(oo_.steady_state(k_inst),M_,options_,oo_,it_); + else + oo_.steady_state = dynare_solve('dyn_ramsey_static_', ... + oo_.steady_state,0,M_,options_,oo_,it_); + [junk,junk,multbar] = dyn_ramsey_static_(oo_.steady_state,M_,options_,oo_,it_); + end + check1 = max(abs(feval([M_.fname '_static'],... + oo_.steady_state,... + [oo_.exo_steady_state; ... + oo_.exo_det_steady_state], M_.params))) > options_.dynatol ; + if check1 + error(['The steadystate values returned by ' M_.fname ... + '_steadystate.m don''t solve the static model!' ]) + end + + [jacobia_,M_] = dyn_ramsey_dynamic_(oo_.steady_state,multbar,M_,options_,oo_,it_); + klen = M_.maximum_lag + M_.maximum_lead + 1; + dr.ys = [oo_.steady_state;zeros(M_.exo_nbr,1);multbar]; +else + klen = M_.maximum_lag + M_.maximum_lead + 1; iyv = M_.lead_lag_incidence'; iyv = iyv(:); iyr0 = find(iyv) ; @@ -69,277 +140,129 @@ function [dr,info,M_,options_,oo_] = dr1(dr,task,M_,options_,oo_) oo_.exo_steady_state = [] ; end - % expanding system for Optimal Linear Regulator - if options_.ramsey_policy - if isfield(M_,'orig_model') - orig_model = M_.orig_model; - M_.endo_nbr = orig_model.endo_nbr; - M_.orig_endo_nbr = orig_model.orig_endo_nbr; - M_.aux_vars = orig_model.aux_vars; - M_.endo_names = orig_model.endo_names; - M_.lead_lag_incidence = orig_model.lead_lag_incidence; - M_.maximum_lead = orig_model.maximum_lead; - M_.maximum_endo_lead = orig_model.maximum_endo_lead; - M_.maximum_lag = orig_model.maximum_lag; - M_.maximum_endo_lag = orig_model.maximum_endo_lag; + it_ = M_.maximum_lag + 1; + z = repmat(dr.ys,1,klen); + z = z(iyr0) ; + if options_.order == 1 + [junk,jacobia_] = feval([M_.fname '_dynamic'],z,[oo_.exo_simul ... + oo_.exo_det_simul], M_.params, it_); + elseif options_.order == 2 + [junk,jacobia_,hessian1] = feval([M_.fname '_dynamic'],z,... + [oo_.exo_simul ... + oo_.exo_det_simul], M_.params, it_); + if options_.use_dll + % In USE_DLL mode, the hessian is in the 3-column sparse representation + hessian1 = sparse(hessian1(:,1), hessian1(:,2), hessian1(:,3), ... + size(jacobia_, 1), size(jacobia_, 2)*size(jacobia_, 2)); end + end +end - if options_.steadystate_flag - k_inst = []; - instruments = options_.instruments; - for i = 1:size(instruments,1) - k_inst = [k_inst; strmatch(options_.instruments(i,:), ... - M_.endo_names,'exact')]; - end - ys = oo_.steady_state; - inst_val = dynare_solve('dyn_ramsey_static_', ... - oo_.steady_state(k_inst),0, ... - M_,options_,oo_,it_); - ys(k_inst) = inst_val; - [x,check] = feval([M_.fname '_steadystate'],... - ys,[oo_.exo_steady_state; ... - oo_.exo_det_steady_state]); - if size(x,1) < M_.endo_nbr - if length(M_.aux_vars) > 0 - x = add_auxiliary_variables_to_steadystate(x,M_.aux_vars,... - M_.fname,... - oo_.exo_steady_state,... - oo_.exo_det_steady_state,... - M_.params); - else - error([M_.fname '_steadystate.m doesn''t match the model']); - end - end - oo_.steady_state = x; - [junk,junk,multbar] = dyn_ramsey_static_(oo_.steady_state(k_inst),M_,options_,oo_,it_); - else - oo_.steady_state = dynare_solve('dyn_ramsey_static_', ... - oo_.steady_state,0,M_,options_,oo_,it_); - [junk,junk,multbar] = dyn_ramsey_static_(oo_.steady_state,M_,options_,oo_,it_); - end - check1 = max(abs(feval([M_.fname '_static'],... - oo_.steady_state,... - [oo_.exo_steady_state; ... - oo_.exo_det_steady_state], M_.params))) > options_.dynatol ; - if check1 - error(['The steadystate values returned by ' M_.fname ... - '_steadystate.m don''t solve the static model!' ]) - end +if options_.debug + save([M_.fname '_debug.mat'],'jacobia_') +end - [jacobia_,M_] = dyn_ramsey_dynamic_(oo_.steady_state,multbar,M_,options_,oo_,it_); - klen = M_.maximum_lag + M_.maximum_lead + 1; - dr.ys = [oo_.steady_state;zeros(M_.exo_nbr,1);multbar]; +if ~isreal(jacobia_) + if max(max(abs(imag(jacobia_)))) < 1e-15 + jacobia_ = real(jacobia_); else - klen = M_.maximum_lag + M_.maximum_lead + 1; - iyv = M_.lead_lag_incidence'; - iyv = iyv(:); - iyr0 = find(iyv) ; - it_ = M_.maximum_lag + 1 ; - - if M_.exo_nbr == 0 - oo_.exo_steady_state = [] ; - end - - it_ = M_.maximum_lag + 1; - z = repmat(dr.ys,1,klen); - z = z(iyr0) ; - if options_.order == 1 - [junk,jacobia_] = feval([M_.fname '_dynamic'],z,[oo_.exo_simul ... - oo_.exo_det_simul], M_.params, it_); - elseif options_.order == 2 - [junk,jacobia_,hessian1] = feval([M_.fname '_dynamic'],z,... - [oo_.exo_simul ... - oo_.exo_det_simul], M_.params, it_); - if options_.use_dll - % In USE_DLL mode, the hessian is in the 3-column sparse representation - hessian1 = sparse(hessian1(:,1), hessian1(:,2), hessian1(:,3), ... - size(jacobia_, 1), size(jacobia_, 2)*size(jacobia_, 2)); - end - end - end - - if options_.debug - save([M_.fname '_debug.mat'],'jacobia_') - end - - if ~isreal(jacobia_) - if max(max(abs(imag(jacobia_)))) < 1e-15 - jacobia_ = real(jacobia_); - else - info(1) = 6; - info(2) = sum(sum(imag(jacobia_).^2)); - return - end - end - - dr=set_state_space(dr,M_); - kstate = dr.kstate; - kad = dr.kad; - kae = dr.kae; - nstatic = dr.nstatic; - nfwrd = dr.nfwrd; - npred = dr.npred; - nboth = dr.nboth; - order_var = dr.order_var; - nd = size(kstate,1); - nz = nnz(M_.lead_lag_incidence); - - sdyn = M_.endo_nbr - nstatic; - - [junk,cols_b,cols_j] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+1, ... - order_var)); - b = zeros(M_.endo_nbr,M_.endo_nbr); - b(:,cols_b) = jacobia_(:,cols_j); - - if M_.maximum_endo_lead == 0 && options_.order == 1 - % backward models: simplified code exist only at order == 1 - % If required, use AIM solver if not check only - if (options_.aim_solver == 1) && (task == 0) - if options_.order > 1 - error('Option "aim_solver" is incompatible with order >= 2') - end - try - [dr,aimcode]=dynAIMsolver1(jacobia_,M_,dr); - if aimcode ~=1 - info(1) = aimcode; - info(2) = 1.0e+8; - return - end - catch - disp(lasterror.message) - error('Problem with AIM solver - Try to remove the "aim_solver" option'); - end - else % use original Dynare solver - [k1,junk,k2] = find(kstate(:,4)); - dr.ghx(:,k1) = -b\jacobia_(:,k2); - if M_.exo_nbr - dr.ghu = -b\jacobia_(:,nz+1:end); - end - end % if not use AIM or not... - dr.eigval = eig(transition_matrix(dr)); - dr.rank = 0; - if any(abs(dr.eigval) > options_.qz_criterium) - temp = sort(abs(dr.eigval)); - nba = nnz(abs(dr.eigval) > options_.qz_criterium); - temp = temp(nd-nba+1:nd)-1-options_.qz_criterium; - info(1) = 3; - info(2) = temp'*temp; - end - if options_.loglinear == 1 - klags = find(M_.lead_lag_incidence(1,:)); - dr.ghx = repmat(1./dr.ys,1,size(dr.ghx,2)).*dr.ghx.* ... - repmat(dr.ys(klags),size(dr.ghx,1),1); - dr.ghu = repmat(1./dr.ys,1,size(dr.ghu,2)).*dr.ghu; - end + info(1) = 6; + info(2) = sum(sum(imag(jacobia_).^2)); return end - - %forward--looking models - if nstatic > 0 - [Q,R] = qr(b(:,1:nstatic)); - aa = Q'*jacobia_; - else - aa = jacobia_; - end +end + +dr=set_state_space(dr,M_); +kstate = dr.kstate; +kad = dr.kad; +kae = dr.kae; +nstatic = dr.nstatic; +nfwrd = dr.nfwrd; +npred = dr.npred; +nboth = dr.nboth; +order_var = dr.order_var; +nd = size(kstate,1); +nz = nnz(M_.lead_lag_incidence); + +sdyn = M_.endo_nbr - nstatic; +[junk,cols_b,cols_j] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+1, ... + order_var)); +b = zeros(M_.endo_nbr,M_.endo_nbr); +b(:,cols_b) = jacobia_(:,cols_j); + +if M_.maximum_endo_lead == 0 && options_.order == 1 + % backward models: simplified code exist only at order == 1 % If required, use AIM solver if not check only if (options_.aim_solver == 1) && (task == 0) if options_.order > 1 error('Option "aim_solver" is incompatible with order >= 2') end try - [dr,aimcode]=dynAIMsolver1(aa,M_,dr); - - % reuse some of the bypassed code and tests that may be needed - + [dr,aimcode]=dynAIMsolver1(jacobia_,M_,dr); if aimcode ~=1 info(1) = aimcode; info(2) = 1.0e+8; return end - [A,B] =transition_matrix(dr); - dr.eigval = eig(A); - sdim = sum( abs(dr.eigval) < options_.qz_criterium ); - nba = nd-sdim; - - nyf = sum(kstate(:,2) > M_.maximum_endo_lag+1); - if nba ~= nyf - temp = sort(abs(dr.eigval)); - if nba > nyf - temp = temp(nd-nba+1:nd-nyf)-1-options_.qz_criterium; - info(1) = 3; - elseif nba < nyf; - temp = temp(nd-nyf+1:nd-nba)-1-options_.qz_criterium; - info(1) = 4; - end - info(2) = temp'*temp; - return - end catch disp(lasterror.message) - error('Problem with AIM solver - Try to remove the "aim_solver" option') + error('Problem with AIM solver - Try to remove the "aim_solver" option'); end - else % use original Dynare solver - k1 = M_.lead_lag_incidence(find([1:klen] ~= M_.maximum_endo_lag+1),:); - a = aa(:,nonzeros(k1')); - b(:,cols_b) = aa(:,cols_j); - b10 = b(1:nstatic,1:nstatic); - b11 = b(1:nstatic,nstatic+1:end); - b2 = b(nstatic+1:end,nstatic+1:end); - if any(isinf(a(:))) - info = 1; - return + else % use original Dynare solver + [k1,junk,k2] = find(kstate(:,4)); + dr.ghx(:,k1) = -b\jacobia_(:,k2); + if M_.exo_nbr + dr.ghu = -b\jacobia_(:,nz+1:end); end + end % if not use AIM or not... + dr.eigval = eig(transition_matrix(dr)); + dr.rank = 0; + if any(abs(dr.eigval) > options_.qz_criterium) + temp = sort(abs(dr.eigval)); + nba = nnz(abs(dr.eigval) > options_.qz_criterium); + temp = temp(nd-nba+1:nd)-1-options_.qz_criterium; + info(1) = 3; + info(2) = temp'*temp; + end + if options_.loglinear == 1 + klags = find(M_.lead_lag_incidence(1,:)); + dr.ghx = repmat(1./dr.ys,1,size(dr.ghx,2)).*dr.ghx.* ... + repmat(dr.ys(klags),size(dr.ghx,1),1); + dr.ghu = repmat(1./dr.ys,1,size(dr.ghu,2)).*dr.ghu; + end + return +end - % buildind D and E - d = zeros(nd,nd) ; - e = d ; - - k = find(kstate(:,2) >= M_.maximum_endo_lag+2 & kstate(:,3)); - d(1:sdyn,k) = a(nstatic+1:end,kstate(k,3)) ; - k1 = find(kstate(:,2) == M_.maximum_endo_lag+2); - e(1:sdyn,k1) = -b2(:,kstate(k1,1)-nstatic); - k = find(kstate(:,2) <= M_.maximum_endo_lag+1 & kstate(:,4)); - e(1:sdyn,k) = -a(nstatic+1:end,kstate(k,4)) ; - k2 = find(kstate(:,2) == M_.maximum_endo_lag+1); - k2 = k2(~ismember(kstate(k2,1),kstate(k1,1))); - d(1:sdyn,k2) = b2(:,kstate(k2,1)-nstatic); - - if ~isempty(kad) - for j = 1:size(kad,1) - d(sdyn+j,kad(j)) = 1 ; - e(sdyn+j,kae(j)) = 1 ; - end - end +%forward--looking models +if nstatic > 0 + [Q,R] = qr(b(:,1:nstatic)); + aa = Q'*jacobia_; +else + aa = jacobia_; +end - % 1) if mjdgges.dll (or .mexw32 or ....) doesn't exit, - % matlab/qz is added to the path. There exists now qz/mjdgges.m that - % contains the calls to the old Sims code - % 2) In global_initialization.m, if mjdgges.m is visible exist(...)==2, - % this means that the DLL isn't avaiable and use_qzdiv is set to 1 - - [ss,tt,w,sdim,dr.eigval,info1] = mjdgges(e,d,options_.qz_criterium); +% If required, use AIM solver if not check only +if (options_.aim_solver == 1) && (task == 0) + if options_.order > 1 + error('Option "aim_solver" is incompatible with order >= 2') + end + try + [dr,aimcode]=dynAIMsolver1(aa,M_,dr); - if info1 - info(1) = 2; - info(2) = info1; + % reuse some of the bypassed code and tests that may be needed + + if aimcode ~=1 + info(1) = aimcode; + info(2) = 1.0e+8; return end - + [A,B] =transition_matrix(dr); + dr.eigval = eig(A); + sdim = sum( abs(dr.eigval) < options_.qz_criterium ); nba = nd-sdim; nyf = sum(kstate(:,2) > M_.maximum_endo_lag+1); - - if task == 1 - dr.rank = rank(w(1:nyf,nd-nyf+1:end)); - % Under Octave, eig(A,B) doesn't exist, and - % lambda = qz(A,B) won't return infinite eigenvalues - if ~exist('OCTAVE_VERSION') - dr.eigval = eig(e,d); - end - return - end - if nba ~= nyf temp = sort(abs(dr.eigval)); if nba > nyf @@ -352,352 +275,429 @@ function [dr,info,M_,options_,oo_] = dr1(dr,task,M_,options_,oo_) info(2) = temp'*temp; return end + catch + disp(lasterror.message) + error('Problem with AIM solver - Try to remove the "aim_solver" option') + end +else % use original Dynare solver + k1 = M_.lead_lag_incidence(find([1:klen] ~= M_.maximum_endo_lag+1),:); + a = aa(:,nonzeros(k1')); + b(:,cols_b) = aa(:,cols_j); + b10 = b(1:nstatic,1:nstatic); + b11 = b(1:nstatic,nstatic+1:end); + b2 = b(nstatic+1:end,nstatic+1:end); + if any(isinf(a(:))) + info = 1; + return + end - np = nd - nyf; - n2 = np + 1; - n3 = nyf; - n4 = n3 + 1; - % derivatives with respect to dynamic state variables - % forward variables - w1 =w(1:n3,n2:nd); - if condest(w1) > 1e9; - info(1) = 5; - info(2) = condest(w1); - return; - else - gx = -w1'\w(n4:nd,n2:nd)'; - end - - % predetermined variables - hx = w(1:n3,1:np)'*gx+w(n4:nd,1:np)'; - hx = (tt(1:np,1:np)*hx)\(ss(1:np,1:np)*hx); - - k1 = find(kstate(n4:nd,2) == M_.maximum_endo_lag+1); - k2 = find(kstate(1:n3,2) == M_.maximum_endo_lag+2); - dr.ghx = [hx(k1,:); gx(k2(nboth+1:end),:)]; - - %lead variables actually present in the model - j3 = nonzeros(kstate(:,3)); - j4 = find(kstate(:,3)); - % derivatives with respect to exogenous variables - if M_.exo_nbr - fu = aa(:,nz+(1:M_.exo_nbr)); - a1 = b; - aa1 = []; - if nstatic > 0 - aa1 = a1(:,1:nstatic); - end - dr.ghu = -[aa1 a(:,j3)*gx(j4,1:npred)+a1(:,nstatic+1:nstatic+ ... - npred) a1(:,nstatic+npred+1:end)]\fu; - else - dr.ghu = []; - end + % buildind D and E + d = zeros(nd,nd) ; + e = d ; - % static variables - if nstatic > 0 - temp = -a(1:nstatic,j3)*gx(j4,:)*hx; - j5 = find(kstate(n4:nd,4)); - temp(:,j5) = temp(:,j5)-a(1:nstatic,nonzeros(kstate(:,4))); - temp = b10\(temp-b11*dr.ghx); - dr.ghx = [temp; dr.ghx]; - temp = []; + k = find(kstate(:,2) >= M_.maximum_endo_lag+2 & kstate(:,3)); + d(1:sdyn,k) = a(nstatic+1:end,kstate(k,3)) ; + k1 = find(kstate(:,2) == M_.maximum_endo_lag+2); + e(1:sdyn,k1) = -b2(:,kstate(k1,1)-nstatic); + k = find(kstate(:,2) <= M_.maximum_endo_lag+1 & kstate(:,4)); + e(1:sdyn,k) = -a(nstatic+1:end,kstate(k,4)) ; + k2 = find(kstate(:,2) == M_.maximum_endo_lag+1); + k2 = k2(~ismember(kstate(k2,1),kstate(k1,1))); + d(1:sdyn,k2) = b2(:,kstate(k2,1)-nstatic); + + if ~isempty(kad) + for j = 1:size(kad,1) + d(sdyn+j,kad(j)) = 1 ; + e(sdyn+j,kae(j)) = 1 ; end - end % if not use AIM and .... - % End of if... and if not... main AIM Blocks, continue as per usual... - - if options_.loglinear == 1 - k = find(dr.kstate(:,2) <= M_.maximum_endo_lag+1); - klag = dr.kstate(k,[1 2]); - k1 = dr.order_var; - - dr.ghx = repmat(1./dr.ys(k1),1,size(dr.ghx,2)).*dr.ghx.* ... - repmat(dr.ys(k1(klag(:,1)))',size(dr.ghx,1),1); - dr.ghu = repmat(1./dr.ys(k1),1,size(dr.ghu,2)).*dr.ghu; end + + % 1) if mjdgges.dll (or .mexw32 or ....) doesn't exit, + % matlab/qz is added to the path. There exists now qz/mjdgges.m that + % contains the calls to the old Sims code + % 2) In global_initialization.m, if mjdgges.m is visible exist(...)==2, + % this means that the DLL isn't avaiable and use_qzdiv is set to 1 - if options_.aim_solver ~= 1 && options_.use_qzdiv - %% Necessary when using Sims' routines for QZ - gx = real(gx); - hx = real(hx); - dr.ghx = real(dr.ghx); - dr.ghu = real(dr.ghu); + [ss,tt,w,sdim,dr.eigval,info1] = mjdgges(e,d,options_.qz_criterium); + + if info1 + info(1) = 2; + info(2) = info1; + return end - - %exogenous deterministic variables - if M_.exo_det_nbr > 0 - f1 = sparse(jacobia_(:,nonzeros(M_.lead_lag_incidence(M_.maximum_endo_lag+2:end,order_var)))); - f0 = sparse(jacobia_(:,nonzeros(M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var)))); - fudet = sparse(jacobia_(:,nz+M_.exo_nbr+1:end)); - M1 = inv(f0+[zeros(M_.endo_nbr,nstatic) f1*gx zeros(M_.endo_nbr,nyf-nboth)]); - M2 = M1*f1; - dr.ghud = cell(M_.exo_det_length,1); - dr.ghud{1} = -M1*fudet; - for i = 2:M_.exo_det_length - dr.ghud{i} = -M2*dr.ghud{i-1}(end-nyf+1:end,:); + + nba = nd-sdim; + + nyf = sum(kstate(:,2) > M_.maximum_endo_lag+1); + + if task == 1 + dr.rank = rank(w(1:nyf,nd-nyf+1:end)); + % Under Octave, eig(A,B) doesn't exist, and + % lambda = qz(A,B) won't return infinite eigenvalues + if ~exist('OCTAVE_VERSION') + dr.eigval = eig(e,d); end + return end - - if options_.order == 1 + + if nba ~= nyf + temp = sort(abs(dr.eigval)); + if nba > nyf + temp = temp(nd-nba+1:nd-nyf)-1-options_.qz_criterium; + info(1) = 3; + elseif nba < nyf; + temp = temp(nd-nyf+1:nd-nba)-1-options_.qz_criterium; + info(1) = 4; + end + info(2) = temp'*temp; return end - - % Second order - %tempex = oo_.exo_simul ; - - %hessian = real(hessext('ff1_',[z; oo_.exo_steady_state]))' ; - kk = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1)); - if M_.maximum_endo_lag > 0 - kk = [cumsum(M_.lead_lag_incidence(1:M_.maximum_endo_lag,order_var),1); kk]; + + np = nd - nyf; + n2 = np + 1; + n3 = nyf; + n4 = n3 + 1; + % derivatives with respect to dynamic state variables + % forward variables + w1 =w(1:n3,n2:nd); + if condest(w1) > 1e9; + info(1) = 5; + info(2) = condest(w1); + return; + else + gx = -w1'\w(n4:nd,n2:nd)'; + end + + % predetermined variables + hx = w(1:n3,1:np)'*gx+w(n4:nd,1:np)'; + hx = (tt(1:np,1:np)*hx)\(ss(1:np,1:np)*hx); + + k1 = find(kstate(n4:nd,2) == M_.maximum_endo_lag+1); + k2 = find(kstate(1:n3,2) == M_.maximum_endo_lag+2); + dr.ghx = [hx(k1,:); gx(k2(nboth+1:end),:)]; + + %lead variables actually present in the model + j3 = nonzeros(kstate(:,3)); + j4 = find(kstate(:,3)); + % derivatives with respect to exogenous variables + if M_.exo_nbr + fu = aa(:,nz+(1:M_.exo_nbr)); + a1 = b; + aa1 = []; + if nstatic > 0 + aa1 = a1(:,1:nstatic); + end + dr.ghu = -[aa1 a(:,j3)*gx(j4,1:npred)+a1(:,nstatic+1:nstatic+ ... + npred) a1(:,nstatic+npred+1:end)]\fu; + else + dr.ghu = []; end - kk = kk'; - kk = find(kk(:)); - nk = size(kk,1) + M_.exo_nbr + M_.exo_det_nbr; - k1 = M_.lead_lag_incidence(:,order_var); - k1 = k1'; - k1 = k1(:); - k1 = k1(kk); - k2 = find(k1); - kk1(k1(k2)) = k2; - kk1 = [kk1 length(k1)+1:length(k1)+M_.exo_nbr+M_.exo_det_nbr]; - kk = reshape([1:nk^2],nk,nk); - kk1 = kk(kk1,kk1); - %[junk,junk,hessian] = feval([M_.fname '_dynamic'],z, oo_.exo_steady_state); - hessian(:,kk1(:)) = hessian1; - clear hessian1 - - %oo_.exo_simul = tempex ; - %clear tempex - - n1 = 0; - n2 = np; - zx = zeros(np,np); - zu=zeros(np,M_.exo_nbr); - for i=2:M_.maximum_endo_lag+1 - k1 = sum(kstate(:,2) == i); - zx(n1+1:n1+k1,n2-k1+1:n2)=eye(k1); - n1 = n1+k1; - n2 = n2-k1; + + % static variables + if nstatic > 0 + temp = -a(1:nstatic,j3)*gx(j4,:)*hx; + j5 = find(kstate(n4:nd,4)); + temp(:,j5) = temp(:,j5)-a(1:nstatic,nonzeros(kstate(:,4))); + temp = b10\(temp-b11*dr.ghx); + dr.ghx = [temp; dr.ghx]; + temp = []; end - kk = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1)); - k0 = [1:M_.endo_nbr]; - gx1 = dr.ghx; - hu = dr.ghu(nstatic+[1:npred],:); - zx = [zx; gx1]; - zu = [zu; dr.ghu]; - for i=1:M_.maximum_endo_lead - k1 = find(kk(i+1,k0) > 0); - zu = [zu; gx1(k1,1:npred)*hu]; - gx1 = gx1(k1,:)*hx; - zx = [zx; gx1]; - kk = kk(:,k0); - k0 = k1; +end % if not use AIM and .... + % End of if... and if not... main AIM Blocks, continue as per usual... + +if options_.loglinear == 1 + k = find(dr.kstate(:,2) <= M_.maximum_endo_lag+1); + klag = dr.kstate(k,[1 2]); + k1 = dr.order_var; + + dr.ghx = repmat(1./dr.ys(k1),1,size(dr.ghx,2)).*dr.ghx.* ... + repmat(dr.ys(k1(klag(:,1)))',size(dr.ghx,1),1); + dr.ghu = repmat(1./dr.ys(k1),1,size(dr.ghu,2)).*dr.ghu; +end + +if options_.aim_solver ~= 1 && options_.use_qzdiv + %% Necessary when using Sims' routines for QZ + gx = real(gx); + hx = real(hx); + dr.ghx = real(dr.ghx); + dr.ghu = real(dr.ghu); +end + +%exogenous deterministic variables +if M_.exo_det_nbr > 0 + f1 = sparse(jacobia_(:,nonzeros(M_.lead_lag_incidence(M_.maximum_endo_lag+2:end,order_var)))); + f0 = sparse(jacobia_(:,nonzeros(M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var)))); + fudet = sparse(jacobia_(:,nz+M_.exo_nbr+1:end)); + M1 = inv(f0+[zeros(M_.endo_nbr,nstatic) f1*gx zeros(M_.endo_nbr,nyf-nboth)]); + M2 = M1*f1; + dr.ghud = cell(M_.exo_det_length,1); + dr.ghud{1} = -M1*fudet; + for i = 2:M_.exo_det_length + dr.ghud{i} = -M2*dr.ghud{i-1}(end-nyf+1:end,:); end - zx=[zx; zeros(M_.exo_nbr,np);zeros(M_.exo_det_nbr,np)]; - zu=[zu; eye(M_.exo_nbr);zeros(M_.exo_det_nbr,M_.exo_nbr)]; - [nrzx,nczx] = size(zx); +end - rhs = -sparse_hessian_times_B_kronecker_C(hessian,zx); - - %lhs - n = M_.endo_nbr+sum(kstate(:,2) > M_.maximum_endo_lag+1 & kstate(:,2) < M_.maximum_endo_lag+M_.maximum_endo_lead+1); - A = zeros(n,n); - B = zeros(n,n); - A(1:M_.endo_nbr,1:M_.endo_nbr) = jacobia_(:,M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var)); - % variables with the highest lead - k1 = find(kstate(:,2) == M_.maximum_endo_lag+M_.maximum_endo_lead+1); - if M_.maximum_endo_lead > 1 - k2 = find(kstate(:,2) == M_.maximum_endo_lag+M_.maximum_endo_lead); - [junk,junk,k3] = intersect(kstate(k1,1),kstate(k2,1)); +if options_.order == 1 + return +end + +% Second order +%tempex = oo_.exo_simul ; + +%hessian = real(hessext('ff1_',[z; oo_.exo_steady_state]))' ; +kk = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1)); +if M_.maximum_endo_lag > 0 + kk = [cumsum(M_.lead_lag_incidence(1:M_.maximum_endo_lag,order_var),1); kk]; +end +kk = kk'; +kk = find(kk(:)); +nk = size(kk,1) + M_.exo_nbr + M_.exo_det_nbr; +k1 = M_.lead_lag_incidence(:,order_var); +k1 = k1'; +k1 = k1(:); +k1 = k1(kk); +k2 = find(k1); +kk1(k1(k2)) = k2; +kk1 = [kk1 length(k1)+1:length(k1)+M_.exo_nbr+M_.exo_det_nbr]; +kk = reshape([1:nk^2],nk,nk); +kk1 = kk(kk1,kk1); +%[junk,junk,hessian] = feval([M_.fname '_dynamic'],z, oo_.exo_steady_state); +hessian(:,kk1(:)) = hessian1; +clear hessian1 + +%oo_.exo_simul = tempex ; +%clear tempex + +n1 = 0; +n2 = np; +zx = zeros(np,np); +zu=zeros(np,M_.exo_nbr); +for i=2:M_.maximum_endo_lag+1 + k1 = sum(kstate(:,2) == i); + zx(n1+1:n1+k1,n2-k1+1:n2)=eye(k1); + n1 = n1+k1; + n2 = n2-k1; +end +kk = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1)); +k0 = [1:M_.endo_nbr]; +gx1 = dr.ghx; +hu = dr.ghu(nstatic+[1:npred],:); +zx = [zx; gx1]; +zu = [zu; dr.ghu]; +for i=1:M_.maximum_endo_lead + k1 = find(kk(i+1,k0) > 0); + zu = [zu; gx1(k1,1:npred)*hu]; + gx1 = gx1(k1,:)*hx; + zx = [zx; gx1]; + kk = kk(:,k0); + k0 = k1; +end +zx=[zx; zeros(M_.exo_nbr,np);zeros(M_.exo_det_nbr,np)]; +zu=[zu; eye(M_.exo_nbr);zeros(M_.exo_det_nbr,M_.exo_nbr)]; +[nrzx,nczx] = size(zx); + +rhs = -sparse_hessian_times_B_kronecker_C(hessian,zx); + +%lhs +n = M_.endo_nbr+sum(kstate(:,2) > M_.maximum_endo_lag+1 & kstate(:,2) < M_.maximum_endo_lag+M_.maximum_endo_lead+1); +A = zeros(n,n); +B = zeros(n,n); +A(1:M_.endo_nbr,1:M_.endo_nbr) = jacobia_(:,M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var)); +% variables with the highest lead +k1 = find(kstate(:,2) == M_.maximum_endo_lag+M_.maximum_endo_lead+1); +if M_.maximum_endo_lead > 1 + k2 = find(kstate(:,2) == M_.maximum_endo_lag+M_.maximum_endo_lead); + [junk,junk,k3] = intersect(kstate(k1,1),kstate(k2,1)); +else + k2 = [1:M_.endo_nbr]; + k3 = kstate(k1,1); +end +% Jacobian with respect to the variables with the highest lead +B(1:M_.endo_nbr,end-length(k2)+k3) = jacobia_(:,kstate(k1,3)+M_.endo_nbr); +offset = M_.endo_nbr; +k0 = [1:M_.endo_nbr]; +gx1 = dr.ghx; +for i=1:M_.maximum_endo_lead-1 + k1 = find(kstate(:,2) == M_.maximum_endo_lag+i+1); + [k2,junk,k3] = find(kstate(k1,3)); + A(1:M_.endo_nbr,offset+k2) = jacobia_(:,k3+M_.endo_nbr); + n1 = length(k1); + A(offset+[1:n1],nstatic+[1:npred]) = -gx1(kstate(k1,1),1:npred); + gx1 = gx1*hx; + A(offset+[1:n1],offset+[1:n1]) = eye(n1); + n0 = length(k0); + E = eye(n0); + if i == 1 + [junk,junk,k4]=intersect(kstate(k1,1),[1:M_.endo_nbr]); else - k2 = [1:M_.endo_nbr]; - k3 = kstate(k1,1); + [junk,junk,k4]=intersect(kstate(k1,1),kstate(k0,1)); end - % Jacobian with respect to the variables with the highest lead - B(1:M_.endo_nbr,end-length(k2)+k3) = jacobia_(:,kstate(k1,3)+M_.endo_nbr); - offset = M_.endo_nbr; - k0 = [1:M_.endo_nbr]; - gx1 = dr.ghx; - for i=1:M_.maximum_endo_lead-1 - k1 = find(kstate(:,2) == M_.maximum_endo_lag+i+1); - [k2,junk,k3] = find(kstate(k1,3)); - A(1:M_.endo_nbr,offset+k2) = jacobia_(:,k3+M_.endo_nbr); - n1 = length(k1); - A(offset+[1:n1],nstatic+[1:npred]) = -gx1(kstate(k1,1),1:npred); - gx1 = gx1*hx; - A(offset+[1:n1],offset+[1:n1]) = eye(n1); - n0 = length(k0); - E = eye(n0); - if i == 1 - [junk,junk,k4]=intersect(kstate(k1,1),[1:M_.endo_nbr]); - else - [junk,junk,k4]=intersect(kstate(k1,1),kstate(k0,1)); - end - i1 = offset-n0+n1; - B(offset+[1:n1],offset-n0+[1:n0]) = -E(k4,:); - k0 = k1; - offset = offset + n1; + i1 = offset-n0+n1; + B(offset+[1:n1],offset-n0+[1:n0]) = -E(k4,:); + k0 = k1; + offset = offset + n1; +end +[junk,k1,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+M_.maximum_endo_lead+1,order_var)); +A(1:M_.endo_nbr,nstatic+1:nstatic+npred)=... + A(1:M_.endo_nbr,nstatic+[1:npred])+jacobia_(:,k2)*gx1(k1,1:npred); +C = hx; +D = [rhs; zeros(n-M_.endo_nbr,size(rhs,2))]; + + +dr.ghxx = gensylv(2,A,B,C,D); + +%ghxu +%rhs +hu = dr.ghu(nstatic+1:nstatic+npred,:); +%kk = reshape([1:np*np],np,np); +%kk = kk(1:npred,1:npred); +%rhs = -hessian*kron(zx,zu)-f1*dr.ghxx(end-nyf+1:end,kk(:))*kron(hx(1:npred,:),hu(1:npred,:)); + +rhs = sparse_hessian_times_B_kronecker_C(hessian,zx,zu); + +nyf1 = sum(kstate(:,2) == M_.maximum_endo_lag+2); +hu1 = [hu;zeros(np-npred,M_.exo_nbr)]; +%B1 = [B(1:M_.endo_nbr,:);zeros(size(A,1)-M_.endo_nbr,size(B,2))]; +[nrhx,nchx] = size(hx); +[nrhu1,nchu1] = size(hu1); + +B1 = B*A_times_B_kronecker_C(dr.ghxx,hx,hu1); +rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1; + + +%lhs +dr.ghxu = A\rhs; + +%ghuu +%rhs +kk = reshape([1:np*np],np,np); +kk = kk(1:npred,1:npred); + +rhs = sparse_hessian_times_B_kronecker_C(hessian,zu); + + +B1 = A_times_B_kronecker_C(B*dr.ghxx,hu1); +rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1; + +%lhs +dr.ghuu = A\rhs; + +dr.ghxx = dr.ghxx(1:M_.endo_nbr,:); +dr.ghxu = dr.ghxu(1:M_.endo_nbr,:); +dr.ghuu = dr.ghuu(1:M_.endo_nbr,:); + + +% dr.ghs2 +% derivatives of F with respect to forward variables +% reordering predetermined variables in diminishing lag order +O1 = zeros(M_.endo_nbr,nstatic); +O2 = zeros(M_.endo_nbr,M_.endo_nbr-nstatic-npred); +LHS = jacobia_(:,M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var)); +RHS = zeros(M_.endo_nbr,M_.exo_nbr^2); +kk = find(kstate(:,2) == M_.maximum_endo_lag+2); +gu = dr.ghu; +guu = dr.ghuu; +Gu = [dr.ghu(nstatic+[1:npred],:); zeros(np-npred,M_.exo_nbr)]; +Guu = [dr.ghuu(nstatic+[1:npred],:); zeros(np-npred,M_.exo_nbr*M_.exo_nbr)]; +E = eye(M_.endo_nbr); +M_.lead_lag_incidenceordered = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1)); +if M_.maximum_endo_lag > 0 + M_.lead_lag_incidenceordered = [cumsum(M_.lead_lag_incidence(1:M_.maximum_endo_lag,order_var),1); M_.lead_lag_incidenceordered]; +end +M_.lead_lag_incidenceordered = M_.lead_lag_incidenceordered'; +M_.lead_lag_incidenceordered = M_.lead_lag_incidenceordered(:); +k1 = find(M_.lead_lag_incidenceordered); +M_.lead_lag_incidenceordered(k1) = [1:length(k1)]'; +M_.lead_lag_incidenceordered =reshape(M_.lead_lag_incidenceordered,M_.endo_nbr,M_.maximum_endo_lag+M_.maximum_endo_lead+1)'; +kh = reshape([1:nk^2],nk,nk); +kp = sum(kstate(:,2) <= M_.maximum_endo_lag+1); +E1 = [eye(npred); zeros(kp-npred,npred)]; +H = E1; +hxx = dr.ghxx(nstatic+[1:npred],:); +for i=1:M_.maximum_endo_lead + for j=i:M_.maximum_endo_lead + [junk,k2a,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+j+1,order_var)); + [junk,k3a,k3] = ... + find(M_.lead_lag_incidenceordered(M_.maximum_endo_lag+j+1,:)); + nk3a = length(k3a); + B1 = sparse_hessian_times_B_kronecker_C(hessian(:,kh(k3,k3)),gu(k3a,:)); + RHS = RHS + jacobia_(:,k2)*guu(k2a,:)+B1; end - [junk,k1,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+M_.maximum_endo_lead+1,order_var)); - A(1:M_.endo_nbr,nstatic+1:nstatic+npred)=... - A(1:M_.endo_nbr,nstatic+[1:npred])+jacobia_(:,k2)*gx1(k1,1:npred); - C = hx; - D = [rhs; zeros(n-M_.endo_nbr,size(rhs,2))]; - - - dr.ghxx = gensylv(2,A,B,C,D); - - %ghxu - %rhs - hu = dr.ghu(nstatic+1:nstatic+npred,:); - %kk = reshape([1:np*np],np,np); - %kk = kk(1:npred,1:npred); - %rhs = -hessian*kron(zx,zu)-f1*dr.ghxx(end-nyf+1:end,kk(:))*kron(hx(1:npred,:),hu(1:npred,:)); - - rhs = sparse_hessian_times_B_kronecker_C(hessian,zx,zu); - - nyf1 = sum(kstate(:,2) == M_.maximum_endo_lag+2); - hu1 = [hu;zeros(np-npred,M_.exo_nbr)]; - %B1 = [B(1:M_.endo_nbr,:);zeros(size(A,1)-M_.endo_nbr,size(B,2))]; - [nrhx,nchx] = size(hx); - [nrhu1,nchu1] = size(hu1); - - B1 = B*A_times_B_kronecker_C(dr.ghxx,hx,hu1); - rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1; - - - %lhs - dr.ghxu = A\rhs; - - %ghuu - %rhs - kk = reshape([1:np*np],np,np); - kk = kk(1:npred,1:npred); - - rhs = sparse_hessian_times_B_kronecker_C(hessian,zu); - - - B1 = A_times_B_kronecker_C(B*dr.ghxx,hu1); - rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1; - - %lhs - dr.ghuu = A\rhs; - - dr.ghxx = dr.ghxx(1:M_.endo_nbr,:); - dr.ghxu = dr.ghxu(1:M_.endo_nbr,:); - dr.ghuu = dr.ghuu(1:M_.endo_nbr,:); + % LHS + [junk,k2a,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+i+1,order_var)); + LHS = LHS + jacobia_(:,k2)*(E(k2a,:)+[O1(k2a,:) dr.ghx(k2a,:)*H O2(k2a,:)]); + if i == M_.maximum_endo_lead + break + end - % dr.ghs2 - % derivatives of F with respect to forward variables - % reordering predetermined variables in diminishing lag order - O1 = zeros(M_.endo_nbr,nstatic); - O2 = zeros(M_.endo_nbr,M_.endo_nbr-nstatic-npred); - LHS = jacobia_(:,M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var)); - RHS = zeros(M_.endo_nbr,M_.exo_nbr^2); - kk = find(kstate(:,2) == M_.maximum_endo_lag+2); - gu = dr.ghu; - guu = dr.ghuu; - Gu = [dr.ghu(nstatic+[1:npred],:); zeros(np-npred,M_.exo_nbr)]; - Guu = [dr.ghuu(nstatic+[1:npred],:); zeros(np-npred,M_.exo_nbr*M_.exo_nbr)]; - E = eye(M_.endo_nbr); - M_.lead_lag_incidenceordered = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1)); - if M_.maximum_endo_lag > 0 - M_.lead_lag_incidenceordered = [cumsum(M_.lead_lag_incidence(1:M_.maximum_endo_lag,order_var),1); M_.lead_lag_incidenceordered]; + kk = find(kstate(:,2) == M_.maximum_endo_lag+i+1); + gu = dr.ghx*Gu; + [nrGu,ncGu] = size(Gu); + G1 = A_times_B_kronecker_C(dr.ghxx,Gu); + G2 = A_times_B_kronecker_C(hxx,Gu); + guu = dr.ghx*Guu+G1; + Gu = hx*Gu; + Guu = hx*Guu; + Guu(end-npred+1:end,:) = Guu(end-npred+1:end,:) + G2; + H = E1 + hx*H; +end +RHS = RHS*M_.Sigma_e(:); +dr.fuu = RHS; +%RHS = -RHS-dr.fbias; +RHS = -RHS; +dr.ghs2 = LHS\RHS; + +% deterministic exogenous variables +if M_.exo_det_nbr > 0 + hud = dr.ghud{1}(nstatic+1:nstatic+npred,:); + zud=[zeros(np,M_.exo_det_nbr);dr.ghud{1};gx(:,1:npred)*hud;zeros(M_.exo_nbr,M_.exo_det_nbr);eye(M_.exo_det_nbr)]; + R1 = hessian*kron(zx,zud); + dr.ghxud = cell(M_.exo_det_length,1); + kf = [M_.endo_nbr-nyf+1:M_.endo_nbr]; + kp = nstatic+[1:npred]; + dr.ghxud{1} = -M1*(R1+f1*dr.ghxx(kf,:)*kron(dr.ghx(kp,:),dr.ghud{1}(kp,:))); + Eud = eye(M_.exo_det_nbr); + for i = 2:M_.exo_det_length + hudi = dr.ghud{i}(kp,:); + zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)]; + R2 = hessian*kron(zx,zudi); + dr.ghxud{i} = -M2*(dr.ghxud{i-1}(kf,:)*kron(hx,Eud)+dr.ghxx(kf,:)*kron(dr.ghx(kp,:),dr.ghud{i}(kp,:)))-M1*R2; end - M_.lead_lag_incidenceordered = M_.lead_lag_incidenceordered'; - M_.lead_lag_incidenceordered = M_.lead_lag_incidenceordered(:); - k1 = find(M_.lead_lag_incidenceordered); - M_.lead_lag_incidenceordered(k1) = [1:length(k1)]'; - M_.lead_lag_incidenceordered =reshape(M_.lead_lag_incidenceordered,M_.endo_nbr,M_.maximum_endo_lag+M_.maximum_endo_lead+1)'; - kh = reshape([1:nk^2],nk,nk); - kp = sum(kstate(:,2) <= M_.maximum_endo_lag+1); - E1 = [eye(npred); zeros(kp-npred,npred)]; - H = E1; - hxx = dr.ghxx(nstatic+[1:npred],:); - for i=1:M_.maximum_endo_lead - for j=i:M_.maximum_endo_lead - [junk,k2a,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+j+1,order_var)); - [junk,k3a,k3] = ... - find(M_.lead_lag_incidenceordered(M_.maximum_endo_lag+j+1,:)); - nk3a = length(k3a); - B1 = sparse_hessian_times_B_kronecker_C(hessian(:,kh(k3,k3)),gu(k3a,:)); - RHS = RHS + jacobia_(:,k2)*guu(k2a,:)+B1; - end - % LHS - [junk,k2a,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+i+1,order_var)); - LHS = LHS + jacobia_(:,k2)*(E(k2a,:)+[O1(k2a,:) dr.ghx(k2a,:)*H O2(k2a,:)]); - - if i == M_.maximum_endo_lead - break - end - - kk = find(kstate(:,2) == M_.maximum_endo_lag+i+1); - gu = dr.ghx*Gu; - [nrGu,ncGu] = size(Gu); - G1 = A_times_B_kronecker_C(dr.ghxx,Gu); - G2 = A_times_B_kronecker_C(hxx,Gu); - guu = dr.ghx*Guu+G1; - Gu = hx*Gu; - Guu = hx*Guu; - Guu(end-npred+1:end,:) = Guu(end-npred+1:end,:) + G2; - H = E1 + hx*H; + R1 = hessian*kron(zu,zud); + dr.ghudud = cell(M_.exo_det_length,1); + kf = [M_.endo_nbr-nyf+1:M_.endo_nbr]; + + dr.ghuud{1} = -M1*(R1+f1*dr.ghxx(kf,:)*kron(dr.ghu(kp,:),dr.ghud{1}(kp,:))); + Eud = eye(M_.exo_det_nbr); + for i = 2:M_.exo_det_length + hudi = dr.ghud{i}(kp,:); + zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)]; + R2 = hessian*kron(zu,zudi); + dr.ghuud{i} = -M2*dr.ghxud{i-1}(kf,:)*kron(hu,Eud)-M1*R2; end - RHS = RHS*M_.Sigma_e(:); - dr.fuu = RHS; - %RHS = -RHS-dr.fbias; - RHS = -RHS; - dr.ghs2 = LHS\RHS; - - % deterministic exogenous variables - if M_.exo_det_nbr > 0 - hud = dr.ghud{1}(nstatic+1:nstatic+npred,:); - zud=[zeros(np,M_.exo_det_nbr);dr.ghud{1};gx(:,1:npred)*hud;zeros(M_.exo_nbr,M_.exo_det_nbr);eye(M_.exo_det_nbr)]; - R1 = hessian*kron(zx,zud); - dr.ghxud = cell(M_.exo_det_length,1); - kf = [M_.endo_nbr-nyf+1:M_.endo_nbr]; - kp = nstatic+[1:npred]; - dr.ghxud{1} = -M1*(R1+f1*dr.ghxx(kf,:)*kron(dr.ghx(kp,:),dr.ghud{1}(kp,:))); - Eud = eye(M_.exo_det_nbr); - for i = 2:M_.exo_det_length - hudi = dr.ghud{i}(kp,:); - zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)]; - R2 = hessian*kron(zx,zudi); - dr.ghxud{i} = -M2*(dr.ghxud{i-1}(kf,:)*kron(hx,Eud)+dr.ghxx(kf,:)*kron(dr.ghx(kp,:),dr.ghud{i}(kp,:)))-M1*R2; + R1 = hessian*kron(zud,zud); + dr.ghudud = cell(M_.exo_det_length,M_.exo_det_length); + dr.ghudud{1,1} = -M1*R1-M2*dr.ghxx(kf,:)*kron(hud,hud); + for i = 2:M_.exo_det_length + hudi = dr.ghud{i}(nstatic+1:nstatic+npred,:); + zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi+dr.ghud{i-1}(kf,:);zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)]; + R2 = hessian*kron(zudi,zudi); + dr.ghudud{i,i} = -M2*(dr.ghudud{i-1,i-1}(kf,:)+... + 2*dr.ghxud{i-1}(kf,:)*kron(hudi,Eud) ... + +dr.ghxx(kf,:)*kron(hudi,hudi))-M1*R2; + R2 = hessian*kron(zud,zudi); + dr.ghudud{1,i} = -M2*(dr.ghxud{i-1}(kf,:)*kron(hud,Eud)+... + dr.ghxx(kf,:)*kron(hud,hudi))... + -M1*R2; + for j=2:i-1 + hudj = dr.ghud{j}(kp,:); + zudj=[zeros(np,M_.exo_det_nbr);dr.ghud{j};gx(:,1:npred)*hudj;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)]; + R2 = hessian*kron(zudj,zudi); + dr.ghudud{j,i} = -M2*(dr.ghudud{j-1,i-1}(kf,:)+dr.ghxud{j-1}(kf,:)* ... + kron(hudi,Eud)+dr.ghxud{i-1}(kf,:)* ... + kron(hudj,Eud)+dr.ghxx(kf,:)*kron(hudj,hudi))-M1*R2; end - R1 = hessian*kron(zu,zud); - dr.ghudud = cell(M_.exo_det_length,1); - kf = [M_.endo_nbr-nyf+1:M_.endo_nbr]; - dr.ghuud{1} = -M1*(R1+f1*dr.ghxx(kf,:)*kron(dr.ghu(kp,:),dr.ghud{1}(kp,:))); - Eud = eye(M_.exo_det_nbr); - for i = 2:M_.exo_det_length - hudi = dr.ghud{i}(kp,:); - zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)]; - R2 = hessian*kron(zu,zudi); - dr.ghuud{i} = -M2*dr.ghxud{i-1}(kf,:)*kron(hu,Eud)-M1*R2; - end - R1 = hessian*kron(zud,zud); - dr.ghudud = cell(M_.exo_det_length,M_.exo_det_length); - dr.ghudud{1,1} = -M1*R1-M2*dr.ghxx(kf,:)*kron(hud,hud); - for i = 2:M_.exo_det_length - hudi = dr.ghud{i}(nstatic+1:nstatic+npred,:); - zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi+dr.ghud{i-1}(kf,:);zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)]; - R2 = hessian*kron(zudi,zudi); - dr.ghudud{i,i} = -M2*(dr.ghudud{i-1,i-1}(kf,:)+... - 2*dr.ghxud{i-1}(kf,:)*kron(hudi,Eud) ... - +dr.ghxx(kf,:)*kron(hudi,hudi))-M1*R2; - R2 = hessian*kron(zud,zudi); - dr.ghudud{1,i} = -M2*(dr.ghxud{i-1}(kf,:)*kron(hud,Eud)+... - dr.ghxx(kf,:)*kron(hud,hudi))... - -M1*R2; - for j=2:i-1 - hudj = dr.ghud{j}(kp,:); - zudj=[zeros(np,M_.exo_det_nbr);dr.ghud{j};gx(:,1:npred)*hudj;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)]; - R2 = hessian*kron(zudj,zudi); - dr.ghudud{j,i} = -M2*(dr.ghudud{j-1,i-1}(kf,:)+dr.ghxud{j-1}(kf,:)* ... - kron(hudi,Eud)+dr.ghxud{i-1}(kf,:)* ... - kron(hudj,Eud)+dr.ghxx(kf,:)*kron(hudj,hudi))-M1*R2; - end - - end end +end diff --git a/matlab/dr11_sparse.m b/matlab/dr11_sparse.m index 2d9a981ef0..742a1689a9 100644 --- a/matlab/dr11_sparse.m +++ b/matlab/dr11_sparse.m @@ -1,489 +1,489 @@ -function [dr,info,M_,options_,oo_] = dr11_sparse(dr,task,M_,options_,oo_, jacobia_, hessian) -%function [dr,info,M_,options_,oo_] = dr11_sparse(dr,task,M_,options_,oo_, jacobia_, hessian) - -% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. - %task - info = 0; - klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1; - kstate = dr.kstate; - kad = dr.kad; - kae = dr.kae; - nstatic = dr.nstatic; - nfwrd = dr.nfwrd; - npred = dr.npred; - nboth = dr.nboth; - order_var = dr.order_var; - nd = size(kstate,1); - nz = nnz(M_.lead_lag_incidence); - - sdyn = M_.endo_nbr - nstatic; - k0 = M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var); - k1 = M_.lead_lag_incidence(find([1:klen] ~= M_.maximum_endo_lag+1),:); - b = jacobia_(:,k0); - - if M_.maximum_endo_lead == 0; % backward models - a = jacobia_(:,nonzeros(k1')); - dr.ghx = zeros(size(a)); - m = 0; - for i=M_.maximum_endo_lag:-1:1 - k = nonzeros(M_.lead_lag_incidence(i,order_var)); - dr.ghx(:,m+[1:length(k)]) = -b\a(:,k); - m = m+length(k); - end - if M_.exo_nbr & task~=1 - jacobia_ - jacobia_(:,nz+1:end) - b - dr.ghu = -b\jacobia_(:,nz+1:end); - disp(['nz=' int2str(nz) ]); - dr.ghu - end - dr.eigval = eig(transition_matrix(dr,M_)); - dr.rank = 0; - if any(abs(dr.eigval) > options_.qz_criterium) - temp = sort(abs(dr.eigval)); - nba = nnz(abs(dr.eigval) > options_.qz_criterium); - temp = temp(nd-nba+1:nd)-1-options_.qz_criterium; - info(1) = 3; - info(2) = temp'*temp; - end - return; - end - %forward--looking models - if nstatic > 0 - [Q,R] = qr(b(:,1:nstatic)); - aa = Q'*jacobia_; - else - aa = jacobia_; - end - a = aa(:,nonzeros(k1')); - b = aa(:,k0); - b10 = b(1:nstatic,1:nstatic); - b11 = b(1:nstatic,nstatic+1:end); - b2 = b(nstatic+1:end,nstatic+1:end); - if any(isinf(a(:))) - info = 1; - return - end - - % buildind D and E - %nd - d = zeros(nd,nd) ; - e = d ; - k = find(kstate(:,2) >= M_.maximum_endo_lag+2 & kstate(:,3)); - d(1:sdyn,k) = a(nstatic+1:end,kstate(k,3)) ; - k1 = find(kstate(:,2) == M_.maximum_endo_lag+2); - e(1:sdyn,k1) = -b2(:,kstate(k1,1)-nstatic); - k = find(kstate(:,2) <= M_.maximum_endo_lag+1 & kstate(:,4)); - e(1:sdyn,k) = -a(nstatic+1:end,kstate(k,4)) ; - k2 = find(kstate(:,2) == M_.maximum_endo_lag+1); - k2 = k2(~ismember(kstate(k2,1),kstate(k1,1))); - d(1:sdyn,k2) = b2(:,kstate(k2,1)-nstatic); - - if ~isempty(kad) - for j = 1:size(kad,1) - d(sdyn+j,kad(j)) = 1 ; - e(sdyn+j,kae(j)) = 1 ; - end - end - %e - %d - - [ss,tt,w,sdim,dr.eigval,info1] = mjdgges(e,d,options_.qz_criterium); - - - if info1 - info(1) = 2; - info(2) = info1; - return - end - - nba = nd-sdim; - - nyf = sum(kstate(:,2) > M_.maximum_endo_lag+1); - - if task == 1 - dr.rank = rank(w(1:nyf,nd-nyf+1:end)); - % Under Octave, eig(A,B) doesn't exist, and - % lambda = qz(A,B) won't return infinite eigenvalues - if ~exist('OCTAVE_VERSION') - dr.eigval = eig(e,d); - end - return - end - - if nba ~= nyf - temp = sort(abs(dr.eigval)); - if nba > nyf - temp = temp(nd-nba+1:nd-nyf)-1-options_.qz_criterium; - info(1) = 3; - elseif nba < nyf; - temp = temp(nd-nyf+1:nd-nba)-1-options_.qz_criterium; - info(1) = 4; - end - info(2) = temp'*temp; - return - end - - np = nd - nyf; - n2 = np + 1; - n3 = nyf; - n4 = n3 + 1; - % derivatives with respect to dynamic state variables - % forward variables - w1 =w(1:n3,n2:nd); - if condest(w1) > 1e9; - info(1) = 5; - info(2) = condest(w1); - return; - else - gx = -w1'\w(n4:nd,n2:nd)'; - end - - % predetermined variables - hx = w(1:n3,1:np)'*gx+w(n4:nd,1:np)'; - hx = (tt(1:np,1:np)*hx)\(ss(1:np,1:np)*hx); - - k1 = find(kstate(n4:nd,2) == M_.maximum_endo_lag+1); - k2 = find(kstate(1:n3,2) == M_.maximum_endo_lag+2); - hx(k1,:) - gx(k2(nboth+1:end),:) - dr.ghx = [hx(k1,:); gx(k2(nboth+1:end),:)]; - dr.ghx - %lead variables actually present in the model - j3 = nonzeros(kstate(:,3)); - j4 = find(kstate(:,3)); - % derivatives with respect to exogenous variables - disp(['M_.exo_nbr=' int2str(M_.exo_nbr)]); - if M_.exo_nbr - fu = aa(:,nz+(1:M_.exo_nbr)); - a1 = b; - aa1 = []; - if nstatic > 0 - aa1 = a1(:,1:nstatic); - end - dr.ghu = -[aa1 a(:,j3)*gx(j4,1:npred)+a1(:,nstatic+1:nstatic+ ... - npred) a1(:,nstatic+npred+1:end)]\fu; - else - dr.ghu = []; - end - - % static variables - if nstatic > 0 - temp = -a(1:nstatic,j3)*gx(j4,:)*hx; - j5 = find(kstate(n4:nd,4)); - temp(:,j5) = temp(:,j5)-a(1:nstatic,nonzeros(kstate(:,4))); - temp = b10\(temp-b11*dr.ghx); - dr.ghx = [temp; dr.ghx]; - temp = []; - end - - if options_.loglinear == 1 - k = find(dr.kstate(:,2) <= M_.maximum_endo_lag+1); - klag = dr.kstate(k,[1 2]); - k1 = dr.order_var; - - dr.ghx = repmat(1./dr.ys(k1),1,size(dr.ghx,2)).*dr.ghx.* ... - repmat(dr.ys(k1(klag(:,1)))',size(dr.ghx,1),1); - dr.ghu = repmat(1./dr.ys(k1),1,size(dr.ghu,2)).*dr.ghu; - end - - %% Necessary when using Sims' routines for QZ - if options_.use_qzdiv - gx = real(gx); - hx = real(hx); - dr.ghx = real(dr.ghx); - dr.ghu = real(dr.ghu); - end - - %exogenous deterministic variables - if M_.exo_det_nbr > 0 - f1 = sparse(jacobia_(:,nonzeros(M_.lead_lag_incidence(M_.maximum_endo_lag+2:end,order_var)))); - f0 = sparse(jacobia_(:,nonzeros(M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var)))); - fudet = sparse(jacobia_(:,nz+M_.exo_nbr+1:end)); - M1 = inv(f0+[zeros(M_.endo_nbr,nstatic) f1*gx zeros(M_.endo_nbr,nyf-nboth)]); - M2 = M1*f1; - dr.ghud = cell(M_.exo_det_length,1); - dr.ghud{1} = -M1*fudet; - for i = 2:M_.exo_det_length - dr.ghud{i} = -M2*dr.ghud{i-1}(end-nyf+1:end,:); - end - end - if options_.order == 1 - return - end - - % Second order - %tempex = oo_.exo_simul ; - - %hessian = real(hessext('ff1_',[z; oo_.exo_steady_state]))' ; - kk = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1)); - if M_.maximum_endo_lag > 0 - kk = [cumsum(M_.lead_lag_incidence(1:M_.maximum_endo_lag,order_var),1); kk]; - end - kk = kk'; - kk = find(kk(:)); - nk = size(kk,1) + M_.exo_nbr + M_.exo_det_nbr; - k1 = M_.lead_lag_incidence(:,order_var); - k1 = k1'; - k1 = k1(:); - k1 = k1(kk); - k2 = find(k1); - kk1(k1(k2)) = k2; - kk1 = [kk1 length(k1)+1:length(k1)+M_.exo_nbr+M_.exo_det_nbr]; - kk = reshape([1:nk^2],nk,nk); - kk1 = kk(kk1,kk1); - %[junk,junk,hessian] = feval([M_.fname '_dynamic'],z, oo_.exo_steady_state); - hessian(:,kk1(:)) = hessian; - - %oo_.exo_simul = tempex ; - %clear tempex - - n1 = 0; - n2 = np; - zx = zeros(np,np); - zu=zeros(np,M_.exo_nbr); - for i=2:M_.maximum_endo_lag+1 - k1 = sum(kstate(:,2) == i); - zx(n1+1:n1+k1,n2-k1+1:n2)=eye(k1); - n1 = n1+k1; - n2 = n2-k1; - end - kk = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1)); - k0 = [1:M_.endo_nbr]; - gx1 = dr.ghx; - hu = dr.ghu(nstatic+[1:npred],:); - zx = [zx; gx1]; - zu = [zu; dr.ghu]; - for i=1:M_.maximum_endo_lead - k1 = find(kk(i+1,k0) > 0); - zu = [zu; gx1(k1,1:npred)*hu]; - gx1 = gx1(k1,:)*hx; - zx = [zx; gx1]; - kk = kk(:,k0); - k0 = k1; - end - zx=[zx; zeros(M_.exo_nbr,np);zeros(M_.exo_det_nbr,np)]; - zu=[zu; eye(M_.exo_nbr);zeros(M_.exo_det_nbr,M_.exo_nbr)]; - [nrzx,nczx] = size(zx); - - rhs = -sparse_hessian_times_B_kronecker_C(hessian,zx); - - %lhs - n = M_.endo_nbr+sum(kstate(:,2) > M_.maximum_endo_lag+1 & kstate(:,2) < M_.maximum_endo_lag+M_.maximum_endo_lead+1); - A = zeros(n,n); - B = zeros(n,n); - A(1:M_.endo_nbr,1:M_.endo_nbr) = jacobia_(:,M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var)); - % variables with the highest lead - k1 = find(kstate(:,2) == M_.maximum_endo_lag+M_.maximum_endo_lead+1); - if M_.maximum_endo_lead > 1 - k2 = find(kstate(:,2) == M_.maximum_endo_lag+M_.maximum_endo_lead); - [junk,junk,k3] = intersect(kstate(k1,1),kstate(k2,1)); - else - k2 = [1:M_.endo_nbr]; - k3 = kstate(k1,1); - end - % Jacobian with respect to the variables with the highest lead - B(1:M_.endo_nbr,end-length(k2)+k3) = jacobia_(:,kstate(k1,3)+M_.endo_nbr); - offset = M_.endo_nbr; - k0 = [1:M_.endo_nbr]; - gx1 = dr.ghx; - for i=1:M_.maximum_endo_lead-1 - k1 = find(kstate(:,2) == M_.maximum_endo_lag+i+1); - [k2,junk,k3] = find(kstate(k1,3)); - A(1:M_.endo_nbr,offset+k2) = jacobia_(:,k3+M_.endo_nbr); - n1 = length(k1); - A(offset+[1:n1],nstatic+[1:npred]) = -gx1(kstate(k1,1),1:npred); - gx1 = gx1*hx; - A(offset+[1:n1],offset+[1:n1]) = eye(n1); - n0 = length(k0); - E = eye(n0); - if i == 1 - [junk,junk,k4]=intersect(kstate(k1,1),[1:M_.endo_nbr]); - else - [junk,junk,k4]=intersect(kstate(k1,1),kstate(k0,1)); - end - i1 = offset-n0+n1; - B(offset+[1:n1],offset-n0+[1:n0]) = -E(k4,:); - k0 = k1; - offset = offset + n1; - end - [junk,k1,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+M_.maximum_endo_lead+1,order_var)); - A(1:M_.endo_nbr,nstatic+1:nstatic+npred)=... - A(1:M_.endo_nbr,nstatic+[1:npred])+jacobia_(:,k2)*gx1(k1,1:npred); - C = hx; - D = [rhs; zeros(n-M_.endo_nbr,size(rhs,2))]; - - - dr.ghxx = gensylv(2,A,B,C,D); - - %ghxu - %rhs - hu = dr.ghu(nstatic+1:nstatic+npred,:); - %kk = reshape([1:np*np],np,np); - %kk = kk(1:npred,1:npred); - %rhs = -hessian*kron(zx,zu)-f1*dr.ghxx(end-nyf+1:end,kk(:))*kron(hx(1:npred,:),hu(1:npred,:)); - - rhs = sparse_hessian_times_B_kronecker_C(hessian,zx,zu); - - nyf1 = sum(kstate(:,2) == M_.maximum_endo_lag+2); - hu1 = [hu;zeros(np-npred,M_.exo_nbr)]; - %B1 = [B(1:M_.endo_nbr,:);zeros(size(A,1)-M_.endo_nbr,size(B,2))]; - [nrhx,nchx] = size(hx); - [nrhu1,nchu1] = size(hu1); - - B1 = B*A_times_B_kronecker_C(dr.ghxx,hx,hu1); - rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1; - - - %lhs - dr.ghxu = A\rhs; - - %ghuu - %rhs - kk = reshape([1:np*np],np,np); - kk = kk(1:npred,1:npred); - - rhs = sparse_hessian_times_B_kronecker_C(hessian,zu); - - - B1 = A_times_B_kronecker_C(B*dr.ghxx,hu1); - rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1; - - %lhs - dr.ghuu = A\rhs; - - dr.ghxx = dr.ghxx(1:M_.endo_nbr,:); - dr.ghxu = dr.ghxu(1:M_.endo_nbr,:); - dr.ghuu = dr.ghuu(1:M_.endo_nbr,:); - - - % dr.ghs2 - % derivatives of F with respect to forward variables - % reordering predetermined variables in diminishing lag order - O1 = zeros(M_.endo_nbr,nstatic); - O2 = zeros(M_.endo_nbr,M_.endo_nbr-nstatic-npred); - LHS = jacobia_(:,M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var)); - RHS = zeros(M_.endo_nbr,M_.exo_nbr^2); - kk = find(kstate(:,2) == M_.maximum_endo_lag+2); - gu = dr.ghu; - guu = dr.ghuu; - Gu = [dr.ghu(nstatic+[1:npred],:); zeros(np-npred,M_.exo_nbr)]; - Guu = [dr.ghuu(nstatic+[1:npred],:); zeros(np-npred,M_.exo_nbr*M_.exo_nbr)]; - E = eye(M_.endo_nbr); - M_.lead_lag_incidenceordered = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1)); - if M_.maximum_endo_lag > 0 - M_.lead_lag_incidenceordered = [cumsum(M_.lead_lag_incidence(1:M_.maximum_endo_lag,order_var),1); M_.lead_lag_incidenceordered]; - end - M_.lead_lag_incidenceordered = M_.lead_lag_incidenceordered'; - M_.lead_lag_incidenceordered = M_.lead_lag_incidenceordered(:); - k1 = find(M_.lead_lag_incidenceordered); - M_.lead_lag_incidenceordered(k1) = [1:length(k1)]'; - M_.lead_lag_incidenceordered =reshape(M_.lead_lag_incidenceordered,M_.endo_nbr,M_.maximum_endo_lag+M_.maximum_endo_lead+1)'; - kh = reshape([1:nk^2],nk,nk); - kp = sum(kstate(:,2) <= M_.maximum_endo_lag+1); - E1 = [eye(npred); zeros(kp-npred,npred)]; - H = E1; - hxx = dr.ghxx(nstatic+[1:npred],:); - for i=1:M_.maximum_endo_lead - for j=i:M_.maximum_endo_lead - [junk,k2a,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+j+1,order_var)); - [junk,k3a,k3] = ... - find(M_.lead_lag_incidenceordered(M_.maximum_endo_lag+j+1,:)); - nk3a = length(k3a); - B1 = sparse_hessian_times_B_kronecker_C(hessian(:,kh(k3,k3)),gu(k3a,:)); - RHS = RHS + jacobia_(:,k2)*guu(k2a,:)+B1; - end - % LHS - [junk,k2a,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+i+1,order_var)); - LHS = LHS + jacobia_(:,k2)*(E(k2a,:)+[O1(k2a,:) dr.ghx(k2a,:)*H O2(k2a,:)]); - - if i == M_.maximum_endo_lead - break - end - - kk = find(kstate(:,2) == M_.maximum_endo_lag+i+1); - gu = dr.ghx*Gu; - [nrGu,ncGu] = size(Gu); - G1 = A_times_B_kronecker_C(dr.ghxx,Gu); - G2 = A_times_B_kronecker_C(hxx,Gu); - guu = dr.ghx*Guu+G1; - Gu = hx*Gu; - Guu = hx*Guu; - Guu(end-npred+1:end,:) = Guu(end-npred+1:end,:) + G2; - H = E1 + hx*H; - end - RHS = RHS*M_.Sigma_e(:); - dr.fuu = RHS; - %RHS = -RHS-dr.fbias; - RHS = -RHS; - dr.ghs2 = LHS\RHS; - - % deterministic exogenous variables - if M_.exo_det_nbr > 0 - hud = dr.ghud{1}(nstatic+1:nstatic+npred,:); - zud=[zeros(np,M_.exo_det_nbr);dr.ghud{1};gx(:,1:npred)*hud;zeros(M_.exo_nbr,M_.exo_det_nbr);eye(M_.exo_det_nbr)]; - R1 = hessian*kron(zx,zud); - dr.ghxud = cell(M_.exo_det_length,1); - kf = [M_.endo_nbr-nyf+1:M_.endo_nbr]; - kp = nstatic+[1:npred]; - dr.ghxud{1} = -M1*(R1+f1*dr.ghxx(kf,:)*kron(dr.ghx(kp,:),dr.ghud{1}(kp,:))); - Eud = eye(M_.exo_det_nbr); - for i = 2:M_.exo_det_length - hudi = dr.ghud{i}(kp,:); - zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)]; - R2 = hessian*kron(zx,zudi); - dr.ghxud{i} = -M2*(dr.ghxud{i-1}(kf,:)*kron(hx,Eud)+dr.ghxx(kf,:)*kron(dr.ghx(kp,:),dr.ghud{i}(kp,:)))-M1*R2; - end - R1 = hessian*kron(zu,zud); - dr.ghudud = cell(M_.exo_det_length,1); - kf = [M_.endo_nbr-nyf+1:M_.endo_nbr]; - - dr.ghuud{1} = -M1*(R1+f1*dr.ghxx(kf,:)*kron(dr.ghu(kp,:),dr.ghud{1}(kp,:))); - Eud = eye(M_.exo_det_nbr); - for i = 2:M_.exo_det_length - hudi = dr.ghud{i}(kp,:); - zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)]; - R2 = hessian*kron(zu,zudi); - dr.ghuud{i} = -M2*dr.ghxud{i-1}(kf,:)*kron(hu,Eud)-M1*R2; - end - R1 = hessian*kron(zud,zud); - dr.ghudud = cell(M_.exo_det_length,M_.exo_det_length); - dr.ghudud{1,1} = -M1*R1-M2*dr.ghxx(kf,:)*kron(hud,hud); - for i = 2:M_.exo_det_length - hudi = dr.ghud{i}(nstatic+1:nstatic+npred,:); - zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi+dr.ghud{i-1}(kf,:);zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)]; - R2 = hessian*kron(zudi,zudi); - dr.ghudud{i,i} = -M2*(dr.ghudud{i-1,i-1}(kf,:)+... - 2*dr.ghxud{i-1}(kf,:)*kron(hudi,Eud) ... - +dr.ghxx(kf,:)*kron(hudi,hudi))-M1*R2; - R2 = hessian*kron(zud,zudi); - dr.ghudud{1,i} = -M2*(dr.ghxud{i-1}(kf,:)*kron(hud,Eud)+... - dr.ghxx(kf,:)*kron(hud,hudi))... - -M1*R2; - for j=2:i-1 - hudj = dr.ghud{j}(kp,:); - zudj=[zeros(np,M_.exo_det_nbr);dr.ghud{j};gx(:,1:npred)*hudj;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)]; - R2 = hessian*kron(zudj,zudi); - dr.ghudud{j,i} = -M2*(dr.ghudud{j-1,i-1}(kf,:)+dr.ghxud{j-1}(kf,:)* ... - kron(hudi,Eud)+dr.ghxud{i-1}(kf,:)* ... - kron(hudj,Eud)+dr.ghxx(kf,:)*kron(hudj,hudi))-M1*R2; - end - - end - end \ No newline at end of file +function [dr,info,M_,options_,oo_] = dr11_sparse(dr,task,M_,options_,oo_, jacobia_, hessian) +%function [dr,info,M_,options_,oo_] = dr11_sparse(dr,task,M_,options_,oo_, jacobia_, hessian) + +% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. +%task +info = 0; +klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1; +kstate = dr.kstate; +kad = dr.kad; +kae = dr.kae; +nstatic = dr.nstatic; +nfwrd = dr.nfwrd; +npred = dr.npred; +nboth = dr.nboth; +order_var = dr.order_var; +nd = size(kstate,1); +nz = nnz(M_.lead_lag_incidence); + +sdyn = M_.endo_nbr - nstatic; +k0 = M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var); +k1 = M_.lead_lag_incidence(find([1:klen] ~= M_.maximum_endo_lag+1),:); +b = jacobia_(:,k0); + +if M_.maximum_endo_lead == 0; % backward models + a = jacobia_(:,nonzeros(k1')); + dr.ghx = zeros(size(a)); + m = 0; + for i=M_.maximum_endo_lag:-1:1 + k = nonzeros(M_.lead_lag_incidence(i,order_var)); + dr.ghx(:,m+[1:length(k)]) = -b\a(:,k); + m = m+length(k); + end + if M_.exo_nbr & task~=1 + jacobia_ + jacobia_(:,nz+1:end) + b + dr.ghu = -b\jacobia_(:,nz+1:end); + disp(['nz=' int2str(nz) ]); + dr.ghu + end + dr.eigval = eig(transition_matrix(dr,M_)); + dr.rank = 0; + if any(abs(dr.eigval) > options_.qz_criterium) + temp = sort(abs(dr.eigval)); + nba = nnz(abs(dr.eigval) > options_.qz_criterium); + temp = temp(nd-nba+1:nd)-1-options_.qz_criterium; + info(1) = 3; + info(2) = temp'*temp; + end + return; +end +%forward--looking models +if nstatic > 0 + [Q,R] = qr(b(:,1:nstatic)); + aa = Q'*jacobia_; +else + aa = jacobia_; +end +a = aa(:,nonzeros(k1')); +b = aa(:,k0); +b10 = b(1:nstatic,1:nstatic); +b11 = b(1:nstatic,nstatic+1:end); +b2 = b(nstatic+1:end,nstatic+1:end); +if any(isinf(a(:))) + info = 1; + return +end + +% buildind D and E +%nd +d = zeros(nd,nd) ; +e = d ; +k = find(kstate(:,2) >= M_.maximum_endo_lag+2 & kstate(:,3)); +d(1:sdyn,k) = a(nstatic+1:end,kstate(k,3)) ; +k1 = find(kstate(:,2) == M_.maximum_endo_lag+2); +e(1:sdyn,k1) = -b2(:,kstate(k1,1)-nstatic); +k = find(kstate(:,2) <= M_.maximum_endo_lag+1 & kstate(:,4)); +e(1:sdyn,k) = -a(nstatic+1:end,kstate(k,4)) ; +k2 = find(kstate(:,2) == M_.maximum_endo_lag+1); +k2 = k2(~ismember(kstate(k2,1),kstate(k1,1))); +d(1:sdyn,k2) = b2(:,kstate(k2,1)-nstatic); + +if ~isempty(kad) + for j = 1:size(kad,1) + d(sdyn+j,kad(j)) = 1 ; + e(sdyn+j,kae(j)) = 1 ; + end +end +%e +%d + +[ss,tt,w,sdim,dr.eigval,info1] = mjdgges(e,d,options_.qz_criterium); + + +if info1 + info(1) = 2; + info(2) = info1; + return +end + +nba = nd-sdim; + +nyf = sum(kstate(:,2) > M_.maximum_endo_lag+1); + +if task == 1 + dr.rank = rank(w(1:nyf,nd-nyf+1:end)); + % Under Octave, eig(A,B) doesn't exist, and + % lambda = qz(A,B) won't return infinite eigenvalues + if ~exist('OCTAVE_VERSION') + dr.eigval = eig(e,d); + end + return +end + +if nba ~= nyf + temp = sort(abs(dr.eigval)); + if nba > nyf + temp = temp(nd-nba+1:nd-nyf)-1-options_.qz_criterium; + info(1) = 3; + elseif nba < nyf; + temp = temp(nd-nyf+1:nd-nba)-1-options_.qz_criterium; + info(1) = 4; + end + info(2) = temp'*temp; + return +end + +np = nd - nyf; +n2 = np + 1; +n3 = nyf; +n4 = n3 + 1; +% derivatives with respect to dynamic state variables +% forward variables +w1 =w(1:n3,n2:nd); +if condest(w1) > 1e9; + info(1) = 5; + info(2) = condest(w1); + return; +else + gx = -w1'\w(n4:nd,n2:nd)'; +end + +% predetermined variables +hx = w(1:n3,1:np)'*gx+w(n4:nd,1:np)'; +hx = (tt(1:np,1:np)*hx)\(ss(1:np,1:np)*hx); + +k1 = find(kstate(n4:nd,2) == M_.maximum_endo_lag+1); +k2 = find(kstate(1:n3,2) == M_.maximum_endo_lag+2); +hx(k1,:) +gx(k2(nboth+1:end),:) +dr.ghx = [hx(k1,:); gx(k2(nboth+1:end),:)]; +dr.ghx +%lead variables actually present in the model +j3 = nonzeros(kstate(:,3)); +j4 = find(kstate(:,3)); +% derivatives with respect to exogenous variables +disp(['M_.exo_nbr=' int2str(M_.exo_nbr)]); +if M_.exo_nbr + fu = aa(:,nz+(1:M_.exo_nbr)); + a1 = b; + aa1 = []; + if nstatic > 0 + aa1 = a1(:,1:nstatic); + end + dr.ghu = -[aa1 a(:,j3)*gx(j4,1:npred)+a1(:,nstatic+1:nstatic+ ... + npred) a1(:,nstatic+npred+1:end)]\fu; +else + dr.ghu = []; +end + +% static variables +if nstatic > 0 + temp = -a(1:nstatic,j3)*gx(j4,:)*hx; + j5 = find(kstate(n4:nd,4)); + temp(:,j5) = temp(:,j5)-a(1:nstatic,nonzeros(kstate(:,4))); + temp = b10\(temp-b11*dr.ghx); + dr.ghx = [temp; dr.ghx]; + temp = []; +end + +if options_.loglinear == 1 + k = find(dr.kstate(:,2) <= M_.maximum_endo_lag+1); + klag = dr.kstate(k,[1 2]); + k1 = dr.order_var; + + dr.ghx = repmat(1./dr.ys(k1),1,size(dr.ghx,2)).*dr.ghx.* ... + repmat(dr.ys(k1(klag(:,1)))',size(dr.ghx,1),1); + dr.ghu = repmat(1./dr.ys(k1),1,size(dr.ghu,2)).*dr.ghu; +end + +%% Necessary when using Sims' routines for QZ +if options_.use_qzdiv + gx = real(gx); + hx = real(hx); + dr.ghx = real(dr.ghx); + dr.ghu = real(dr.ghu); +end + +%exogenous deterministic variables +if M_.exo_det_nbr > 0 + f1 = sparse(jacobia_(:,nonzeros(M_.lead_lag_incidence(M_.maximum_endo_lag+2:end,order_var)))); + f0 = sparse(jacobia_(:,nonzeros(M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var)))); + fudet = sparse(jacobia_(:,nz+M_.exo_nbr+1:end)); + M1 = inv(f0+[zeros(M_.endo_nbr,nstatic) f1*gx zeros(M_.endo_nbr,nyf-nboth)]); + M2 = M1*f1; + dr.ghud = cell(M_.exo_det_length,1); + dr.ghud{1} = -M1*fudet; + for i = 2:M_.exo_det_length + dr.ghud{i} = -M2*dr.ghud{i-1}(end-nyf+1:end,:); + end +end +if options_.order == 1 + return +end + +% Second order +%tempex = oo_.exo_simul ; + +%hessian = real(hessext('ff1_',[z; oo_.exo_steady_state]))' ; +kk = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1)); +if M_.maximum_endo_lag > 0 + kk = [cumsum(M_.lead_lag_incidence(1:M_.maximum_endo_lag,order_var),1); kk]; +end +kk = kk'; +kk = find(kk(:)); +nk = size(kk,1) + M_.exo_nbr + M_.exo_det_nbr; +k1 = M_.lead_lag_incidence(:,order_var); +k1 = k1'; +k1 = k1(:); +k1 = k1(kk); +k2 = find(k1); +kk1(k1(k2)) = k2; +kk1 = [kk1 length(k1)+1:length(k1)+M_.exo_nbr+M_.exo_det_nbr]; +kk = reshape([1:nk^2],nk,nk); +kk1 = kk(kk1,kk1); +%[junk,junk,hessian] = feval([M_.fname '_dynamic'],z, oo_.exo_steady_state); +hessian(:,kk1(:)) = hessian; + +%oo_.exo_simul = tempex ; +%clear tempex + +n1 = 0; +n2 = np; +zx = zeros(np,np); +zu=zeros(np,M_.exo_nbr); +for i=2:M_.maximum_endo_lag+1 + k1 = sum(kstate(:,2) == i); + zx(n1+1:n1+k1,n2-k1+1:n2)=eye(k1); + n1 = n1+k1; + n2 = n2-k1; +end +kk = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1)); +k0 = [1:M_.endo_nbr]; +gx1 = dr.ghx; +hu = dr.ghu(nstatic+[1:npred],:); +zx = [zx; gx1]; +zu = [zu; dr.ghu]; +for i=1:M_.maximum_endo_lead + k1 = find(kk(i+1,k0) > 0); + zu = [zu; gx1(k1,1:npred)*hu]; + gx1 = gx1(k1,:)*hx; + zx = [zx; gx1]; + kk = kk(:,k0); + k0 = k1; +end +zx=[zx; zeros(M_.exo_nbr,np);zeros(M_.exo_det_nbr,np)]; +zu=[zu; eye(M_.exo_nbr);zeros(M_.exo_det_nbr,M_.exo_nbr)]; +[nrzx,nczx] = size(zx); + +rhs = -sparse_hessian_times_B_kronecker_C(hessian,zx); + +%lhs +n = M_.endo_nbr+sum(kstate(:,2) > M_.maximum_endo_lag+1 & kstate(:,2) < M_.maximum_endo_lag+M_.maximum_endo_lead+1); +A = zeros(n,n); +B = zeros(n,n); +A(1:M_.endo_nbr,1:M_.endo_nbr) = jacobia_(:,M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var)); +% variables with the highest lead +k1 = find(kstate(:,2) == M_.maximum_endo_lag+M_.maximum_endo_lead+1); +if M_.maximum_endo_lead > 1 + k2 = find(kstate(:,2) == M_.maximum_endo_lag+M_.maximum_endo_lead); + [junk,junk,k3] = intersect(kstate(k1,1),kstate(k2,1)); +else + k2 = [1:M_.endo_nbr]; + k3 = kstate(k1,1); +end +% Jacobian with respect to the variables with the highest lead +B(1:M_.endo_nbr,end-length(k2)+k3) = jacobia_(:,kstate(k1,3)+M_.endo_nbr); +offset = M_.endo_nbr; +k0 = [1:M_.endo_nbr]; +gx1 = dr.ghx; +for i=1:M_.maximum_endo_lead-1 + k1 = find(kstate(:,2) == M_.maximum_endo_lag+i+1); + [k2,junk,k3] = find(kstate(k1,3)); + A(1:M_.endo_nbr,offset+k2) = jacobia_(:,k3+M_.endo_nbr); + n1 = length(k1); + A(offset+[1:n1],nstatic+[1:npred]) = -gx1(kstate(k1,1),1:npred); + gx1 = gx1*hx; + A(offset+[1:n1],offset+[1:n1]) = eye(n1); + n0 = length(k0); + E = eye(n0); + if i == 1 + [junk,junk,k4]=intersect(kstate(k1,1),[1:M_.endo_nbr]); + else + [junk,junk,k4]=intersect(kstate(k1,1),kstate(k0,1)); + end + i1 = offset-n0+n1; + B(offset+[1:n1],offset-n0+[1:n0]) = -E(k4,:); + k0 = k1; + offset = offset + n1; +end +[junk,k1,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+M_.maximum_endo_lead+1,order_var)); +A(1:M_.endo_nbr,nstatic+1:nstatic+npred)=... + A(1:M_.endo_nbr,nstatic+[1:npred])+jacobia_(:,k2)*gx1(k1,1:npred); +C = hx; +D = [rhs; zeros(n-M_.endo_nbr,size(rhs,2))]; + + +dr.ghxx = gensylv(2,A,B,C,D); + +%ghxu +%rhs +hu = dr.ghu(nstatic+1:nstatic+npred,:); +%kk = reshape([1:np*np],np,np); +%kk = kk(1:npred,1:npred); +%rhs = -hessian*kron(zx,zu)-f1*dr.ghxx(end-nyf+1:end,kk(:))*kron(hx(1:npred,:),hu(1:npred,:)); + +rhs = sparse_hessian_times_B_kronecker_C(hessian,zx,zu); + +nyf1 = sum(kstate(:,2) == M_.maximum_endo_lag+2); +hu1 = [hu;zeros(np-npred,M_.exo_nbr)]; +%B1 = [B(1:M_.endo_nbr,:);zeros(size(A,1)-M_.endo_nbr,size(B,2))]; +[nrhx,nchx] = size(hx); +[nrhu1,nchu1] = size(hu1); + +B1 = B*A_times_B_kronecker_C(dr.ghxx,hx,hu1); +rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1; + + +%lhs +dr.ghxu = A\rhs; + +%ghuu +%rhs +kk = reshape([1:np*np],np,np); +kk = kk(1:npred,1:npred); + +rhs = sparse_hessian_times_B_kronecker_C(hessian,zu); + + +B1 = A_times_B_kronecker_C(B*dr.ghxx,hu1); +rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1; + +%lhs +dr.ghuu = A\rhs; + +dr.ghxx = dr.ghxx(1:M_.endo_nbr,:); +dr.ghxu = dr.ghxu(1:M_.endo_nbr,:); +dr.ghuu = dr.ghuu(1:M_.endo_nbr,:); + + +% dr.ghs2 +% derivatives of F with respect to forward variables +% reordering predetermined variables in diminishing lag order +O1 = zeros(M_.endo_nbr,nstatic); +O2 = zeros(M_.endo_nbr,M_.endo_nbr-nstatic-npred); +LHS = jacobia_(:,M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var)); +RHS = zeros(M_.endo_nbr,M_.exo_nbr^2); +kk = find(kstate(:,2) == M_.maximum_endo_lag+2); +gu = dr.ghu; +guu = dr.ghuu; +Gu = [dr.ghu(nstatic+[1:npred],:); zeros(np-npred,M_.exo_nbr)]; +Guu = [dr.ghuu(nstatic+[1:npred],:); zeros(np-npred,M_.exo_nbr*M_.exo_nbr)]; +E = eye(M_.endo_nbr); +M_.lead_lag_incidenceordered = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1)); +if M_.maximum_endo_lag > 0 + M_.lead_lag_incidenceordered = [cumsum(M_.lead_lag_incidence(1:M_.maximum_endo_lag,order_var),1); M_.lead_lag_incidenceordered]; +end +M_.lead_lag_incidenceordered = M_.lead_lag_incidenceordered'; +M_.lead_lag_incidenceordered = M_.lead_lag_incidenceordered(:); +k1 = find(M_.lead_lag_incidenceordered); +M_.lead_lag_incidenceordered(k1) = [1:length(k1)]'; +M_.lead_lag_incidenceordered =reshape(M_.lead_lag_incidenceordered,M_.endo_nbr,M_.maximum_endo_lag+M_.maximum_endo_lead+1)'; +kh = reshape([1:nk^2],nk,nk); +kp = sum(kstate(:,2) <= M_.maximum_endo_lag+1); +E1 = [eye(npred); zeros(kp-npred,npred)]; +H = E1; +hxx = dr.ghxx(nstatic+[1:npred],:); +for i=1:M_.maximum_endo_lead + for j=i:M_.maximum_endo_lead + [junk,k2a,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+j+1,order_var)); + [junk,k3a,k3] = ... + find(M_.lead_lag_incidenceordered(M_.maximum_endo_lag+j+1,:)); + nk3a = length(k3a); + B1 = sparse_hessian_times_B_kronecker_C(hessian(:,kh(k3,k3)),gu(k3a,:)); + RHS = RHS + jacobia_(:,k2)*guu(k2a,:)+B1; + end + % LHS + [junk,k2a,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+i+1,order_var)); + LHS = LHS + jacobia_(:,k2)*(E(k2a,:)+[O1(k2a,:) dr.ghx(k2a,:)*H O2(k2a,:)]); + + if i == M_.maximum_endo_lead + break + end + + kk = find(kstate(:,2) == M_.maximum_endo_lag+i+1); + gu = dr.ghx*Gu; + [nrGu,ncGu] = size(Gu); + G1 = A_times_B_kronecker_C(dr.ghxx,Gu); + G2 = A_times_B_kronecker_C(hxx,Gu); + guu = dr.ghx*Guu+G1; + Gu = hx*Gu; + Guu = hx*Guu; + Guu(end-npred+1:end,:) = Guu(end-npred+1:end,:) + G2; + H = E1 + hx*H; +end +RHS = RHS*M_.Sigma_e(:); +dr.fuu = RHS; +%RHS = -RHS-dr.fbias; +RHS = -RHS; +dr.ghs2 = LHS\RHS; + +% deterministic exogenous variables +if M_.exo_det_nbr > 0 + hud = dr.ghud{1}(nstatic+1:nstatic+npred,:); + zud=[zeros(np,M_.exo_det_nbr);dr.ghud{1};gx(:,1:npred)*hud;zeros(M_.exo_nbr,M_.exo_det_nbr);eye(M_.exo_det_nbr)]; + R1 = hessian*kron(zx,zud); + dr.ghxud = cell(M_.exo_det_length,1); + kf = [M_.endo_nbr-nyf+1:M_.endo_nbr]; + kp = nstatic+[1:npred]; + dr.ghxud{1} = -M1*(R1+f1*dr.ghxx(kf,:)*kron(dr.ghx(kp,:),dr.ghud{1}(kp,:))); + Eud = eye(M_.exo_det_nbr); + for i = 2:M_.exo_det_length + hudi = dr.ghud{i}(kp,:); + zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)]; + R2 = hessian*kron(zx,zudi); + dr.ghxud{i} = -M2*(dr.ghxud{i-1}(kf,:)*kron(hx,Eud)+dr.ghxx(kf,:)*kron(dr.ghx(kp,:),dr.ghud{i}(kp,:)))-M1*R2; + end + R1 = hessian*kron(zu,zud); + dr.ghudud = cell(M_.exo_det_length,1); + kf = [M_.endo_nbr-nyf+1:M_.endo_nbr]; + + dr.ghuud{1} = -M1*(R1+f1*dr.ghxx(kf,:)*kron(dr.ghu(kp,:),dr.ghud{1}(kp,:))); + Eud = eye(M_.exo_det_nbr); + for i = 2:M_.exo_det_length + hudi = dr.ghud{i}(kp,:); + zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)]; + R2 = hessian*kron(zu,zudi); + dr.ghuud{i} = -M2*dr.ghxud{i-1}(kf,:)*kron(hu,Eud)-M1*R2; + end + R1 = hessian*kron(zud,zud); + dr.ghudud = cell(M_.exo_det_length,M_.exo_det_length); + dr.ghudud{1,1} = -M1*R1-M2*dr.ghxx(kf,:)*kron(hud,hud); + for i = 2:M_.exo_det_length + hudi = dr.ghud{i}(nstatic+1:nstatic+npred,:); + zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi+dr.ghud{i-1}(kf,:);zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)]; + R2 = hessian*kron(zudi,zudi); + dr.ghudud{i,i} = -M2*(dr.ghudud{i-1,i-1}(kf,:)+... + 2*dr.ghxud{i-1}(kf,:)*kron(hudi,Eud) ... + +dr.ghxx(kf,:)*kron(hudi,hudi))-M1*R2; + R2 = hessian*kron(zud,zudi); + dr.ghudud{1,i} = -M2*(dr.ghxud{i-1}(kf,:)*kron(hud,Eud)+... + dr.ghxx(kf,:)*kron(hud,hudi))... + -M1*R2; + for j=2:i-1 + hudj = dr.ghud{j}(kp,:); + zudj=[zeros(np,M_.exo_det_nbr);dr.ghud{j};gx(:,1:npred)*hudj;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)]; + R2 = hessian*kron(zudj,zudi); + dr.ghudud{j,i} = -M2*(dr.ghudud{j-1,i-1}(kf,:)+dr.ghxud{j-1}(kf,:)* ... + kron(hudi,Eud)+dr.ghxud{i-1}(kf,:)* ... + kron(hudj,Eud)+dr.ghxx(kf,:)*kron(hudj,hudi))-M1*R2; + end + + end +end \ No newline at end of file diff --git a/matlab/dr1_sparse.m b/matlab/dr1_sparse.m index b6df040377..5ec8be77a0 100644 --- a/matlab/dr1_sparse.m +++ b/matlab/dr1_sparse.m @@ -47,47 +47,47 @@ function [dr,info,M_,options_,oo_] = dr1_sparse(dr,task,M_,options_,oo_) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - info = 0; - - options_ = set_default_option(options_,'loglinear',0); - options_ = set_default_option(options_,'noprint',0); - options_ = set_default_option(options_,'olr',0); - options_ = set_default_option(options_,'olr_beta',1); - options_ = set_default_option(options_,'qz_criterium',1.000001); - - xlen = M_.maximum_endo_lead + M_.maximum_endo_lag + 1; - klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1; - iyv = M_.lead_lag_incidence'; - iyv = iyv(:); - iyr0 = find(iyv) ; - it_ = M_.maximum_lag + 1 ; - - if M_.exo_nbr == 0 - oo_.exo_steady_state = [] ; +info = 0; + +options_ = set_default_option(options_,'loglinear',0); +options_ = set_default_option(options_,'noprint',0); +options_ = set_default_option(options_,'olr',0); +options_ = set_default_option(options_,'olr_beta',1); +options_ = set_default_option(options_,'qz_criterium',1.000001); + +xlen = M_.maximum_endo_lead + M_.maximum_endo_lag + 1; +klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1; +iyv = M_.lead_lag_incidence'; +iyv = iyv(:); +iyr0 = find(iyv) ; +it_ = M_.maximum_lag + 1 ; + +if M_.exo_nbr == 0 + oo_.exo_steady_state = [] ; +end + +% expanding system for Optimal Linear Regulator +if options_.ramsey_policy + if isfield(M_,'orig_model') + orig_model = M_.orig_model; + M_.endo_nbr = orig_model.endo_nbr; + M_.orig_endo_nbr = orig_model.orig_endo_nbr; + M_.aux_vars = orig_model.aux_vars; + M_.endo_names = orig_model.endo_names; + M_.lead_lag_incidence = orig_model.lead_lag_incidence; + M_.maximum_lead = orig_model.maximum_lead; + M_.maximum_endo_lead = orig_model.maximum_endo_lead; + M_.maximum_lag = orig_model.maximum_lag; + M_.maximum_endo_lag = orig_model.maximum_endo_lag; end - - % expanding system for Optimal Linear Regulator - if options_.ramsey_policy - if isfield(M_,'orig_model') - orig_model = M_.orig_model; - M_.endo_nbr = orig_model.endo_nbr; - M_.orig_endo_nbr = orig_model.orig_endo_nbr; - M_.aux_vars = orig_model.aux_vars; - M_.endo_names = orig_model.endo_names; - M_.lead_lag_incidence = orig_model.lead_lag_incidence; - M_.maximum_lead = orig_model.maximum_lead; - M_.maximum_endo_lead = orig_model.maximum_endo_lead; - M_.maximum_lag = orig_model.maximum_lag; - M_.maximum_endo_lag = orig_model.maximum_endo_lag; - end - old_solve_algo = options_.solve_algo; - % options_.solve_algo = 1; - oo_.steady_state = dynare_solve('dyn_ramsey_static_',oo_.steady_state,0,M_,options_,oo_,it_); - options_.solve_algo = old_solve_algo; - [junk,junk,multbar] = dyn_ramsey_static_(oo_.steady_state,M_,options_,oo_,it_); - [jacobia_,M_] = dyn_ramsey_dynamic_(oo_.steady_state,multbar,M_,options_,oo_,it_); - klen = M_.maximum_lag + M_.maximum_lead + 1; - dr.ys = [oo_.steady_state;zeros(M_.exo_nbr,1);multbar]; + old_solve_algo = options_.solve_algo; + % options_.solve_algo = 1; + oo_.steady_state = dynare_solve('dyn_ramsey_static_',oo_.steady_state,0,M_,options_,oo_,it_); + options_.solve_algo = old_solve_algo; + [junk,junk,multbar] = dyn_ramsey_static_(oo_.steady_state,M_,options_,oo_,it_); + [jacobia_,M_] = dyn_ramsey_dynamic_(oo_.steady_state,multbar,M_,options_,oo_,it_); + klen = M_.maximum_lag + M_.maximum_lead + 1; + dr.ys = [oo_.steady_state;zeros(M_.exo_nbr,1);multbar]; % $$$ if options_.ramsey_policy == 2 % $$$ mask = M_.orig_model.lead_lag_incidence ~= 0; % $$$ incidence_submatrix = M_.lead_lag_incidence(M_.orig_model.maximum_lead+(1:size(mask,1)),1:M_.orig_model.endo_nbr); @@ -178,91 +178,91 @@ function [dr,info,M_,options_,oo_] = dr1_sparse(dr,task,M_,options_,oo_) % $$$ M_.endo_names = strvcat(M_.orig_model.endo_names, M_.endo_names(endo_nbr1+k,:)); % $$$ M_.endo_nbr = endo_nbr1+length(k); % $$$ end - else - klen = M_.maximum_lag + M_.maximum_lead + 1; - iyv = M_.lead_lag_incidence'; - iyv = iyv(:); - iyr0 = find(iyv) ; - it_ = M_.maximum_lag + 1 ; - - if M_.exo_nbr == 0 - oo_.exo_steady_state = [] ; +else + klen = M_.maximum_lag + M_.maximum_lead + 1; + iyv = M_.lead_lag_incidence'; + iyv = iyv(:); + iyr0 = find(iyv) ; + it_ = M_.maximum_lag + 1 ; + + if M_.exo_nbr == 0 + oo_.exo_steady_state = [] ; + end + + it_ = M_.maximum_lag + 1; + z = repmat(dr.ys,1,klen); + z = z(iyr0) ; + if options_.model_mode==0 || options_.model_mode == 2 + if options_.order == 1 + [junk,jacobia_] = feval([M_.fname '_dynamic'],z,[oo_.exo_simul ... + oo_.exo_det_simul], M_.params, it_); + hessian = 0; + elseif options_.order == 2 + [junk,jacobia_,hessian] = feval([M_.fname '_dynamic'],z,... + [oo_.exo_simul ... + oo_.exo_det_simul], M_.params, it_); end - - it_ = M_.maximum_lag + 1; - z = repmat(dr.ys,1,klen); - z = z(iyr0) ; - if options_.model_mode==0 || options_.model_mode == 2 - if options_.order == 1 - [junk,jacobia_] = feval([M_.fname '_dynamic'],z,[oo_.exo_simul ... - oo_.exo_det_simul], M_.params, it_); - hessian = 0; - elseif options_.order == 2 - [junk,jacobia_,hessian] = feval([M_.fname '_dynamic'],z,... - [oo_.exo_simul ... - oo_.exo_det_simul], M_.params, it_); - end - dr=set_state_space(dr,M_); - if options_.debug + dr=set_state_space(dr,M_); + if options_.debug save([M_.fname '_debug.mat'],'jacobia_') - end - [dr,info,M_,options_,oo_] = dr11_sparse(dr,task,M_,options_,oo_, jacobia_, hessian); - dr.nyf = nnz(dr.kstate(:,2)>M_.maximum_lag+1); - elseif options_.model_mode==1 - if options_.order == 1 + end + [dr,info,M_,options_,oo_] = dr11_sparse(dr,task,M_,options_,oo_, jacobia_, hessian); + dr.nyf = nnz(dr.kstate(:,2)>M_.maximum_lag+1); + elseif options_.model_mode==1 + if options_.order == 1 + + [junk,derivate] = feval([M_.fname '_dynamic'],ones(M_.maximum_lag+M_.maximum_lead+1,1)*dr.ys',[oo_.exo_simul ... + oo_.exo_det_simul], M_.params, it_); + %full(jacobia_) + dr.eigval = []; + dr.nyf = 0; + dr.rank = 0; + first_col_exo = M_.endo_nbr * (M_.maximum_endo_lag + M_.maximum_endo_lead + 1); + for i=1:length(M_.block_structure.block) + %disp(['block = ' int2str(i)]); + M_.block_structure.block(i).dr.Null=0; + M_.block_structure.block(i).dr=set_state_space(M_.block_structure.block(i).dr,M_.block_structure.block(i)); + col_selector=repmat(M_.block_structure.block(i).variable,1,M_.block_structure.block(i).maximum_endo_lag+M_.block_structure.block(i).maximum_endo_lead+1)+kron([M_.maximum_endo_lag-M_.block_structure.block(i).maximum_endo_lag:M_.maximum_endo_lag+M_.block_structure.block(i).maximum_endo_lead],M_.endo_nbr*ones(1,M_.block_structure.block(i).endo_nbr)); + row_selector = M_.block_structure.block(i).equation; + %jcb_=jacobia_(row_selector,col_selector); + jcb_=derivate(i).g1; + %disp('jcb_'); + %full(jcb_) + %M_.block_structure.block(i).lead_lag_incidence' + jcb_ = jcb_(:,find(M_.block_structure.block(i).lead_lag_incidence')) ; + if M_.block_structure.block(i).exo_nbr>0 + col_selector = [ first_col_exo + ... + repmat(M_.block_structure.block(i).exogenous,1,M_.block_structure.block(i).maximum_exo_lag+M_.block_structure.block(i).maximum_exo_lead+1)+kron([M_.maximum_exo_lag-M_.block_structure.block(i).maximum_exo_lag:M_.maximum_exo_lag+M_.block_structure.block(i).maximum_exo_lead],M_.exo_nbr*ones(1,M_.block_structure.block(i).exo_nbr))]; + end + %derivate(i).g1 + %derivate(i).g1_x + %col_selector + %jcb_ = [ jcb_ jacobia_(row_selector,col_selector)]; + jcb_ = [ jcb_ derivate(i).g1_x]; + %full(jcb_) - [junk,derivate] = feval([M_.fname '_dynamic'],ones(M_.maximum_lag+M_.maximum_lead+1,1)*dr.ys',[oo_.exo_simul ... - oo_.exo_det_simul], M_.params, it_); - %full(jacobia_) - dr.eigval = []; - dr.nyf = 0; - dr.rank = 0; - first_col_exo = M_.endo_nbr * (M_.maximum_endo_lag + M_.maximum_endo_lead + 1); - for i=1:length(M_.block_structure.block) - %disp(['block = ' int2str(i)]); - M_.block_structure.block(i).dr.Null=0; - M_.block_structure.block(i).dr=set_state_space(M_.block_structure.block(i).dr,M_.block_structure.block(i)); - col_selector=repmat(M_.block_structure.block(i).variable,1,M_.block_structure.block(i).maximum_endo_lag+M_.block_structure.block(i).maximum_endo_lead+1)+kron([M_.maximum_endo_lag-M_.block_structure.block(i).maximum_endo_lag:M_.maximum_endo_lag+M_.block_structure.block(i).maximum_endo_lead],M_.endo_nbr*ones(1,M_.block_structure.block(i).endo_nbr)); - row_selector = M_.block_structure.block(i).equation; - %jcb_=jacobia_(row_selector,col_selector); - jcb_=derivate(i).g1; - %disp('jcb_'); - %full(jcb_) - %M_.block_structure.block(i).lead_lag_incidence' - jcb_ = jcb_(:,find(M_.block_structure.block(i).lead_lag_incidence')) ; - if M_.block_structure.block(i).exo_nbr>0 - col_selector = [ first_col_exo + ... - repmat(M_.block_structure.block(i).exogenous,1,M_.block_structure.block(i).maximum_exo_lag+M_.block_structure.block(i).maximum_exo_lead+1)+kron([M_.maximum_exo_lag-M_.block_structure.block(i).maximum_exo_lag:M_.maximum_exo_lag+M_.block_structure.block(i).maximum_exo_lead],M_.exo_nbr*ones(1,M_.block_structure.block(i).exo_nbr))]; - end - %derivate(i).g1 - %derivate(i).g1_x - %col_selector - %jcb_ = [ jcb_ jacobia_(row_selector,col_selector)]; - jcb_ = [ jcb_ derivate(i).g1_x]; - %full(jcb_) - - hss_=0; %hessian(M_.block_structure.block(i).equation,M_.block_structure.block(i).variable); - dra = M_.block_structure.block(i).dr; - %M_.block_structure.block(i).exo_nbr=M_.exo_nbr; - [dra ,info,M_.block_structure.block(i),options_,oo_] = dr11_sparse(dra ,task,M_.block_structure.block(i),options_,oo_, jcb_, hss_); - M_.block_structure.block(i).dr = dra; - dr.eigval = [dr.eigval; dra.eigval]; - nyf = nnz(dra.kstate(:,2)>M_.block_structure.block(i).maximum_endo_lag+1); - n_explod = nnz(abs(dra.eigval) > options_.qz_criterium); - if nyf ~= n_explod - disp(['EIGENVALUES in block ' int2str(i) ':']); - [m_lambda,ii]=sort(abs(dra.eigval)); - disp(sprintf('%16s %16s %16s\n','Modulus','Real','Imaginary')) - z=[m_lambda real(dra.eigval(ii)) imag(dra.eigval(ii))]'; - disp(sprintf('%16.4g %16.4g %16.4g\n',z)) - disp(['The rank condition is not satisfy in block ' int2str(i) ' :']); - disp([' ' int2str(nyf) ' forward-looking variable(s) for ' ... - int2str(n_explod) ' eigenvalue(s) larger than 1 in modulus']); - end - dr.nyf = dr.nyf + nyf; - dr.rank = dr.rank + dra.rank; - end; - end + hss_=0; %hessian(M_.block_structure.block(i).equation,M_.block_structure.block(i).variable); + dra = M_.block_structure.block(i).dr; + %M_.block_structure.block(i).exo_nbr=M_.exo_nbr; + [dra ,info,M_.block_structure.block(i),options_,oo_] = dr11_sparse(dra ,task,M_.block_structure.block(i),options_,oo_, jcb_, hss_); + M_.block_structure.block(i).dr = dra; + dr.eigval = [dr.eigval; dra.eigval]; + nyf = nnz(dra.kstate(:,2)>M_.block_structure.block(i).maximum_endo_lag+1); + n_explod = nnz(abs(dra.eigval) > options_.qz_criterium); + if nyf ~= n_explod + disp(['EIGENVALUES in block ' int2str(i) ':']); + [m_lambda,ii]=sort(abs(dra.eigval)); + disp(sprintf('%16s %16s %16s\n','Modulus','Real','Imaginary')) + z=[m_lambda real(dra.eigval(ii)) imag(dra.eigval(ii))]'; + disp(sprintf('%16.4g %16.4g %16.4g\n',z)) + disp(['The rank condition is not satisfy in block ' int2str(i) ' :']); + disp([' ' int2str(nyf) ' forward-looking variable(s) for ' ... + int2str(n_explod) ' eigenvalue(s) larger than 1 in modulus']); + end + dr.nyf = dr.nyf + nyf; + dr.rank = dr.rank + dra.rank; + end; end end - +end + diff --git a/matlab/dsample.m b/matlab/dsample.m index 1aa20c7c5c..80dd616b6c 100644 --- a/matlab/dsample.m +++ b/matlab/dsample.m @@ -37,20 +37,20 @@ global options_ options_.smpl = zeros(2,1) ; if nargin == 0 - options_.smpl(1) = 1 ; - options_.smpl(2) = options_.periods ; + options_.smpl(1) = 1 ; + options_.smpl(2) = options_.periods ; elseif nargin == 1 - if s1 > options_.periods - error('DSAMPLE: argument greater than number of periods'); - end - options_.smpl(1) = 1 ; - options_.smpl(2) = s1 ; + if s1 > options_.periods + error('DSAMPLE: argument greater than number of periods'); + end + options_.smpl(1) = 1 ; + options_.smpl(2) = s1 ; else - if s1 > options_.periods || s2 > options_.periods - error('DSAMPLE: one of the arguments is greater than number of periods'); - end - options_.smpl(1) = s1 ; - options_.smpl(2) = s2 ; + if s1 > options_.periods || s2 > options_.periods + error('DSAMPLE: one of the arguments is greater than number of periods'); + end + options_.smpl(1) = s1 ; + options_.smpl(2) = s2 ; end % 02/23/01 MJ added error checking \ No newline at end of file diff --git a/matlab/dsge_posterior_kernel.m b/matlab/dsge_posterior_kernel.m index 3893a47b59..1f53ec58c5 100644 --- a/matlab/dsge_posterior_kernel.m +++ b/matlab/dsge_posterior_kernel.m @@ -38,274 +38,274 @@ function [fval,cost_flag,ys,trend_coeff,info] = dsge_posterior_kernel(xparam1,ge % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_ - fval = []; - ys = []; - trend_coeff = []; - cost_flag = 1; - nobs = size(options_.varobs,1); - %------------------------------------------------------------------------------ - % 1. Get the structural parameters & define penalties - %------------------------------------------------------------------------------ - if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb) - k = find(xparam1 < bayestopt_.lb); - fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2); - cost_flag = 0; - info = 41; - return; - end - if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub) - k = find(xparam1 > bayestopt_.ub); - fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2); - cost_flag = 0; - info = 42; - return; - end - Q = M_.Sigma_e; - H = M_.H; - for i=1:estim_params_.nvx +global bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_ +fval = []; +ys = []; +trend_coeff = []; +cost_flag = 1; +nobs = size(options_.varobs,1); +%------------------------------------------------------------------------------ +% 1. Get the structural parameters & define penalties +%------------------------------------------------------------------------------ +if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb) + k = find(xparam1 < bayestopt_.lb); + fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2); + cost_flag = 0; + info = 41; + return; +end +if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub) + k = find(xparam1 > bayestopt_.ub); + fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2); + cost_flag = 0; + info = 42; + return; +end +Q = M_.Sigma_e; +H = M_.H; +for i=1:estim_params_.nvx k =estim_params_.var_exo(i,1); Q(k,k) = xparam1(i)*xparam1(i); - end - offset = estim_params_.nvx; - if estim_params_.nvn +end +offset = estim_params_.nvx; +if estim_params_.nvn for i=1:estim_params_.nvn - k = estim_params_.var_endo(i,1); - H(k,k) = xparam1(i+offset)*xparam1(i+offset); + k = estim_params_.var_endo(i,1); + H(k,k) = xparam1(i+offset)*xparam1(i+offset); end offset = offset+estim_params_.nvn; - end - if estim_params_.ncx +end +if estim_params_.ncx for i=1:estim_params_.ncx - k1 =estim_params_.corrx(i,1); - k2 =estim_params_.corrx(i,2); - Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2)); - Q(k2,k1) = Q(k1,k2); + k1 =estim_params_.corrx(i,1); + k2 =estim_params_.corrx(i,2); + Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2)); + Q(k2,k1) = Q(k1,k2); end [CholQ,testQ] = chol(Q); if testQ %% The variance-covariance matrix of the structural innovations is not definite positive. - %% We have to compute the eigenvalues of this matrix in order to build the penalty. - a = diag(eig(Q)); - k = find(a < 0); - if k > 0 - fval = bayestopt_.penalty+sum(-a(k)); - cost_flag = 0; - info = 43; - return - end + %% We have to compute the eigenvalues of this matrix in order to build the penalty. + a = diag(eig(Q)); + k = find(a < 0); + if k > 0 + fval = bayestopt_.penalty+sum(-a(k)); + cost_flag = 0; + info = 43; + return + end end offset = offset+estim_params_.ncx; - end - if estim_params_.ncn +end +if estim_params_.ncn for i=1:estim_params_.ncn - k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1)); - k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2)); - H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2)); - H(k2,k1) = H(k1,k2); + k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1)); + k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2)); + H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2)); + H(k2,k1) = H(k1,k2); end [CholH,testH] = chol(H); if testH - a = diag(eig(H)); - k = find(a < 0); - if k > 0 - fval = bayestopt_.penalty+sum(-a(k)); - cost_flag = 0; - info = 44; - return - end + a = diag(eig(H)); + k = find(a < 0); + if k > 0 + fval = bayestopt_.penalty+sum(-a(k)); + cost_flag = 0; + info = 44; + return + end end offset = offset+estim_params_.ncn; - end - if estim_params_.np > 0 - M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end); - end - M_.Sigma_e = Q; - M_.H = H; - %------------------------------------------------------------------------------ - % 2. call model setup & reduction program - %------------------------------------------------------------------------------ - [T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,... - bayestopt_.restrict_columns,... - bayestopt_.restrict_aux); - if info(1) == 1 | info(1) == 2 | info(1) == 5 +end +if estim_params_.np > 0 + M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end); +end +M_.Sigma_e = Q; +M_.H = H; +%------------------------------------------------------------------------------ +% 2. call model setup & reduction program +%------------------------------------------------------------------------------ +[T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,... + bayestopt_.restrict_columns,... + bayestopt_.restrict_aux); +if info(1) == 1 | info(1) == 2 | info(1) == 5 fval = bayestopt_.penalty+1; cost_flag = 0; return - elseif info(1) == 3 | info(1) == 4 | info(1) == 20 +elseif info(1) == 3 | info(1) == 4 | info(1) == 20 fval = bayestopt_.penalty+info(2);%^2; % penalty power raised in DR1.m and resol already. GP July'08 cost_flag = 0; return - end - bayestopt_.mf = bayestopt_.mf1; - if ~options_.noconstant +end +bayestopt_.mf = bayestopt_.mf1; +if ~options_.noconstant if options_.loglinear == 1 - constant = log(SteadyState(bayestopt_.mfys)); + constant = log(SteadyState(bayestopt_.mfys)); else - constant = SteadyState(bayestopt_.mfys); + constant = SteadyState(bayestopt_.mfys); end - else +else constant = zeros(nobs,1); - end - if bayestopt_.with_trend == 1 +end +if bayestopt_.with_trend == 1 trend_coeff = zeros(nobs,1); t = options_.trend_coeffs; for i=1:length(t) - if ~isempty(t{i}) - trend_coeff(i) = evalin('base',t{i}); - end + if ~isempty(t{i}) + trend_coeff(i) = evalin('base',t{i}); + end end trend = repmat(constant,1,gend)+trend_coeff*[1:gend]; - else +else trend = repmat(constant,1,gend); - end - start = options_.presample+1; - np = size(T,1); - mf = bayestopt_.mf; - no_missing_data_flag = (number_of_observations==gend*nobs); - %------------------------------------------------------------------------------ - % 3. Initial condition of the Kalman filter - %------------------------------------------------------------------------------ - kalman_algo = options_.kalman_algo; - if options_.lik_init == 1 % Kalman filter - if kalman_algo ~= 2 - kalman_algo = 1; - end - Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold); - Pinf = []; - elseif options_.lik_init == 2 % Old Diffuse Kalman filter - if kalman_algo ~= 2 - kalman_algo = 1; - end - Pstar = 10*eye(np); - Pinf = []; - elseif options_.lik_init == 3 % Diffuse Kalman filter - if kalman_algo ~= 4 - kalman_algo = 3; - end - [QT,ST] = schur(T); - e1 = abs(ordeig(ST)) > 2-options_.qz_criterium; - [QT,ST] = ordschur(QT,ST,e1); - k = find(abs(ordeig(ST)) > 2-options_.qz_criterium); - nk = length(k); - nk1 = nk+1; - Pinf = zeros(np,np); - Pinf(1:nk,1:nk) = eye(nk); - Pstar = zeros(np,np); - B = QT'*R*Q*R'*QT; - for i=np:-1:nk+2 - if ST(i,i-1) == 0 - if i == np - c = zeros(np-nk,1); - else - c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... - ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i); - end - q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i); - Pstar(nk1:i,i) = q\(B(nk1:i,i)+c); - Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; - else - if i == np - c = zeros(np-nk,1); - c1 = zeros(np-nk,1); - else - c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... - ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i)+... - ST(i,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1); - c1 = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i-1,i+1:end)')+... - ST(i-1,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1)+... - ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i); - end - q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);... - -ST(nk1:i,nk1:i)*ST(i-1,i) eye(i-nk)-ST(nk1:i,nk1:i)*ST(i-1,i-1)]; - z = q\[B(nk1:i,i)+c;B(nk1:i,i-1)+c1]; - Pstar(nk1:i,i) = z(1:(i-nk)); - Pstar(nk1:i,i-1) = z(i-nk+1:end); - Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; - Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)'; - i = i - 1; - end - end - if i == nk+2 - c = ST(nk+1,:)*(Pstar(:,nk+2:end)*ST(nk1,nk+2:end)')+ST(nk1,nk1)*ST(nk1,nk+2:end)*Pstar(nk+2:end,nk1); - Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1)); - end - Z = QT(mf,:); - R1 = QT'*R; - [QQ,RR,EE] = qr(Z*ST(:,1:nk),0); - k = find(abs(diag(RR)) < 1e-8); - if length(k) > 0 - k1 = EE(:,k); - dd =ones(nk,1); - dd(k1) = zeros(length(k1),1); - Pinf(1:nk,1:nk) = diag(dd); - end - end - if kalman_algo == 2 - no_correlation_flag = 1; - if length(H)==1 - H = zeros(nobs,1); - else - if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal... - H = diag(H); - else - no_correlation_flag = 0; - end - end - end - kalman_tol = options_.kalman_tol; - riccati_tol = options_.riccati_tol; - mf = bayestopt_.mf1; - Y = data-trend; - %------------------------------------------------------------------------------ - % 4. Likelihood evaluation - %------------------------------------------------------------------------------ - if (kalman_algo==1)% Multivariate Kalman Filter - if no_missing_data_flag - LIK = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol); - else - LIK = ... - missing_observations_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol, ... - data_index,number_of_observations,no_more_missing_observations); - end - if isinf(LIK) - kalman_algo = 2; - end - end - if (kalman_algo==2)% Univariate Kalman Filter - if no_correlation_flag - LIK = univariate_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations); - else - LIK = univariate_kalman_filter_corr(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations); - end - end - if (kalman_algo==3)% Multivariate Diffuse Kalman Filter - if no_missing_data_flag - LIK = diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol); - else - LIK = missing_observations_diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol,... - data_index,number_of_observations,no_more_missing_observations); - end - if isinf(LIK) - kalman_algo = 4; - end - end - if (kalman_algo==4)% Univariate Diffuse Kalman Filter - if no_correlation_flag - LIK = univariate_diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol,... - data_index,number_of_observations,no_more_missing_observations); - else - LIK = univariate_diffuse_kalman_filter_corr(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol,... - data_index,number_of_observations,no_more_missing_observations); - end - end - if imag(LIK) ~= 0 - likelihood = bayestopt_.penalty; - else - likelihood = LIK; - end - % ------------------------------------------------------------------------------ - % Adds prior if necessary - % ------------------------------------------------------------------------------ - lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4); - fval = (likelihood-lnprior); - options_.kalman_algo = kalman_algo; \ No newline at end of file +end +start = options_.presample+1; +np = size(T,1); +mf = bayestopt_.mf; +no_missing_data_flag = (number_of_observations==gend*nobs); +%------------------------------------------------------------------------------ +% 3. Initial condition of the Kalman filter +%------------------------------------------------------------------------------ +kalman_algo = options_.kalman_algo; +if options_.lik_init == 1 % Kalman filter + if kalman_algo ~= 2 + kalman_algo = 1; + end + Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold); + Pinf = []; +elseif options_.lik_init == 2 % Old Diffuse Kalman filter + if kalman_algo ~= 2 + kalman_algo = 1; + end + Pstar = 10*eye(np); + Pinf = []; +elseif options_.lik_init == 3 % Diffuse Kalman filter + if kalman_algo ~= 4 + kalman_algo = 3; + end + [QT,ST] = schur(T); + e1 = abs(ordeig(ST)) > 2-options_.qz_criterium; + [QT,ST] = ordschur(QT,ST,e1); + k = find(abs(ordeig(ST)) > 2-options_.qz_criterium); + nk = length(k); + nk1 = nk+1; + Pinf = zeros(np,np); + Pinf(1:nk,1:nk) = eye(nk); + Pstar = zeros(np,np); + B = QT'*R*Q*R'*QT; + for i=np:-1:nk+2 + if ST(i,i-1) == 0 + if i == np + c = zeros(np-nk,1); + else + c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... + ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i); + end + q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i); + Pstar(nk1:i,i) = q\(B(nk1:i,i)+c); + Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; + else + if i == np + c = zeros(np-nk,1); + c1 = zeros(np-nk,1); + else + c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... + ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i)+... + ST(i,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1); + c1 = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i-1,i+1:end)')+... + ST(i-1,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1)+... + ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i); + end + q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);... + -ST(nk1:i,nk1:i)*ST(i-1,i) eye(i-nk)-ST(nk1:i,nk1:i)*ST(i-1,i-1)]; + z = q\[B(nk1:i,i)+c;B(nk1:i,i-1)+c1]; + Pstar(nk1:i,i) = z(1:(i-nk)); + Pstar(nk1:i,i-1) = z(i-nk+1:end); + Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; + Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)'; + i = i - 1; + end + end + if i == nk+2 + c = ST(nk+1,:)*(Pstar(:,nk+2:end)*ST(nk1,nk+2:end)')+ST(nk1,nk1)*ST(nk1,nk+2:end)*Pstar(nk+2:end,nk1); + Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1)); + end + Z = QT(mf,:); + R1 = QT'*R; + [QQ,RR,EE] = qr(Z*ST(:,1:nk),0); + k = find(abs(diag(RR)) < 1e-8); + if length(k) > 0 + k1 = EE(:,k); + dd =ones(nk,1); + dd(k1) = zeros(length(k1),1); + Pinf(1:nk,1:nk) = diag(dd); + end +end +if kalman_algo == 2 + no_correlation_flag = 1; + if length(H)==1 + H = zeros(nobs,1); + else + if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal... + H = diag(H); + else + no_correlation_flag = 0; + end + end +end +kalman_tol = options_.kalman_tol; +riccati_tol = options_.riccati_tol; +mf = bayestopt_.mf1; +Y = data-trend; +%------------------------------------------------------------------------------ +% 4. Likelihood evaluation +%------------------------------------------------------------------------------ +if (kalman_algo==1)% Multivariate Kalman Filter + if no_missing_data_flag + LIK = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol); + else + LIK = ... + missing_observations_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol, ... + data_index,number_of_observations,no_more_missing_observations); + end + if isinf(LIK) + kalman_algo = 2; + end +end +if (kalman_algo==2)% Univariate Kalman Filter + if no_correlation_flag + LIK = univariate_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations); + else + LIK = univariate_kalman_filter_corr(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations); + end +end +if (kalman_algo==3)% Multivariate Diffuse Kalman Filter + if no_missing_data_flag + LIK = diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol); + else + LIK = missing_observations_diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol,... + data_index,number_of_observations,no_more_missing_observations); + end + if isinf(LIK) + kalman_algo = 4; + end +end +if (kalman_algo==4)% Univariate Diffuse Kalman Filter + if no_correlation_flag + LIK = univariate_diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol,... + data_index,number_of_observations,no_more_missing_observations); + else + LIK = univariate_diffuse_kalman_filter_corr(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol,... + data_index,number_of_observations,no_more_missing_observations); + end +end +if imag(LIK) ~= 0 + likelihood = bayestopt_.penalty; +else + likelihood = LIK; +end +% ------------------------------------------------------------------------------ +% Adds prior if necessary +% ------------------------------------------------------------------------------ +lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4); +fval = (likelihood-lnprior); +options_.kalman_algo = kalman_algo; \ No newline at end of file diff --git a/matlab/dsge_simulated_theoretical_conditional_variance_decomposition.m b/matlab/dsge_simulated_theoretical_conditional_variance_decomposition.m index 041924c372..b35166dcb2 100644 --- a/matlab/dsge_simulated_theoretical_conditional_variance_decomposition.m +++ b/matlab/dsge_simulated_theoretical_conditional_variance_decomposition.m @@ -1,5 +1,5 @@ function [nvar,vartan,NumberOfConditionalDecompFiles] = ... - dsge_simulated_theoretical_conditional_variance_decomposition(SampleSize,Steps,M_,options_,oo_,type) + dsge_simulated_theoretical_conditional_variance_decomposition(SampleSize,Steps,M_,options_,oo_,type) % This function computes the posterior or prior distribution of the conditional variance % decomposition of the endogenous variables (or a subset of the endogenous variables). % diff --git a/matlab/dsge_simulated_theoretical_correlation.m b/matlab/dsge_simulated_theoretical_correlation.m index 30ce0c5164..c411238331 100644 --- a/matlab/dsge_simulated_theoretical_correlation.m +++ b/matlab/dsge_simulated_theoretical_correlation.m @@ -47,7 +47,7 @@ else error() end NumberOfDrawsFiles = length(DrawsFiles); - + % Set varlist (vartan) if ~posterior if isfield(options_,'varlist') diff --git a/matlab/dsge_simulated_theoretical_variance_decomposition.m b/matlab/dsge_simulated_theoretical_variance_decomposition.m index 53a70588ed..f838559111 100644 --- a/matlab/dsge_simulated_theoretical_variance_decomposition.m +++ b/matlab/dsge_simulated_theoretical_variance_decomposition.m @@ -1,5 +1,5 @@ function [nvar,vartan,NumberOfDecompFiles] = ... - dsge_simulated_theoretical_variance_decomposition(SampleSize,M_,options_,oo_,type) + dsge_simulated_theoretical_variance_decomposition(SampleSize,M_,options_,oo_,type) % This function computes the posterior or prior distribution of the variance % decomposition of the observed endogenous variables. % diff --git a/matlab/dy_date.m b/matlab/dy_date.m index 3acc500884..4d605b6371 100644 --- a/matlab/dy_date.m +++ b/matlab/dy_date.m @@ -17,8 +17,7 @@ function y=dy_date(year,period) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ - - y = M_.freq*(year-M_.start_date(1))+period-M_.start_date(2)+1; - - \ No newline at end of file +global M_ + +y = M_.freq*(year-M_.start_date(1))+period-M_.start_date(2)+1; + diff --git a/matlab/dyn2vec.m b/matlab/dyn2vec.m index 7a3ee987eb..5219dca138 100644 --- a/matlab/dyn2vec.m +++ b/matlab/dyn2vec.m @@ -31,54 +31,54 @@ function [z,zss]=dyn2vec(s1,s2) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ oo_ options_ +global M_ oo_ options_ - if options_.smpl == 0 +if options_.smpl == 0 k = [1:size(oo_.endo_simul,2)]; - else +else k = [M_.maximum_lag+options_.smpl(1):M_.maximum_lag+options_.smpl(2)]; - end +end - if nargin == 0 +if nargin == 0 if nargout > 0 - t = ['DYNARE dyn2vec error: the function doesn''t return values when' ... - ' used without input argument']; - error(t); + t = ['DYNARE dyn2vec error: the function doesn''t return values when' ... + ' used without input argument']; + error(t); end for i=1:size(oo_.endo_simul,1) - assignin('base',deblank(M_.endo_names(i,:)),oo_.endo_simul(i,k)'); + assignin('base',deblank(M_.endo_names(i,:)),oo_.endo_simul(i,k)'); end return - else +else j = strmatch(s1,M_.endo_names,'exact'); if ~ isempty(j) - z = oo_.endo_simul(j,k)'; + z = oo_.endo_simul(j,k)'; else - j = strmatch(s1,M_.exo_names,'exact'); - if ~ isempty(j) - if options_.smpl == 0 - z = oo_.exo_simul(:,j); - else - z = oo_.exo_simul(M_.maximum_lag+options_.smpl(1):M_.maximum_lag+options_.smpl(2)); - end - else - t = ['DYNARE dyn2vec error: variable ' deblank(s1(i,:)) ' doesn''t' ... - ' exist.'] ; - error (t) ; - end + j = strmatch(s1,M_.exo_names,'exact'); + if ~ isempty(j) + if options_.smpl == 0 + z = oo_.exo_simul(:,j); + else + z = oo_.exo_simul(M_.maximum_lag+options_.smpl(1):M_.maximum_lag+options_.smpl(2)); + end + else + t = ['DYNARE dyn2vec error: variable ' deblank(s1(i,:)) ' doesn''t' ... + ' exist.'] ; + error (t) ; + end end - end +end - if nargout == 0 +if nargout == 0 if nargin == 1 - assignin('base',s1,z); + assignin('base',s1,z); elseif nargin == 2 - assignin('base',s2,z); + assignin('base',s2,z); end - else +else zss=oo_.steady_state(j); - end - +end + % 02/23/01 MJ redone, incorporating FC's improvements % 08/24/01 MJ replaced globlize by internal assignin % 08/24/01 MJ added 'exact' to strmatch (thanks to David Vavra) diff --git a/matlab/dyn_ramsey_dynamic_.m b/matlab/dyn_ramsey_dynamic_.m index 7503f6fcd5..177a96bc49 100644 --- a/matlab/dyn_ramsey_dynamic_.m +++ b/matlab/dyn_ramsey_dynamic_.m @@ -1,239 +1,239 @@ -function [J,M_] = dyn_ramsey_dynamic_(ys,lbar,M_,options_,oo_,it_) -% function J = dyn_ramsey_dynamic_(ys,lbar) -% dyn_ramsey_dynamic_ sets up the Jacobian of the expanded model for optimal -% policies. It modifies several fields of M_ -% -% INPUTS: -% ys: steady state of original endogenous variables -% lbar: steady state of Lagrange multipliers -% -% OUPTUTS: -% J: jaocobian of expanded model -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2003-2009 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 <http://www.gnu.org/licenses/>. - - % retrieving model parameters - endo_nbr = M_.endo_nbr; - i_endo_nbr = 1:endo_nbr; - endo_names = M_.endo_names; - % exo_nbr = M_.exo_nbr+M_.exo_det_nbr; - % exo_names = vertcat(M_.exo_names,M_.exo_det_names); - exo_nbr = M_.exo_nbr; - exo_names = M_.exo_names; - i_leadlag = M_.lead_lag_incidence; - max_lead = M_.maximum_lead; - max_endo_lead = M_.maximum_endo_lead; - max_lag = M_.maximum_lag; - max_endo_lag = M_.maximum_endo_lag; - leadlag_nbr = max_lead+max_lag+1; - fname = M_.fname; - % instr_names = options_.olr_inst; - % instr_nbr = size(options_.olr_inst,1); - - % discount factor - beta = options_.planner_discount; - - % storing original values - orig_model.endo_nbr = endo_nbr; - orig_model.orig_endo_nbr = M_.orig_endo_nbr; - orig_model.aux_vars = M_.aux_vars; - orig_model.endo_names = endo_names; - orig_model.lead_lag_incidence = i_leadlag; - orig_model.maximum_lead = max_lead; - orig_model.maximum_endo_lead = max_endo_lead; - orig_model.maximum_lag = max_lag; - orig_model.maximum_endo_lag = max_endo_lag; - - y = repmat(ys,1,max_lag+max_lead+1); - k = find(i_leadlag'); - - % retrieving derivatives of the objective function - [U,Uy,Uyy] = feval([fname '_objective_static'],ys,zeros(1,exo_nbr), M_.params); - Uy = Uy'; - Uyy = reshape(Uyy,endo_nbr,endo_nbr); - - % retrieving derivatives of original model - [f,fJ,fH] = feval([fname '_dynamic'],y(k),[oo_.exo_simul oo_.exo_det_simul], M_.params, it_); - instr_nbr = endo_nbr - size(f,1); - mult_nbr = endo_nbr-instr_nbr; - - % parameters for expanded model - endo_nbr1 = 2*endo_nbr-instr_nbr+exo_nbr; - max_lead1 = max_lead + max_lag; - max_lag1 = max_lead1; - max_leadlag1 = max_lead1; - - % adding new variables names - endo_names1 = endo_names; - % adding shocks to endogenous variables - endo_names1 = strvcat(endo_names1, exo_names); - % adding multipliers names - for i=1:mult_nbr; - endo_names1 = strvcat(endo_names1,['mult_' int2str(i)]); - end - - % expanding matrix of lead/lag incidence - % - % multipliers lead/lag incidence - i_mult = []; - for i=1:leadlag_nbr - i_mult = [any(fJ(:,nonzeros(i_leadlag(i,:))) ~= 0,2)' ; i_mult]; - end - % putting it all together: - % original variables, exogenous variables made endogenous, multipliers - % - % number of original dynamic variables - n_dyn = nnz(i_leadlag); - % numbering columns of dynamic multipliers to be put in the last columns - % of the new Jacobian - i_leadlag1 = [cumsum(i_leadlag(1:max_lag,:),1); ... - repmat(i_leadlag(max_lag+1,:),leadlag_nbr,1); ... - flipud(cumsum(flipud(i_leadlag(max_lag+2:end,:)),1))]; - i_leadlag1 = i_leadlag1'; - k = find(i_leadlag1 > 0); - n = length(k); - i_leadlag1(k) = 1:n; - i_leadlag1 = i_leadlag1'; - i_mult = i_mult'; - k = find(i_mult > 0); - i_mult(k) = n+leadlag_nbr*exo_nbr+(1:length(k)); - i_mult = i_mult'; - i_leadlag1 = [ i_leadlag1 ... - [zeros(max_lag,exo_nbr);... - reshape(n+(1:leadlag_nbr*exo_nbr),exo_nbr,leadlag_nbr)'; ... - zeros(max_lead,exo_nbr)] ... - [zeros(max_lag,mult_nbr);... - i_mult;... - zeros(max_lead,mult_nbr)]]; - i_leadlag1 = i_leadlag1'; - k = find(i_leadlag1 > 0); - n = length(k); - i_leadlag1(k) = 1:n; - i_leadlag1 = i_leadlag1'; - - % building Jacobian of expanded model - jacobian = zeros(endo_nbr+mult_nbr,nnz(i_leadlag1)+exo_nbr); - % derivatives of f.o.c. w.r. to endogenous variables - % to be rearranged further down - lbarfH = lbar'*fH; - % indices of Hessian columns - n1 = nnz(i_leadlag)+exo_nbr; - iH = reshape(1:n1^2,n1,n1); - J = zeros(endo_nbr1,nnz(i_leadlag1)+exo_nbr); - % second order derivatives of objective function - J(1:endo_nbr,i_leadlag1(max_leadlag1+1,1:endo_nbr)) = Uyy; - % loop on lead/lags in expanded model - for i=1:2*max_leadlag1 + 1 - % index of variables at the current lag in expanded model - kc = find(i_leadlag1(i,i_endo_nbr) > 0); - t1 = max(1,i-max_leadlag1); - t2 = min(i,max_leadlag1+1); - % loop on lead/lag blocks of relevant 1st order derivatives - for j = t1:t2 - % derivatives w.r. endogenous variables - ic = find(i_leadlag(i-j+1,:) > 0 ); - kc1 = i_leadlag(i-j+1,ic); - [junk,ic1,ic2] = intersect(ic,kc); - kc2 = i_leadlag1(i,kc(ic2)); - ir = find(i_leadlag(max_leadlag1+2-j,:) > 0 ); - kr1 = i_leadlag(max_leadlag1+2-j,ir); - J(ir,kc2) = J(ir,kc2) + beta^(j-max_lead-1)... - *reshape(lbarfH(iH(kr1,kc1)),length(kr1),length(kc1)); - end - end - % derivatives w.r. aux. variables for lead/lag exogenous shocks - for i=1:leadlag_nbr - kc = i_leadlag1(max_lag+i,endo_nbr+(1:exo_nbr)); - ir = find(i_leadlag(leadlag_nbr+1-i,:) > 0); - kr1 = i_leadlag(leadlag_nbr+1-i,ir); - J(ir,kc) = beta^(i-max_lead-1)... - *reshape(lbarfH(iH(kr1,n_dyn+(1:exo_nbr))),length(kr1), ... - exo_nbr); - end - % derivatives w.r. Lagrange multipliers - for i=1:leadlag_nbr - ic1 = find(i_leadlag(leadlag_nbr+1-i,:) > 0); - kc1 = i_leadlag(leadlag_nbr+1-i,ic1); - ic2 = find(i_leadlag1(max_lag+i,endo_nbr+exo_nbr+(1:mult_nbr)) > 0); - kc2 = i_leadlag1(max_lag+i,endo_nbr+exo_nbr+ic2); - J(ic1,kc2) = beta^(i-max_lead-1)*fJ(ic2,kc1)'; - end - - % Jacobian of original equations - % - % w.r. endogenous variables - ir = endo_nbr+(1:endo_nbr-instr_nbr); - for i=1:leadlag_nbr - ic1 = find(i_leadlag(i,:) > 0); - kc1 = i_leadlag(i,ic1); - ic2 = find(i_leadlag1(max_lead+i,:) > 0); - kc2 = i_leadlag1(max_lead+i,ic2); - [junk,junk,ic3] = intersect(ic1,ic2); - J(ir,kc2(ic3)) = fJ(:,kc1); - end - % w.r. exogenous variables - J(ir,nnz(i_leadlag1)+(1:exo_nbr)) = fJ(:,nnz(i_leadlag)+(1:exo_nbr)); - - % auxiliary variable for exogenous shocks - ir = 2*endo_nbr-instr_nbr+(1:exo_nbr); - kc = i_leadlag1(leadlag_nbr,endo_nbr+(1:exo_nbr)); - J(ir,kc) = eye(exo_nbr); - J(ir,nnz(i_leadlag1)+(1:exo_nbr)) = -eye(exo_nbr); - - % eliminating empty columns - - % getting indices of nonzero entries - m = find(i_leadlag1'); - n1 = max_lag1*endo_nbr1+1; - n2 = n1+endo_nbr-1; - - - n = length(m); - k = 1:size(J,2); - - for i=1:n - if sum(abs(J(:,i))) < 1e-8 - if m(i) < n1 | m(i) > n2 - k(i) = 0; - m(i) = 0; - end - end - end - - J = J(:,nonzeros(k)); - i_leadlag1 = zeros(size(i_leadlag1))'; - i_leadlag1(nonzeros(m)) = 1:nnz(m); - i_leadlag1 = i_leadlag1'; - - % setting expanded model parameters - % storing original values - M_.endo_nbr = endo_nbr1; - % Consider that there is no auxiliary variable, because otherwise it - % interacts badly with the auxiliary variables from the preprocessor. - M_.orig_endo_nbr = endo_nbr1; - M_.aux_vars = []; - M_.endo_names = endo_names1; - M_.lead_lag_incidence = i_leadlag1; - M_.maximum_lead = max_lead1; - M_.maximum_endo_lead = max_lead1; - M_.maximum_lag = max_lag1; - M_.maximum_endo_lag = max_lag1; - M_.orig_model = orig_model; +function [J,M_] = dyn_ramsey_dynamic_(ys,lbar,M_,options_,oo_,it_) +% function J = dyn_ramsey_dynamic_(ys,lbar) +% dyn_ramsey_dynamic_ sets up the Jacobian of the expanded model for optimal +% policies. It modifies several fields of M_ +% +% INPUTS: +% ys: steady state of original endogenous variables +% lbar: steady state of Lagrange multipliers +% +% OUPTUTS: +% J: jaocobian of expanded model +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2003-2009 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 <http://www.gnu.org/licenses/>. + +% retrieving model parameters +endo_nbr = M_.endo_nbr; +i_endo_nbr = 1:endo_nbr; +endo_names = M_.endo_names; +% exo_nbr = M_.exo_nbr+M_.exo_det_nbr; +% exo_names = vertcat(M_.exo_names,M_.exo_det_names); +exo_nbr = M_.exo_nbr; +exo_names = M_.exo_names; +i_leadlag = M_.lead_lag_incidence; +max_lead = M_.maximum_lead; +max_endo_lead = M_.maximum_endo_lead; +max_lag = M_.maximum_lag; +max_endo_lag = M_.maximum_endo_lag; +leadlag_nbr = max_lead+max_lag+1; +fname = M_.fname; +% instr_names = options_.olr_inst; +% instr_nbr = size(options_.olr_inst,1); + +% discount factor +beta = options_.planner_discount; + +% storing original values +orig_model.endo_nbr = endo_nbr; +orig_model.orig_endo_nbr = M_.orig_endo_nbr; +orig_model.aux_vars = M_.aux_vars; +orig_model.endo_names = endo_names; +orig_model.lead_lag_incidence = i_leadlag; +orig_model.maximum_lead = max_lead; +orig_model.maximum_endo_lead = max_endo_lead; +orig_model.maximum_lag = max_lag; +orig_model.maximum_endo_lag = max_endo_lag; + +y = repmat(ys,1,max_lag+max_lead+1); +k = find(i_leadlag'); + +% retrieving derivatives of the objective function +[U,Uy,Uyy] = feval([fname '_objective_static'],ys,zeros(1,exo_nbr), M_.params); +Uy = Uy'; +Uyy = reshape(Uyy,endo_nbr,endo_nbr); + +% retrieving derivatives of original model +[f,fJ,fH] = feval([fname '_dynamic'],y(k),[oo_.exo_simul oo_.exo_det_simul], M_.params, it_); +instr_nbr = endo_nbr - size(f,1); +mult_nbr = endo_nbr-instr_nbr; + +% parameters for expanded model +endo_nbr1 = 2*endo_nbr-instr_nbr+exo_nbr; +max_lead1 = max_lead + max_lag; +max_lag1 = max_lead1; +max_leadlag1 = max_lead1; + +% adding new variables names +endo_names1 = endo_names; +% adding shocks to endogenous variables +endo_names1 = strvcat(endo_names1, exo_names); +% adding multipliers names +for i=1:mult_nbr; + endo_names1 = strvcat(endo_names1,['mult_' int2str(i)]); +end + +% expanding matrix of lead/lag incidence +% +% multipliers lead/lag incidence +i_mult = []; +for i=1:leadlag_nbr + i_mult = [any(fJ(:,nonzeros(i_leadlag(i,:))) ~= 0,2)' ; i_mult]; +end +% putting it all together: +% original variables, exogenous variables made endogenous, multipliers +% +% number of original dynamic variables +n_dyn = nnz(i_leadlag); +% numbering columns of dynamic multipliers to be put in the last columns +% of the new Jacobian +i_leadlag1 = [cumsum(i_leadlag(1:max_lag,:),1); ... + repmat(i_leadlag(max_lag+1,:),leadlag_nbr,1); ... + flipud(cumsum(flipud(i_leadlag(max_lag+2:end,:)),1))]; +i_leadlag1 = i_leadlag1'; +k = find(i_leadlag1 > 0); +n = length(k); +i_leadlag1(k) = 1:n; +i_leadlag1 = i_leadlag1'; +i_mult = i_mult'; +k = find(i_mult > 0); +i_mult(k) = n+leadlag_nbr*exo_nbr+(1:length(k)); +i_mult = i_mult'; +i_leadlag1 = [ i_leadlag1 ... + [zeros(max_lag,exo_nbr);... + reshape(n+(1:leadlag_nbr*exo_nbr),exo_nbr,leadlag_nbr)'; ... + zeros(max_lead,exo_nbr)] ... + [zeros(max_lag,mult_nbr);... + i_mult;... + zeros(max_lead,mult_nbr)]]; +i_leadlag1 = i_leadlag1'; +k = find(i_leadlag1 > 0); +n = length(k); +i_leadlag1(k) = 1:n; +i_leadlag1 = i_leadlag1'; + +% building Jacobian of expanded model +jacobian = zeros(endo_nbr+mult_nbr,nnz(i_leadlag1)+exo_nbr); +% derivatives of f.o.c. w.r. to endogenous variables +% to be rearranged further down +lbarfH = lbar'*fH; +% indices of Hessian columns +n1 = nnz(i_leadlag)+exo_nbr; +iH = reshape(1:n1^2,n1,n1); +J = zeros(endo_nbr1,nnz(i_leadlag1)+exo_nbr); +% second order derivatives of objective function +J(1:endo_nbr,i_leadlag1(max_leadlag1+1,1:endo_nbr)) = Uyy; +% loop on lead/lags in expanded model +for i=1:2*max_leadlag1 + 1 + % index of variables at the current lag in expanded model + kc = find(i_leadlag1(i,i_endo_nbr) > 0); + t1 = max(1,i-max_leadlag1); + t2 = min(i,max_leadlag1+1); + % loop on lead/lag blocks of relevant 1st order derivatives + for j = t1:t2 + % derivatives w.r. endogenous variables + ic = find(i_leadlag(i-j+1,:) > 0 ); + kc1 = i_leadlag(i-j+1,ic); + [junk,ic1,ic2] = intersect(ic,kc); + kc2 = i_leadlag1(i,kc(ic2)); + ir = find(i_leadlag(max_leadlag1+2-j,:) > 0 ); + kr1 = i_leadlag(max_leadlag1+2-j,ir); + J(ir,kc2) = J(ir,kc2) + beta^(j-max_lead-1)... + *reshape(lbarfH(iH(kr1,kc1)),length(kr1),length(kc1)); + end +end +% derivatives w.r. aux. variables for lead/lag exogenous shocks +for i=1:leadlag_nbr + kc = i_leadlag1(max_lag+i,endo_nbr+(1:exo_nbr)); + ir = find(i_leadlag(leadlag_nbr+1-i,:) > 0); + kr1 = i_leadlag(leadlag_nbr+1-i,ir); + J(ir,kc) = beta^(i-max_lead-1)... + *reshape(lbarfH(iH(kr1,n_dyn+(1:exo_nbr))),length(kr1), ... + exo_nbr); +end +% derivatives w.r. Lagrange multipliers +for i=1:leadlag_nbr + ic1 = find(i_leadlag(leadlag_nbr+1-i,:) > 0); + kc1 = i_leadlag(leadlag_nbr+1-i,ic1); + ic2 = find(i_leadlag1(max_lag+i,endo_nbr+exo_nbr+(1:mult_nbr)) > 0); + kc2 = i_leadlag1(max_lag+i,endo_nbr+exo_nbr+ic2); + J(ic1,kc2) = beta^(i-max_lead-1)*fJ(ic2,kc1)'; +end + +% Jacobian of original equations +% +% w.r. endogenous variables +ir = endo_nbr+(1:endo_nbr-instr_nbr); +for i=1:leadlag_nbr + ic1 = find(i_leadlag(i,:) > 0); + kc1 = i_leadlag(i,ic1); + ic2 = find(i_leadlag1(max_lead+i,:) > 0); + kc2 = i_leadlag1(max_lead+i,ic2); + [junk,junk,ic3] = intersect(ic1,ic2); + J(ir,kc2(ic3)) = fJ(:,kc1); +end +% w.r. exogenous variables +J(ir,nnz(i_leadlag1)+(1:exo_nbr)) = fJ(:,nnz(i_leadlag)+(1:exo_nbr)); + +% auxiliary variable for exogenous shocks +ir = 2*endo_nbr-instr_nbr+(1:exo_nbr); +kc = i_leadlag1(leadlag_nbr,endo_nbr+(1:exo_nbr)); +J(ir,kc) = eye(exo_nbr); +J(ir,nnz(i_leadlag1)+(1:exo_nbr)) = -eye(exo_nbr); + +% eliminating empty columns + +% getting indices of nonzero entries +m = find(i_leadlag1'); +n1 = max_lag1*endo_nbr1+1; +n2 = n1+endo_nbr-1; + + +n = length(m); +k = 1:size(J,2); + +for i=1:n + if sum(abs(J(:,i))) < 1e-8 + if m(i) < n1 | m(i) > n2 + k(i) = 0; + m(i) = 0; + end + end +end + +J = J(:,nonzeros(k)); +i_leadlag1 = zeros(size(i_leadlag1))'; +i_leadlag1(nonzeros(m)) = 1:nnz(m); +i_leadlag1 = i_leadlag1'; + +% setting expanded model parameters +% storing original values +M_.endo_nbr = endo_nbr1; +% Consider that there is no auxiliary variable, because otherwise it +% interacts badly with the auxiliary variables from the preprocessor. +M_.orig_endo_nbr = endo_nbr1; +M_.aux_vars = []; +M_.endo_names = endo_names1; +M_.lead_lag_incidence = i_leadlag1; +M_.maximum_lead = max_lead1; +M_.maximum_endo_lead = max_lead1; +M_.maximum_lag = max_lag1; +M_.maximum_endo_lag = max_lag1; +M_.orig_model = orig_model; diff --git a/matlab/dyn_ramsey_static_.m b/matlab/dyn_ramsey_static_.m index 0bff491eae..f887de4db8 100644 --- a/matlab/dyn_ramsey_static_.m +++ b/matlab/dyn_ramsey_static_.m @@ -1,138 +1,137 @@ -function [resids, rJ,mult] = dyn_ramsey_static_(x,M_,options_,oo_,it_) - -% function [resids, rJ,mult] = dyn_ramsey_static_(x) -% Computes the static first order conditions for optimal policy -% -% INPUTS -% x: vector of endogenous variables -% -% OUTPUTS -% resids: residuals of non linear equations -% rJ: Jacobian -% mult: Lagrangian multipliers -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2003-2007 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 <http://www.gnu.org/licenses/>. - - - % recovering usefull fields - endo_nbr = M_.endo_nbr; - exo_nbr = M_.exo_nbr; - fname = M_.fname; - % inst_nbr = M_.inst_nbr; - % i_endo_no_inst = M_.endogenous_variables_without_instruments; - max_lead = M_.maximum_lead; - max_lag = M_.maximum_lag; - beta = options_.planner_discount; - - % indices of all endogenous variables - i_endo = [1:endo_nbr]'; - % indices of endogenous variable except instruments - % i_inst = M_.instruments; - % lead_lag incidence matrix for endogenous variables - i_lag = M_.lead_lag_incidence; - - if options_.steadystate_flag - k_inst = []; - instruments = options_.instruments; - for i = 1:size(instruments,1) - k_inst = [k_inst; strmatch(options_.instruments(i,:), ... - M_.endo_names,'exact')]; - end - oo_.steady_state(k_inst) = x; - [x,check] = feval([M_.fname '_steadystate'],... - oo_.steady_state,... - [oo_.exo_steady_state; ... - oo_.exo_det_steady_state]); - if size(x,1) < M_.endo_nbr - if length(M_.aux_vars) > 0 - x = add_auxiliary_variables_to_steadystate(x,M_.aux_vars,... - M_.fname,... - oo_.exo_steady_state,... - oo_.exo_det_steady_state,... - M_.params); - else - error([M_.fname '_steadystate.m doesn''t match the model']); - end - end - end - - % value and Jacobian of objective function - ex = zeros(1,M_.exo_nbr); - [U,Uy,Uyy] = feval([fname '_objective_static'],x(i_endo),ex, M_.params); - Uy = Uy'; - Uyy = reshape(Uyy,endo_nbr,endo_nbr); - - y = repmat(x(i_endo),1,max_lag+max_lead+1); - % value and Jacobian of dynamic function - k = find(i_lag'); - it_ = 1; -% [f,fJ,fH] = feval([fname '_dynamic'],y(k),ex); - [f,fJ] = feval([fname '_dynamic'],y(k),[oo_.exo_simul oo_.exo_det_simul], M_.params, it_); - % indices of Lagrange multipliers - inst_nbr = endo_nbr - size(f,1); - i_mult = [endo_nbr+1:2*endo_nbr-inst_nbr]'; - - % derivatives of Lagrangian with respect to endogenous variables -% res1 = Uy; - A = zeros(endo_nbr,endo_nbr-inst_nbr); - for i=1:max_lag+max_lead+1 - % select variables present in the model at a given lag - [junk,k1,k2] = find(i_lag(i,:)); -% res1(k1) = res1(k1) + beta^(max_lag-i+1)*fJ(:,k2)'*x(i_mult); - A(k1,:) = A(k1,:) + beta^(max_lag-i+1)*fJ(:,k2)'; - end - -% i_inst = var_index(options_.olr_inst); -% k = setdiff(1:size(A,1),i_inst); -% mult = -A(k,:)\Uy(k); - mult = -A\Uy; -% resids = [f; Uy(i_inst)+A(i_inst,:)*mult]; - resids1 = Uy+A*mult; -% resids = [f; sqrt(resids1'*resids1/endo_nbr)]; - [q,r,e] = qr([A Uy]'); - if options_.steadystate_flag - resids = [r(end,(endo_nbr-inst_nbr+1:end))']; - else - resids = [f; r(end,(endo_nbr-inst_nbr+1:end))']; - end - rJ = []; - return; - - % Jacobian of first order conditions - n = nnz(i_lag)+exo_nbr; - iH = reshape(1:n^2,n,n); - rJ = zeros(2*endo_nbr-inst_nbr,2*endo_nbr-inst_nbr); - - rJ(i_endo,i_endo) = Uyy; - for i=1:max_lag+max_lead+1 - % select variables present in the model at a given lag - [junk,k1,k2] = find(i_lag(i,:)); - k3 = length(k2); - rJ(k1,k1) = rJ(k1,k1) + beta^(max_lag-i+1)*reshape(fH(:,iH(k2,k2))'*x(i_mult),k3,k3); - rJ(k1,i_mult) = rJ(k1,i_mult) + beta^(max_lag-1+1)*fJ(:,k2)'; - rJ(i_mult,k1) = rJ(i_mult,k1) + fJ(:,k2); - end - -% rJ = 1e-3*rJ; -% rJ(209,210) = rJ(209,210)+1-1e-3; - - - \ No newline at end of file +function [resids, rJ,mult] = dyn_ramsey_static_(x,M_,options_,oo_,it_) + +% function [resids, rJ,mult] = dyn_ramsey_static_(x) +% Computes the static first order conditions for optimal policy +% +% INPUTS +% x: vector of endogenous variables +% +% OUTPUTS +% resids: residuals of non linear equations +% rJ: Jacobian +% mult: Lagrangian multipliers +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2003-2007 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 <http://www.gnu.org/licenses/>. + + +% recovering usefull fields +endo_nbr = M_.endo_nbr; +exo_nbr = M_.exo_nbr; +fname = M_.fname; +% inst_nbr = M_.inst_nbr; +% i_endo_no_inst = M_.endogenous_variables_without_instruments; +max_lead = M_.maximum_lead; +max_lag = M_.maximum_lag; +beta = options_.planner_discount; + +% indices of all endogenous variables +i_endo = [1:endo_nbr]'; +% indices of endogenous variable except instruments +% i_inst = M_.instruments; +% lead_lag incidence matrix for endogenous variables +i_lag = M_.lead_lag_incidence; + +if options_.steadystate_flag + k_inst = []; + instruments = options_.instruments; + for i = 1:size(instruments,1) + k_inst = [k_inst; strmatch(options_.instruments(i,:), ... + M_.endo_names,'exact')]; + end + oo_.steady_state(k_inst) = x; + [x,check] = feval([M_.fname '_steadystate'],... + oo_.steady_state,... + [oo_.exo_steady_state; ... + oo_.exo_det_steady_state]); + if size(x,1) < M_.endo_nbr + if length(M_.aux_vars) > 0 + x = add_auxiliary_variables_to_steadystate(x,M_.aux_vars,... + M_.fname,... + oo_.exo_steady_state,... + oo_.exo_det_steady_state,... + M_.params); + else + error([M_.fname '_steadystate.m doesn''t match the model']); + end + end +end + +% value and Jacobian of objective function +ex = zeros(1,M_.exo_nbr); +[U,Uy,Uyy] = feval([fname '_objective_static'],x(i_endo),ex, M_.params); +Uy = Uy'; +Uyy = reshape(Uyy,endo_nbr,endo_nbr); + +y = repmat(x(i_endo),1,max_lag+max_lead+1); +% value and Jacobian of dynamic function +k = find(i_lag'); +it_ = 1; +% [f,fJ,fH] = feval([fname '_dynamic'],y(k),ex); +[f,fJ] = feval([fname '_dynamic'],y(k),[oo_.exo_simul oo_.exo_det_simul], M_.params, it_); +% indices of Lagrange multipliers +inst_nbr = endo_nbr - size(f,1); +i_mult = [endo_nbr+1:2*endo_nbr-inst_nbr]'; + +% derivatives of Lagrangian with respect to endogenous variables +% res1 = Uy; +A = zeros(endo_nbr,endo_nbr-inst_nbr); +for i=1:max_lag+max_lead+1 + % select variables present in the model at a given lag + [junk,k1,k2] = find(i_lag(i,:)); + % res1(k1) = res1(k1) + beta^(max_lag-i+1)*fJ(:,k2)'*x(i_mult); + A(k1,:) = A(k1,:) + beta^(max_lag-i+1)*fJ(:,k2)'; +end + +% i_inst = var_index(options_.olr_inst); +% k = setdiff(1:size(A,1),i_inst); +% mult = -A(k,:)\Uy(k); +mult = -A\Uy; +% resids = [f; Uy(i_inst)+A(i_inst,:)*mult]; +resids1 = Uy+A*mult; +% resids = [f; sqrt(resids1'*resids1/endo_nbr)]; +[q,r,e] = qr([A Uy]'); +if options_.steadystate_flag + resids = [r(end,(endo_nbr-inst_nbr+1:end))']; +else + resids = [f; r(end,(endo_nbr-inst_nbr+1:end))']; +end +rJ = []; +return; + +% Jacobian of first order conditions +n = nnz(i_lag)+exo_nbr; +iH = reshape(1:n^2,n,n); +rJ = zeros(2*endo_nbr-inst_nbr,2*endo_nbr-inst_nbr); + +rJ(i_endo,i_endo) = Uyy; +for i=1:max_lag+max_lead+1 + % select variables present in the model at a given lag + [junk,k1,k2] = find(i_lag(i,:)); + k3 = length(k2); + rJ(k1,k1) = rJ(k1,k1) + beta^(max_lag-i+1)*reshape(fH(:,iH(k2,k2))'*x(i_mult),k3,k3); + rJ(k1,i_mult) = rJ(k1,i_mult) + beta^(max_lag-1+1)*fJ(:,k2)'; + rJ(i_mult,k1) = rJ(i_mult,k1) + fJ(:,k2); +end + +% rJ = 1e-3*rJ; +% rJ(209,210) = rJ(209,210)+1-1e-3; + + diff --git a/matlab/dynare.m b/matlab/dynare.m index 9f2a8d58a9..6fcee82f62 100644 --- a/matlab/dynare.m +++ b/matlab/dynare.m @@ -59,13 +59,13 @@ end warning_config() if exist('OCTAVE_VERSION') - if octave_ver_less_than('3.0.0') - warning('This version of Dynare has only been tested on Octave 3.0.0 and above. Since your Octave version is older than that, Dynare may fail to run, or give unexpected results. Consider upgrading your Octave installation.'); - end + if octave_ver_less_than('3.0.0') + warning('This version of Dynare has only been tested on Octave 3.0.0 and above. Since your Octave version is older than that, Dynare may fail to run, or give unexpected results. Consider upgrading your Octave installation.'); + end else - if matlab_ver_less_than('6.5') - warning('This version of Dynare has only been tested on Matlab 6.5 and above. Since your Matlab version is older than that, Dynare may fail to run, or give unexpected results. Consider upgrading your Matlab installation (or switch to Octave).'); - end + if matlab_ver_less_than('6.5') + warning('This version of Dynare has only been tested on Matlab 6.5 and above. Since your Matlab version is older than that, Dynare may fail to run, or give unexpected results. Consider upgrading your Matlab installation (or switch to Octave).'); + end end % disable output paging (it is on by default on Octave) @@ -73,44 +73,44 @@ more off % sets default format for save() command if exist('OCTAVE_VERSION') - default_save_options('-mat') + default_save_options('-mat') end % detect if MEX files are present; if not, use alternative M-files dynareroot = dynare_config; if nargin < 1 - error('DYNARE: you must provide the name of the MOD file in argument') + error('DYNARE: you must provide the name of the MOD file in argument') end if ~ischar(fname) - error('DYNARE: argument of dynare must be a text string') + error('DYNARE: argument of dynare must be a text string') end % Testing if file have extension % If no extension default .mod is added if isempty(strfind(fname,'.')) - fname1 = [fname '.dyn']; - d = dir(fname1); - if length(d) == 0 - fname1 = [fname '.mod']; - end - fname = fname1; - % Checking file extension + fname1 = [fname '.dyn']; + d = dir(fname1); + if length(d) == 0 + fname1 = [fname '.mod']; + end + fname = fname1; + % Checking file extension else - if ~strcmp(upper(fname(size(fname,2)-3:size(fname,2))),'.MOD') ... - && ~strcmp(upper(fname(size(fname,2)-3:size(fname,2))),'.DYN') - error('DYNARE: argument must be a filename with .mod or .dyn extension') - end; + if ~strcmp(upper(fname(size(fname,2)-3:size(fname,2))),'.MOD') ... + && ~strcmp(upper(fname(size(fname,2)-3:size(fname,2))),'.DYN') + error('DYNARE: argument must be a filename with .mod or .dyn extension') + end; end; d = dir(fname); if length(d) == 0 - error(['DYNARE: can''t open ' fname]) + error(['DYNARE: can''t open ' fname]) end command = ['"' dynareroot 'dynare_m" ' fname] ; for i=2:nargin - command = [command ' ' varargin{i-1}]; + command = [command ' ' varargin{i-1}]; end % Workaround for bug in Octave >= 3.2 @@ -122,11 +122,11 @@ end [status, result] = system(command); disp(result) if status - % Should not use "error(result)" since message will be truncated if too long - error('DYNARE: preprocessing failed') + % Should not use "error(result)" since message will be truncated if too long + error('DYNARE: preprocessing failed') end if ~ isempty(find(abs(fname) == 46)) - fname = fname(:,1:find(abs(fname) == 46)-1) ; + fname = fname(:,1:find(abs(fname) == 46)-1) ; end evalin('base',fname) ; diff --git a/matlab/dynare_config.m b/matlab/dynare_config.m index 9878f7b64b..d3a8c8d55b 100644 --- a/matlab/dynare_config.m +++ b/matlab/dynare_config.m @@ -189,29 +189,29 @@ end % Test if bytecode DLL is present if exist('bytecode') == 3 - if ~multithread_flag - message = '[mex] '; - else - message = [ '[mex][multithread version, ' int2str(multithread_flag+1) ' threads are used] ' ]; - end + if ~multithread_flag + message = '[mex] '; + else + message = [ '[mex][multithread version, ' int2str(multithread_flag+1) ' threads are used] ' ]; + end else - message = '[no] '; + message = '[no] '; end disp([ message 'Bytecode evaluation.' ]) % Test if k-order perturbation DLL is present if exist('k_order_perturbation') == 3 - message = '[mex] '; + message = '[mex] '; else - message = '[no] '; + message = '[no] '; end disp([ message 'k-order perturbation solver.' ]) % Test if dynare_simul_ DLL is present if exist('dynare_simul_') == 3 - message = '[mex] '; + message = '[mex] '; else - message = '[no] '; + message = '[no] '; end disp([ message 'k-order solution simulation.' ]) diff --git a/matlab/dynare_estimation_1.m b/matlab/dynare_estimation_1.m index 6d6399458a..87727053e7 100644 --- a/matlab/dynare_estimation_1.m +++ b/matlab/dynare_estimation_1.m @@ -1,1586 +1,1586 @@ -function dynare_estimation_1(var_list_,dname) -% function dynare_estimation_1(var_list_,dname) -% runs the estimation of the model -% -% INPUTS -% var_list_: selected endogenous variables vector -% dname: alternative directory name -% -% OUTPUTS -% none -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2003-2009 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 <http://www.gnu.org/licenses/>. - -global M_ options_ oo_ estim_params_ bayestopt_ - -options_.lgyidx2varobs = zeros(size(M_.endo_names,1),1); -for i = 1:size(M_.endo_names,1) - tmp = strmatch(deblank(M_.endo_names(i,:)),options_.varobs,'exact'); - if ~isempty(tmp) - options_.lgyidx2varobs(i,1) = tmp; - end -end - -%% Set the order of approximation to one (if needed). -if options_.order > 1 - options_.order = 1; -end - -%% Set options_.lik_init equal to 3 if diffuse filter is used. -if (options_.diffuse_filter==1) && (options_.lik_init==1) - options_.lik_init = 3; -end - -%% If the data are prefiltered then there must not be constants in the -%% measurement equation of the DSGE model or in the DSGE-VAR model. -if options_.prefilter == 1 - options_.noconstant = 1; -end - -%% Set options related to filtered variables. -if options_.filtered_vars ~= 0 & isempty(options_.filter_step_ahead), - options_.filter_step_ahead = 1; -end -if options_.filtered_vars ~= 0 & options_.filter_step_ahead == 0, - options_.filter_step_ahead = 1; -end -if options_.filter_step_ahead ~= 0 - options_.nk = max(options_.filter_step_ahead); -end - -%% Set the name of the directory where (intermediary) results will be saved. -if nargin>1 - M_.dname = dname; -else - M_.dname = M_.fname; -end -%% Set the names of the priors. -pnames = [' ';'beta ';'gamm ';'norm ';'invg ';'unif ';'invg2']; - -%% Set the number of observed variables. -n_varobs = size(options_.varobs,1); - -%% Set priors over the estimated parameters. -if ~isempty(estim_params_) - [xparam1,estim_params_,bayestopt_,lb,ub,M_] = set_prior(estim_params_,M_,options_); - if any(bayestopt_.pshape > 0) - % Plot prior densities. - if options_.plot_priors - plot_priors(bayestopt_,M_,options_) - end - % Set prior bounds - bounds = prior_bounds(bayestopt_); - bounds(:,1)=max(bounds(:,1),lb); - bounds(:,2)=min(bounds(:,2),ub); - else - % No priors are declared so Dynare will estimate the model by - % maximum likelihood with inequality constraints for the parameters. - options_.mh_replic = 0;% No metropolis. - bounds(:,1) = lb; - bounds(:,2) = ub; - end - % Test if initial values of the estimated parameters are all between - % the prior lower and upper bounds. - if any(xparam1 < bounds(:,1)) | any(xparam1 > bounds(:,2)) - find(xparam1 < bounds(:,1)) - find(xparam1 > bounds(:,2)) - error('Initial parameter values are outside parameter bounds') - end - lb = bounds(:,1); - ub = bounds(:,2); - bayestopt_.lb = lb; - bayestopt_.ub = ub; -else% If estim_params_ is empty... - xparam1 = []; - bayestopt_.lb = []; - bayestopt_.ub = []; - bayestopt_.jscale = []; - bayestopt_.pshape = []; - bayestopt_.p1 = []; - bayestopt_.p2 = []; - bayestopt_.p3 = []; - bayestopt_.p4 = []; - bayestopt_.p5 = []; - bayestopt_.p6 = []; - bayestopt_.p7 = []; - estim_params_.nvx = 0; - estim_params_.nvn = 0; - estim_params_.ncx = 0; - estim_params_.ncn = 0; - estim_params_.np = 0; -end - -%% Get the number of parameters to be estimated. -nvx = estim_params_.nvx; % Variance of the structural innovations (number of parameters). -nvn = estim_params_.nvn; % Variance of the measurement innovations (number of parameters). -ncx = estim_params_.ncx; % Covariance of the structural innovations (number of parameters). -ncn = estim_params_.ncn; % Covariance of the measurement innovations (number of parameters). -np = estim_params_.np ; % Number of deep parameters. -nx = nvx+nvn+ncx+ncn+np; % Total number of parameters to be estimated. - -%% Is there a linear trend in the measurement equation? -if ~isfield(options_,'trend_coeffs') % No! - bayestopt_.with_trend = 0; -else% Yes! - bayestopt_.with_trend = 1; - bayestopt_.trend_coeff = {}; - trend_coeffs = options_.trend_coeffs; - nt = length(trend_coeffs); - for i=1:n_varobs - if i > length(trend_coeffs) - bayestopt_.trend_coeff{i} = '0'; - else - bayestopt_.trend_coeff{i} = trend_coeffs{i}; - end - end -end - -%% Set the "size" of penalty. -bayestopt_.penalty = 1e8; - -%% Get informations about the variables of the model. -dr = set_state_space([],M_); -nstatic = dr.nstatic; % Number of static variables. -npred = dr.npred; % Number of predetermined variables. -nspred = dr.nspred; % Number of predetermined variables in the state equation. - -%% Test if observed variables are declared. -if isempty(options_.varobs) - error('ESTIMATION: VAROBS is missing') -end - -%% Setting resticted state space (observed + predetermined variables) -k = []; -k1 = []; -for i=1:n_varobs - k = [k strmatch(deblank(options_.varobs(i,:)),M_.endo_names(dr.order_var,:),'exact')]; - k1 = [k1 strmatch(deblank(options_.varobs(i,:)),M_.endo_names, 'exact')]; -end -% Define union of observed and state variables -k2 = union(k',[dr.nstatic+1:dr.nstatic+dr.npred]'); -% Set restrict_state to postion of observed + state variables in expanded state vector. -bayestopt_.restrict_var_list = k2; -% set mf0 to positions of state variables in restricted state vector for likelihood computation. -[junk,bayestopt_.mf0] = ismember([dr.nstatic+1:dr.nstatic+dr.npred]',k2); -% Set mf1 to positions of observed variables in restricted state vector for likelihood computation. -[junk,bayestopt_.mf1] = ismember(k,k2); -% Set mf2 to positions of observed variables in expanded state vector for filtering and smoothing. -bayestopt_.mf2 = k; -bayestopt_.mfys = k1; - -[junk,ic] = intersect(k2,nstatic+(1:npred)'); -bayestopt_.restrict_columns = [ic; length(k2)+(1:nspred-npred)']; -aux = dr.transition_auxiliary_variables; -aux(:,2) = aux(:,2) + sum(k2 <= nstatic); -k = find(aux(:,2) > npred); -aux(k,2) = aux(k,2) + sum(k2 > nstatic+npred); -bayestopt_.restrict_aux = aux; - -%% Initialization with unit-root variables. -if ~isempty(options_.unit_root_vars) - n_ur = size(options_.unit_root_vars,1); - i_ur = zeros(n_ur,1); - for i=1:n_ur - i1 = strmatch(deblank(options_.unit_root_vars(i,:)),M_.endo_names(dr.order_var,:),'exact'); - if isempty(i1) - error('Undeclared variable in unit_root_vars statement') - end - i_ur(i) = i1; - end - bayestopt_.var_list_stationary = setdiff((1:M_.endo_nbr)',i_ur); - [junk,bayestopt_.restrict_var_list_nonstationary] = ... - intersect(bayestopt_.restrict_var_list,i_ur); - bayestopt_.restrict_var_list_stationary = ... - setdiff((1:length(bayestopt_.restrict_var_list))', ... - bayestopt_.restrict_var_list_nonstationary); - if M_.maximum_lag > 1 - l1 = flipud([cumsum(M_.lead_lag_incidence(1:M_.maximum_lag-1,dr.order_var),1);ones(1,M_.endo_nbr)]); - l2 = l1(:,bayestopt_.restrict_var_list); - il2 = find(l2' > 0); - l2(il2) = (1:length(il2))'; - bayestopt_.restrict_var_list_stationary = ... - nonzeros(l2(:,bayestopt_.restrict_var_list_stationary)); - bayestopt_.restrict_var_list_nonstationary = ... - nonzeros(l2(:,bayestopt_.restrict_var_list_nonstationary)); - end - options_.lik_init = 3; -end % if ~isempty(options_.unit_root_vars) - -%% Test if the data file is declared. -if isempty(options_.datafile) - error('ESTIMATION: datafile option is missing') -end - -%% If jscale isn't specified for an estimated parameter, use global option options_.jscale, set to 0.2, by default. -k = find(isnan(bayestopt_.jscale)); -bayestopt_.jscale(k) = options_.mh_jscale; - -%% Load and transform data. -rawdata = read_variables(options_.datafile,options_.varobs,[],options_.xls_sheet,options_.xls_range); -% Set the number of observations (nobs) and build a subsample between first_obs and nobs. -options_ = set_default_option(options_,'nobs',size(rawdata,1)-options_.first_obs+1); -gend = options_.nobs; -rawdata = rawdata(options_.first_obs:options_.first_obs+gend-1,:); -% Take the log of the variables if needed -if options_.loglinear % If the model is log-linearized... - if ~options_.logdata % and if the data are not in logs, then... - rawdata = log(rawdata); - end -end -% Test if the observations are real numbers. -if ~isreal(rawdata) - error('There are complex values in the data! Probably a wrong transformation') -end -% Test for missing observations. -options_.missing_data = any(any(isnan(rawdata))); -% Prefilter the data if needed. -if options_.prefilter == 1 - if options_.missing_data - bayestopt_.mean_varobs = zeros(n_varobs,1); - for variable=1:n_varobs - rdx = find(~isnan(rawdata(:,variable))); - m = mean(rawdata(rdx,variable)); - rawdata(rdx,variable) = rawdata(rdx,variable)-m; - bayestopt_.mean_varobs(variable) = m; - end - else - bayestopt_.mean_varobs = mean(rawdata,1)'; - rawdata = rawdata-repmat(bayestopt_.mean_varobs',gend,1); - end -end -% Transpose the dataset array. -data = transpose(rawdata); - -%% Set various options. -options_ = set_default_option(options_,'mh_nblck',2); -options_ = set_default_option(options_,'nodiagnostic',0); - -% load mode file is necessary -if length(options_.mode_file) > 0 && options_.posterior_mode_estimation - load(options_.mode_file); -end - -%% Compute the steady state: -if ~isempty(estim_params_) - set_parameters(xparam1); -end -if options_.steadystate_flag% if the *_steadystate.m file is provided. - [ys,tchek] = feval([M_.fname '_steadystate'],... - [zeros(M_.exo_nbr,1);... - oo_.exo_det_steady_state]); - if size(ys,1) < M_.endo_nbr - if length(M_.aux_vars) > 0 - ys = add_auxiliary_variables_to_steadystate(ys,M_.aux_vars,... - M_.fname,... - zeros(M_.exo_nbr,1),... - oo_.exo_det_steady_state,... - M_.params); - else - error([M_.fname '_steadystate.m doesn''t match the model']); - end - end - oo_.steady_state = ys; -else% if the steady state file is not provided. - [dd,info] = resol(oo_.steady_state,0); - oo_.steady_state = dd.ys; clear('dd'); -end -if all(abs(oo_.steady_state(bayestopt_.mfys))<1e-9) - options_.noconstant = 1; -else - options_.noconstant = 0; -end - - -%% compute sample moments if needed (bvar-dsge) -if options_.bvar_dsge - if options_.missing_data - error('I cannot estimate a DSGE-VAR model with missing observations!') - end - if options_.noconstant - evalin('base',... - ['[mYY,mXY,mYX,mXX,Ydata,Xdata] = ' ... - 'var_sample_moments(options_.first_obs,' ... - 'options_.first_obs+options_.nobs-1,options_.varlag,-1,' ... - 'options_.datafile, options_.varobs,options_.xls_sheet,options_.xls_range);']) - else% The steady state is non zero ==> a constant in the VAR is needed! - evalin('base',['[mYY,mXY,mYX,mXX,Ydata,Xdata] = ' ... - 'var_sample_moments(options_.first_obs,' ... - 'options_.first_obs+options_.nobs-1,options_.varlag,0,' ... - 'options_.datafile, options_.varobs,options_.xls_sheet,options_.xls_range);']) - end -end - -[data_index,number_of_observations,no_more_missing_observations] = describe_missing_data(data,gend,n_varobs); -missing_value = ~(number_of_observations == gend*n_varobs); - -initial_estimation_checks(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations); - -if options_.mode_compute == 0 - if options_.smoother == 1 - [atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,T,R,P,PK,d,decomp] = DsgeSmoother(xparam1,gend,data,data_index,missing_value); - oo_.Smoother.SteadyState = ys; - oo_.Smoother.TrendCoeffs = trend_coeff; - oo_.Smoother.integration_order = d; - oo_.Smoother.variance = P; - i_endo_nbr = 1:M_.endo_nbr; - if options_.nk ~= 0 - oo_.FilteredVariablesKStepAhead = aK(options_.filter_step_ahead,i_endo_nbr,:); - oo_.FilteredVariablesKStepAheadVariances = PK(options_.filter_step_ahead,i_endo_nbr,i_endo_nbr,:); - oo_.FilteredVariablesShockDecomposition = decomp(options_.filter_step_ahead,i_endo_nbr,:,:); - end - for i=1:M_.endo_nbr - eval(['oo_.SmoothedVariables.' deblank(M_.endo_names(dr.order_var(i),:)) ' = atT(i,:)'';']); - eval(['oo_.FilteredVariables.' deblank(M_.endo_names(dr.order_var(i),:)) ' = squeeze(aK(1,i,:));']); - eval(['oo_.UpdatedVariables.' deblank(M_.endo_names(dr.order_var(i),:)) ' = updated_variables(i,:)'';']); - end - for i=1:M_.exo_nbr - eval(['oo_.SmoothedShocks.' deblank(M_.exo_names(i,:)) ' = innov(i,:)'';']); - end - end - if length(options_.mode_file) == 0 - return; - end -end - -%% Estimation of the posterior mode or likelihood mode -if options_.mode_compute > 0 & options_.posterior_mode_estimation - if ~options_.bvar_dsge - fh=str2func('DsgeLikelihood'); - else - fh=str2func('DsgeVarLikelihood'); - end - switch options_.mode_compute - case 1 - optim_options = optimset('display','iter','LargeScale','off', ... - 'MaxFunEvals',100000,'TolFun',1e-8,'TolX',1e-6); - if isfield(options_,'optim_opt') - eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']); - end - if ~options_.bvar_dsge - [xparam1,fval,exitflag,output,lamdba,grad,hessian_fmincon] = ... - fmincon(fh,xparam1,[],[],[],[],lb,ub,[],optim_options,gend,data,data_index,number_of_observations,no_more_missing_observations); - else - [xparam1,fval,exitflag,output,lamdba,grad,hessian_fmincon] = ... - fmincon(fh,xparam1,[],[],[],[],lb,ub,[],optim_options,gend); - end - case 2 - error('ESTIMATION: mode_compute=2 option (Lester Ingber''s Adaptive Simulated Annealing) is no longer available') - case 3 - optim_options = optimset('display','iter','MaxFunEvals',100000,'TolFun',1e-8,'TolX',1e-6); - if isfield(options_,'optim_opt') - eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']); - end - if ~options_.bvar_dsge - [xparam1,fval,exitflag] = fminunc(fh,xparam1,optim_options,gend,data,data_index,number_of_observations,no_more_missing_observations); - else - [xparam1,fval,exitflag] = fminunc(fh,xparam1,optim_options,gend); - end - case 4 - H0 = 1e-4*eye(nx); - crit = 1e-7; - nit = 1000; - verbose = 2; - if ~options_.bvar_dsge - [fval,xparam1,grad,hessian_csminwel,itct,fcount,retcodehat] = ... - csminwel('DsgeLikelihood',xparam1,H0,[],crit,nit,options_.gradient_method,gend,data,data_index,number_of_observations,no_more_missing_observations); - disp(sprintf('Objective function at mode: %f',fval)) - disp(sprintf('Objective function at mode: %f',DsgeLikelihood(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations))) - else - [fval,xparam1,grad,hessian_csminwel,itct,fcount,retcodehat] = ... - csminwel('DsgeVarLikelihood',xparam1,H0,[],crit,nit,options_.gradient_method,gend); - disp(sprintf('Objective function at mode: %f',fval)) - disp(sprintf('Objective function at mode: %f',DsgeVarLikelihood(xparam1,gend))) - end - case 5 - if isfield(options_,'hess') - flag = options_.hess; - else - flag = 1; - end - if ~exist('igg'), % by M. Ratto - hh=[]; - gg=[]; - igg=[]; - end % by M. Ratto - if isfield(options_,'ftol') - crit = options_.ftol; - else - crit = 1.e-7; - end - if isfield(options_,'nit') - nit = options_.nit; - else - nit=1000; - end - if ~options_.bvar_dsge - [xparam1,hh,gg,fval,invhess] = newrat('DsgeLikelihood',xparam1,hh,gg,igg,crit,nit,flag,gend,data,data_index,number_of_observations,no_more_missing_observations); - else - [xparam1,hh,gg,fval,invhess] = newrat('DsgeVarLikelihood',xparam1,hh,gg,igg,crit,nit,flag,gend); - end - parameter_names = bayestopt_.name; - save([M_.fname '_mode.mat'],'xparam1','hh','gg','fval','invhess','parameter_names'); - case 6 - if ~options_.bvar_dsge - fval = DsgeLikelihood(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations); - else - fval = DsgeVarLikelihood(xparam1,gend); - end - OldMode = fval; - if ~exist('MeanPar') - MeanPar = xparam1; - end - if exist('hh') - CovJump = inv(hh); - else% The covariance matrix is initialized with the prior - % covariance (a diagonal matrix) %%Except for infinite variances ;-) - varinit = 'prior'; - if strcmpi(varinit,'prior') - stdev = bayestopt_.p2; - indx = find(isinf(stdev)); - stdev(indx) = ones(length(indx),1)*sqrt(10); - vars = stdev.^2; - CovJump = diag(vars); - elseif strcmpi(varinit,'eye') - vars = ones(length(bayestopt_.p2),1)*0.1; - CovJump = diag(vars); - else - disp('gmhmaxlik :: Error!') - return - end - end - OldPostVar = CovJump; - Scale = options_.mh_jscale; - for i=1:options_.Opt6Iter - if i == 1 - if options_.Opt6Iter > 1 - flag = ''; - else - flag = 'LastCall'; - end - if ~options_.bvar_dsge - [xparam1,PostVar,Scale,PostMean] = ... - gmhmaxlik('DsgeLikelihood',xparam1,bounds,options_.Opt6Numb,Scale,flag,MeanPar,CovJump,gend,data,... - data_index,number_of_observations,no_more_missing_observations); - fval = DsgeLikelihood(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations); - else - [xparam1,PostVar,Scale,PostMean] = ... - gmhmaxlik('DsgeVarLikelihood',xparam1,bounds,options_.Opt6Numb,Scale,flag,MeanPar,CovJump,gend); - fval = DsgeVarLikelihood(xparam1,gend); - end - options_.mh_jscale = Scale; - mouvement = max(max(abs(PostVar-OldPostVar))); - disp(['Change in the covariance matrix = ' num2str(mouvement) '.']) - disp(['Mode improvement = ' num2str(abs(OldMode-fval))]) - OldMode = fval; - else - OldPostVar = PostVar; - if i<options_.Opt6Iter - flag = ''; - else - flag = 'LastCall'; - end - if ~options_.bvar_dsge - [xparam1,PostVar,Scale,PostMean] = ... - gmhmaxlik('DsgeLikelihood',xparam1,bounds,... - options_.Opt6Numb,Scale,flag,PostMean,PostVar,gend,data,data_index,number_of_observations,no_more_missing_observations); - fval = DsgeLikelihood(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations); - else - [xparam1,PostVar,Scale,PostMean] = ... - gmhmaxlik('DsgeVarLikelihood',xparam1,bounds,... - options_.Opt6Numb,Scale,flag,PostMean,PostVar,gend); - fval = DsgeVarLikelihood(xparam1,gend); - end - options_.mh_jscale = Scale; - mouvement = max(max(abs(PostVar-OldPostVar))); - fval = DsgeLikelihood(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations); - disp(['Change in the covariance matrix = ' num2str(mouvement) '.']) - disp(['Mode improvement = ' num2str(abs(OldMode-fval))]) - OldMode = fval; - end - hh = inv(PostVar); - save([M_.fname '_mode.mat'],'xparam1','hh'); - bayestopt_.jscale = ones(length(xparam1),1)*Scale;%??! - end - case 7 - optim_options = optimset('display','iter','MaxFunEvals',1000000,'MaxIter',6000,'TolFun',1e-8,'TolX',1e-6); - if isfield(options_,'optim_opt') - eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']); - end - if ~options_.bvar_dsge - [xparam1,fval,exitflag] = fminsearch(fh,xparam1,optim_options,gend,data,data_index,number_of_observations,no_more_missing_observations); - else - [xparam1,fval,exitflag] = fminsearch(fh,xparam1,optim_options,gend); - end - - case 101 - myoptions=soptions; - myoptions(2)=1e-6; %accuracy of argument - myoptions(3)=1e-6; %accuracy of function (see Solvopt p.29) - myoptions(5)= 1.0; - - [xparam1,fval]=solvopt(xparam1,fh,[],myoptions,gend,data); - case 102 - %simulating annealing - % LB=zeros(size(xparam1))-20; - % UB=zeros(size(xparam1))+20; - LB = xparam1 - 1; - UB = xparam1 + 1; - neps=10; - % Set input parameters. - maxy=0; - eps=1.0e-9; - rt_=.10; - t=15.0; - ns=10; - nt=10; - maxevl=100000000; - idisp =1; - npar=length(xparam1); - - disp(['size of param',num2str(length(xparam1))]) - c=.1*ones(npar,1); - %* Set input values of the input/output parameters.* - - vm=1*ones(npar,1); - disp(['number of parameters= ' num2str(npar) 'max= ' num2str(maxy) 't= ' num2str(t)]); - disp(['rt_= ' num2str(rt_) 'eps= ' num2str(eps) 'ns= ' num2str(ns)]); - disp(['nt= ' num2str(nt) 'neps= ' num2str(neps) 'maxevl= ' num2str(maxevl)]); - % disp(['iprint= ' num2str(iprint) 'seed= ' num2str(seed)]); - disp ' '; - disp ' '; - disp(['starting values(x) ' num2str(xparam1')]); - disp(['initial step length(vm) ' num2str(vm')]); - disp(['lower bound(lb)', 'initial conditions', 'upper bound(ub)' ]); - disp([LB xparam1 UB]); - disp(['c vector ' num2str(c')]); - - % keyboard - if ~options_.bvar_dsge - [xparam1, fval, nacc, nfcnev, nobds, ier, t, vm] = sa(fh,xparam1,maxy,rt_,eps,ns,nt ... - ,neps,maxevl,LB,UB,c,idisp ,t,vm,gend,data,data_index,number_of_observations,no_more_missing_observations); - else - [xparam1, fval, nacc, nfcnev, nobds, ier, t, vm] = sa(fh,xparam1,maxy,rt_,eps,ns,nt ... - ,neps,maxevl,LB,UB,c,idisp ,t,vm,gend); - end - otherwise - if ischar(options_.mode_compute) - if options_.bvar_dsge - [xparam1, fval, retcode ] = feval(options_.mode_compute,fh,xparam1,gend,data); - else - [xparam1, fval, retcode ] = feval(options_.mode_compute, ... - fh,xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations); - end - else - error(['ESTIMATION: mode_compute=' int2str(options_.mode_compute) ... - ' option is unknown!']) - end - end - if options_.mode_compute ~= 5 - if options_.mode_compute ~= 6 - if options_.cova_compute == 1 - if ~options_.bvar_dsge - hh = reshape(hessian('DsgeLikelihood',xparam1, ... - options_.gstep,gend,data,data_index,number_of_observations,... - no_more_missing_observations),nx,nx); - else - hh = reshape(hessian('DsgeVarLikelihood',xparam1,options_.gstep,gend),nx,nx); - end - else - nn = repmat(NaN,length(xparam1),length(xparam1)) - end - end - parameter_names = bayestopt_.name; - if options_.cova_compute - save([M_.fname '_mode.mat'],'xparam1','hh','parameter_names'); - else - save([M_.fname '_mode.mat'],'xparam1','parameter_names'); - end - end -end - -if options_.cova_compute == 0 - hh = repmat(NaN,length(xparam1),length(xparam1)); -end - -try - chol(hh); -catch - disp(' ') - disp('POSTERIOR KERNEL OPTIMIZATION PROBLEM!') - disp(' (minus) the hessian matrix at the "mode" is not positive definite!') - disp('=> posterior variance of the estimated parameters are not positive.') - disp('You should try to change the initial values of the parameters using') - disp('the estimated_params_init block, or use another optimization routine.') - warning('The results below are most likely wrong!'); -end - -if options_.mode_check == 1 & options_.posterior_mode_estimation - mode_check(xparam1,0,hh,gend,data,lb,ub,data_index,number_of_observations,no_more_missing_observations); -end - -if options_.posterior_mode_estimation - %hh = generalized_cholesky(hh); - invhess = inv(hh); - stdh = sqrt(diag(invhess)); -else - variances = bayestopt_.p2.^2; - invhess = 0.01*diag(variances); - %invhess = 0.01*eye(length(variances)); -end - - -if any(bayestopt_.pshape > 0) & options_.posterior_mode_estimation - disp(' ') - disp('RESULTS FROM POSTERIOR MAXIMIZATION') - tstath = zeros(nx,1); - for i = 1:nx - tstath(i) = abs(xparam1(i))/stdh(i); - end - - header_width = row_header_width(M_,estim_params_,bayestopt_); - - tit1 = sprintf('%-*s %7s %8s %7s %6s %4s %6s\n',header_width-2,' ','prior mean', ... - 'mode','s.d.','t-stat','prior','pstdev'); - if np - ip = nvx+nvn+ncx+ncn+1; - disp('parameters') - disp(tit1) - for i=1:np - name = bayestopt_.name{ip}; - disp(sprintf('%-*s %7.3f %8.4f %7.4f %7.4f %4s %6.4f', ... - header_width,name, ... - bayestopt_.p1(ip),xparam1(ip),stdh(ip),tstath(ip), ... - pnames(bayestopt_.pshape(ip)+1,:), ... - bayestopt_.p2(ip))); - eval(['oo_.posterior_mode.parameters.' name ' = xparam1(ip);']); - eval(['oo_.posterior_std.parameters.' name ' = stdh(ip);']); - ip = ip+1; - end - end - if nvx - ip = 1; - disp('standard deviation of shocks') - disp(tit1) - for i=1:nvx - k = estim_params_.var_exo(i,1); - name = deblank(M_.exo_names(k,:)); - disp(sprintf('%-*s %7.3f %8.4f %7.4f %7.4f %4s %6.4f', ... - header_width,name,bayestopt_.p1(ip),xparam1(ip), ... - stdh(ip),tstath(ip),pnames(bayestopt_.pshape(ip)+1,:), ... - bayestopt_.p2(ip))); - M_.Sigma_e(k,k) = xparam1(ip)*xparam1(ip); - eval(['oo_.posterior_mode.shocks_std.' name ' = xparam1(ip);']); - eval(['oo_.posterior_std.shocks_std.' name ' = stdh(ip);']); - ip = ip+1; - end - end - if nvn - disp('standard deviation of measurement errors') - disp(tit1) - ip = nvx+1; - for i=1:nvn - name = deblank(options_.varobs(estim_params_.var_endo(i,1),:)); - disp(sprintf('%-*s %7.3f %8.4f %7.4f %7.4f %4s %6.4f', ... - header_width,name,bayestopt_.p1(ip), ... - xparam1(ip),stdh(ip),tstath(ip), ... - pnames(bayestopt_.pshape(ip)+1,:), ... - bayestopt_.p2(ip))); - eval(['oo_.posterior_mode.measurement_errors_std.' name ' = xparam1(ip);']); - eval(['oo_.posterior_std.measurement_errors_std.' name ' = stdh(ip);']); - ip = ip+1; - end - end - if ncx - disp('correlation of shocks') - disp(tit1) - ip = nvx+nvn+1; - for i=1:ncx - k1 = estim_params_.corrx(i,1); - k2 = estim_params_.corrx(i,2); - name = [deblank(M_.exo_names(k1,:)) ',' deblank(M_.exo_names(k2,:))]; - NAME = [deblank(M_.exo_names(k1,:)) '_' deblank(M_.exo_names(k2,:))]; - disp(sprintf('%-*s %7.3f %8.4f %7.4f %7.4f %4s %6.4f', name, ... - header_width,bayestopt_.p1(ip),xparam1(ip),stdh(ip),tstath(ip), ... - pnames(bayestopt_.pshape(ip)+1,:), bayestopt_.p2(ip))); - M_.Sigma_e(k1,k2) = xparam1(ip)*sqrt(M_.Sigma_e(k1,k1)*M_.Sigma_e(k2,k2)); - M_.Sigma_e(k2,k1) = M_.Sigma_e(k1,k2); - eval(['oo_.posterior_mode.shocks_corr.' NAME ' = xparam1(ip);']); - eval(['oo_.posterior_std.shocks_corr.' NAME ' = stdh(ip);']); - ip = ip+1; - end - end - if ncn - disp('correlation of measurement errors') - disp(tit1) - ip = nvx+nvn+ncx+1; - for i=1:ncn - k1 = estim_params_.corrn(i,1); - k2 = estim_params_.corrn(i,2); - name = [deblank(M_.endo_names(k1,:)) ',' deblank(M_.endo_names(k2,:))]; - NAME = [deblank(M_.endo_names(k1,:)) '_' deblank(M_.endo_names(k2,:))]; - disp(sprintf('%-*s %7.3f %8.4f %7.4f %7.4f %4s %6.4f', name, ... - header_width,bayestopt_.p1(ip),xparam1(ip),stdh(ip),tstath(ip), ... - pnames(bayestopt_.pshape(ip)+1,:), bayestopt_.p2(ip))); - eval(['oo_.posterior_mode.measurement_errors_corr.' NAME ' = xparam1(ip);']); - eval(['oo_.posterior_std.measurement_errors_corr.' NAME ' = stdh(ip);']); - ip = ip+1; - end - end - %% Laplace approximation to the marginal log density: - estim_params_nbr = size(xparam1,1); - scale_factor = -sum(log10(diag(invhess))); - log_det_invhess = -estim_params_nbr*log(scale_factor)+log(det(scale_factor*invhess)); - if ~options_.bvar_dsge - md_Laplace = .5*estim_params_nbr*log(2*pi) + .5*log_det_invhess ... - - DsgeLikelihood(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations); - else - md_Laplace = .5*estim_params_nbr*log(2*pi) + .5*log_det_invhess ... - - DsgeVarLikelihood(xparam1,gend); - end - oo_.MarginalDensity.LaplaceApproximation = md_Laplace; - disp(' ') - disp(sprintf('Log data density [Laplace approximation] is %f.',md_Laplace)) - disp(' ') -elseif ~any(bayestopt_.pshape > 0) & options_.posterior_mode_estimation - disp(' ') - disp('RESULTS FROM MAXIMUM LIKELIHOOD') - tstath = zeros(nx,1); - for i = 1:nx - tstath(i) = abs(xparam1(i))/stdh(i); - end - header_width = row_header_width(M_,estim_params_,bayestopt_); - tit1 = sprintf('%-*s %10s %7s %6s\n',header_width-2,' ','Estimate','s.d.','t-stat'); - if np - ip = nvx+nvn+ncx+ncn+1; - disp('parameters') - disp(tit1) - for i=1:np - name = bayestopt_.name{ip}; - disp(sprintf('%-*s %8.4f %7.4f %7.4f', ... - header_width,name,xparam1(ip),stdh(ip),tstath(ip))); - eval(['oo_.mle_mode.parameters.' name ' = xparam1(ip);']); - eval(['oo_.mle_std.parameters.' name ' = stdh(ip);']); - ip = ip+1; - end - end - if nvx - ip = 1; - disp('standard deviation of shocks') - disp(tit1) - for i=1:nvx - k = estim_params_.var_exo(i,1); - name = deblank(M_.exo_names(k,:)); - disp(sprintf('%-*s %8.4f %7.4f %7.4f',header_width,name,xparam1(ip),stdh(ip),tstath(ip))); - M_.Sigma_e(k,k) = xparam1(ip)*xparam1(ip); - eval(['oo_.mle_mode.shocks_std.' name ' = xparam1(ip);']); - eval(['oo_.mle_std.shocks_std.' name ' = stdh(ip);']); - ip = ip+1; - end - end - if nvn - disp('standard deviation of measurement errors') - disp(tit1) - ip = nvx+1; - for i=1:nvn - name = deblank(options_.varobs(estim_params_.var_endo(i,1),:)); - disp(sprintf('%-*s %8.4f %7.4f %7.4f',header_width,name,xparam1(ip),stdh(ip),tstath(ip))) - eval(['oo_.mle_mode.measurement_errors_std.' name ' = xparam1(ip);']); - eval(['oo_.mle_std.measurement_errors_std.' name ' = stdh(ip);']); - ip = ip+1; - end - end - if ncx - disp('correlation of shocks') - disp(tit1) - ip = nvx+nvn+1; - for i=1:ncx - k1 = estim_params_.corrx(i,1); - k2 = estim_params_.corrx(i,2); - name = [deblank(M_.exo_names(k1,:)) ',' deblank(M_.exo_names(k2,:))]; - NAME = [deblank(M_.exo_names(k1,:)) '_' deblank(M_.exo_names(k2,:))]; - disp(sprintf('%-*s %8.4f %7.4f %7.4f', header_width,name,xparam1(ip),stdh(ip),tstath(ip))); - M_.Sigma_e(k1,k2) = xparam1(ip)*sqrt(M_.Sigma_e(k1,k1)*M_.Sigma_e(k2,k2)); - M_.Sigma_e(k2,k1) = M_.Sigma_e(k1,k2); - eval(['oo_.mle_mode.shocks_corr.' NAME ' = xparam1(ip);']); - eval(['oo_.mle_std.shocks_corr.' NAME ' = stdh(ip);']); - ip = ip+1; - end - end - if ncn - disp('correlation of measurement errors') - disp(tit1) - ip = nvx+nvn+ncx+1; - for i=1:ncn - k1 = estim_params_.corrn(i,1); - k2 = estim_params_.corrn(i,2); - name = [deblank(M_.endo_names(k1,:)) ',' deblank(M_.endo_names(k2,:))]; - NAME = [deblank(M_.endo_names(k1,:)) '_' deblank(M_.endo_names(k2,:))]; - disp(sprintf('%-*s %8.4f %7.4f %7.4f',header_width,name,xparam1(ip),stdh(ip),tstath(ip))); - eval(['oo_.mle_mode.measurement_error_corr.' NAME ' = xparam1(ip);']); - eval(['oo_.mle_std.measurement_error_corr.' NAME ' = stdh(ip);']); - ip = ip+1; - end - end -end - - -OutputDirectoryName = CheckPath('Output'); - -if any(bayestopt_.pshape > 0) & options_.TeX %% Bayesian estimation (posterior mode) Latex output - if np - filename = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_1.TeX']; - fidTeX = fopen(filename,'w'); - fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n'); - fprintf(fidTeX,'%% RESULTS FROM POSTERIOR MAXIMIZATION (parameters)\n'); - fprintf(fidTeX,['%% ' datestr(now,0)]); - fprintf(fidTeX,' \n'); - fprintf(fidTeX,' \n'); - fprintf(fidTeX,'{\\tiny \n') - fprintf(fidTeX,'\\begin{table}\n'); - fprintf(fidTeX,'\\centering\n'); - fprintf(fidTeX,'\\begin{tabular}{l|lcccc} \n'); - fprintf(fidTeX,'\\hline\\hline \\\\ \n'); - fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Posterior mode & s.d. \\\\ \n'); - fprintf(fidTeX,'\\hline \\\\ \n'); - ip = nvx+nvn+ncx+ncn+1; - for i=1:np - fprintf(fidTeX,'$%s$ & %s & %7.3f & %6.4f & %8.4f & %7.4f \\\\ \n',... - M_.param_names_tex(estim_params_.param_vals(i,1),:),... - deblank(pnames(bayestopt_.pshape(ip)+1,:)),... - bayestopt_.p1(ip),... - bayestopt_.p2(ip),... - xparam1(ip),... - stdh(ip)); - ip = ip + 1; - end - fprintf(fidTeX,'\\hline\\hline \n'); - fprintf(fidTeX,'\\end{tabular}\n '); - fprintf(fidTeX,'\\caption{Results from posterior parameters (parameters)}\n '); - fprintf(fidTeX,'\\label{Table:Posterior:1}\n'); - fprintf(fidTeX,'\\end{table}\n'); - fprintf(fidTeX,'} \n') - fprintf(fidTeX,'%% End of TeX file.\n'); - fclose(fidTeX); - end - if nvx - TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_2.TeX']; - fidTeX = fopen(TeXfile,'w'); - fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n'); - fprintf(fidTeX,'%% RESULTS FROM POSTERIOR MAXIMIZATION (standard deviation of structural shocks)\n'); - fprintf(fidTeX,['%% ' datestr(now,0)]); - fprintf(fidTeX,' \n'); - fprintf(fidTeX,' \n'); - fprintf(fidTeX,'{\\tiny \n'); - fprintf(fidTeX,'\\begin{table}\n'); - fprintf(fidTeX,'\\centering\n'); - fprintf(fidTeX,'\\begin{tabular}{l|lcccc} \n'); - fprintf(fidTeX,'\\hline\\hline \\\\ \n'); - fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Posterior mode & s.d. \\\\ \n') - fprintf(fidTeX,'\\hline \\\\ \n'); - ip = 1; - for i=1:nvx - k = estim_params_.var_exo(i,1); - fprintf(fidTeX,[ '$%s$ & %4s & %7.3f & %6.4f & %8.4f & %7.4f \\\\ \n'],... - deblank(M_.exo_names_tex(k,:)),... - deblank(pnames(bayestopt_.pshape(ip)+1,:)),... - bayestopt_.p1(ip),... - bayestopt_.p2(ip),... - xparam1(ip), ... - stdh(ip)); - ip = ip+1; - end - fprintf(fidTeX,'\\hline\\hline \n'); - fprintf(fidTeX,'\\end{tabular}\n '); - fprintf(fidTeX,'\\caption{Results from posterior parameters (standard deviation of structural shocks)}\n '); - fprintf(fidTeX,'\\label{Table:Posterior:2}\n'); - fprintf(fidTeX,'\\end{table}\n'); - fprintf(fidTeX,'} \n') - fprintf(fidTeX,'%% End of TeX file.\n'); - fclose(fidTeX); - end - if nvn - TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_3.TeX']; - fidTeX = fopen(TeXfile,'w'); - fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n'); - fprintf(fidTeX,'%% RESULTS FROM POSTERIOR MAXIMIZATION (standard deviation of measurement errors)\n'); - fprintf(fidTeX,['%% ' datestr(now,0)]); - fprintf(fidTeX,' \n'); - fprintf(fidTeX,' \n'); - fprintf(fidTeX,'\\begin{table}\n'); - fprintf(fidTeX,'\\centering\n'); - fprintf(fidTeX,'\\begin{tabular}{l|lcccc} \n'); - fprintf(fidTeX,'\\hline\\hline \\\\ \n'); - fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Posterior mode & s.d. \\\\ \n') - fprintf(fidTeX,'\\hline \\\\ \n'); - ip = nvx+1; - for i=1:nvn - idx = strmatch(options_.varobs(estim_params_.var_endo(i,1),:),M_.endo_names); - fprintf(fidTeX,'$%s$ & %4s & %7.3f & %6.4f & %8.4f & %7.4f \\\\ \n',... - deblank(M_.endo_names_tex(idx,:)), ... - deblank(pnames(bayestopt_.pshape(ip)+1,:)), ... - bayestopt_.p1(ip), ... - bayestopt_.p2(ip),... - xparam1(ip),... - stdh(ip)); - ip = ip+1; - end - fprintf(fidTeX,'\\hline\\hline \n'); - fprintf(fidTeX,'\\end{tabular}\n '); - fprintf(fidTeX,'\\caption{Results from posterior parameters (standard deviation of measurement errors)}\n '); - fprintf(fidTeX,'\\label{Table:Posterior:3}\n'); - fprintf(fidTeX,'\\end{table}\n'); - fprintf(fidTeX,'%% End of TeX file.\n'); - fclose(fidTeX); - end - if ncx - TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_4.TeX']; - fidTeX = fopen(TeXfile,'w'); - fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n'); - fprintf(fidTeX,'%% RESULTS FROM POSTERIOR MAXIMIZATION (correlation of structural shocks)\n'); - fprintf(fidTeX,['%% ' datestr(now,0)]); - fprintf(fidTeX,' \n'); - fprintf(fidTeX,' \n'); - fprintf(fidTeX,'\\begin{table}\n'); - fprintf(fidTeX,'\\centering\n'); - fprintf(fidTeX,'\\begin{tabular}{l|lcccc} \n'); - fprintf(fidTeX,'\\hline\\hline \\\\ \n'); - fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Posterior mode & s.d. \\\\ \n') - fprintf(fidTeX,'\\hline \\\\ \n'); - ip = nvx+nvn+1; - for i=1:ncx - k1 = estim_params_.corrx(i,1); - k2 = estim_params_.corrx(i,2); - fprintf(fidTeX,[ '$%s$ & %s & %7.3f & %6.4f & %8.4f & %7.4f \\\\ \n'],... - [deblank(M_.exo_names_tex(k1,:)) ',' deblank(M_.exo_names_tex(k2,:))], ... - deblank(pnames(bayestopt_.pshape(ip)+1,:)), ... - bayestopt_.p1(ip), ... - bayestopt_.p2(ip), ... - xparam1(ip), ... - stdh(ip)); - ip = ip+1; - end - fprintf(fidTeX,'\\hline\\hline \n'); - fprintf(fidTeX,'\\end{tabular}\n '); - fprintf(fidTeX,'\\caption{Results from posterior parameters (correlation of structural shocks)}\n '); - fprintf(fidTeX,'\\label{Table:Posterior:4}\n'); - fprintf(fidTeX,'\\end{table}\n'); - fprintf(fidTeX,'%% End of TeX file.\n'); - fclose(fidTeX); - end - if ncn - TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_5.TeX']; - fidTeX = fopen(TeXfile,'w'); - fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n'); - fprintf(fidTeX,'%% RESULTS FROM POSTERIOR MAXIMIZATION (correlation of measurement errors)\n'); - fprintf(fidTeX,['%% ' datestr(now,0)]); - fprintf(fidTeX,' \n'); - fprintf(fidTeX,' \n'); - fprintf(fidTeX,'\\begin{table}\n'); - fprintf(fidTeX,'\\centering\n'); - fprintf(fidTeX,'\\begin{tabular}{l|lcccc} \n'); - fprintf(fidTeX,'\\hline\\hline \\\\ \n'); - fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Posterior mode & s.d. \\\\ \n') - fprintf(fidTeX,'\\hline \\\\ \n'); - ip = nvx+nvn+ncx+1; - for i=1:ncn - k1 = estim_params_.corrn(i,1); - k2 = estim_params_.corrn(i,2); - fprintf(fidTeX,'$%s$ & %s & %7.3f & %6.4f & %8.4f & %7.4f \\\\ \n',... - [deblank(M_.endo_names_tex(k1,:)) ',' deblank(M_.endo_names_tex(k2,:))], ... - pnames(bayestopt_.pshape(ip)+1,:), ... - bayestopt_.p1(ip), ... - bayestopt_.p2(ip), ... - xparam1(ip), ... - stdh(ip)); - ip = ip+1; - end - fprintf(fidTeX,'\\hline\\hline \n'); - fprintf(fidTeX,'\\end{tabular}\n '); - fprintf(fidTeX,'\\caption{Results from posterior parameters (correlation of measurement errors)}\n '); - fprintf(fidTeX,'\\label{Table:Posterior:5}\n'); - fprintf(fidTeX,'\\end{table}\n'); - fprintf(fidTeX,'%% End of TeX file.\n'); - fclose(fidTeX); - end -end - -if np > 0 - pindx = estim_params_.param_vals(:,1); - save([M_.fname '_params.mat'],'pindx'); -end - -if (any(bayestopt_.pshape >0 ) & options_.mh_replic) | ... - (any(bayestopt_.pshape >0 ) & options_.load_mh_file) %% not ML estimation - bounds = prior_bounds(bayestopt_); - bounds(:,1)=max(bounds(:,1),lb); - bounds(:,2)=min(bounds(:,2),ub); - bayestopt_.lb = bounds(:,1); - bayestopt_.ub = bounds(:,2); - if any(xparam1 < bounds(:,1)) | any(xparam1 > bounds(:,2)) - find(xparam1 < bounds(:,1)) - find(xparam1 > bounds(:,2)) - error('Mode values are outside prior bounds. Reduce prior_trunc.') - end - % runs MCMC - if options_.mh_replic - if options_.load_mh_file & options_.use_mh_covariance_matrix - invhess = compute_mh_covariance_matrix; - end - if options_.bvar_dsge - feval(options_.posterior_sampling_method,'DsgeVarLikelihood',options_.proposal_distribution,xparam1,invhess,bounds,gend); - else - feval(options_.posterior_sampling_method,'DsgeLikelihood',options_.proposal_distribution,xparam1,invhess,bounds,gend,data,... - data_index,number_of_observations,no_more_missing_observations); - end - end - if ~options_.nodiagnostic & options_.mh_replic > 1000 & options_.mh_nblck > 1 - McMCDiagnostics(options_, estim_params_, M_); - end - %% Here i discard first half of the draws: - CutSample(M_, options_, estim_params_); - %% Estimation of the marginal density from the Mh draws: - if options_.mh_replic - [marginal,oo_] = marginal_density(M_, options_, estim_params_, oo_); - end - oo_ = GetPosteriorParametersStatistics(estim_params_, M_, options_, bayestopt_, oo_); - oo_ = PlotPosteriorDistributions(estim_params_, M_, options_, bayestopt_, oo_); - metropolis_draw(1); - if options_.bayesian_irf - PosteriorIRF('posterior'); - end - if options_.moments_varendo - oo_ = compute_moments_varendo('posterior',options_,M_,oo_,var_list_); - end - if options_.smoother | ~isempty(options_.filter_step_ahead) | options_.forecast - prior_posterior_statistics('posterior',data,gend,data_index,missing_value); - end - xparam = get_posterior_parameters('mean'); - set_all_parameters(xparam); -end - -if (~((any(bayestopt_.pshape > 0) & options_.mh_replic) | (any(bayestopt_.pshape ... - > 0) & options_.load_mh_file)) ... - | ~options_.smoother ) & M_.endo_nbr^2*gend < 1e7 % to be fixed - %% ML estimation, or posterior mode without metropolis-hastings or metropolis without bayesian smooth variable - [atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,T,R,P,PK,d,decomp] = DsgeSmoother(xparam1,gend,data,data_index,missing_value); - oo_.Smoother.SteadyState = ys; - oo_.Smoother.TrendCoeffs = trend_coeff; - oo_.Smoother.integration_order = d; - oo_.Smoother.variance = P; - i_endo_nbr = 1:M_.endo_nbr; - if options_.nk ~= 0 - oo_.FilteredVariablesKStepAhead = aK(options_.filter_step_ahead, ... - i_endo_nbr,:); - if isfield(options_,'kalman_algo') - if options_.kalman_algo > 2 - oo_.FilteredVariablesKStepAheadVariances = PK(options_.filter_step_ahead,i_endo_nbr,i_endo_nbr,:); - oo_.FilteredVariablesShockDecomposition = ... - decomp(options_.filter_step_ahead,i_endo_nbr,:,:); - end - end - end - for i=1:M_.endo_nbr - eval(['oo_.SmoothedVariables.' deblank(M_.endo_names(dr.order_var(i),:)) ' = atT(i,:)'';']); - eval(['oo_.FilteredVariables.' deblank(M_.endo_names(dr.order_var(i),:)) ' = squeeze(aK(1,i,:));']); - eval(['oo_.UpdatedVariables.' deblank(M_.endo_names(dr.order_var(i),:)) ... - ' = updated_variables(i,:)'';']); - end - [nbplt,nr,nc,lr,lc,nstar] = pltorg(M_.exo_nbr); - if options_.TeX - fidTeX = fopen([M_.fname '_SmoothedShocks.TeX'],'w'); - fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation.m (Dynare).\n'); - fprintf(fidTeX,['%% ' datestr(now,0) '\n']); - fprintf(fidTeX,' \n'); - end - if nbplt == 1 - hh = figure('Name','Smoothed shocks'); - NAMES = []; - if options_.TeX, TeXNAMES = []; end - for i=1:M_.exo_nbr - subplot(nr,nc,i); - plot(1:gend,innov(i,:),'-k','linewidth',1) - hold on - plot([1 gend],[0 0],'-r','linewidth',.5) - hold off - xlim([1 gend]) - name = deblank(M_.exo_names(i,:)); - NAMES = strvcat(NAMES,name); - if ~isempty(options_.XTick) - set(gca,'XTick',options_.XTick) - set(gca,'XTickLabel',options_.XTickLabel) - end - if options_.TeX - texname = M_.exo_names_tex(i,1); - TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']); - end - title(name,'Interpreter','none') - eval(['oo_.SmoothedShocks.' deblank(M_.exo_names(i,:)) ' = innov(i,:)'';']); - end - eval(['print -depsc2 ' M_.fname '_SmoothedShocks' int2str(1) '.eps']); - if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' M_.fname '_SmoothedShocks' int2str(1)]); - saveas(hh,[M_.fname '_SmoothedShocks' int2str(1) '.fig']); - end - if options_.nograph, close(hh), end - if options_.TeX - fprintf(fidTeX,'\\begin{figure}[H]\n'); - for jj = 1:M_.exo_nbr - fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); - end - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_SmoothedShocks%s}\n',M_.fname,int2str(1)); - fprintf(fidTeX,'\\caption{Smoothed shocks.}'); - fprintf(fidTeX,'\\label{Fig:SmoothedShocks:%s}\n',int2str(1)); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,'\n'); - fprintf(fidTeX,'%% End of TeX file.\n'); - fclose(fidTeX); - end - else - for plt = 1:nbplt-1 - hh = figure('Name','Smoothed shocks'); - set(0,'CurrentFigure',hh) - NAMES = []; - if options_.TeX, TeXNAMES = []; end - for i=1:nstar - k = (plt-1)*nstar+i; - subplot(nr,nc,i); - plot([1 gend],[0 0],'-r','linewidth',.5) - hold on - plot(1:gend,innov(k,:),'-k','linewidth',1) - hold off - name = deblank(M_.exo_names(k,:)); - NAMES = strvcat(NAMES,name); - if ~isempty(options_.XTick) - set(gca,'XTick',options_.XTick) - set(gca,'XTickLabel',options_.XTickLabel) - end - xlim([1 gend]) - if options_.TeX - texname = M_.exo_names_tex(k,:); - TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']); - end - title(name,'Interpreter','none') - eval(['oo_.SmoothedShocks.' deblank(name) ' = innov(k,:)'';']); - end - eval(['print -depsc2 ' M_.fname '_SmoothedShocks' int2str(plt) '.eps']); - if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' M_.fname '_SmoothedShocks' int2str(plt)]); - saveas(hh,[M_.fname '_SmoothedShocks' int2str(plt) '.fig']); - end - if options_.nograph, close(hh), end - if options_.TeX - fprintf(fidTeX,'\\begin{figure}[H]\n'); - for jj = 1:nstar - fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); - end - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_SmoothedShocks%s}\n',M_.fname,int2str(plt)); - fprintf(fidTeX,'\\caption{Smoothed shocks.}'); - fprintf(fidTeX,'\\label{Fig:SmoothedShocks:%s}\n',int2str(plt)); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,'\n'); - end - end - hh = figure('Name','Smoothed shocks'); - set(0,'CurrentFigure',hh) - NAMES = []; - if options_.TeX, TeXNAMES = []; end - for i=1:M_.exo_nbr-(nbplt-1)*nstar - k = (nbplt-1)*nstar+i; - if lr ~= 0 - subplot(lr,lc,i); - else - subplot(nr,nc,i); - end - plot([1 gend],[0 0],'-r','linewidth',0.5) - hold on - plot(1:gend,innov(k,:),'-k','linewidth',1) - hold off - name = deblank(M_.exo_names(k,:)); - NAMES = strvcat(NAMES,name); - if ~isempty(options_.XTick) - set(gca,'XTick',options_.XTick) - set(gca,'XTickLabel',options_.XTickLabel) - end - xlim([1 gend]) - if options_.TeX - texname = M_.exo_names_tex(k,:); - TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']); - end - title(name,'Interpreter','none') - eval(['oo_.SmoothedShocks.' deblank(name) ' = innov(k,:)'';']); - end - eval(['print -depsc2 ' M_.fname '_SmoothedShocks' int2str(nbplt) '.eps']); - if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' M_.fname '_SmoothedShocks' int2str(nbplt)]); - saveas(hh,[M_.fname '_SmoothedShocks' int2str(nbplt) '.fig']); - end - if options_.nograph, close(hh), end - if options_.TeX - fprintf(fidTeX,'\\begin{figure}[H]\n'); - for jj = 1:size(NAMES,1); - fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); - end - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_SmoothedShocks%s}\n',M_.fname,int2str(nbplt)); - fprintf(fidTeX,'\\caption{Smoothed shocks.}'); - fprintf(fidTeX,'\\label{Fig:SmoothedShocks:%s}\n',int2str(nbplt)); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,'\n'); - fprintf(fidTeX,'%% End of TeX file.\n'); - fclose(fidTeX); - end - end - %% - %% Smooth observational errors... - %% - if options_.noconstant - yf = zeros(n_varobs,gend); - else - if options_.prefilter == 1 - yf = atT(bayestopt_.mf,:)+repmat(bayestopt_.mean_varobs,1,gend); - elseif options_.loglinear == 1 - yf = atT(bayestopt_.mf,:)+repmat(log(ys(bayestopt_.mfys)),1,gend)+... - trend_coeff*[1:gend]; - else - yf = atT(bayestopt_.mf,:)+repmat(ys(bayestopt_.mfys),1,gend)+... - trend_coeff*[1:gend]; - end - end - if nvn - number_of_plots_to_draw = 0; - index = []; - for i=1:n_varobs - if max(abs(measurement_error(10:end))) > 0.000000001 - number_of_plots_to_draw = number_of_plots_to_draw + 1; - index = cat(1,index,i); - end - eval(['oo_.SmoothedMeasurementErrors.' deblank(options_.varobs(i,:)) ... - ' = measurement_error(i,:)'';']); - end - [nbplt,nr,nc,lr,lc,nstar] = pltorg(number_of_plots_to_draw); - if options_.TeX - fidTeX = fopen([M_.fname '_SmoothedObservationErrors.TeX'],'w'); - fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation.m (Dynare).\n'); - fprintf(fidTeX,['%% ' datestr(now,0) '\n']); - fprintf(fidTeX,' \n'); - end - if nbplt == 1 - hh = figure('Name','Smoothed observation errors'); - set(0,'CurrentFigure',hh) - NAMES = []; - if options_.TeX, TeXNAMES = []; end - for i=1:number_of_plots_to_draw - subplot(nr,nc,i); - plot(1:gend,measurement_error(index(i),:),'-k','linewidth',1) - hold on - plot([1 gend],[0 0],'-r','linewidth',.5) - hold off - name = deblank(options_.varobs(index(i),:)); - NAMES = strvcat(NAMES,name); - if ~isempty(options_.XTick) - set(gca,'XTick',options_.XTick) - set(gca,'XTickLabel',options_.XTickLabel) - end - if options_.TeX - idx = strmatch(options_.varobs(indx(i),:),M_.endo_names,'exact'); - texname = M_.endo_names_tex(idx,:); - TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']); - end - title(name,'Interpreter','none') - end - eval(['print -depsc2 ' M_.fname '_SmoothedObservationErrors' int2str(1) '.eps']); - if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' M_.fname '_SmoothedObservationErrors' int2str(1)]); - saveas(hh,[M_.fname '_SmoothedObservationErrors' int2str(1) '.fig']); - end - if options_.nograph, close(hh), end - if options_.TeX - fprintf(fidTeX,'\\begin{figure}[H]\n'); - for jj = 1:number_of_plots_to_draw - fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); - end - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_SmoothedObservationErrors%s}\n',M_.fname,int2str(1)); - fprintf(fidTeX,'\\caption{Smoothed observation errors.}'); - fprintf(fidTeX,'\\label{Fig:SmoothedObservationErrors:%s',int2str(1)); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,'\n'); - fprintf(fidTeX,'%% End of TeX file.\n'); - fclose(fidTeX); - end - else - for plt = 1:nbplt-1 - hh = figure('Name','Smoothed observation errors'); - set(0,'CurrentFigure',hh) - NAMES = []; - if options_.TeX, TeXNAMES = []; end - for i=1:nstar - k = (plt-1)*nstar+i; - subplot(nr,nc,i); - plot([1 gend],[0 0],'-r','linewidth',.5) - hold on - plot(1:gend,measurement_error(index(k),:),'-k','linewidth',1) - hold off - name = deblank(options_.varobs(index(k),:)); - NAMES = strvcat(NAMES,name); - if ~isempty(options_.XTick) - set(gca,'XTick',options_.XTick) - set(gca,'XTickLabel',options_.XTickLabel) - end - if options_.TeX - idx = strmatch(options_.varobs(k),M_.endo_names,'exact'); - texname = M_.endo_names_tex(idx,:); - TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']); - end - title(name,'Interpreter','none') - end - eval(['print -depsc2 ' M_.fname '_SmoothedObservationErrors' int2str(plt) '.eps']); - if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' M_.fname '_SmoothedObservationErrors' int2str(plt)]); - saveas(hh,[M_.fname '_SmoothedObservationErrors' int2str(plt) '.fig']); - end - if options_.nograph, close(hh), end - if options_.TeX - fprintf(fidTeX,'\\begin{figure}[H]\n'); - for jj = 1:nstar - fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); - end - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_SmoothedObservationErrors%s}\n',M_.fname,int2str(plt)); - fprintf(fidTeX,'\\caption{Smoothed observation errors.}'); - fprintf(fidTeX,'\\label{Fig:SmoothedObservationErrors:%s}\n',int2str(plt)); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,'\n'); - end - end - hh = figure('Name','Smoothed observation errors'); - set(0,'CurrentFigure',hh) - NAMES = []; - if options_.TeX, TeXNAMES = []; end - for i=1:number_of_plots_to_draw-(nbplt-1)*nstar - k = (nbplt-1)*nstar+i; - if lr ~= 0 - subplot(lr,lc,i); - else - subplot(nr,nc,i); - end - plot([1 gend],[0 0],'-r','linewidth',0.5) - hold on - plot(1:gend,measurement_error(index(k),:),'-k','linewidth',1) - hold off - name = deblank(options_.varobs(index(k),:)); - NAMES = strvcat(NAMES,name); - if ~isempty(options_.XTick) - set(gca,'XTick',options_.XTick) - set(gca,'XTickLabel',options_.XTickLabel) - end - if options_.TeX - idx = strmatch(options_.varobs(index(k)),M_.endo_names,'exact'); - texname = M_.endo_names_tex(idx,:); - TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']); - end - title(name,'Interpreter','none'); - end - eval(['print -depsc2 ' M_.fname '_SmoothedObservationErrors' int2str(nbplt) '.eps']); - if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' M_.fname '_SmoothedObservationErrors' int2str(nbplt)]); - saveas(hh,[M_.fname '_SmoothedObservationErrors' int2str(nbplt) '.fig']); - end - if options_.nograph, close(hh), end - if options_.TeX - fprintf(fidTeX,'\\begin{figure}[H]\n'); - for jj = 1:size(NAMES,1); - fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); - end - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_SmoothedObservedErrors%s}\n',M_.fname,int2str(nbplt)); - fprintf(fidTeX,'\\caption{Smoothed observed errors.}'); - fprintf(fidTeX,'\\label{Fig:SmoothedObservedErrors:%s}\n',int2str(nbplt)); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,'\n'); - fprintf(fidTeX,'%% End of TeX file.\n'); - fclose(fidTeX); - end - end - end - %% - %% Historical and smoothed variabes - %% - [nbplt,nr,nc,lr,lc,nstar] = pltorg(n_varobs); - if options_.TeX - fidTeX = fopen([M_.fname '_HistoricalAndSmoothedVariables.TeX'],'w'); - fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation.m (Dynare).\n'); - fprintf(fidTeX,['%% ' datestr(now,0) '\n']); - fprintf(fidTeX,' \n'); - end - if nbplt == 1 - hh = figure('Name','Historical and smoothed variables'); - NAMES = []; - if options_.TeX, TeXNAMES = []; end - for i=1:n_varobs - subplot(nr,nc,i); - plot(1:gend,yf(i,:),'-r','linewidth',1) - hold on - plot(1:gend,rawdata(:,i),'-k','linewidth',1) - hold off - name = deblank(options_.varobs(i,:)); - NAMES = strvcat(NAMES,name); - if ~isempty(options_.XTick) - set(gca,'XTick',options_.XTick) - set(gca,'XTickLabel',options_.XTickLabel) - end - xlim([1 gend]) - if options_.TeX - idx = strmatch(options_.varobs(i),M_.endo_names,'exact'); - texname = M_.endo_names_tex(idx,:); - TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']); - end - title(name,'Interpreter','none') - end - eval(['print -depsc2 ' M_.fname '_HistoricalAndSmoothedVariables' int2str(1) '.eps']); - if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' M_.fname '_HistoricalAndSmoothedVariables' int2str(1)]); - saveas(hh,[M_.fname '_HistoricalAndSmoothedVariables' int2str(1) '.fig']); - end - if options_.nograph, close(hh), end - if options_.TeX - fprintf(fidTeX,'\\begin{figure}[H]\n'); - for jj = 1:n_varobs - fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); - end - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_HistoricalAndSmoothedVariables%s}\n',M_.fname,int2str(1)); - fprintf(fidTeX,'\\caption{Historical and smoothed variables.}'); - fprintf(fidTeX,'\\label{Fig:HistoricalAndSmoothedVariables:%s}\n',int2str(1)); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,'\n'); - fprintf(fidTeX,'%% End of TeX file.\n'); - fclose(fidTeX); - end - else - for plt = 1:nbplt-1 - hh = figure('Name','Historical and smoothed variables'); - set(0,'CurrentFigure',hh) - NAMES = []; - if options_.TeX, TeXNAMES = []; end - for i=1:nstar - k = (plt-1)*nstar+i; - subplot(nr,nc,i); - plot(1:gend,yf(k,:),'-r','linewidth',1) - hold on - plot(1:gend,rawdata(:,k),'-k','linewidth',1) - hold off - name = deblank(options_.varobs(k,:)); - NAMES = strvcat(NAMES,name); - if ~isempty(options_.XTick) - set(gca,'XTick',options_.XTick) - set(gca,'XTickLabel',options_.XTickLabel) - end - xlim([1 gend]) - if options_.TeX - idx = strmatch(options_.varobs(k),M_.endo_names,'exact'); - texname = M_.endo_names_tex(idx,:); - TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']); - end - title(name,'Interpreter','none') - end - eval(['print -depsc2 ' M_.fname '_HistoricalAndSmoothedVariables' int2str(plt) '.eps']); - if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' M_.fname '_HistoricalAndSmoothedVariables' int2str(plt)]); - saveas(hh,[M_.fname '_HistoricalAndSmoothedVariables' int2str(plt) '.fig']); - end - if options_.nograph, close(hh), end - if options_.TeX - fprintf(fidTeX,'\\begin{figure}[H]\n'); - for jj = 1:nstar - fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); - end - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_HistoricalAndSmoothedVariables%s}\n',M_.fname,int2str(plt)); - fprintf(fidTeX,'\\caption{Historical and smoothed variables.}'); - fprintf(fidTeX,'\\label{Fig:HistoricalAndSmoothedVariables:%s}\n',int2str(plt)); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,'\n'); - end - end - hh = figure('Name','Historical and smoothed variables'); - set(0,'CurrentFigure',hh) - NAMES = []; - if options_.TeX, TeXNAMES = []; end - for i=1:n_varobs-(nbplt-1)*nstar - k = (nbplt-1)*nstar+i; - if lr ~= 0 - subplot(lr,lc,i); - else - subplot(nr,nc,i); - end - plot(1:gend,yf(k,:),'-r','linewidth',1) - hold on - plot(1:gend,rawdata(:,k),'-k','linewidth',1) - hold off - name = deblank(options_.varobs(k,:)); - NAMES = strvcat(NAMES,name); - if ~isempty(options_.XTick) - set(gca,'XTick',options_.XTick) - set(gca,'XTickLabel',options_.XTickLabel) - end - xlim([1 gend]) - if options_.TeX - idx = strmatch(options_.varobs(i),M_.endo_names,'exact'); - texname = M_.endo_names_tex(idx,:); - TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']); - end - title(name,'Interpreter','none'); - end - eval(['print -depsc2 ' M_.fname '_HistoricalAndSmoothedVariables' int2str(nbplt) '.eps']); - if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' M_.fname '_HistoricalAndSmoothedVariables' int2str(nbplt)]); - saveas(hh,[M_.fname '_HistoricalAndSmoothedVariables' int2str(nbplt) '.fig']); - end - if options_.nograph, close(hh), end - if options_.TeX - fprintf(fidTeX,'\\begin{figure}[H]\n'); - for jj = 1:size(NAMES,1); - fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); - end - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_HistoricalAndSmoothedVariables%s}\n',M_.fname,int2str(nbplt)); - fprintf(fidTeX,'\\caption{Historical and smoothed variables.}'); - fprintf(fidTeX,'\\label{Fig:HistoricalAndSmoothedVariables:%s}\n',int2str(nbplt)); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,'\n'); - fprintf(fidTeX,'%% End of TeX file.\n'); - fclose(fidTeX); - end - end -end - -if options_.forecast > 0 & options_.mh_replic == 0 & ~options_.load_mh_file - forecast(var_list_,'smoother'); -end - -if np > 0 - pindx = estim_params_.param_vals(:,1); - save([M_.fname '_pindx.mat'] ,'pindx'); -end - +function dynare_estimation_1(var_list_,dname) +% function dynare_estimation_1(var_list_,dname) +% runs the estimation of the model +% +% INPUTS +% var_list_: selected endogenous variables vector +% dname: alternative directory name +% +% OUTPUTS +% none +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2003-2009 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 <http://www.gnu.org/licenses/>. + +global M_ options_ oo_ estim_params_ bayestopt_ + +options_.lgyidx2varobs = zeros(size(M_.endo_names,1),1); +for i = 1:size(M_.endo_names,1) + tmp = strmatch(deblank(M_.endo_names(i,:)),options_.varobs,'exact'); + if ~isempty(tmp) + options_.lgyidx2varobs(i,1) = tmp; + end +end + +%% Set the order of approximation to one (if needed). +if options_.order > 1 + options_.order = 1; +end + +%% Set options_.lik_init equal to 3 if diffuse filter is used. +if (options_.diffuse_filter==1) && (options_.lik_init==1) + options_.lik_init = 3; +end + +%% If the data are prefiltered then there must not be constants in the +%% measurement equation of the DSGE model or in the DSGE-VAR model. +if options_.prefilter == 1 + options_.noconstant = 1; +end + +%% Set options related to filtered variables. +if options_.filtered_vars ~= 0 & isempty(options_.filter_step_ahead), + options_.filter_step_ahead = 1; +end +if options_.filtered_vars ~= 0 & options_.filter_step_ahead == 0, + options_.filter_step_ahead = 1; +end +if options_.filter_step_ahead ~= 0 + options_.nk = max(options_.filter_step_ahead); +end + +%% Set the name of the directory where (intermediary) results will be saved. +if nargin>1 + M_.dname = dname; +else + M_.dname = M_.fname; +end +%% Set the names of the priors. +pnames = [' ';'beta ';'gamm ';'norm ';'invg ';'unif ';'invg2']; + +%% Set the number of observed variables. +n_varobs = size(options_.varobs,1); + +%% Set priors over the estimated parameters. +if ~isempty(estim_params_) + [xparam1,estim_params_,bayestopt_,lb,ub,M_] = set_prior(estim_params_,M_,options_); + if any(bayestopt_.pshape > 0) + % Plot prior densities. + if options_.plot_priors + plot_priors(bayestopt_,M_,options_) + end + % Set prior bounds + bounds = prior_bounds(bayestopt_); + bounds(:,1)=max(bounds(:,1),lb); + bounds(:,2)=min(bounds(:,2),ub); + else + % No priors are declared so Dynare will estimate the model by + % maximum likelihood with inequality constraints for the parameters. + options_.mh_replic = 0;% No metropolis. + bounds(:,1) = lb; + bounds(:,2) = ub; + end + % Test if initial values of the estimated parameters are all between + % the prior lower and upper bounds. + if any(xparam1 < bounds(:,1)) | any(xparam1 > bounds(:,2)) + find(xparam1 < bounds(:,1)) + find(xparam1 > bounds(:,2)) + error('Initial parameter values are outside parameter bounds') + end + lb = bounds(:,1); + ub = bounds(:,2); + bayestopt_.lb = lb; + bayestopt_.ub = ub; +else% If estim_params_ is empty... + xparam1 = []; + bayestopt_.lb = []; + bayestopt_.ub = []; + bayestopt_.jscale = []; + bayestopt_.pshape = []; + bayestopt_.p1 = []; + bayestopt_.p2 = []; + bayestopt_.p3 = []; + bayestopt_.p4 = []; + bayestopt_.p5 = []; + bayestopt_.p6 = []; + bayestopt_.p7 = []; + estim_params_.nvx = 0; + estim_params_.nvn = 0; + estim_params_.ncx = 0; + estim_params_.ncn = 0; + estim_params_.np = 0; +end + +%% Get the number of parameters to be estimated. +nvx = estim_params_.nvx; % Variance of the structural innovations (number of parameters). +nvn = estim_params_.nvn; % Variance of the measurement innovations (number of parameters). +ncx = estim_params_.ncx; % Covariance of the structural innovations (number of parameters). +ncn = estim_params_.ncn; % Covariance of the measurement innovations (number of parameters). +np = estim_params_.np ; % Number of deep parameters. +nx = nvx+nvn+ncx+ncn+np; % Total number of parameters to be estimated. + +%% Is there a linear trend in the measurement equation? +if ~isfield(options_,'trend_coeffs') % No! + bayestopt_.with_trend = 0; +else% Yes! + bayestopt_.with_trend = 1; + bayestopt_.trend_coeff = {}; + trend_coeffs = options_.trend_coeffs; + nt = length(trend_coeffs); + for i=1:n_varobs + if i > length(trend_coeffs) + bayestopt_.trend_coeff{i} = '0'; + else + bayestopt_.trend_coeff{i} = trend_coeffs{i}; + end + end +end + +%% Set the "size" of penalty. +bayestopt_.penalty = 1e8; + +%% Get informations about the variables of the model. +dr = set_state_space([],M_); +nstatic = dr.nstatic; % Number of static variables. +npred = dr.npred; % Number of predetermined variables. +nspred = dr.nspred; % Number of predetermined variables in the state equation. + +%% Test if observed variables are declared. +if isempty(options_.varobs) + error('ESTIMATION: VAROBS is missing') +end + +%% Setting resticted state space (observed + predetermined variables) +k = []; +k1 = []; +for i=1:n_varobs + k = [k strmatch(deblank(options_.varobs(i,:)),M_.endo_names(dr.order_var,:),'exact')]; + k1 = [k1 strmatch(deblank(options_.varobs(i,:)),M_.endo_names, 'exact')]; +end +% Define union of observed and state variables +k2 = union(k',[dr.nstatic+1:dr.nstatic+dr.npred]'); +% Set restrict_state to postion of observed + state variables in expanded state vector. +bayestopt_.restrict_var_list = k2; +% set mf0 to positions of state variables in restricted state vector for likelihood computation. +[junk,bayestopt_.mf0] = ismember([dr.nstatic+1:dr.nstatic+dr.npred]',k2); +% Set mf1 to positions of observed variables in restricted state vector for likelihood computation. +[junk,bayestopt_.mf1] = ismember(k,k2); +% Set mf2 to positions of observed variables in expanded state vector for filtering and smoothing. +bayestopt_.mf2 = k; +bayestopt_.mfys = k1; + +[junk,ic] = intersect(k2,nstatic+(1:npred)'); +bayestopt_.restrict_columns = [ic; length(k2)+(1:nspred-npred)']; +aux = dr.transition_auxiliary_variables; +aux(:,2) = aux(:,2) + sum(k2 <= nstatic); +k = find(aux(:,2) > npred); +aux(k,2) = aux(k,2) + sum(k2 > nstatic+npred); +bayestopt_.restrict_aux = aux; + +%% Initialization with unit-root variables. +if ~isempty(options_.unit_root_vars) + n_ur = size(options_.unit_root_vars,1); + i_ur = zeros(n_ur,1); + for i=1:n_ur + i1 = strmatch(deblank(options_.unit_root_vars(i,:)),M_.endo_names(dr.order_var,:),'exact'); + if isempty(i1) + error('Undeclared variable in unit_root_vars statement') + end + i_ur(i) = i1; + end + bayestopt_.var_list_stationary = setdiff((1:M_.endo_nbr)',i_ur); + [junk,bayestopt_.restrict_var_list_nonstationary] = ... + intersect(bayestopt_.restrict_var_list,i_ur); + bayestopt_.restrict_var_list_stationary = ... + setdiff((1:length(bayestopt_.restrict_var_list))', ... + bayestopt_.restrict_var_list_nonstationary); + if M_.maximum_lag > 1 + l1 = flipud([cumsum(M_.lead_lag_incidence(1:M_.maximum_lag-1,dr.order_var),1);ones(1,M_.endo_nbr)]); + l2 = l1(:,bayestopt_.restrict_var_list); + il2 = find(l2' > 0); + l2(il2) = (1:length(il2))'; + bayestopt_.restrict_var_list_stationary = ... + nonzeros(l2(:,bayestopt_.restrict_var_list_stationary)); + bayestopt_.restrict_var_list_nonstationary = ... + nonzeros(l2(:,bayestopt_.restrict_var_list_nonstationary)); + end + options_.lik_init = 3; +end % if ~isempty(options_.unit_root_vars) + +%% Test if the data file is declared. +if isempty(options_.datafile) + error('ESTIMATION: datafile option is missing') +end + +%% If jscale isn't specified for an estimated parameter, use global option options_.jscale, set to 0.2, by default. +k = find(isnan(bayestopt_.jscale)); +bayestopt_.jscale(k) = options_.mh_jscale; + +%% Load and transform data. +rawdata = read_variables(options_.datafile,options_.varobs,[],options_.xls_sheet,options_.xls_range); +% Set the number of observations (nobs) and build a subsample between first_obs and nobs. +options_ = set_default_option(options_,'nobs',size(rawdata,1)-options_.first_obs+1); +gend = options_.nobs; +rawdata = rawdata(options_.first_obs:options_.first_obs+gend-1,:); +% Take the log of the variables if needed +if options_.loglinear % If the model is log-linearized... + if ~options_.logdata % and if the data are not in logs, then... + rawdata = log(rawdata); + end +end +% Test if the observations are real numbers. +if ~isreal(rawdata) + error('There are complex values in the data! Probably a wrong transformation') +end +% Test for missing observations. +options_.missing_data = any(any(isnan(rawdata))); +% Prefilter the data if needed. +if options_.prefilter == 1 + if options_.missing_data + bayestopt_.mean_varobs = zeros(n_varobs,1); + for variable=1:n_varobs + rdx = find(~isnan(rawdata(:,variable))); + m = mean(rawdata(rdx,variable)); + rawdata(rdx,variable) = rawdata(rdx,variable)-m; + bayestopt_.mean_varobs(variable) = m; + end + else + bayestopt_.mean_varobs = mean(rawdata,1)'; + rawdata = rawdata-repmat(bayestopt_.mean_varobs',gend,1); + end +end +% Transpose the dataset array. +data = transpose(rawdata); + +%% Set various options. +options_ = set_default_option(options_,'mh_nblck',2); +options_ = set_default_option(options_,'nodiagnostic',0); + +% load mode file is necessary +if length(options_.mode_file) > 0 && options_.posterior_mode_estimation + load(options_.mode_file); +end + +%% Compute the steady state: +if ~isempty(estim_params_) + set_parameters(xparam1); +end +if options_.steadystate_flag% if the *_steadystate.m file is provided. + [ys,tchek] = feval([M_.fname '_steadystate'],... + [zeros(M_.exo_nbr,1);... + oo_.exo_det_steady_state]); + if size(ys,1) < M_.endo_nbr + if length(M_.aux_vars) > 0 + ys = add_auxiliary_variables_to_steadystate(ys,M_.aux_vars,... + M_.fname,... + zeros(M_.exo_nbr,1),... + oo_.exo_det_steady_state,... + M_.params); + else + error([M_.fname '_steadystate.m doesn''t match the model']); + end + end + oo_.steady_state = ys; +else% if the steady state file is not provided. + [dd,info] = resol(oo_.steady_state,0); + oo_.steady_state = dd.ys; clear('dd'); +end +if all(abs(oo_.steady_state(bayestopt_.mfys))<1e-9) + options_.noconstant = 1; +else + options_.noconstant = 0; +end + + +%% compute sample moments if needed (bvar-dsge) +if options_.bvar_dsge + if options_.missing_data + error('I cannot estimate a DSGE-VAR model with missing observations!') + end + if options_.noconstant + evalin('base',... + ['[mYY,mXY,mYX,mXX,Ydata,Xdata] = ' ... + 'var_sample_moments(options_.first_obs,' ... + 'options_.first_obs+options_.nobs-1,options_.varlag,-1,' ... + 'options_.datafile, options_.varobs,options_.xls_sheet,options_.xls_range);']) + else% The steady state is non zero ==> a constant in the VAR is needed! + evalin('base',['[mYY,mXY,mYX,mXX,Ydata,Xdata] = ' ... + 'var_sample_moments(options_.first_obs,' ... + 'options_.first_obs+options_.nobs-1,options_.varlag,0,' ... + 'options_.datafile, options_.varobs,options_.xls_sheet,options_.xls_range);']) + end +end + +[data_index,number_of_observations,no_more_missing_observations] = describe_missing_data(data,gend,n_varobs); +missing_value = ~(number_of_observations == gend*n_varobs); + +initial_estimation_checks(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations); + +if options_.mode_compute == 0 + if options_.smoother == 1 + [atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,T,R,P,PK,d,decomp] = DsgeSmoother(xparam1,gend,data,data_index,missing_value); + oo_.Smoother.SteadyState = ys; + oo_.Smoother.TrendCoeffs = trend_coeff; + oo_.Smoother.integration_order = d; + oo_.Smoother.variance = P; + i_endo_nbr = 1:M_.endo_nbr; + if options_.nk ~= 0 + oo_.FilteredVariablesKStepAhead = aK(options_.filter_step_ahead,i_endo_nbr,:); + oo_.FilteredVariablesKStepAheadVariances = PK(options_.filter_step_ahead,i_endo_nbr,i_endo_nbr,:); + oo_.FilteredVariablesShockDecomposition = decomp(options_.filter_step_ahead,i_endo_nbr,:,:); + end + for i=1:M_.endo_nbr + eval(['oo_.SmoothedVariables.' deblank(M_.endo_names(dr.order_var(i),:)) ' = atT(i,:)'';']); + eval(['oo_.FilteredVariables.' deblank(M_.endo_names(dr.order_var(i),:)) ' = squeeze(aK(1,i,:));']); + eval(['oo_.UpdatedVariables.' deblank(M_.endo_names(dr.order_var(i),:)) ' = updated_variables(i,:)'';']); + end + for i=1:M_.exo_nbr + eval(['oo_.SmoothedShocks.' deblank(M_.exo_names(i,:)) ' = innov(i,:)'';']); + end + end + if length(options_.mode_file) == 0 + return; + end +end + +%% Estimation of the posterior mode or likelihood mode +if options_.mode_compute > 0 & options_.posterior_mode_estimation + if ~options_.bvar_dsge + fh=str2func('DsgeLikelihood'); + else + fh=str2func('DsgeVarLikelihood'); + end + switch options_.mode_compute + case 1 + optim_options = optimset('display','iter','LargeScale','off', ... + 'MaxFunEvals',100000,'TolFun',1e-8,'TolX',1e-6); + if isfield(options_,'optim_opt') + eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']); + end + if ~options_.bvar_dsge + [xparam1,fval,exitflag,output,lamdba,grad,hessian_fmincon] = ... + fmincon(fh,xparam1,[],[],[],[],lb,ub,[],optim_options,gend,data,data_index,number_of_observations,no_more_missing_observations); + else + [xparam1,fval,exitflag,output,lamdba,grad,hessian_fmincon] = ... + fmincon(fh,xparam1,[],[],[],[],lb,ub,[],optim_options,gend); + end + case 2 + error('ESTIMATION: mode_compute=2 option (Lester Ingber''s Adaptive Simulated Annealing) is no longer available') + case 3 + optim_options = optimset('display','iter','MaxFunEvals',100000,'TolFun',1e-8,'TolX',1e-6); + if isfield(options_,'optim_opt') + eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']); + end + if ~options_.bvar_dsge + [xparam1,fval,exitflag] = fminunc(fh,xparam1,optim_options,gend,data,data_index,number_of_observations,no_more_missing_observations); + else + [xparam1,fval,exitflag] = fminunc(fh,xparam1,optim_options,gend); + end + case 4 + H0 = 1e-4*eye(nx); + crit = 1e-7; + nit = 1000; + verbose = 2; + if ~options_.bvar_dsge + [fval,xparam1,grad,hessian_csminwel,itct,fcount,retcodehat] = ... + csminwel('DsgeLikelihood',xparam1,H0,[],crit,nit,options_.gradient_method,gend,data,data_index,number_of_observations,no_more_missing_observations); + disp(sprintf('Objective function at mode: %f',fval)) + disp(sprintf('Objective function at mode: %f',DsgeLikelihood(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations))) + else + [fval,xparam1,grad,hessian_csminwel,itct,fcount,retcodehat] = ... + csminwel('DsgeVarLikelihood',xparam1,H0,[],crit,nit,options_.gradient_method,gend); + disp(sprintf('Objective function at mode: %f',fval)) + disp(sprintf('Objective function at mode: %f',DsgeVarLikelihood(xparam1,gend))) + end + case 5 + if isfield(options_,'hess') + flag = options_.hess; + else + flag = 1; + end + if ~exist('igg'), % by M. Ratto + hh=[]; + gg=[]; + igg=[]; + end % by M. Ratto + if isfield(options_,'ftol') + crit = options_.ftol; + else + crit = 1.e-7; + end + if isfield(options_,'nit') + nit = options_.nit; + else + nit=1000; + end + if ~options_.bvar_dsge + [xparam1,hh,gg,fval,invhess] = newrat('DsgeLikelihood',xparam1,hh,gg,igg,crit,nit,flag,gend,data,data_index,number_of_observations,no_more_missing_observations); + else + [xparam1,hh,gg,fval,invhess] = newrat('DsgeVarLikelihood',xparam1,hh,gg,igg,crit,nit,flag,gend); + end + parameter_names = bayestopt_.name; + save([M_.fname '_mode.mat'],'xparam1','hh','gg','fval','invhess','parameter_names'); + case 6 + if ~options_.bvar_dsge + fval = DsgeLikelihood(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations); + else + fval = DsgeVarLikelihood(xparam1,gend); + end + OldMode = fval; + if ~exist('MeanPar') + MeanPar = xparam1; + end + if exist('hh') + CovJump = inv(hh); + else% The covariance matrix is initialized with the prior + % covariance (a diagonal matrix) %%Except for infinite variances ;-) + varinit = 'prior'; + if strcmpi(varinit,'prior') + stdev = bayestopt_.p2; + indx = find(isinf(stdev)); + stdev(indx) = ones(length(indx),1)*sqrt(10); + vars = stdev.^2; + CovJump = diag(vars); + elseif strcmpi(varinit,'eye') + vars = ones(length(bayestopt_.p2),1)*0.1; + CovJump = diag(vars); + else + disp('gmhmaxlik :: Error!') + return + end + end + OldPostVar = CovJump; + Scale = options_.mh_jscale; + for i=1:options_.Opt6Iter + if i == 1 + if options_.Opt6Iter > 1 + flag = ''; + else + flag = 'LastCall'; + end + if ~options_.bvar_dsge + [xparam1,PostVar,Scale,PostMean] = ... + gmhmaxlik('DsgeLikelihood',xparam1,bounds,options_.Opt6Numb,Scale,flag,MeanPar,CovJump,gend,data,... + data_index,number_of_observations,no_more_missing_observations); + fval = DsgeLikelihood(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations); + else + [xparam1,PostVar,Scale,PostMean] = ... + gmhmaxlik('DsgeVarLikelihood',xparam1,bounds,options_.Opt6Numb,Scale,flag,MeanPar,CovJump,gend); + fval = DsgeVarLikelihood(xparam1,gend); + end + options_.mh_jscale = Scale; + mouvement = max(max(abs(PostVar-OldPostVar))); + disp(['Change in the covariance matrix = ' num2str(mouvement) '.']) + disp(['Mode improvement = ' num2str(abs(OldMode-fval))]) + OldMode = fval; + else + OldPostVar = PostVar; + if i<options_.Opt6Iter + flag = ''; + else + flag = 'LastCall'; + end + if ~options_.bvar_dsge + [xparam1,PostVar,Scale,PostMean] = ... + gmhmaxlik('DsgeLikelihood',xparam1,bounds,... + options_.Opt6Numb,Scale,flag,PostMean,PostVar,gend,data,data_index,number_of_observations,no_more_missing_observations); + fval = DsgeLikelihood(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations); + else + [xparam1,PostVar,Scale,PostMean] = ... + gmhmaxlik('DsgeVarLikelihood',xparam1,bounds,... + options_.Opt6Numb,Scale,flag,PostMean,PostVar,gend); + fval = DsgeVarLikelihood(xparam1,gend); + end + options_.mh_jscale = Scale; + mouvement = max(max(abs(PostVar-OldPostVar))); + fval = DsgeLikelihood(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations); + disp(['Change in the covariance matrix = ' num2str(mouvement) '.']) + disp(['Mode improvement = ' num2str(abs(OldMode-fval))]) + OldMode = fval; + end + hh = inv(PostVar); + save([M_.fname '_mode.mat'],'xparam1','hh'); + bayestopt_.jscale = ones(length(xparam1),1)*Scale;%??! + end + case 7 + optim_options = optimset('display','iter','MaxFunEvals',1000000,'MaxIter',6000,'TolFun',1e-8,'TolX',1e-6); + if isfield(options_,'optim_opt') + eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']); + end + if ~options_.bvar_dsge + [xparam1,fval,exitflag] = fminsearch(fh,xparam1,optim_options,gend,data,data_index,number_of_observations,no_more_missing_observations); + else + [xparam1,fval,exitflag] = fminsearch(fh,xparam1,optim_options,gend); + end + + case 101 + myoptions=soptions; + myoptions(2)=1e-6; %accuracy of argument + myoptions(3)=1e-6; %accuracy of function (see Solvopt p.29) + myoptions(5)= 1.0; + + [xparam1,fval]=solvopt(xparam1,fh,[],myoptions,gend,data); + case 102 + %simulating annealing + % LB=zeros(size(xparam1))-20; + % UB=zeros(size(xparam1))+20; + LB = xparam1 - 1; + UB = xparam1 + 1; + neps=10; + % Set input parameters. + maxy=0; + eps=1.0e-9; + rt_=.10; + t=15.0; + ns=10; + nt=10; + maxevl=100000000; + idisp =1; + npar=length(xparam1); + + disp(['size of param',num2str(length(xparam1))]) + c=.1*ones(npar,1); + %* Set input values of the input/output parameters.* + + vm=1*ones(npar,1); + disp(['number of parameters= ' num2str(npar) 'max= ' num2str(maxy) 't= ' num2str(t)]); + disp(['rt_= ' num2str(rt_) 'eps= ' num2str(eps) 'ns= ' num2str(ns)]); + disp(['nt= ' num2str(nt) 'neps= ' num2str(neps) 'maxevl= ' num2str(maxevl)]); + % disp(['iprint= ' num2str(iprint) 'seed= ' num2str(seed)]); + disp ' '; + disp ' '; + disp(['starting values(x) ' num2str(xparam1')]); + disp(['initial step length(vm) ' num2str(vm')]); + disp(['lower bound(lb)', 'initial conditions', 'upper bound(ub)' ]); + disp([LB xparam1 UB]); + disp(['c vector ' num2str(c')]); + + % keyboard + if ~options_.bvar_dsge + [xparam1, fval, nacc, nfcnev, nobds, ier, t, vm] = sa(fh,xparam1,maxy,rt_,eps,ns,nt ... + ,neps,maxevl,LB,UB,c,idisp ,t,vm,gend,data,data_index,number_of_observations,no_more_missing_observations); + else + [xparam1, fval, nacc, nfcnev, nobds, ier, t, vm] = sa(fh,xparam1,maxy,rt_,eps,ns,nt ... + ,neps,maxevl,LB,UB,c,idisp ,t,vm,gend); + end + otherwise + if ischar(options_.mode_compute) + if options_.bvar_dsge + [xparam1, fval, retcode ] = feval(options_.mode_compute,fh,xparam1,gend,data); + else + [xparam1, fval, retcode ] = feval(options_.mode_compute, ... + fh,xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations); + end + else + error(['ESTIMATION: mode_compute=' int2str(options_.mode_compute) ... + ' option is unknown!']) + end + end + if options_.mode_compute ~= 5 + if options_.mode_compute ~= 6 + if options_.cova_compute == 1 + if ~options_.bvar_dsge + hh = reshape(hessian('DsgeLikelihood',xparam1, ... + options_.gstep,gend,data,data_index,number_of_observations,... + no_more_missing_observations),nx,nx); + else + hh = reshape(hessian('DsgeVarLikelihood',xparam1,options_.gstep,gend),nx,nx); + end + else + nn = repmat(NaN,length(xparam1),length(xparam1)) + end + end + parameter_names = bayestopt_.name; + if options_.cova_compute + save([M_.fname '_mode.mat'],'xparam1','hh','parameter_names'); + else + save([M_.fname '_mode.mat'],'xparam1','parameter_names'); + end + end +end + +if options_.cova_compute == 0 + hh = repmat(NaN,length(xparam1),length(xparam1)); +end + +try + chol(hh); +catch + disp(' ') + disp('POSTERIOR KERNEL OPTIMIZATION PROBLEM!') + disp(' (minus) the hessian matrix at the "mode" is not positive definite!') + disp('=> posterior variance of the estimated parameters are not positive.') + disp('You should try to change the initial values of the parameters using') + disp('the estimated_params_init block, or use another optimization routine.') + warning('The results below are most likely wrong!'); +end + +if options_.mode_check == 1 & options_.posterior_mode_estimation + mode_check(xparam1,0,hh,gend,data,lb,ub,data_index,number_of_observations,no_more_missing_observations); +end + +if options_.posterior_mode_estimation + %hh = generalized_cholesky(hh); + invhess = inv(hh); + stdh = sqrt(diag(invhess)); +else + variances = bayestopt_.p2.^2; + invhess = 0.01*diag(variances); + %invhess = 0.01*eye(length(variances)); +end + + +if any(bayestopt_.pshape > 0) & options_.posterior_mode_estimation + disp(' ') + disp('RESULTS FROM POSTERIOR MAXIMIZATION') + tstath = zeros(nx,1); + for i = 1:nx + tstath(i) = abs(xparam1(i))/stdh(i); + end + + header_width = row_header_width(M_,estim_params_,bayestopt_); + + tit1 = sprintf('%-*s %7s %8s %7s %6s %4s %6s\n',header_width-2,' ','prior mean', ... + 'mode','s.d.','t-stat','prior','pstdev'); + if np + ip = nvx+nvn+ncx+ncn+1; + disp('parameters') + disp(tit1) + for i=1:np + name = bayestopt_.name{ip}; + disp(sprintf('%-*s %7.3f %8.4f %7.4f %7.4f %4s %6.4f', ... + header_width,name, ... + bayestopt_.p1(ip),xparam1(ip),stdh(ip),tstath(ip), ... + pnames(bayestopt_.pshape(ip)+1,:), ... + bayestopt_.p2(ip))); + eval(['oo_.posterior_mode.parameters.' name ' = xparam1(ip);']); + eval(['oo_.posterior_std.parameters.' name ' = stdh(ip);']); + ip = ip+1; + end + end + if nvx + ip = 1; + disp('standard deviation of shocks') + disp(tit1) + for i=1:nvx + k = estim_params_.var_exo(i,1); + name = deblank(M_.exo_names(k,:)); + disp(sprintf('%-*s %7.3f %8.4f %7.4f %7.4f %4s %6.4f', ... + header_width,name,bayestopt_.p1(ip),xparam1(ip), ... + stdh(ip),tstath(ip),pnames(bayestopt_.pshape(ip)+1,:), ... + bayestopt_.p2(ip))); + M_.Sigma_e(k,k) = xparam1(ip)*xparam1(ip); + eval(['oo_.posterior_mode.shocks_std.' name ' = xparam1(ip);']); + eval(['oo_.posterior_std.shocks_std.' name ' = stdh(ip);']); + ip = ip+1; + end + end + if nvn + disp('standard deviation of measurement errors') + disp(tit1) + ip = nvx+1; + for i=1:nvn + name = deblank(options_.varobs(estim_params_.var_endo(i,1),:)); + disp(sprintf('%-*s %7.3f %8.4f %7.4f %7.4f %4s %6.4f', ... + header_width,name,bayestopt_.p1(ip), ... + xparam1(ip),stdh(ip),tstath(ip), ... + pnames(bayestopt_.pshape(ip)+1,:), ... + bayestopt_.p2(ip))); + eval(['oo_.posterior_mode.measurement_errors_std.' name ' = xparam1(ip);']); + eval(['oo_.posterior_std.measurement_errors_std.' name ' = stdh(ip);']); + ip = ip+1; + end + end + if ncx + disp('correlation of shocks') + disp(tit1) + ip = nvx+nvn+1; + for i=1:ncx + k1 = estim_params_.corrx(i,1); + k2 = estim_params_.corrx(i,2); + name = [deblank(M_.exo_names(k1,:)) ',' deblank(M_.exo_names(k2,:))]; + NAME = [deblank(M_.exo_names(k1,:)) '_' deblank(M_.exo_names(k2,:))]; + disp(sprintf('%-*s %7.3f %8.4f %7.4f %7.4f %4s %6.4f', name, ... + header_width,bayestopt_.p1(ip),xparam1(ip),stdh(ip),tstath(ip), ... + pnames(bayestopt_.pshape(ip)+1,:), bayestopt_.p2(ip))); + M_.Sigma_e(k1,k2) = xparam1(ip)*sqrt(M_.Sigma_e(k1,k1)*M_.Sigma_e(k2,k2)); + M_.Sigma_e(k2,k1) = M_.Sigma_e(k1,k2); + eval(['oo_.posterior_mode.shocks_corr.' NAME ' = xparam1(ip);']); + eval(['oo_.posterior_std.shocks_corr.' NAME ' = stdh(ip);']); + ip = ip+1; + end + end + if ncn + disp('correlation of measurement errors') + disp(tit1) + ip = nvx+nvn+ncx+1; + for i=1:ncn + k1 = estim_params_.corrn(i,1); + k2 = estim_params_.corrn(i,2); + name = [deblank(M_.endo_names(k1,:)) ',' deblank(M_.endo_names(k2,:))]; + NAME = [deblank(M_.endo_names(k1,:)) '_' deblank(M_.endo_names(k2,:))]; + disp(sprintf('%-*s %7.3f %8.4f %7.4f %7.4f %4s %6.4f', name, ... + header_width,bayestopt_.p1(ip),xparam1(ip),stdh(ip),tstath(ip), ... + pnames(bayestopt_.pshape(ip)+1,:), bayestopt_.p2(ip))); + eval(['oo_.posterior_mode.measurement_errors_corr.' NAME ' = xparam1(ip);']); + eval(['oo_.posterior_std.measurement_errors_corr.' NAME ' = stdh(ip);']); + ip = ip+1; + end + end + %% Laplace approximation to the marginal log density: + estim_params_nbr = size(xparam1,1); + scale_factor = -sum(log10(diag(invhess))); + log_det_invhess = -estim_params_nbr*log(scale_factor)+log(det(scale_factor*invhess)); + if ~options_.bvar_dsge + md_Laplace = .5*estim_params_nbr*log(2*pi) + .5*log_det_invhess ... + - DsgeLikelihood(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations); + else + md_Laplace = .5*estim_params_nbr*log(2*pi) + .5*log_det_invhess ... + - DsgeVarLikelihood(xparam1,gend); + end + oo_.MarginalDensity.LaplaceApproximation = md_Laplace; + disp(' ') + disp(sprintf('Log data density [Laplace approximation] is %f.',md_Laplace)) + disp(' ') +elseif ~any(bayestopt_.pshape > 0) & options_.posterior_mode_estimation + disp(' ') + disp('RESULTS FROM MAXIMUM LIKELIHOOD') + tstath = zeros(nx,1); + for i = 1:nx + tstath(i) = abs(xparam1(i))/stdh(i); + end + header_width = row_header_width(M_,estim_params_,bayestopt_); + tit1 = sprintf('%-*s %10s %7s %6s\n',header_width-2,' ','Estimate','s.d.','t-stat'); + if np + ip = nvx+nvn+ncx+ncn+1; + disp('parameters') + disp(tit1) + for i=1:np + name = bayestopt_.name{ip}; + disp(sprintf('%-*s %8.4f %7.4f %7.4f', ... + header_width,name,xparam1(ip),stdh(ip),tstath(ip))); + eval(['oo_.mle_mode.parameters.' name ' = xparam1(ip);']); + eval(['oo_.mle_std.parameters.' name ' = stdh(ip);']); + ip = ip+1; + end + end + if nvx + ip = 1; + disp('standard deviation of shocks') + disp(tit1) + for i=1:nvx + k = estim_params_.var_exo(i,1); + name = deblank(M_.exo_names(k,:)); + disp(sprintf('%-*s %8.4f %7.4f %7.4f',header_width,name,xparam1(ip),stdh(ip),tstath(ip))); + M_.Sigma_e(k,k) = xparam1(ip)*xparam1(ip); + eval(['oo_.mle_mode.shocks_std.' name ' = xparam1(ip);']); + eval(['oo_.mle_std.shocks_std.' name ' = stdh(ip);']); + ip = ip+1; + end + end + if nvn + disp('standard deviation of measurement errors') + disp(tit1) + ip = nvx+1; + for i=1:nvn + name = deblank(options_.varobs(estim_params_.var_endo(i,1),:)); + disp(sprintf('%-*s %8.4f %7.4f %7.4f',header_width,name,xparam1(ip),stdh(ip),tstath(ip))) + eval(['oo_.mle_mode.measurement_errors_std.' name ' = xparam1(ip);']); + eval(['oo_.mle_std.measurement_errors_std.' name ' = stdh(ip);']); + ip = ip+1; + end + end + if ncx + disp('correlation of shocks') + disp(tit1) + ip = nvx+nvn+1; + for i=1:ncx + k1 = estim_params_.corrx(i,1); + k2 = estim_params_.corrx(i,2); + name = [deblank(M_.exo_names(k1,:)) ',' deblank(M_.exo_names(k2,:))]; + NAME = [deblank(M_.exo_names(k1,:)) '_' deblank(M_.exo_names(k2,:))]; + disp(sprintf('%-*s %8.4f %7.4f %7.4f', header_width,name,xparam1(ip),stdh(ip),tstath(ip))); + M_.Sigma_e(k1,k2) = xparam1(ip)*sqrt(M_.Sigma_e(k1,k1)*M_.Sigma_e(k2,k2)); + M_.Sigma_e(k2,k1) = M_.Sigma_e(k1,k2); + eval(['oo_.mle_mode.shocks_corr.' NAME ' = xparam1(ip);']); + eval(['oo_.mle_std.shocks_corr.' NAME ' = stdh(ip);']); + ip = ip+1; + end + end + if ncn + disp('correlation of measurement errors') + disp(tit1) + ip = nvx+nvn+ncx+1; + for i=1:ncn + k1 = estim_params_.corrn(i,1); + k2 = estim_params_.corrn(i,2); + name = [deblank(M_.endo_names(k1,:)) ',' deblank(M_.endo_names(k2,:))]; + NAME = [deblank(M_.endo_names(k1,:)) '_' deblank(M_.endo_names(k2,:))]; + disp(sprintf('%-*s %8.4f %7.4f %7.4f',header_width,name,xparam1(ip),stdh(ip),tstath(ip))); + eval(['oo_.mle_mode.measurement_error_corr.' NAME ' = xparam1(ip);']); + eval(['oo_.mle_std.measurement_error_corr.' NAME ' = stdh(ip);']); + ip = ip+1; + end + end +end + + +OutputDirectoryName = CheckPath('Output'); + +if any(bayestopt_.pshape > 0) & options_.TeX %% Bayesian estimation (posterior mode) Latex output + if np + filename = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_1.TeX']; + fidTeX = fopen(filename,'w'); + fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n'); + fprintf(fidTeX,'%% RESULTS FROM POSTERIOR MAXIMIZATION (parameters)\n'); + fprintf(fidTeX,['%% ' datestr(now,0)]); + fprintf(fidTeX,' \n'); + fprintf(fidTeX,' \n'); + fprintf(fidTeX,'{\\tiny \n') + fprintf(fidTeX,'\\begin{table}\n'); + fprintf(fidTeX,'\\centering\n'); + fprintf(fidTeX,'\\begin{tabular}{l|lcccc} \n'); + fprintf(fidTeX,'\\hline\\hline \\\\ \n'); + fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Posterior mode & s.d. \\\\ \n'); + fprintf(fidTeX,'\\hline \\\\ \n'); + ip = nvx+nvn+ncx+ncn+1; + for i=1:np + fprintf(fidTeX,'$%s$ & %s & %7.3f & %6.4f & %8.4f & %7.4f \\\\ \n',... + M_.param_names_tex(estim_params_.param_vals(i,1),:),... + deblank(pnames(bayestopt_.pshape(ip)+1,:)),... + bayestopt_.p1(ip),... + bayestopt_.p2(ip),... + xparam1(ip),... + stdh(ip)); + ip = ip + 1; + end + fprintf(fidTeX,'\\hline\\hline \n'); + fprintf(fidTeX,'\\end{tabular}\n '); + fprintf(fidTeX,'\\caption{Results from posterior parameters (parameters)}\n '); + fprintf(fidTeX,'\\label{Table:Posterior:1}\n'); + fprintf(fidTeX,'\\end{table}\n'); + fprintf(fidTeX,'} \n') + fprintf(fidTeX,'%% End of TeX file.\n'); + fclose(fidTeX); + end + if nvx + TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_2.TeX']; + fidTeX = fopen(TeXfile,'w'); + fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n'); + fprintf(fidTeX,'%% RESULTS FROM POSTERIOR MAXIMIZATION (standard deviation of structural shocks)\n'); + fprintf(fidTeX,['%% ' datestr(now,0)]); + fprintf(fidTeX,' \n'); + fprintf(fidTeX,' \n'); + fprintf(fidTeX,'{\\tiny \n'); + fprintf(fidTeX,'\\begin{table}\n'); + fprintf(fidTeX,'\\centering\n'); + fprintf(fidTeX,'\\begin{tabular}{l|lcccc} \n'); + fprintf(fidTeX,'\\hline\\hline \\\\ \n'); + fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Posterior mode & s.d. \\\\ \n') + fprintf(fidTeX,'\\hline \\\\ \n'); + ip = 1; + for i=1:nvx + k = estim_params_.var_exo(i,1); + fprintf(fidTeX,[ '$%s$ & %4s & %7.3f & %6.4f & %8.4f & %7.4f \\\\ \n'],... + deblank(M_.exo_names_tex(k,:)),... + deblank(pnames(bayestopt_.pshape(ip)+1,:)),... + bayestopt_.p1(ip),... + bayestopt_.p2(ip),... + xparam1(ip), ... + stdh(ip)); + ip = ip+1; + end + fprintf(fidTeX,'\\hline\\hline \n'); + fprintf(fidTeX,'\\end{tabular}\n '); + fprintf(fidTeX,'\\caption{Results from posterior parameters (standard deviation of structural shocks)}\n '); + fprintf(fidTeX,'\\label{Table:Posterior:2}\n'); + fprintf(fidTeX,'\\end{table}\n'); + fprintf(fidTeX,'} \n') + fprintf(fidTeX,'%% End of TeX file.\n'); + fclose(fidTeX); + end + if nvn + TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_3.TeX']; + fidTeX = fopen(TeXfile,'w'); + fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n'); + fprintf(fidTeX,'%% RESULTS FROM POSTERIOR MAXIMIZATION (standard deviation of measurement errors)\n'); + fprintf(fidTeX,['%% ' datestr(now,0)]); + fprintf(fidTeX,' \n'); + fprintf(fidTeX,' \n'); + fprintf(fidTeX,'\\begin{table}\n'); + fprintf(fidTeX,'\\centering\n'); + fprintf(fidTeX,'\\begin{tabular}{l|lcccc} \n'); + fprintf(fidTeX,'\\hline\\hline \\\\ \n'); + fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Posterior mode & s.d. \\\\ \n') + fprintf(fidTeX,'\\hline \\\\ \n'); + ip = nvx+1; + for i=1:nvn + idx = strmatch(options_.varobs(estim_params_.var_endo(i,1),:),M_.endo_names); + fprintf(fidTeX,'$%s$ & %4s & %7.3f & %6.4f & %8.4f & %7.4f \\\\ \n',... + deblank(M_.endo_names_tex(idx,:)), ... + deblank(pnames(bayestopt_.pshape(ip)+1,:)), ... + bayestopt_.p1(ip), ... + bayestopt_.p2(ip),... + xparam1(ip),... + stdh(ip)); + ip = ip+1; + end + fprintf(fidTeX,'\\hline\\hline \n'); + fprintf(fidTeX,'\\end{tabular}\n '); + fprintf(fidTeX,'\\caption{Results from posterior parameters (standard deviation of measurement errors)}\n '); + fprintf(fidTeX,'\\label{Table:Posterior:3}\n'); + fprintf(fidTeX,'\\end{table}\n'); + fprintf(fidTeX,'%% End of TeX file.\n'); + fclose(fidTeX); + end + if ncx + TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_4.TeX']; + fidTeX = fopen(TeXfile,'w'); + fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n'); + fprintf(fidTeX,'%% RESULTS FROM POSTERIOR MAXIMIZATION (correlation of structural shocks)\n'); + fprintf(fidTeX,['%% ' datestr(now,0)]); + fprintf(fidTeX,' \n'); + fprintf(fidTeX,' \n'); + fprintf(fidTeX,'\\begin{table}\n'); + fprintf(fidTeX,'\\centering\n'); + fprintf(fidTeX,'\\begin{tabular}{l|lcccc} \n'); + fprintf(fidTeX,'\\hline\\hline \\\\ \n'); + fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Posterior mode & s.d. \\\\ \n') + fprintf(fidTeX,'\\hline \\\\ \n'); + ip = nvx+nvn+1; + for i=1:ncx + k1 = estim_params_.corrx(i,1); + k2 = estim_params_.corrx(i,2); + fprintf(fidTeX,[ '$%s$ & %s & %7.3f & %6.4f & %8.4f & %7.4f \\\\ \n'],... + [deblank(M_.exo_names_tex(k1,:)) ',' deblank(M_.exo_names_tex(k2,:))], ... + deblank(pnames(bayestopt_.pshape(ip)+1,:)), ... + bayestopt_.p1(ip), ... + bayestopt_.p2(ip), ... + xparam1(ip), ... + stdh(ip)); + ip = ip+1; + end + fprintf(fidTeX,'\\hline\\hline \n'); + fprintf(fidTeX,'\\end{tabular}\n '); + fprintf(fidTeX,'\\caption{Results from posterior parameters (correlation of structural shocks)}\n '); + fprintf(fidTeX,'\\label{Table:Posterior:4}\n'); + fprintf(fidTeX,'\\end{table}\n'); + fprintf(fidTeX,'%% End of TeX file.\n'); + fclose(fidTeX); + end + if ncn + TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_5.TeX']; + fidTeX = fopen(TeXfile,'w'); + fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n'); + fprintf(fidTeX,'%% RESULTS FROM POSTERIOR MAXIMIZATION (correlation of measurement errors)\n'); + fprintf(fidTeX,['%% ' datestr(now,0)]); + fprintf(fidTeX,' \n'); + fprintf(fidTeX,' \n'); + fprintf(fidTeX,'\\begin{table}\n'); + fprintf(fidTeX,'\\centering\n'); + fprintf(fidTeX,'\\begin{tabular}{l|lcccc} \n'); + fprintf(fidTeX,'\\hline\\hline \\\\ \n'); + fprintf(fidTeX,' & Prior distribution & Prior mean & Prior s.d. & Posterior mode & s.d. \\\\ \n') + fprintf(fidTeX,'\\hline \\\\ \n'); + ip = nvx+nvn+ncx+1; + for i=1:ncn + k1 = estim_params_.corrn(i,1); + k2 = estim_params_.corrn(i,2); + fprintf(fidTeX,'$%s$ & %s & %7.3f & %6.4f & %8.4f & %7.4f \\\\ \n',... + [deblank(M_.endo_names_tex(k1,:)) ',' deblank(M_.endo_names_tex(k2,:))], ... + pnames(bayestopt_.pshape(ip)+1,:), ... + bayestopt_.p1(ip), ... + bayestopt_.p2(ip), ... + xparam1(ip), ... + stdh(ip)); + ip = ip+1; + end + fprintf(fidTeX,'\\hline\\hline \n'); + fprintf(fidTeX,'\\end{tabular}\n '); + fprintf(fidTeX,'\\caption{Results from posterior parameters (correlation of measurement errors)}\n '); + fprintf(fidTeX,'\\label{Table:Posterior:5}\n'); + fprintf(fidTeX,'\\end{table}\n'); + fprintf(fidTeX,'%% End of TeX file.\n'); + fclose(fidTeX); + end +end + +if np > 0 + pindx = estim_params_.param_vals(:,1); + save([M_.fname '_params.mat'],'pindx'); +end + +if (any(bayestopt_.pshape >0 ) & options_.mh_replic) | ... + (any(bayestopt_.pshape >0 ) & options_.load_mh_file) %% not ML estimation + bounds = prior_bounds(bayestopt_); + bounds(:,1)=max(bounds(:,1),lb); + bounds(:,2)=min(bounds(:,2),ub); + bayestopt_.lb = bounds(:,1); + bayestopt_.ub = bounds(:,2); + if any(xparam1 < bounds(:,1)) | any(xparam1 > bounds(:,2)) + find(xparam1 < bounds(:,1)) + find(xparam1 > bounds(:,2)) + error('Mode values are outside prior bounds. Reduce prior_trunc.') + end + % runs MCMC + if options_.mh_replic + if options_.load_mh_file & options_.use_mh_covariance_matrix + invhess = compute_mh_covariance_matrix; + end + if options_.bvar_dsge + feval(options_.posterior_sampling_method,'DsgeVarLikelihood',options_.proposal_distribution,xparam1,invhess,bounds,gend); + else + feval(options_.posterior_sampling_method,'DsgeLikelihood',options_.proposal_distribution,xparam1,invhess,bounds,gend,data,... + data_index,number_of_observations,no_more_missing_observations); + end + end + if ~options_.nodiagnostic & options_.mh_replic > 1000 & options_.mh_nblck > 1 + McMCDiagnostics(options_, estim_params_, M_); + end + %% Here i discard first half of the draws: + CutSample(M_, options_, estim_params_); + %% Estimation of the marginal density from the Mh draws: + if options_.mh_replic + [marginal,oo_] = marginal_density(M_, options_, estim_params_, oo_); + end + oo_ = GetPosteriorParametersStatistics(estim_params_, M_, options_, bayestopt_, oo_); + oo_ = PlotPosteriorDistributions(estim_params_, M_, options_, bayestopt_, oo_); + metropolis_draw(1); + if options_.bayesian_irf + PosteriorIRF('posterior'); + end + if options_.moments_varendo + oo_ = compute_moments_varendo('posterior',options_,M_,oo_,var_list_); + end + if options_.smoother | ~isempty(options_.filter_step_ahead) | options_.forecast + prior_posterior_statistics('posterior',data,gend,data_index,missing_value); + end + xparam = get_posterior_parameters('mean'); + set_all_parameters(xparam); +end + +if (~((any(bayestopt_.pshape > 0) & options_.mh_replic) | (any(bayestopt_.pshape ... + > 0) & options_.load_mh_file)) ... + | ~options_.smoother ) & M_.endo_nbr^2*gend < 1e7 % to be fixed + %% ML estimation, or posterior mode without metropolis-hastings or metropolis without bayesian smooth variable + [atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,T,R,P,PK,d,decomp] = DsgeSmoother(xparam1,gend,data,data_index,missing_value); + oo_.Smoother.SteadyState = ys; + oo_.Smoother.TrendCoeffs = trend_coeff; + oo_.Smoother.integration_order = d; + oo_.Smoother.variance = P; + i_endo_nbr = 1:M_.endo_nbr; + if options_.nk ~= 0 + oo_.FilteredVariablesKStepAhead = aK(options_.filter_step_ahead, ... + i_endo_nbr,:); + if isfield(options_,'kalman_algo') + if options_.kalman_algo > 2 + oo_.FilteredVariablesKStepAheadVariances = PK(options_.filter_step_ahead,i_endo_nbr,i_endo_nbr,:); + oo_.FilteredVariablesShockDecomposition = ... + decomp(options_.filter_step_ahead,i_endo_nbr,:,:); + end + end + end + for i=1:M_.endo_nbr + eval(['oo_.SmoothedVariables.' deblank(M_.endo_names(dr.order_var(i),:)) ' = atT(i,:)'';']); + eval(['oo_.FilteredVariables.' deblank(M_.endo_names(dr.order_var(i),:)) ' = squeeze(aK(1,i,:));']); + eval(['oo_.UpdatedVariables.' deblank(M_.endo_names(dr.order_var(i),:)) ... + ' = updated_variables(i,:)'';']); + end + [nbplt,nr,nc,lr,lc,nstar] = pltorg(M_.exo_nbr); + if options_.TeX + fidTeX = fopen([M_.fname '_SmoothedShocks.TeX'],'w'); + fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation.m (Dynare).\n'); + fprintf(fidTeX,['%% ' datestr(now,0) '\n']); + fprintf(fidTeX,' \n'); + end + if nbplt == 1 + hh = figure('Name','Smoothed shocks'); + NAMES = []; + if options_.TeX, TeXNAMES = []; end + for i=1:M_.exo_nbr + subplot(nr,nc,i); + plot(1:gend,innov(i,:),'-k','linewidth',1) + hold on + plot([1 gend],[0 0],'-r','linewidth',.5) + hold off + xlim([1 gend]) + name = deblank(M_.exo_names(i,:)); + NAMES = strvcat(NAMES,name); + if ~isempty(options_.XTick) + set(gca,'XTick',options_.XTick) + set(gca,'XTickLabel',options_.XTickLabel) + end + if options_.TeX + texname = M_.exo_names_tex(i,1); + TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']); + end + title(name,'Interpreter','none') + eval(['oo_.SmoothedShocks.' deblank(M_.exo_names(i,:)) ' = innov(i,:)'';']); + end + eval(['print -depsc2 ' M_.fname '_SmoothedShocks' int2str(1) '.eps']); + if ~exist('OCTAVE_VERSION') + eval(['print -dpdf ' M_.fname '_SmoothedShocks' int2str(1)]); + saveas(hh,[M_.fname '_SmoothedShocks' int2str(1) '.fig']); + end + if options_.nograph, close(hh), end + if options_.TeX + fprintf(fidTeX,'\\begin{figure}[H]\n'); + for jj = 1:M_.exo_nbr + fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); + end + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_SmoothedShocks%s}\n',M_.fname,int2str(1)); + fprintf(fidTeX,'\\caption{Smoothed shocks.}'); + fprintf(fidTeX,'\\label{Fig:SmoothedShocks:%s}\n',int2str(1)); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,'\n'); + fprintf(fidTeX,'%% End of TeX file.\n'); + fclose(fidTeX); + end + else + for plt = 1:nbplt-1 + hh = figure('Name','Smoothed shocks'); + set(0,'CurrentFigure',hh) + NAMES = []; + if options_.TeX, TeXNAMES = []; end + for i=1:nstar + k = (plt-1)*nstar+i; + subplot(nr,nc,i); + plot([1 gend],[0 0],'-r','linewidth',.5) + hold on + plot(1:gend,innov(k,:),'-k','linewidth',1) + hold off + name = deblank(M_.exo_names(k,:)); + NAMES = strvcat(NAMES,name); + if ~isempty(options_.XTick) + set(gca,'XTick',options_.XTick) + set(gca,'XTickLabel',options_.XTickLabel) + end + xlim([1 gend]) + if options_.TeX + texname = M_.exo_names_tex(k,:); + TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']); + end + title(name,'Interpreter','none') + eval(['oo_.SmoothedShocks.' deblank(name) ' = innov(k,:)'';']); + end + eval(['print -depsc2 ' M_.fname '_SmoothedShocks' int2str(plt) '.eps']); + if ~exist('OCTAVE_VERSION') + eval(['print -dpdf ' M_.fname '_SmoothedShocks' int2str(plt)]); + saveas(hh,[M_.fname '_SmoothedShocks' int2str(plt) '.fig']); + end + if options_.nograph, close(hh), end + if options_.TeX + fprintf(fidTeX,'\\begin{figure}[H]\n'); + for jj = 1:nstar + fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); + end + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_SmoothedShocks%s}\n',M_.fname,int2str(plt)); + fprintf(fidTeX,'\\caption{Smoothed shocks.}'); + fprintf(fidTeX,'\\label{Fig:SmoothedShocks:%s}\n',int2str(plt)); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,'\n'); + end + end + hh = figure('Name','Smoothed shocks'); + set(0,'CurrentFigure',hh) + NAMES = []; + if options_.TeX, TeXNAMES = []; end + for i=1:M_.exo_nbr-(nbplt-1)*nstar + k = (nbplt-1)*nstar+i; + if lr ~= 0 + subplot(lr,lc,i); + else + subplot(nr,nc,i); + end + plot([1 gend],[0 0],'-r','linewidth',0.5) + hold on + plot(1:gend,innov(k,:),'-k','linewidth',1) + hold off + name = deblank(M_.exo_names(k,:)); + NAMES = strvcat(NAMES,name); + if ~isempty(options_.XTick) + set(gca,'XTick',options_.XTick) + set(gca,'XTickLabel',options_.XTickLabel) + end + xlim([1 gend]) + if options_.TeX + texname = M_.exo_names_tex(k,:); + TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']); + end + title(name,'Interpreter','none') + eval(['oo_.SmoothedShocks.' deblank(name) ' = innov(k,:)'';']); + end + eval(['print -depsc2 ' M_.fname '_SmoothedShocks' int2str(nbplt) '.eps']); + if ~exist('OCTAVE_VERSION') + eval(['print -dpdf ' M_.fname '_SmoothedShocks' int2str(nbplt)]); + saveas(hh,[M_.fname '_SmoothedShocks' int2str(nbplt) '.fig']); + end + if options_.nograph, close(hh), end + if options_.TeX + fprintf(fidTeX,'\\begin{figure}[H]\n'); + for jj = 1:size(NAMES,1); + fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); + end + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_SmoothedShocks%s}\n',M_.fname,int2str(nbplt)); + fprintf(fidTeX,'\\caption{Smoothed shocks.}'); + fprintf(fidTeX,'\\label{Fig:SmoothedShocks:%s}\n',int2str(nbplt)); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,'\n'); + fprintf(fidTeX,'%% End of TeX file.\n'); + fclose(fidTeX); + end + end + %% + %% Smooth observational errors... + %% + if options_.noconstant + yf = zeros(n_varobs,gend); + else + if options_.prefilter == 1 + yf = atT(bayestopt_.mf,:)+repmat(bayestopt_.mean_varobs,1,gend); + elseif options_.loglinear == 1 + yf = atT(bayestopt_.mf,:)+repmat(log(ys(bayestopt_.mfys)),1,gend)+... + trend_coeff*[1:gend]; + else + yf = atT(bayestopt_.mf,:)+repmat(ys(bayestopt_.mfys),1,gend)+... + trend_coeff*[1:gend]; + end + end + if nvn + number_of_plots_to_draw = 0; + index = []; + for i=1:n_varobs + if max(abs(measurement_error(10:end))) > 0.000000001 + number_of_plots_to_draw = number_of_plots_to_draw + 1; + index = cat(1,index,i); + end + eval(['oo_.SmoothedMeasurementErrors.' deblank(options_.varobs(i,:)) ... + ' = measurement_error(i,:)'';']); + end + [nbplt,nr,nc,lr,lc,nstar] = pltorg(number_of_plots_to_draw); + if options_.TeX + fidTeX = fopen([M_.fname '_SmoothedObservationErrors.TeX'],'w'); + fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation.m (Dynare).\n'); + fprintf(fidTeX,['%% ' datestr(now,0) '\n']); + fprintf(fidTeX,' \n'); + end + if nbplt == 1 + hh = figure('Name','Smoothed observation errors'); + set(0,'CurrentFigure',hh) + NAMES = []; + if options_.TeX, TeXNAMES = []; end + for i=1:number_of_plots_to_draw + subplot(nr,nc,i); + plot(1:gend,measurement_error(index(i),:),'-k','linewidth',1) + hold on + plot([1 gend],[0 0],'-r','linewidth',.5) + hold off + name = deblank(options_.varobs(index(i),:)); + NAMES = strvcat(NAMES,name); + if ~isempty(options_.XTick) + set(gca,'XTick',options_.XTick) + set(gca,'XTickLabel',options_.XTickLabel) + end + if options_.TeX + idx = strmatch(options_.varobs(indx(i),:),M_.endo_names,'exact'); + texname = M_.endo_names_tex(idx,:); + TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']); + end + title(name,'Interpreter','none') + end + eval(['print -depsc2 ' M_.fname '_SmoothedObservationErrors' int2str(1) '.eps']); + if ~exist('OCTAVE_VERSION') + eval(['print -dpdf ' M_.fname '_SmoothedObservationErrors' int2str(1)]); + saveas(hh,[M_.fname '_SmoothedObservationErrors' int2str(1) '.fig']); + end + if options_.nograph, close(hh), end + if options_.TeX + fprintf(fidTeX,'\\begin{figure}[H]\n'); + for jj = 1:number_of_plots_to_draw + fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); + end + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_SmoothedObservationErrors%s}\n',M_.fname,int2str(1)); + fprintf(fidTeX,'\\caption{Smoothed observation errors.}'); + fprintf(fidTeX,'\\label{Fig:SmoothedObservationErrors:%s',int2str(1)); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,'\n'); + fprintf(fidTeX,'%% End of TeX file.\n'); + fclose(fidTeX); + end + else + for plt = 1:nbplt-1 + hh = figure('Name','Smoothed observation errors'); + set(0,'CurrentFigure',hh) + NAMES = []; + if options_.TeX, TeXNAMES = []; end + for i=1:nstar + k = (plt-1)*nstar+i; + subplot(nr,nc,i); + plot([1 gend],[0 0],'-r','linewidth',.5) + hold on + plot(1:gend,measurement_error(index(k),:),'-k','linewidth',1) + hold off + name = deblank(options_.varobs(index(k),:)); + NAMES = strvcat(NAMES,name); + if ~isempty(options_.XTick) + set(gca,'XTick',options_.XTick) + set(gca,'XTickLabel',options_.XTickLabel) + end + if options_.TeX + idx = strmatch(options_.varobs(k),M_.endo_names,'exact'); + texname = M_.endo_names_tex(idx,:); + TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']); + end + title(name,'Interpreter','none') + end + eval(['print -depsc2 ' M_.fname '_SmoothedObservationErrors' int2str(plt) '.eps']); + if ~exist('OCTAVE_VERSION') + eval(['print -dpdf ' M_.fname '_SmoothedObservationErrors' int2str(plt)]); + saveas(hh,[M_.fname '_SmoothedObservationErrors' int2str(plt) '.fig']); + end + if options_.nograph, close(hh), end + if options_.TeX + fprintf(fidTeX,'\\begin{figure}[H]\n'); + for jj = 1:nstar + fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); + end + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_SmoothedObservationErrors%s}\n',M_.fname,int2str(plt)); + fprintf(fidTeX,'\\caption{Smoothed observation errors.}'); + fprintf(fidTeX,'\\label{Fig:SmoothedObservationErrors:%s}\n',int2str(plt)); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,'\n'); + end + end + hh = figure('Name','Smoothed observation errors'); + set(0,'CurrentFigure',hh) + NAMES = []; + if options_.TeX, TeXNAMES = []; end + for i=1:number_of_plots_to_draw-(nbplt-1)*nstar + k = (nbplt-1)*nstar+i; + if lr ~= 0 + subplot(lr,lc,i); + else + subplot(nr,nc,i); + end + plot([1 gend],[0 0],'-r','linewidth',0.5) + hold on + plot(1:gend,measurement_error(index(k),:),'-k','linewidth',1) + hold off + name = deblank(options_.varobs(index(k),:)); + NAMES = strvcat(NAMES,name); + if ~isempty(options_.XTick) + set(gca,'XTick',options_.XTick) + set(gca,'XTickLabel',options_.XTickLabel) + end + if options_.TeX + idx = strmatch(options_.varobs(index(k)),M_.endo_names,'exact'); + texname = M_.endo_names_tex(idx,:); + TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']); + end + title(name,'Interpreter','none'); + end + eval(['print -depsc2 ' M_.fname '_SmoothedObservationErrors' int2str(nbplt) '.eps']); + if ~exist('OCTAVE_VERSION') + eval(['print -dpdf ' M_.fname '_SmoothedObservationErrors' int2str(nbplt)]); + saveas(hh,[M_.fname '_SmoothedObservationErrors' int2str(nbplt) '.fig']); + end + if options_.nograph, close(hh), end + if options_.TeX + fprintf(fidTeX,'\\begin{figure}[H]\n'); + for jj = 1:size(NAMES,1); + fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); + end + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_SmoothedObservedErrors%s}\n',M_.fname,int2str(nbplt)); + fprintf(fidTeX,'\\caption{Smoothed observed errors.}'); + fprintf(fidTeX,'\\label{Fig:SmoothedObservedErrors:%s}\n',int2str(nbplt)); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,'\n'); + fprintf(fidTeX,'%% End of TeX file.\n'); + fclose(fidTeX); + end + end + end + %% + %% Historical and smoothed variabes + %% + [nbplt,nr,nc,lr,lc,nstar] = pltorg(n_varobs); + if options_.TeX + fidTeX = fopen([M_.fname '_HistoricalAndSmoothedVariables.TeX'],'w'); + fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation.m (Dynare).\n'); + fprintf(fidTeX,['%% ' datestr(now,0) '\n']); + fprintf(fidTeX,' \n'); + end + if nbplt == 1 + hh = figure('Name','Historical and smoothed variables'); + NAMES = []; + if options_.TeX, TeXNAMES = []; end + for i=1:n_varobs + subplot(nr,nc,i); + plot(1:gend,yf(i,:),'-r','linewidth',1) + hold on + plot(1:gend,rawdata(:,i),'-k','linewidth',1) + hold off + name = deblank(options_.varobs(i,:)); + NAMES = strvcat(NAMES,name); + if ~isempty(options_.XTick) + set(gca,'XTick',options_.XTick) + set(gca,'XTickLabel',options_.XTickLabel) + end + xlim([1 gend]) + if options_.TeX + idx = strmatch(options_.varobs(i),M_.endo_names,'exact'); + texname = M_.endo_names_tex(idx,:); + TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']); + end + title(name,'Interpreter','none') + end + eval(['print -depsc2 ' M_.fname '_HistoricalAndSmoothedVariables' int2str(1) '.eps']); + if ~exist('OCTAVE_VERSION') + eval(['print -dpdf ' M_.fname '_HistoricalAndSmoothedVariables' int2str(1)]); + saveas(hh,[M_.fname '_HistoricalAndSmoothedVariables' int2str(1) '.fig']); + end + if options_.nograph, close(hh), end + if options_.TeX + fprintf(fidTeX,'\\begin{figure}[H]\n'); + for jj = 1:n_varobs + fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); + end + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_HistoricalAndSmoothedVariables%s}\n',M_.fname,int2str(1)); + fprintf(fidTeX,'\\caption{Historical and smoothed variables.}'); + fprintf(fidTeX,'\\label{Fig:HistoricalAndSmoothedVariables:%s}\n',int2str(1)); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,'\n'); + fprintf(fidTeX,'%% End of TeX file.\n'); + fclose(fidTeX); + end + else + for plt = 1:nbplt-1 + hh = figure('Name','Historical and smoothed variables'); + set(0,'CurrentFigure',hh) + NAMES = []; + if options_.TeX, TeXNAMES = []; end + for i=1:nstar + k = (plt-1)*nstar+i; + subplot(nr,nc,i); + plot(1:gend,yf(k,:),'-r','linewidth',1) + hold on + plot(1:gend,rawdata(:,k),'-k','linewidth',1) + hold off + name = deblank(options_.varobs(k,:)); + NAMES = strvcat(NAMES,name); + if ~isempty(options_.XTick) + set(gca,'XTick',options_.XTick) + set(gca,'XTickLabel',options_.XTickLabel) + end + xlim([1 gend]) + if options_.TeX + idx = strmatch(options_.varobs(k),M_.endo_names,'exact'); + texname = M_.endo_names_tex(idx,:); + TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']); + end + title(name,'Interpreter','none') + end + eval(['print -depsc2 ' M_.fname '_HistoricalAndSmoothedVariables' int2str(plt) '.eps']); + if ~exist('OCTAVE_VERSION') + eval(['print -dpdf ' M_.fname '_HistoricalAndSmoothedVariables' int2str(plt)]); + saveas(hh,[M_.fname '_HistoricalAndSmoothedVariables' int2str(plt) '.fig']); + end + if options_.nograph, close(hh), end + if options_.TeX + fprintf(fidTeX,'\\begin{figure}[H]\n'); + for jj = 1:nstar + fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); + end + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_HistoricalAndSmoothedVariables%s}\n',M_.fname,int2str(plt)); + fprintf(fidTeX,'\\caption{Historical and smoothed variables.}'); + fprintf(fidTeX,'\\label{Fig:HistoricalAndSmoothedVariables:%s}\n',int2str(plt)); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,'\n'); + end + end + hh = figure('Name','Historical and smoothed variables'); + set(0,'CurrentFigure',hh) + NAMES = []; + if options_.TeX, TeXNAMES = []; end + for i=1:n_varobs-(nbplt-1)*nstar + k = (nbplt-1)*nstar+i; + if lr ~= 0 + subplot(lr,lc,i); + else + subplot(nr,nc,i); + end + plot(1:gend,yf(k,:),'-r','linewidth',1) + hold on + plot(1:gend,rawdata(:,k),'-k','linewidth',1) + hold off + name = deblank(options_.varobs(k,:)); + NAMES = strvcat(NAMES,name); + if ~isempty(options_.XTick) + set(gca,'XTick',options_.XTick) + set(gca,'XTickLabel',options_.XTickLabel) + end + xlim([1 gend]) + if options_.TeX + idx = strmatch(options_.varobs(i),M_.endo_names,'exact'); + texname = M_.endo_names_tex(idx,:); + TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']); + end + title(name,'Interpreter','none'); + end + eval(['print -depsc2 ' M_.fname '_HistoricalAndSmoothedVariables' int2str(nbplt) '.eps']); + if ~exist('OCTAVE_VERSION') + eval(['print -dpdf ' M_.fname '_HistoricalAndSmoothedVariables' int2str(nbplt)]); + saveas(hh,[M_.fname '_HistoricalAndSmoothedVariables' int2str(nbplt) '.fig']); + end + if options_.nograph, close(hh), end + if options_.TeX + fprintf(fidTeX,'\\begin{figure}[H]\n'); + for jj = 1:size(NAMES,1); + fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); + end + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_HistoricalAndSmoothedVariables%s}\n',M_.fname,int2str(nbplt)); + fprintf(fidTeX,'\\caption{Historical and smoothed variables.}'); + fprintf(fidTeX,'\\label{Fig:HistoricalAndSmoothedVariables:%s}\n',int2str(nbplt)); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,'\n'); + fprintf(fidTeX,'%% End of TeX file.\n'); + fclose(fidTeX); + end + end +end + +if options_.forecast > 0 & options_.mh_replic == 0 & ~options_.load_mh_file + forecast(var_list_,'smoother'); +end + +if np > 0 + pindx = estim_params_.param_vals(:,1); + save([M_.fname '_pindx.mat'] ,'pindx'); +end + diff --git a/matlab/dynare_estimation_init.m b/matlab/dynare_estimation_init.m index d8a227f54e..d847eaec9c 100644 --- a/matlab/dynare_estimation_init.m +++ b/matlab/dynare_estimation_init.m @@ -1,254 +1,254 @@ -function [data,rawdata]=dynare_estimation_init(var_list_, igsa) - -% function dynare_estimation_init(var_list_) -% preforms initialization tasks before estimation or -% global sensitivity analysis -% -% INPUTS -% var_list_: selected endogenous variables vector -% -% OUTPUTS -% data: data after required transformation -% rawdat: data as in the data file -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2003-2007 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 <http://www.gnu.org/licenses/>. - -global M_ options_ oo_ estim_params_ -global bayestopt_ - -if nargin<2 | isempty(igsa), - igsa=0; -end - -options_.varlist = var_list_; -options_.lgyidx2varobs = zeros(size(M_.endo_names,1),1); -for i = 1:size(M_.endo_names,1) - tmp = strmatch(deblank(M_.endo_names(i,:)),options_.varobs,'exact'); - if ~isempty(tmp) - options_.lgyidx2varobs(i,1) = tmp; - end -end - -if ~isempty(strmatch('dsge_prior_weight',M_.param_names)) - options_.bvar_dsge = 1; -end - -if options_.order > 1 - options_.order = 1; -end - -if options_.prefilter == 1 - options_.noconstant = 1; -end - -if options_.filtered_vars ~= 0 & options_.filter_step_ahead == 0 - options_.filter_step_ahead = 1; -end -if options_.filter_step_ahead ~= 0 - options_.nk = max(options_.filter_step_ahead); -else - options_.nk = 0; -end - -%% Add something to the parser ++> -% The user should be able to choose another name -% for the directory... -M_.dname = M_.fname; - -pnames = [' ';'beta ';'gamm ';'norm ';'invg ';'unif ';'invg2']; -n_varobs = size(options_.varobs,1); - -if ~isempty(estim_params_) - [xparam1,estim_params_,bayestopt_,lb,ub, M_] = set_prior(estim_params_, M_, options_); - - if any(bayestopt_.pshape > 0) - if options_.mode_compute - plot_priors - end - else - options_.mh_replic = 0; - end - - % set prior bounds and check initial value of the parameters - bounds = prior_bounds(bayestopt_); - bounds(:,1)=max(bounds(:,1),lb); - bounds(:,2)=min(bounds(:,2),ub); - - if any(xparam1 < bounds(:,1)) | any(xparam1 > bounds(:,2)) - find(xparam1 < bounds(:,1)) - find(xparam1 > bounds(:,2)) - error('Initial parameter values are outside parameter bounds') - end - lb = bounds(:,1); - ub = bounds(:,2); - bayestopt_.lb = lb; - bayestopt_.ub = ub; -else - xparam1 = []; - bayestopt_.lb = []; - bayestopt_.ub = []; - bayestopt_.jscale = []; - bayestopt_.pshape = []; - bayestopt_.p1 = []; - bayestopt_.p2 = []; - bayestopt_.p3 = []; - bayestopt_.p4 = []; - estim_params_.nvx = 0; - estim_params_.nvn = 0; - estim_params_.ncx = 0; - estim_params_.ncn = 0; - estim_params_.np = 0; -end -nvx = estim_params_.nvx; -nvn = estim_params_.nvn; -ncx = estim_params_.ncx; -ncn = estim_params_.ncn; -np = estim_params_.np ; -nx = nvx+nvn+ncx+ncn+np; - -if ~isfield(options_,'trend_coeffs') - bayestopt_.with_trend = 0; -else - bayestopt_.with_trend = 1; - bayestopt_.trend_coeff = {}; - trend_coeffs = options_.trend_coeffs; - nt = length(trend_coeffs); - for i=1:n_varobs - if i > length(trend_coeffs) - bayestopt_.trend_coeff{i} = '0'; - else - bayestopt_.trend_coeff{i} = trend_coeffs{i}; - end - end -end - -bayestopt_.penalty = 1e8; % penalty - -dr = set_state_space([],M_); -nstatic = dr.nstatic; -npred = dr.npred; -nspred = dr.nspred; - -if isempty(options_.varobs) - error('ESTIMATION: VAROBS is missing') -end - -%% Setting resticted state space (observed + predetermined variables) - -k = []; -k1 = []; -for i=1:n_varobs - k = [k strmatch(deblank(options_.varobs(i,:)),M_.endo_names(dr.order_var,:),'exact')]; - k1 = [k1 strmatch(deblank(options_.varobs(i,:)),M_.endo_names, 'exact')]; -end -% union of observed and state variables -k2 = union(k',[dr.nstatic+1:dr.nstatic+dr.npred]'); - -% set restrict_state to postion of observed + state variables -% in expanded state vector -bayestopt_.restrict_var_list = k2; -% set mf0 to positions of state variables in restricted state vector -% for likelihood computation. -[junk,bayestopt_.mf0] = ismember([dr.nstatic+1:dr.nstatic+dr.npred]',k2); -% set mf1 to positions of observed variables in restricted state vector -% for likelihood computation. -[junk,bayestopt_.mf1] = ismember(k,k2); -% set mf2 to positions of observed variables in expanded state vector -% for filtering and smoothing -bayestopt_.mf2 = k; -bayestopt_.mfys = k1; - -[junk,ic] = intersect(k2,nstatic+(1:npred)'); -bayestopt_.restrict_columns = [ic; length(k2)+(1:nspred-npred)']; -aux = dr.transition_auxiliary_variables; -aux(:,2) = aux(:,2) + sum(k2 <= nstatic); -k = find(aux(:,2) > npred); -aux(k,2) = aux(k,2) + sum(k2 > nstatic+npred); -bayestopt_.restrict_aux = aux; - - -%% Initialization with unit-root variables -if ~isempty(options_.unit_root_vars) - n_ur = size(options_.unit_root_vars,1); - i_ur = zeros(n_ur,1); - for i=1:n_ur - i1 = strmatch(deblank(options_.unit_root_vars(i,:)),M_.endo_names(dr.order_var,:),'exact'); - if isempty(i1) - error('Undeclared variable in unit_root_vars statement') - end - i_ur(i) = i1; - end - bayestopt_.var_list_stationary = setdiff((1:M_.endo_nbr)',i_ur); - [junk,bayestopt_.restrict_var_list_nonstationary] = ... - intersect(bayestopt_.restrict_var_list,i_ur); - bayestopt_.restrict_var_list_stationary = ... - setdiff((1:length(bayestopt_.restrict_var_list))', ... - bayestopt_.restrict_var_list_nonstationary); - if M_.maximum_lag > 1 - l1 = flipud([cumsum(M_.lead_lag_incidence(1:M_.maximum_lag-1,dr.order_var),1);ones(1,M_.endo_nbr)]); - l2 = l1(:,bayestopt_.restrict_var_list); - il2 = find(l2' > 0); - l2(il2) = (1:length(il2))'; - bayestopt_.restrict_var_list_stationary = ... - nonzeros(l2(:,bayestopt_.restrict_var_list_stationary)); - bayestopt_.restrict_var_list_nonstationary = ... - nonzeros(l2(:,bayestopt_.restrict_var_list_nonstationary)); - end - options_.lik_init = 3; -end % if ~isempty(options_.unit_root_vars) - -if isempty(options_.datafile), - if igsa, - data=[]; - rawdata=[]; - return, - else - error('ESTIMATION: datafile option is missing'), - end -end - -%% If jscale isn't specified for an estimated parameter, use -%% global option options_.jscale, set to 0.2, by default -k = find(isnan(bayestopt_.jscale)); -bayestopt_.jscale(k) = options_.mh_jscale; - -%% Read and demean data -rawdata = read_variables(options_.datafile,options_.varobs,[],options_.xls_sheet,options_.xls_range); - -options_ = set_default_option(options_,'nobs',size(rawdata,1)-options_.first_obs+1); -gend = options_.nobs; - -rawdata = rawdata(options_.first_obs:options_.first_obs+gend-1,:); -if options_.loglinear == 1 & ~options_.logdata - rawdata = log(rawdata); -end -if options_.prefilter == 1 - bayestopt_.mean_varobs = mean(rawdata,1)'; - data = transpose(rawdata-repmat(bayestopt_.mean_varobs',gend,1)); -else - data = transpose(rawdata); -end - -if ~isreal(rawdata) - error(['There are complex values in the data. Probably a wrong' ... - ' transformation']) -end - +function [data,rawdata]=dynare_estimation_init(var_list_, igsa) + +% function dynare_estimation_init(var_list_) +% preforms initialization tasks before estimation or +% global sensitivity analysis +% +% INPUTS +% var_list_: selected endogenous variables vector +% +% OUTPUTS +% data: data after required transformation +% rawdat: data as in the data file +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2003-2007 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 <http://www.gnu.org/licenses/>. + +global M_ options_ oo_ estim_params_ +global bayestopt_ + +if nargin<2 | isempty(igsa), + igsa=0; +end + +options_.varlist = var_list_; +options_.lgyidx2varobs = zeros(size(M_.endo_names,1),1); +for i = 1:size(M_.endo_names,1) + tmp = strmatch(deblank(M_.endo_names(i,:)),options_.varobs,'exact'); + if ~isempty(tmp) + options_.lgyidx2varobs(i,1) = tmp; + end +end + +if ~isempty(strmatch('dsge_prior_weight',M_.param_names)) + options_.bvar_dsge = 1; +end + +if options_.order > 1 + options_.order = 1; +end + +if options_.prefilter == 1 + options_.noconstant = 1; +end + +if options_.filtered_vars ~= 0 & options_.filter_step_ahead == 0 + options_.filter_step_ahead = 1; +end +if options_.filter_step_ahead ~= 0 + options_.nk = max(options_.filter_step_ahead); +else + options_.nk = 0; +end + +%% Add something to the parser ++> +% The user should be able to choose another name +% for the directory... +M_.dname = M_.fname; + +pnames = [' ';'beta ';'gamm ';'norm ';'invg ';'unif ';'invg2']; +n_varobs = size(options_.varobs,1); + +if ~isempty(estim_params_) + [xparam1,estim_params_,bayestopt_,lb,ub, M_] = set_prior(estim_params_, M_, options_); + + if any(bayestopt_.pshape > 0) + if options_.mode_compute + plot_priors + end + else + options_.mh_replic = 0; + end + + % set prior bounds and check initial value of the parameters + bounds = prior_bounds(bayestopt_); + bounds(:,1)=max(bounds(:,1),lb); + bounds(:,2)=min(bounds(:,2),ub); + + if any(xparam1 < bounds(:,1)) | any(xparam1 > bounds(:,2)) + find(xparam1 < bounds(:,1)) + find(xparam1 > bounds(:,2)) + error('Initial parameter values are outside parameter bounds') + end + lb = bounds(:,1); + ub = bounds(:,2); + bayestopt_.lb = lb; + bayestopt_.ub = ub; +else + xparam1 = []; + bayestopt_.lb = []; + bayestopt_.ub = []; + bayestopt_.jscale = []; + bayestopt_.pshape = []; + bayestopt_.p1 = []; + bayestopt_.p2 = []; + bayestopt_.p3 = []; + bayestopt_.p4 = []; + estim_params_.nvx = 0; + estim_params_.nvn = 0; + estim_params_.ncx = 0; + estim_params_.ncn = 0; + estim_params_.np = 0; +end +nvx = estim_params_.nvx; +nvn = estim_params_.nvn; +ncx = estim_params_.ncx; +ncn = estim_params_.ncn; +np = estim_params_.np ; +nx = nvx+nvn+ncx+ncn+np; + +if ~isfield(options_,'trend_coeffs') + bayestopt_.with_trend = 0; +else + bayestopt_.with_trend = 1; + bayestopt_.trend_coeff = {}; + trend_coeffs = options_.trend_coeffs; + nt = length(trend_coeffs); + for i=1:n_varobs + if i > length(trend_coeffs) + bayestopt_.trend_coeff{i} = '0'; + else + bayestopt_.trend_coeff{i} = trend_coeffs{i}; + end + end +end + +bayestopt_.penalty = 1e8; % penalty + +dr = set_state_space([],M_); +nstatic = dr.nstatic; +npred = dr.npred; +nspred = dr.nspred; + +if isempty(options_.varobs) + error('ESTIMATION: VAROBS is missing') +end + +%% Setting resticted state space (observed + predetermined variables) + +k = []; +k1 = []; +for i=1:n_varobs + k = [k strmatch(deblank(options_.varobs(i,:)),M_.endo_names(dr.order_var,:),'exact')]; + k1 = [k1 strmatch(deblank(options_.varobs(i,:)),M_.endo_names, 'exact')]; +end +% union of observed and state variables +k2 = union(k',[dr.nstatic+1:dr.nstatic+dr.npred]'); + +% set restrict_state to postion of observed + state variables +% in expanded state vector +bayestopt_.restrict_var_list = k2; +% set mf0 to positions of state variables in restricted state vector +% for likelihood computation. +[junk,bayestopt_.mf0] = ismember([dr.nstatic+1:dr.nstatic+dr.npred]',k2); +% set mf1 to positions of observed variables in restricted state vector +% for likelihood computation. +[junk,bayestopt_.mf1] = ismember(k,k2); +% set mf2 to positions of observed variables in expanded state vector +% for filtering and smoothing +bayestopt_.mf2 = k; +bayestopt_.mfys = k1; + +[junk,ic] = intersect(k2,nstatic+(1:npred)'); +bayestopt_.restrict_columns = [ic; length(k2)+(1:nspred-npred)']; +aux = dr.transition_auxiliary_variables; +aux(:,2) = aux(:,2) + sum(k2 <= nstatic); +k = find(aux(:,2) > npred); +aux(k,2) = aux(k,2) + sum(k2 > nstatic+npred); +bayestopt_.restrict_aux = aux; + + +%% Initialization with unit-root variables +if ~isempty(options_.unit_root_vars) + n_ur = size(options_.unit_root_vars,1); + i_ur = zeros(n_ur,1); + for i=1:n_ur + i1 = strmatch(deblank(options_.unit_root_vars(i,:)),M_.endo_names(dr.order_var,:),'exact'); + if isempty(i1) + error('Undeclared variable in unit_root_vars statement') + end + i_ur(i) = i1; + end + bayestopt_.var_list_stationary = setdiff((1:M_.endo_nbr)',i_ur); + [junk,bayestopt_.restrict_var_list_nonstationary] = ... + intersect(bayestopt_.restrict_var_list,i_ur); + bayestopt_.restrict_var_list_stationary = ... + setdiff((1:length(bayestopt_.restrict_var_list))', ... + bayestopt_.restrict_var_list_nonstationary); + if M_.maximum_lag > 1 + l1 = flipud([cumsum(M_.lead_lag_incidence(1:M_.maximum_lag-1,dr.order_var),1);ones(1,M_.endo_nbr)]); + l2 = l1(:,bayestopt_.restrict_var_list); + il2 = find(l2' > 0); + l2(il2) = (1:length(il2))'; + bayestopt_.restrict_var_list_stationary = ... + nonzeros(l2(:,bayestopt_.restrict_var_list_stationary)); + bayestopt_.restrict_var_list_nonstationary = ... + nonzeros(l2(:,bayestopt_.restrict_var_list_nonstationary)); + end + options_.lik_init = 3; +end % if ~isempty(options_.unit_root_vars) + +if isempty(options_.datafile), + if igsa, + data=[]; + rawdata=[]; + return, + else + error('ESTIMATION: datafile option is missing'), + end +end + +%% If jscale isn't specified for an estimated parameter, use +%% global option options_.jscale, set to 0.2, by default +k = find(isnan(bayestopt_.jscale)); +bayestopt_.jscale(k) = options_.mh_jscale; + +%% Read and demean data +rawdata = read_variables(options_.datafile,options_.varobs,[],options_.xls_sheet,options_.xls_range); + +options_ = set_default_option(options_,'nobs',size(rawdata,1)-options_.first_obs+1); +gend = options_.nobs; + +rawdata = rawdata(options_.first_obs:options_.first_obs+gend-1,:); +if options_.loglinear == 1 & ~options_.logdata + rawdata = log(rawdata); +end +if options_.prefilter == 1 + bayestopt_.mean_varobs = mean(rawdata,1)'; + data = transpose(rawdata-repmat(bayestopt_.mean_varobs',gend,1)); +else + data = transpose(rawdata); +end + +if ~isreal(rawdata) + error(['There are complex values in the data. Probably a wrong' ... + ' transformation']) +end + diff --git a/matlab/dynare_graph.m b/matlab/dynare_graph.m index 450e26b0d2..ae4383a4a5 100644 --- a/matlab/dynare_graph.m +++ b/matlab/dynare_graph.m @@ -1,56 +1,56 @@ -function dynare_graph(y,tit,x) -% function dynare_graph(y,tit,x) -% graphs -% -% INPUT -% figure_name: name of the figures -% colors: line colors -% -% OUTPUT -% none -% -% SPECIAL REQUIREMENT -% none - -% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. - - global dyn_graph - - if nargin < 3 - x = (1:size(y,1))'; - end - nplot = dyn_graph.plot_nbr + 1; - if nplot > dyn_graph.max_nplot - figure('Name',dyn_graph.figure_name); - nplot = 1; - end - dyn_graph.plot_nbr = nplot; - subplot(dyn_graph.nr,dyn_graph.nc,nplot); - - line_types = dyn_graph.line_types; - line_type = line_types{1}; - for i=1:size(y,2); - if length(line_types) > 1 - line_type = line_types{i}; - end - - plot(x,y(:,i),line_type); - hold on - end - title(tit); - hold off \ No newline at end of file +function dynare_graph(y,tit,x) +% function dynare_graph(y,tit,x) +% graphs +% +% INPUT +% figure_name: name of the figures +% colors: line colors +% +% OUTPUT +% none +% +% SPECIAL REQUIREMENT +% none + +% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. + +global dyn_graph + +if nargin < 3 + x = (1:size(y,1))'; +end +nplot = dyn_graph.plot_nbr + 1; +if nplot > dyn_graph.max_nplot + figure('Name',dyn_graph.figure_name); + nplot = 1; +end +dyn_graph.plot_nbr = nplot; +subplot(dyn_graph.nr,dyn_graph.nc,nplot); + +line_types = dyn_graph.line_types; +line_type = line_types{1}; +for i=1:size(y,2); + if length(line_types) > 1 + line_type = line_types{i}; + end + + plot(x,y(:,i),line_type); + hold on +end +title(tit); +hold off \ No newline at end of file diff --git a/matlab/dynare_graph_close.m b/matlab/dynare_graph_close.m index 056ec80893..07176ee556 100644 --- a/matlab/dynare_graph_close.m +++ b/matlab/dynare_graph_close.m @@ -1,30 +1,30 @@ -function dynare_graph_close() -% function dynare_graph_close() -% close a figure -% -% INPUT -% none -% -% OUTPUT -% none -% -% SPECIAL REQUIREMENT -% none - -% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. - +function dynare_graph_close() +% function dynare_graph_close() +% close a figure +% +% INPUT +% none +% +% OUTPUT +% none +% +% SPECIAL REQUIREMENT +% none + +% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. + diff --git a/matlab/dynare_graph_init.m b/matlab/dynare_graph_init.m index eb272fd7e6..1db23053eb 100644 --- a/matlab/dynare_graph_init.m +++ b/matlab/dynare_graph_init.m @@ -1,79 +1,78 @@ -function dynare_graph_init(figure_name,nplot,line_types,line_width) -% function dynare_graph_init(figure_name,colors) -% initializes set of graphs -% -% INPUTS: -% figure_name: name of the figures -% colors: line colors -% -% OUTPUTS -% none -% -% SPECIAL REQUIREMENT -% none - -% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. - - global dyn_graph options_ - - dyn_graph.fh = figure('Name',figure_name); - dyn_graph.figure_name = figure_name; - if nargin > 2 - dyn_graph.line_types = line_types; - else - dyn_graph.line_types = options_.graphics.line_types; - end - if nargin > 3 - dyn_graph.line_width = line_width; - else - dyn_graph.line_width = options_.graphics.line_width; - end - - dyn_graph.plot_nbr = 0; - - switch(nplot) - case 1 - dyn_graph.nc = 1; - dyn_graph.nr = 1; - case 2 - dyn_graph.nc = 1; - dyn_graph.nr = 2; - case 3 - dyn_graph.nc = 1; - dyn_graph.nr = 3; - case 4 - dyn_graph.nc = 2; - dyn_graph.nr = 2; - case 5 - dyn_graph.nc = 3; - dyn_graph.nr = 2; - case 6 - dyn_graph.nc = 3; - dyn_graph.nr = 2; - case 7 - dyn_graph.nc = 4; - dyn_graph.nr = 2; - case 8 - dyn_graph.nc = 4; - dyn_graph.nr = 2; - otherwise - dyn_graph.nc = min(nplot,options_.graphics.ncols); - dyn_graph.nr = min(ceil(nplot/dyn_graph.nc),options_.graphics.nrows); - end - dyn_graph.max_nplot = dyn_graph.nc*dyn_graph.nr; - \ No newline at end of file +function dynare_graph_init(figure_name,nplot,line_types,line_width) +% function dynare_graph_init(figure_name,colors) +% initializes set of graphs +% +% INPUTS: +% figure_name: name of the figures +% colors: line colors +% +% OUTPUTS +% none +% +% SPECIAL REQUIREMENT +% none + +% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. + +global dyn_graph options_ + +dyn_graph.fh = figure('Name',figure_name); +dyn_graph.figure_name = figure_name; +if nargin > 2 + dyn_graph.line_types = line_types; +else + dyn_graph.line_types = options_.graphics.line_types; +end +if nargin > 3 + dyn_graph.line_width = line_width; +else + dyn_graph.line_width = options_.graphics.line_width; +end + +dyn_graph.plot_nbr = 0; + +switch(nplot) + case 1 + dyn_graph.nc = 1; + dyn_graph.nr = 1; + case 2 + dyn_graph.nc = 1; + dyn_graph.nr = 2; + case 3 + dyn_graph.nc = 1; + dyn_graph.nr = 3; + case 4 + dyn_graph.nc = 2; + dyn_graph.nr = 2; + case 5 + dyn_graph.nc = 3; + dyn_graph.nr = 2; + case 6 + dyn_graph.nc = 3; + dyn_graph.nr = 2; + case 7 + dyn_graph.nc = 4; + dyn_graph.nr = 2; + case 8 + dyn_graph.nc = 4; + dyn_graph.nr = 2; + otherwise + dyn_graph.nc = min(nplot,options_.graphics.ncols); + dyn_graph.nr = min(ceil(nplot/dyn_graph.nc),options_.graphics.nrows); +end +dyn_graph.max_nplot = dyn_graph.nc*dyn_graph.nr; diff --git a/matlab/dynare_identification.m b/matlab/dynare_identification.m index acb5466b0e..db3642fc05 100644 --- a/matlab/dynare_identification.m +++ b/matlab/dynare_identification.m @@ -1,369 +1,369 @@ -function [pdraws, TAU, GAM, H, JJ] = dynare_identification(options_ident, pdraws0) - -% main -% -% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. - -global M_ options_ oo_ bayestopt_ estim_params_ - - options_ident = set_default_option(options_ident,'load_ident_files',0); - options_ident = set_default_option(options_ident,'useautocorr',1); - options_ident = set_default_option(options_ident,'ar',3); - options_ident = set_default_option(options_ident,'prior_mc',2000); - if nargin==2, - options_ident.prior_mc=size(pdraws0,1); - end - - iload = options_ident.load_ident_files; - nlags = options_ident.ar; - useautocorr = options_ident.useautocorr; - options_.ar=nlags; - options_.prior_mc = options_ident.prior_mc; - options_.options_ident = options_ident; - - -options_ = set_default_option(options_,'datafile',[]); -options_.mode_compute = 0; -[data,rawdata]=dynare_estimation_init([],1); -% computes a first linear solution to set up various variables - - - -SampleSize = options_ident.prior_mc; - -% results = prior_sampler(0,M_,bayestopt_,options_,oo_); - -prior_draw(1,bayestopt_); -if ~(exist('sylvester3mr','file')==2), - -dynareroot = strrep(which('dynare'),'dynare.m',''); -addpath([dynareroot 'gensylv']) -end - -IdentifDirectoryName = CheckPath('identification'); - -indx = estim_params_.param_vals(:,1); -indexo=[]; -if ~isempty(estim_params_.var_exo) - indexo = estim_params_.var_exo(:,1); -end - -nparam = length(bayestopt_.name); - -MaxNumberOfBytes=options_.MaxNumberOfBytes; - - -if iload <=0, - -iteration = 0; -burnin_iteration = 0; -loop_indx = 0; -file_index = 0; -run_index = 0; - -h = waitbar(0,'Monte Carlo identification checks ...'); - -while iteration < SampleSize, - loop_indx = loop_indx+1; - if nargin==2, - if burnin_iteration>=50, - params = pdraws0(iteration+1,:); - else - params = pdraws0(burnin_iteration+1,:); - end - else - params = prior_draw(); - end - set_all_parameters(params); - [A,B,ys,info]=dynare_resolve; - - - if info(1)==0, - oo0=oo_; -% [Aa,Bb] = kalman_transition_matrix(oo0.dr, ... -% bayestopt_.restrict_var_list, ... -% bayestopt_.restrict_columns, ... -% bayestopt_.restrict_aux, M_.exo_nbr); -% tau=[vec(Aa); vech(Bb*M_.Sigma_e*Bb')]; - tau=[oo_.dr.ys(oo_.dr.order_var); vec(A); vech(B*M_.Sigma_e*B')]; - if burnin_iteration<50, - burnin_iteration = burnin_iteration + 1; - pdraws(burnin_iteration,:) = params; - TAU(:,burnin_iteration)=tau; - [gam,stationary_vars] = th_autocovariances(oo0.dr,bayestopt_.mfys,M_,options_); - sdy = sqrt(diag(gam{1})); - sy = sdy*sdy'; - if useautocorr, - sy=sy-diag(diag(sy))+eye(length(sy)); - gam{1}=gam{1}./sy; - else - for j=1:nlags, - gam{j+1}=gam{j+1}.*sy; - end - end - dum = vech(gam{1}); - for j=1:nlags, - dum = [dum; vec(gam{j+1})]; - end - GAM(:,burnin_iteration)=[oo_.dr.ys(bayestopt_.mfys); dum]; - else - iteration = iteration + 1; - run_index = run_index + 1; - if iteration==1, - indJJ = (find(std(GAM')>1.e-8)); - indH = (find(std(TAU')>1.e-8)); - TAU = zeros(length(indH),SampleSize); - GAM = zeros(length(indJJ),SampleSize); - MAX_tau = min(SampleSize,ceil(MaxNumberOfBytes/(length(indH)*nparam)/8)); - MAX_gam = min(SampleSize,ceil(MaxNumberOfBytes/(length(indJJ)*nparam)/8)); - stoH = zeros([length(indH),nparam,MAX_tau]); - stoJJ = zeros([length(indJJ),nparam,MAX_tau]); - delete([IdentifDirectoryName '/' M_.fname '_identif_*.mat']) - end - end - - if iteration, - TAU(:,iteration)=tau(indH); - [JJ, H, gam] = getJJ(A, B, M_,oo0,options_,0,indx,indexo,bayestopt_.mf2,nlags,useautocorr); - GAM(:,iteration)=gam(indJJ); - stoH(:,:,run_index) = H(indH,:); - stoJJ(:,:,run_index) = JJ(indJJ,:); - % use relative changes -% siJ = abs(JJ(indJJ,:).*(1./gam(indJJ)*params)); -% siH = abs(H(indH,:).*(1./tau(indH)*params)); - % use prior uncertainty - siJ = abs(JJ(indJJ,:)); - siH = abs(H(indH,:)); -% siJ = abs(JJ(indJJ,:).*(ones(length(indJJ),1)*bayestopt_.p2')); -% siH = abs(H(indH,:).*(ones(length(indH),1)*bayestopt_.p2')); -% siJ = abs(JJ(indJJ,:).*(1./mGAM'*bayestopt_.p2')); -% siH = abs(H(indH,:).*(1./mTAU'*bayestopt_.p2')); - - if iteration ==1, - siJmean = siJ./SampleSize; - siHmean = siH./SampleSize; - else - siJmean = siJ./SampleSize+siJmean; - siHmean = siH./SampleSize+siHmean; - end - pdraws(iteration,:) = params; - [idemodel.Mco(:,iteration), idemoments.Mco(:,iteration), ... - idemodel.Pco(:,:,iteration), idemoments.Pco(:,:,iteration), ... - idemodel.cond(iteration), idemoments.cond(iteration), ... - idemodel.ee(:,:,iteration), idemoments.ee(:,:,iteration), ... - idemodel.ind(:,iteration), idemoments.ind(:,iteration), ... - idemodel.indno{iteration}, idemoments.indno{iteration}] = ... - identification_checks(H(indH,:),JJ(indJJ,:), bayestopt_); - if run_index==MAX_tau | iteration==SampleSize, - file_index = file_index + 1; - if run_index<MAX_tau, - stoH = stoH(:,:,1:run_index); - stoJJ = stoJJ(:,:,1:run_index); - end - save([IdentifDirectoryName '/' M_.fname '_identif_' int2str(file_index)], 'stoH', 'stoJJ') - run_index = 0; - - end - - waitbar(iteration/SampleSize,h) - end - end -end - -siJmean = siJmean.*(ones(length(indJJ),1)*std(pdraws)); -siHmean = siHmean.*(ones(length(indH),1)*std(pdraws)); - -siHmean = siHmean./(max(siHmean')'*ones(size(params))); -siJmean = siJmean./(max(siJmean')'*ones(size(params))); - -close(h) - - -save([IdentifDirectoryName '/' M_.fname '_identif'], 'pdraws', 'idemodel', 'idemoments', ... - 'siHmean', 'siJmean', 'TAU', 'GAM') -else -load([IdentifDirectoryName '/' M_.fname '_identif'], 'pdraws', 'idemodel', 'idemoments', ... - 'siHmean', 'siJmean', 'TAU', 'GAM') -options_ident.prior_mc=size(pdraws,1); -SampleSize = options_ident.prior_mc; - options_.options_ident = options_ident; - -end - -if nargout>3 & iload, - filnam = dir([IdentifDirectoryName '/' M_.fname '_identif_*.mat']); - H=[]; - JJ = []; - for j=1:length(filnam), - load([IdentifDirectoryName '/' M_.fname '_identif_',int2str(j),'.mat']); - H = cat(3,H, stoH(:,abs(iload),:)); - JJ = cat(3,JJ, stoJJ(:,abs(iload),:)); - - end -end - -% mTAU = mean(TAU'); -% mGAM = mean(GAM'); -% sTAU = std(TAU'); -% sGAM = std(GAM'); -% if nargout>=3, -% GAM0=GAM; -% end -% if useautocorr, -% idiag = find(vech(eye(size(options_.varobs,1)))); -% GAM(idiag,:) = GAM(idiag,:)./(sGAM(idiag)'*ones(1,SampleSize)); -% % siJmean(idiag,:) = siJmean(idiag,:)./(sGAM(idiag)'*ones(1,nparam)); -% % siJmean = siJmean./(max(siJmean')'*ones(size(params))); -% end -% -% [pcc, dd] = eig(cov(GAM')); -% [latent, isort] = sort(-diag(dd)); -% latent = -latent; -% pcc=pcc(:,isort); -% siPCA = (siJmean'*abs(pcc')).^2'; -% siPCA = siPCA./(max(siPCA')'*ones(1,nparam)).*(latent*ones(1,nparam)); -% siPCA = sum(siPCA,1); -% siPCA = siPCA./max(siPCA); -% -% [pcc, dd] = eig(corrcoef(GAM')); -% [latent, isort] = sort(-diag(dd)); -% latent = -latent; -% pcc=pcc(:,isort); -% siPCA2 = (siJmean'*abs(pcc')).^2'; -% siPCA2 = siPCA2./(max(siPCA2')'*ones(1,nparam)).*(latent*ones(1,nparam)); -% siPCA2 = sum(siPCA2,1); -% siPCA2 = siPCA2./max(siPCA2); -% -% [pcc, dd] = eig(cov(TAU')); -% [latent, isort] = sort(-diag(dd)); -% latent = -latent; -% pcc=pcc(:,isort); -% siHPCA = (siHmean'*abs(pcc')).^2'; -% siHPCA = siHPCA./(max(siHPCA')'*ones(1,nparam)).*(latent*ones(1,nparam)); -% siHPCA = sum(siHPCA,1); -% siHPCA = siHPCA./max(siHPCA); -% -% [pcc, dd] = eig(corrcoef(TAU')); -% [latent, isort] = sort(-diag(dd)); -% latent = -latent; -% pcc=pcc(:,isort); -% siHPCA2 = (siHmean'*abs(pcc')).^2'; -% siHPCA2 = siHPCA2./(max(siHPCA2')'*ones(1,nparam)).*(latent*ones(1,nparam)); -% siHPCA2 = sum(siHPCA2,1); -% siHPCA2 = siHPCA2./max(siHPCA2); - - -disp_identification(pdraws, idemodel, idemoments) - -% figure, -% % myboxplot(siPCA(1:(max(find(cumsum(latent)./length(indJJ)<0.99))+1),:)) -% subplot(221) -% bar(siHPCA) -% % set(gca,'ylim',[0 1]) -% set(gca,'xticklabel','') -% set(gca,'xlim',[0.5 nparam+0.5]) -% for ip=1:nparam, -% text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% title('Sensitivity in TAU''s PCA') -% -% subplot(222) -% % myboxplot(siPCA(1:(max(find(cumsum(latent)./length(indJJ)<0.99))+1),:)) -% bar(siHPCA2) -% % set(gca,'ylim',[0 1]) -% set(gca,'xticklabel','') -% set(gca,'xlim',[0.5 nparam+0.5]) -% for ip=1:nparam, -% text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% title('Sensitivity in standardized TAU''s PCA') -% -% -% subplot(223) -% % myboxplot(siPCA(1:(max(find(cumsum(latent)./length(indJJ)<0.99))+1),:)) -% bar(siPCA) -% % set(gca,'ylim',[0 1]) -% set(gca,'xticklabel','') -% set(gca,'xlim',[0.5 nparam+0.5]) -% for ip=1:nparam, -% text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% title('Sensitivity in moments'' PCA') -% -% subplot(224) -% % myboxplot(siPCA(1:(max(find(cumsum(latent)./length(indJJ)<0.99))+1),:)) -% bar(siPCA2) -% % set(gca,'ylim',[0 1]) -% set(gca,'xticklabel','') -% set(gca,'xlim',[0.5 nparam+0.5]) -% for ip=1:nparam, -% text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% title('Sensitivity in standardized moments'' PCA') - -figure, -subplot(221) -myboxplot(siHmean) -set(gca,'ylim',[0 1.05]) -set(gca,'xticklabel','') -for ip=1:nparam, - text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -end -title('Sensitivity in the model') - -subplot(222) -myboxplot(siJmean) -set(gca,'ylim',[0 1.05]) -set(gca,'xticklabel','') -for ip=1:nparam, - text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -end -title('Sensitivity in the moments') - -subplot(223) -myboxplot(idemodel.Mco') -set(gca,'ylim',[0 1]) -set(gca,'xticklabel','') -for ip=1:nparam, - text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -end -title('Multicollinearity in the model') - -subplot(224) -myboxplot(idemoments.Mco') -set(gca,'ylim',[0 1]) -set(gca,'xticklabel','') -for ip=1:nparam, - text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -end -title('Multicollinearity in the moments') - saveas(gcf,[IdentifDirectoryName,'/',M_.fname,'_ident']) - eval(['print -depsc2 ' IdentifDirectoryName '/' M_.fname '_ident']); - eval(['print -dpdf ' IdentifDirectoryName '/' M_.fname '_ident']); - - -figure, -subplot(221) -hist(log10(idemodel.cond)) -title('log10 of Condition number in the model') -subplot(222) -hist(log10(idemoments.cond)) -title('log10 of Condition number in the moments') - saveas(gcf,[IdentifDirectoryName,'/',M_.fname,'_ident_COND']) - eval(['print -depsc2 ' IdentifDirectoryName '/' M_.fname '_ident_COND']); - eval(['print -dpdf ' IdentifDirectoryName '/' M_.fname '_ident_COND']); +function [pdraws, TAU, GAM, H, JJ] = dynare_identification(options_ident, pdraws0) + +% main +% +% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. + +global M_ options_ oo_ bayestopt_ estim_params_ + +options_ident = set_default_option(options_ident,'load_ident_files',0); +options_ident = set_default_option(options_ident,'useautocorr',1); +options_ident = set_default_option(options_ident,'ar',3); +options_ident = set_default_option(options_ident,'prior_mc',2000); +if nargin==2, + options_ident.prior_mc=size(pdraws0,1); +end + +iload = options_ident.load_ident_files; +nlags = options_ident.ar; +useautocorr = options_ident.useautocorr; +options_.ar=nlags; +options_.prior_mc = options_ident.prior_mc; +options_.options_ident = options_ident; + + +options_ = set_default_option(options_,'datafile',[]); +options_.mode_compute = 0; +[data,rawdata]=dynare_estimation_init([],1); +% computes a first linear solution to set up various variables + + + +SampleSize = options_ident.prior_mc; + +% results = prior_sampler(0,M_,bayestopt_,options_,oo_); + +prior_draw(1,bayestopt_); +if ~(exist('sylvester3mr','file')==2), + + dynareroot = strrep(which('dynare'),'dynare.m',''); + addpath([dynareroot 'gensylv']) +end + +IdentifDirectoryName = CheckPath('identification'); + +indx = estim_params_.param_vals(:,1); +indexo=[]; +if ~isempty(estim_params_.var_exo) + indexo = estim_params_.var_exo(:,1); +end + +nparam = length(bayestopt_.name); + +MaxNumberOfBytes=options_.MaxNumberOfBytes; + + +if iload <=0, + + iteration = 0; + burnin_iteration = 0; + loop_indx = 0; + file_index = 0; + run_index = 0; + + h = waitbar(0,'Monte Carlo identification checks ...'); + + while iteration < SampleSize, + loop_indx = loop_indx+1; + if nargin==2, + if burnin_iteration>=50, + params = pdraws0(iteration+1,:); + else + params = pdraws0(burnin_iteration+1,:); + end + else + params = prior_draw(); + end + set_all_parameters(params); + [A,B,ys,info]=dynare_resolve; + + + if info(1)==0, + oo0=oo_; + % [Aa,Bb] = kalman_transition_matrix(oo0.dr, ... + % bayestopt_.restrict_var_list, ... + % bayestopt_.restrict_columns, ... + % bayestopt_.restrict_aux, M_.exo_nbr); + % tau=[vec(Aa); vech(Bb*M_.Sigma_e*Bb')]; + tau=[oo_.dr.ys(oo_.dr.order_var); vec(A); vech(B*M_.Sigma_e*B')]; + if burnin_iteration<50, + burnin_iteration = burnin_iteration + 1; + pdraws(burnin_iteration,:) = params; + TAU(:,burnin_iteration)=tau; + [gam,stationary_vars] = th_autocovariances(oo0.dr,bayestopt_.mfys,M_,options_); + sdy = sqrt(diag(gam{1})); + sy = sdy*sdy'; + if useautocorr, + sy=sy-diag(diag(sy))+eye(length(sy)); + gam{1}=gam{1}./sy; + else + for j=1:nlags, + gam{j+1}=gam{j+1}.*sy; + end + end + dum = vech(gam{1}); + for j=1:nlags, + dum = [dum; vec(gam{j+1})]; + end + GAM(:,burnin_iteration)=[oo_.dr.ys(bayestopt_.mfys); dum]; + else + iteration = iteration + 1; + run_index = run_index + 1; + if iteration==1, + indJJ = (find(std(GAM')>1.e-8)); + indH = (find(std(TAU')>1.e-8)); + TAU = zeros(length(indH),SampleSize); + GAM = zeros(length(indJJ),SampleSize); + MAX_tau = min(SampleSize,ceil(MaxNumberOfBytes/(length(indH)*nparam)/8)); + MAX_gam = min(SampleSize,ceil(MaxNumberOfBytes/(length(indJJ)*nparam)/8)); + stoH = zeros([length(indH),nparam,MAX_tau]); + stoJJ = zeros([length(indJJ),nparam,MAX_tau]); + delete([IdentifDirectoryName '/' M_.fname '_identif_*.mat']) + end + end + + if iteration, + TAU(:,iteration)=tau(indH); + [JJ, H, gam] = getJJ(A, B, M_,oo0,options_,0,indx,indexo,bayestopt_.mf2,nlags,useautocorr); + GAM(:,iteration)=gam(indJJ); + stoH(:,:,run_index) = H(indH,:); + stoJJ(:,:,run_index) = JJ(indJJ,:); + % use relative changes + % siJ = abs(JJ(indJJ,:).*(1./gam(indJJ)*params)); + % siH = abs(H(indH,:).*(1./tau(indH)*params)); + % use prior uncertainty + siJ = abs(JJ(indJJ,:)); + siH = abs(H(indH,:)); + % siJ = abs(JJ(indJJ,:).*(ones(length(indJJ),1)*bayestopt_.p2')); + % siH = abs(H(indH,:).*(ones(length(indH),1)*bayestopt_.p2')); + % siJ = abs(JJ(indJJ,:).*(1./mGAM'*bayestopt_.p2')); + % siH = abs(H(indH,:).*(1./mTAU'*bayestopt_.p2')); + + if iteration ==1, + siJmean = siJ./SampleSize; + siHmean = siH./SampleSize; + else + siJmean = siJ./SampleSize+siJmean; + siHmean = siH./SampleSize+siHmean; + end + pdraws(iteration,:) = params; + [idemodel.Mco(:,iteration), idemoments.Mco(:,iteration), ... + idemodel.Pco(:,:,iteration), idemoments.Pco(:,:,iteration), ... + idemodel.cond(iteration), idemoments.cond(iteration), ... + idemodel.ee(:,:,iteration), idemoments.ee(:,:,iteration), ... + idemodel.ind(:,iteration), idemoments.ind(:,iteration), ... + idemodel.indno{iteration}, idemoments.indno{iteration}] = ... + identification_checks(H(indH,:),JJ(indJJ,:), bayestopt_); + if run_index==MAX_tau | iteration==SampleSize, + file_index = file_index + 1; + if run_index<MAX_tau, + stoH = stoH(:,:,1:run_index); + stoJJ = stoJJ(:,:,1:run_index); + end + save([IdentifDirectoryName '/' M_.fname '_identif_' int2str(file_index)], 'stoH', 'stoJJ') + run_index = 0; + + end + + waitbar(iteration/SampleSize,h) + end + end + end + + siJmean = siJmean.*(ones(length(indJJ),1)*std(pdraws)); + siHmean = siHmean.*(ones(length(indH),1)*std(pdraws)); + + siHmean = siHmean./(max(siHmean')'*ones(size(params))); + siJmean = siJmean./(max(siJmean')'*ones(size(params))); + + close(h) + + + save([IdentifDirectoryName '/' M_.fname '_identif'], 'pdraws', 'idemodel', 'idemoments', ... + 'siHmean', 'siJmean', 'TAU', 'GAM') +else + load([IdentifDirectoryName '/' M_.fname '_identif'], 'pdraws', 'idemodel', 'idemoments', ... + 'siHmean', 'siJmean', 'TAU', 'GAM') + options_ident.prior_mc=size(pdraws,1); + SampleSize = options_ident.prior_mc; + options_.options_ident = options_ident; + +end + +if nargout>3 & iload, + filnam = dir([IdentifDirectoryName '/' M_.fname '_identif_*.mat']); + H=[]; + JJ = []; + for j=1:length(filnam), + load([IdentifDirectoryName '/' M_.fname '_identif_',int2str(j),'.mat']); + H = cat(3,H, stoH(:,abs(iload),:)); + JJ = cat(3,JJ, stoJJ(:,abs(iload),:)); + + end +end + +% mTAU = mean(TAU'); +% mGAM = mean(GAM'); +% sTAU = std(TAU'); +% sGAM = std(GAM'); +% if nargout>=3, +% GAM0=GAM; +% end +% if useautocorr, +% idiag = find(vech(eye(size(options_.varobs,1)))); +% GAM(idiag,:) = GAM(idiag,:)./(sGAM(idiag)'*ones(1,SampleSize)); +% % siJmean(idiag,:) = siJmean(idiag,:)./(sGAM(idiag)'*ones(1,nparam)); +% % siJmean = siJmean./(max(siJmean')'*ones(size(params))); +% end +% +% [pcc, dd] = eig(cov(GAM')); +% [latent, isort] = sort(-diag(dd)); +% latent = -latent; +% pcc=pcc(:,isort); +% siPCA = (siJmean'*abs(pcc')).^2'; +% siPCA = siPCA./(max(siPCA')'*ones(1,nparam)).*(latent*ones(1,nparam)); +% siPCA = sum(siPCA,1); +% siPCA = siPCA./max(siPCA); +% +% [pcc, dd] = eig(corrcoef(GAM')); +% [latent, isort] = sort(-diag(dd)); +% latent = -latent; +% pcc=pcc(:,isort); +% siPCA2 = (siJmean'*abs(pcc')).^2'; +% siPCA2 = siPCA2./(max(siPCA2')'*ones(1,nparam)).*(latent*ones(1,nparam)); +% siPCA2 = sum(siPCA2,1); +% siPCA2 = siPCA2./max(siPCA2); +% +% [pcc, dd] = eig(cov(TAU')); +% [latent, isort] = sort(-diag(dd)); +% latent = -latent; +% pcc=pcc(:,isort); +% siHPCA = (siHmean'*abs(pcc')).^2'; +% siHPCA = siHPCA./(max(siHPCA')'*ones(1,nparam)).*(latent*ones(1,nparam)); +% siHPCA = sum(siHPCA,1); +% siHPCA = siHPCA./max(siHPCA); +% +% [pcc, dd] = eig(corrcoef(TAU')); +% [latent, isort] = sort(-diag(dd)); +% latent = -latent; +% pcc=pcc(:,isort); +% siHPCA2 = (siHmean'*abs(pcc')).^2'; +% siHPCA2 = siHPCA2./(max(siHPCA2')'*ones(1,nparam)).*(latent*ones(1,nparam)); +% siHPCA2 = sum(siHPCA2,1); +% siHPCA2 = siHPCA2./max(siHPCA2); + + +disp_identification(pdraws, idemodel, idemoments) + +% figure, +% % myboxplot(siPCA(1:(max(find(cumsum(latent)./length(indJJ)<0.99))+1),:)) +% subplot(221) +% bar(siHPCA) +% % set(gca,'ylim',[0 1]) +% set(gca,'xticklabel','') +% set(gca,'xlim',[0.5 nparam+0.5]) +% for ip=1:nparam, +% text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') +% end +% title('Sensitivity in TAU''s PCA') +% +% subplot(222) +% % myboxplot(siPCA(1:(max(find(cumsum(latent)./length(indJJ)<0.99))+1),:)) +% bar(siHPCA2) +% % set(gca,'ylim',[0 1]) +% set(gca,'xticklabel','') +% set(gca,'xlim',[0.5 nparam+0.5]) +% for ip=1:nparam, +% text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') +% end +% title('Sensitivity in standardized TAU''s PCA') +% +% +% subplot(223) +% % myboxplot(siPCA(1:(max(find(cumsum(latent)./length(indJJ)<0.99))+1),:)) +% bar(siPCA) +% % set(gca,'ylim',[0 1]) +% set(gca,'xticklabel','') +% set(gca,'xlim',[0.5 nparam+0.5]) +% for ip=1:nparam, +% text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') +% end +% title('Sensitivity in moments'' PCA') +% +% subplot(224) +% % myboxplot(siPCA(1:(max(find(cumsum(latent)./length(indJJ)<0.99))+1),:)) +% bar(siPCA2) +% % set(gca,'ylim',[0 1]) +% set(gca,'xticklabel','') +% set(gca,'xlim',[0.5 nparam+0.5]) +% for ip=1:nparam, +% text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') +% end +% title('Sensitivity in standardized moments'' PCA') + +figure, +subplot(221) +myboxplot(siHmean) +set(gca,'ylim',[0 1.05]) +set(gca,'xticklabel','') +for ip=1:nparam, + text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') +end +title('Sensitivity in the model') + +subplot(222) +myboxplot(siJmean) +set(gca,'ylim',[0 1.05]) +set(gca,'xticklabel','') +for ip=1:nparam, + text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') +end +title('Sensitivity in the moments') + +subplot(223) +myboxplot(idemodel.Mco') +set(gca,'ylim',[0 1]) +set(gca,'xticklabel','') +for ip=1:nparam, + text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') +end +title('Multicollinearity in the model') + +subplot(224) +myboxplot(idemoments.Mco') +set(gca,'ylim',[0 1]) +set(gca,'xticklabel','') +for ip=1:nparam, + text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') +end +title('Multicollinearity in the moments') +saveas(gcf,[IdentifDirectoryName,'/',M_.fname,'_ident']) +eval(['print -depsc2 ' IdentifDirectoryName '/' M_.fname '_ident']); +eval(['print -dpdf ' IdentifDirectoryName '/' M_.fname '_ident']); + + +figure, +subplot(221) +hist(log10(idemodel.cond)) +title('log10 of Condition number in the model') +subplot(222) +hist(log10(idemoments.cond)) +title('log10 of Condition number in the moments') +saveas(gcf,[IdentifDirectoryName,'/',M_.fname,'_ident_COND']) +eval(['print -depsc2 ' IdentifDirectoryName '/' M_.fname '_ident_COND']); +eval(['print -dpdf ' IdentifDirectoryName '/' M_.fname '_ident_COND']); diff --git a/matlab/dynare_resolve.m b/matlab/dynare_resolve.m index 546edf4960..d6bca09371 100644 --- a/matlab/dynare_resolve.m +++ b/matlab/dynare_resolve.m @@ -1,76 +1,76 @@ -function [A,B,ys,info] = dynare_resolve(iv,ic,aux) -% function [A,B,ys,info] = dynare_resolve(iv,ic,aux) -% Computes the linear approximation and the matrices A and B of the -% transition equation -% -% INPUTS -% iv: selected variables (observed and state variables) -% ic: state variables position in the transition matrix columns -% aux: indices for auxiliary equations -% -% OUTPUTS -% A: matrix of predetermined variables effects in linear solution (ghx) -% B: matrix of shocks effects in linear solution (ghu) -% ys: steady state of original endogenous variables -% info=1: the model doesn't determine the current variables '...' uniquely -% info=2: MJDGGES returns the following error code' -% info=3: Blanchard Kahn conditions are not satisfied: no stable '...' equilibrium -% info=4: Blanchard Kahn conditions are not satisfied:'...' indeterminacy -% info=5: Blanchard Kahn conditions are not satisfied:'...' indeterminacy due to rank failure -% info=20: can't find steady state info(2) contains sum of sqare residuals -% info=30: variance can't be computed -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2003-2007 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 <http://www.gnu.org/licenses/>. - - global oo_ M_ - - [oo_.dr,info] = resol(oo_.steady_state,0); - - if info(1) > 0 - A = []; - if nargout>1 - B = []; - if nargout>2 - ys = []; - end - end - return - end - - if nargin == 0 - endo_nbr = M_.endo_nbr; - nstatic = oo_.dr.nstatic; - npred = oo_.dr.npred; - iv = (1:endo_nbr)'; - ic = [ nstatic+(1:npred) endo_nbr+(1:size(oo_.dr.ghx,2)-npred) ]'; - aux = oo_.dr.transition_auxiliary_variables; - k = find(aux(:,2) > npred); - aux(:,2) = aux(:,2) + nstatic; - aux(k,2) = aux(k,2) + oo_.dr.nfwrd; - end - - if nargout==1 - A = kalman_transition_matrix(oo_.dr,iv,ic,aux,M_.exo_nbr); - return - end - - [A,B] = kalman_transition_matrix(oo_.dr,iv,ic,aux,M_.exo_nbr); - ys = oo_.dr.ys; \ No newline at end of file +function [A,B,ys,info] = dynare_resolve(iv,ic,aux) +% function [A,B,ys,info] = dynare_resolve(iv,ic,aux) +% Computes the linear approximation and the matrices A and B of the +% transition equation +% +% INPUTS +% iv: selected variables (observed and state variables) +% ic: state variables position in the transition matrix columns +% aux: indices for auxiliary equations +% +% OUTPUTS +% A: matrix of predetermined variables effects in linear solution (ghx) +% B: matrix of shocks effects in linear solution (ghu) +% ys: steady state of original endogenous variables +% info=1: the model doesn't determine the current variables '...' uniquely +% info=2: MJDGGES returns the following error code' +% info=3: Blanchard Kahn conditions are not satisfied: no stable '...' equilibrium +% info=4: Blanchard Kahn conditions are not satisfied:'...' indeterminacy +% info=5: Blanchard Kahn conditions are not satisfied:'...' indeterminacy due to rank failure +% info=20: can't find steady state info(2) contains sum of sqare residuals +% info=30: variance can't be computed +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2003-2007 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 <http://www.gnu.org/licenses/>. + +global oo_ M_ + +[oo_.dr,info] = resol(oo_.steady_state,0); + +if info(1) > 0 + A = []; + if nargout>1 + B = []; + if nargout>2 + ys = []; + end + end + return +end + +if nargin == 0 + endo_nbr = M_.endo_nbr; + nstatic = oo_.dr.nstatic; + npred = oo_.dr.npred; + iv = (1:endo_nbr)'; + ic = [ nstatic+(1:npred) endo_nbr+(1:size(oo_.dr.ghx,2)-npred) ]'; + aux = oo_.dr.transition_auxiliary_variables; + k = find(aux(:,2) > npred); + aux(:,2) = aux(:,2) + nstatic; + aux(k,2) = aux(k,2) + oo_.dr.nfwrd; +end + +if nargout==1 + A = kalman_transition_matrix(oo_.dr,iv,ic,aux,M_.exo_nbr); + return +end + +[A,B] = kalman_transition_matrix(oo_.dr,iv,ic,aux,M_.exo_nbr); +ys = oo_.dr.ys; \ No newline at end of file diff --git a/matlab/dynare_sensitivity.m b/matlab/dynare_sensitivity.m index f6b9488236..9343e28f8c 100644 --- a/matlab/dynare_sensitivity.m +++ b/matlab/dynare_sensitivity.m @@ -1,396 +1,396 @@ -function x0=dynare_sensitivity(options_gsa) -% Frontend to the Sensitivity Analysis Toolbox for DYNARE -% -% Reference: -% M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006. - -% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. - -global M_ options_ oo_ bayestopt_ estim_params_ - -fname_ = M_.fname; -M_.dname = fname_; -lgy_ = M_.endo_names; -x0=[]; - -options_gsa = set_default_option(options_gsa,'datafile',[]); -if isfield(options_gsa,'nograph'), - options_.nograph=options_gsa.nograph; -end -if isfield(options_gsa,'mode_file'), - options_.mode_file=options_gsa.mode_file; -end - -dynare_resolve; - -if ~isempty(options_gsa.datafile) | isempty(bayestopt_), - options_.datafile = options_gsa.datafile; - if isfield(options_gsa,'first_obs'), - options_.first_obs=options_gsa.first_obs; - end - if isfield(options_gsa,'nobs'), - options_.nobs=options_gsa.nobs; - end - if isfield(options_gsa,'presample'), - options_.presample=options_gsa.presample; - end - if isfield(options_gsa,'prefilter'), - options_.prefilter=options_gsa.prefilter; - end - if isfield(options_gsa,'loglinear'), - options_.loglinear=options_gsa.loglinear; - end - options_.mode_compute = 0; - [data,rawdata]=dynare_estimation_init([],1); - % computes a first linear solution to set up various variables -end - -options_gsa = set_default_option(options_gsa,'identification',0); -if options_gsa.identification, - options_gsa.redform=0; - options_gsa = set_default_option(options_gsa,'morris',1); - options_gsa = set_default_option(options_gsa,'trans_ident',0); - options_gsa = set_default_option(options_gsa,'load_ident_files',0); - options_gsa = set_default_option(options_gsa,'ar',3); - options_gsa = set_default_option(options_gsa,'useautocorr',1); - options_.ar = options_gsa.ar; - if options_gsa.morris==2, - options_ident=[]; - options_ident = set_default_option(options_ident,'load_ident_files',options_gsa.load_ident_files); - options_ident = set_default_option(options_ident,'useautocorr',options_gsa.useautocorr); - options_ident = set_default_option(options_ident,'ar',options_gsa.ar); - options_.options_ident = options_ident; - end -end - -% map stability -options_gsa = set_default_option(options_gsa,'stab',1); -options_gsa = set_default_option(options_gsa,'redform',0); -options_gsa = set_default_option(options_gsa,'pprior',1); -options_gsa = set_default_option(options_gsa,'prior_range',1); -options_gsa = set_default_option(options_gsa,'ppost',0); -options_gsa = set_default_option(options_gsa,'ilptau',1); -options_gsa = set_default_option(options_gsa,'morris',0); -options_gsa = set_default_option(options_gsa,'glue',0); -options_gsa = set_default_option(options_gsa,'morris_nliv',6); -options_gsa = set_default_option(options_gsa,'morris_ntra',20); -options_gsa = set_default_option(options_gsa,'Nsam',2048); -options_gsa = set_default_option(options_gsa,'load_redform',0); -options_gsa = set_default_option(options_gsa,'load_rmse',0); -options_gsa = set_default_option(options_gsa,'load_stab',0); -options_gsa = set_default_option(options_gsa,'alpha2_stab',0.3); -options_gsa = set_default_option(options_gsa,'ksstat',0.1); -%options_gsa = set_default_option(options_gsa,'load_mh',0); - -if options_gsa.redform, - options_gsa.pprior=1; - options_gsa.ppost=0; -end - -if ~(exist('stab_map_','file')==6 | exist('stab_map_','file')==2), - dynare_root = strrep(which('dynare.m'),'dynare.m',''); - gsa_path = [dynare_root 'gsa']; - if exist(gsa_path) - addpath(gsa_path,path) - else - disp('Download Dynare sensitivity routines at:') - disp('http://eemc.jrc.ec.europa.eu/softwareDYNARE-Dowload.htm') - disp(' ' ) - error('GSA routines missing!') - end -end - - -if options_gsa.morris==1 | options_gsa.morris==3, - if ~options_gsa.identification, - options_gsa.redform=1; - end - options_gsa.pprior=1; - options_gsa.ppost=0; - %options_gsa.stab=1; - options_gsa.glue=0; - options_gsa.rmse=0; - options_gsa.load_rmse=0; - options_gsa.alpha2_stab=1; - options_gsa.ksstat=1; - if options_gsa.morris==3, - options_gsa = set_default_option(options_gsa,'Nsam',256); - OutputDirectoryName = CheckPath('GSA/IDENTIF'); - else - OutputDirectoryName = CheckPath('GSA/SCREEN'); - end -else - OutputDirectoryName = CheckPath('GSA'); -end - -options_.opt_gsa = options_gsa; - -if (options_gsa.load_stab | options_gsa.load_rmse | options_gsa.load_redform) ... - & options_gsa.pprior, - filetoload=[OutputDirectoryName '/' fname_ '_prior.mat']; - if isempty(ls(filetoload)), - disp([filetoload,' not found!']) - disp(['You asked to load a non existent analysis']) - %options_gsa.load_stab=0; - return, - else - if isempty(strmatch('bkpprior',who('-file', filetoload),'exact')), - disp('Warning! Missing prior info for saved sample') % trap for files previous - disp('The saved files are generated with previous version of GSA package') % trap for files previous - else - load(filetoload,'bkpprior'), - if any(bayestopt_.pshape~=bkpprior.pshape) | ... - any(bayestopt_.p1~=bkpprior.p1) | ... - any(bayestopt_.p2~=bkpprior.p2) | ... - any(bayestopt_.p3(~isnan(bayestopt_.p3))~=bkpprior.p3(~isnan(bkpprior.p3))) | ... - any(bayestopt_.p4(~isnan(bayestopt_.p4))~=bkpprior.p4(~isnan(bkpprior.p4))), - disp('WARNING!') - disp('The saved sample has different priors w.r.t. to current ones!!') - disp('') - disp('Press ENTER to continue') - pause; - end - end - end -end - -if options_gsa.stab & ~options_gsa.ppost, - x0 = stab_map_(OutputDirectoryName); -end - -% reduced form -% redform_map(namendo, namlagendo, namexo, icomp, pprior, ilog, threshold) -options_gsa = set_default_option(options_gsa,'logtrans_redform',0); -options_gsa = set_default_option(options_gsa,'threshold_redform',[]); -options_gsa = set_default_option(options_gsa,'ksstat_redform',0.1); -options_gsa = set_default_option(options_gsa,'alpha2_redform',0.3); -options_gsa = set_default_option(options_gsa,'namendo',[]); -options_gsa = set_default_option(options_gsa,'namlagendo',[]); -options_gsa = set_default_option(options_gsa,'namexo',[]); - -options_.opt_gsa = options_gsa; -if options_gsa.identification, - map_ident_(OutputDirectoryName); -end - -if options_gsa.redform & ~isempty(options_gsa.namendo) ... - & ~options_gsa.ppost, - if strmatch(':',options_gsa.namendo,'exact'), - options_gsa.namendo=M_.endo_names; - end - if strmatch(':',options_gsa.namexo,'exact'), - options_gsa.namexo=M_.exo_names; - end - if strmatch(':',options_gsa.namlagendo,'exact'), - options_gsa.namlagendo=M_.endo_names; - end - options_.opt_gsa = options_gsa; - if options_gsa.morris==1, - redform_screen(OutputDirectoryName); - else - % check existence of the SS_ANOVA toolbox - if ~(exist('gsa_sdp','file')==6 | exist('gsa_sdp','file')==2), - disp('Download Mapping routines at:') - disp('http://eemc.jrc.ec.europa.eu/softwareDYNARE-Dowload.htm') - disp(' ' ) - error('Mapping routines missing!') - end - - redform_map(OutputDirectoryName); - end -end -% RMSE mapping -% function [rmse_MC, ixx] = filt_mc_(vvarvecm, loadSA, pfilt, alpha, alpha2) -options_gsa = set_default_option(options_gsa,'rmse',0); -options_gsa = set_default_option(options_gsa,'lik_only',0); -options_gsa = set_default_option(options_gsa,'var_rmse',options_.varobs); -options_gsa = set_default_option(options_gsa,'pfilt_rmse',0.1); -options_gsa = set_default_option(options_gsa,'istart_rmse',options_.presample+1); -options_gsa = set_default_option(options_gsa,'alpha_rmse',0.002); -options_gsa = set_default_option(options_gsa,'alpha2_rmse',1); -options_.opt_gsa = options_gsa; -if options_gsa.rmse, - if ~options_gsa.ppost - if options_gsa.pprior - a=whos('-file',[OutputDirectoryName,'/',fname_,'_prior'],'logpo2'); - else - a=whos('-file',[OutputDirectoryName,'/',fname_,'_mc'],'logpo2'); - end - if isempty(a), - dynare_MC([],OutputDirectoryName); - options_gsa.load_rmse=0; -% else -% if options_gsa.load_rmse==0, -% disp('You already saved a MC filter/smoother analysis ') -% disp('Do you want to overwrite ?') -% pause; -% if options_gsa.pprior -% delete([OutputDirectoryName,'/',fname_,'_prior_*.mat']) -% else -% delete([OutputDirectoryName,'/',fname_,'_mc_*.mat']) -% end -% dynare_MC([],OutputDirectoryName); -% options_gsa.load_rmse=0; -% end - - end - end - clear a; - filt_mc_(OutputDirectoryName); -end - - -if options_gsa.glue, - dr_ = oo_.dr; - if options_gsa.ppost - load([OutputDirectoryName,'/',fname_,'_post']); - DirectoryName = CheckPath('metropolis'); - else - if options_gsa.pprior - load([OutputDirectoryName,'/',fname_,'_prior']); - else - load([OutputDirectoryName,'/',fname_,'_mc']); - end - end - if ~exist('x'), - disp(['No RMSE analysis is available for current options']) - disp(['No GLUE file prepared']) - return, - end - nruns=size(x,1); - gend = options_.nobs; - rawdata = read_variables(options_.datafile,options_.varobs,[],options_.xls_sheet,options_.xls_range); - rawdata = rawdata(options_.first_obs:options_.first_obs+gend-1,:); - if options_.loglinear == 1 - rawdata = log(rawdata); - end - if options_.prefilter == 1 - %data = transpose(rawdata-ones(gend,1)*bayestopt_.mean_varobs); - data = transpose(rawdata-ones(gend,1)*mean(rawdata,1)); - else - data = transpose(rawdata); - end - - Obs.data = data; - Obs.time = [1:gend]; - Obs.num = gend; - for j=1:size(options_.varobs,1) - Obs.name{j} = deblank(options_.varobs(j,:)); - vj=deblank(options_.varobs(j,:)); - - jxj = strmatch(vj,lgy_(dr_.order_var,:),'exact'); - js = strmatch(vj,lgy_,'exact'); - if ~options_gsa.ppost -% y0=zeros(gend+1,nruns); -% nb = size(stock_filter,3); -% y0 = squeeze(stock_filter(:,jxj,:)) + ... -% kron(stock_ys(js,:),ones(size(stock_filter,1),1)); -% Out(j).data = y0'; -% Out(j).time = [1:size(y0,1)]; - Out(j).data = jxj; - Out(j).time = [pwd,'/',OutputDirectoryName]; - else - Out(j).data = jxj; - Out(j).time = [pwd,'/',DirectoryName]; - end - Out(j).name = vj; - Out(j).ini = 'yes'; - Lik(j).name = ['rmse_',vj]; - Lik(j).ini = 'yes'; - Lik(j).isam = 1; - Lik(j).data = rmse_MC(:,j)'; - - if ~options_gsa.ppost -% y0 = squeeze(stock_smooth(:,jxj,:)) + ... -% kron(stock_ys(js,:),ones(size(stock_smooth,1),1)); -% Out1(j).name = vj; -% Out1(j).ini = 'yes'; -% Out1(j).time = [1:size(y0,1)]; -% Out1(j).data = y0'; - Out1=Out; - else - Out1=Out; - end - ismoo(j)=jxj; - - end - jsmoo = size(options_.varobs,1); - for j=1:M_.endo_nbr, - if ~ismember(j,ismoo), - jsmoo=jsmoo+1; - vj=deblank(M_.endo_names(dr_.order_var(j),:)); - if ~options_gsa.ppost -% y0 = squeeze(stock_smooth(:,j,:)) + ... -% kron(stock_ys(j,:),ones(size(stock_smooth,1),1)); -% Out1(jsmoo).time = [1:size(y0,1)]; -% Out1(jsmoo).data = y0'; - Out1(jsmoo).data = j; - Out1(jsmoo).time = [pwd,'/',OutputDirectoryName]; - else - Out1(jsmoo).data = j; - Out1(jsmoo).time = [pwd,'/',DirectoryName]; - end - Out1(jsmoo).name = vj; - Out1(jsmoo).ini = 'yes'; - end - end - tit(M_.exo_names_orig_ord,:) = M_.exo_names; - for j=1:M_.exo_nbr, - Exo(j).name = deblank(tit(j,:)); - end - if ~options_gsa.ppost - Lik(size(options_.varobs,1)+1).name = 'logpo'; - Lik(size(options_.varobs,1)+1).ini = 'yes'; - Lik(size(options_.varobs,1)+1).isam = 1; - Lik(size(options_.varobs,1)+1).data = -logpo2; - end - Sam.name = bayestopt_.name; - Sam.dim = [size(x) 0]; - Sam.data = [x]; - - Rem.id = 'Original'; - Rem.ind= [1:size(x,1)]; - - Info.dynare=M_.fname; - Info.order_var=dr_.order_var; - Out=Out1; - if options_gsa.ppost -% Info.dynare=M_.fname; -% Info.order_var=dr_.order_var; -% Out=Out1; - Info.TypeofSample='post'; - save([OutputDirectoryName,'/',fname_,'_glue_post'], 'Out', 'Sam', 'Lik', 'Obs', 'Rem','Info', 'Exo') - %save([fname_,'_post_glue_smooth'], 'Out', 'Sam', 'Lik', 'Obs', 'Rem','Info') - - else - if options_gsa.pprior - Info.TypeofSample='prior'; - save([OutputDirectoryName,'/',fname_,'_glue_prior'], 'Out', 'Sam', 'Lik', 'Obs', 'Rem','Info', 'Exo') -% save([OutputDirectoryName,'/',fname_,'_prior_glue'], 'Out', 'Sam', 'Lik', 'Obs', 'Rem') -% Out=Out1; -% save([OutputDirectoryName,'/',fname_,'_prior_glue_smooth'], 'Out', 'Sam', 'Lik', 'Obs', 'Rem') - else - Info.TypeofSample='mc'; - save([OutputDirectoryName,'/',fname_,'_glue_mc'], 'Out', 'Sam', 'Lik', 'Obs', 'Rem','Info', 'Exo') -% save([OutputDirectoryName,'/',fname_,'_mc_glue'], 'Out', 'Sam', 'Lik', 'Obs', 'Rem') -% Out=Out1; -% save([OutputDirectoryName,'/',fname_,'_mc_glue_smooth'], 'Out', 'Sam', 'Lik', 'Obs', 'Rem') - end - end - -end +function x0=dynare_sensitivity(options_gsa) +% Frontend to the Sensitivity Analysis Toolbox for DYNARE +% +% Reference: +% M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006. + +% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. + +global M_ options_ oo_ bayestopt_ estim_params_ + +fname_ = M_.fname; +M_.dname = fname_; +lgy_ = M_.endo_names; +x0=[]; + +options_gsa = set_default_option(options_gsa,'datafile',[]); +if isfield(options_gsa,'nograph'), + options_.nograph=options_gsa.nograph; +end +if isfield(options_gsa,'mode_file'), + options_.mode_file=options_gsa.mode_file; +end + +dynare_resolve; + +if ~isempty(options_gsa.datafile) | isempty(bayestopt_), + options_.datafile = options_gsa.datafile; + if isfield(options_gsa,'first_obs'), + options_.first_obs=options_gsa.first_obs; + end + if isfield(options_gsa,'nobs'), + options_.nobs=options_gsa.nobs; + end + if isfield(options_gsa,'presample'), + options_.presample=options_gsa.presample; + end + if isfield(options_gsa,'prefilter'), + options_.prefilter=options_gsa.prefilter; + end + if isfield(options_gsa,'loglinear'), + options_.loglinear=options_gsa.loglinear; + end + options_.mode_compute = 0; + [data,rawdata]=dynare_estimation_init([],1); + % computes a first linear solution to set up various variables +end + +options_gsa = set_default_option(options_gsa,'identification',0); +if options_gsa.identification, + options_gsa.redform=0; + options_gsa = set_default_option(options_gsa,'morris',1); + options_gsa = set_default_option(options_gsa,'trans_ident',0); + options_gsa = set_default_option(options_gsa,'load_ident_files',0); + options_gsa = set_default_option(options_gsa,'ar',3); + options_gsa = set_default_option(options_gsa,'useautocorr',1); + options_.ar = options_gsa.ar; + if options_gsa.morris==2, + options_ident=[]; + options_ident = set_default_option(options_ident,'load_ident_files',options_gsa.load_ident_files); + options_ident = set_default_option(options_ident,'useautocorr',options_gsa.useautocorr); + options_ident = set_default_option(options_ident,'ar',options_gsa.ar); + options_.options_ident = options_ident; + end +end + +% map stability +options_gsa = set_default_option(options_gsa,'stab',1); +options_gsa = set_default_option(options_gsa,'redform',0); +options_gsa = set_default_option(options_gsa,'pprior',1); +options_gsa = set_default_option(options_gsa,'prior_range',1); +options_gsa = set_default_option(options_gsa,'ppost',0); +options_gsa = set_default_option(options_gsa,'ilptau',1); +options_gsa = set_default_option(options_gsa,'morris',0); +options_gsa = set_default_option(options_gsa,'glue',0); +options_gsa = set_default_option(options_gsa,'morris_nliv',6); +options_gsa = set_default_option(options_gsa,'morris_ntra',20); +options_gsa = set_default_option(options_gsa,'Nsam',2048); +options_gsa = set_default_option(options_gsa,'load_redform',0); +options_gsa = set_default_option(options_gsa,'load_rmse',0); +options_gsa = set_default_option(options_gsa,'load_stab',0); +options_gsa = set_default_option(options_gsa,'alpha2_stab',0.3); +options_gsa = set_default_option(options_gsa,'ksstat',0.1); +%options_gsa = set_default_option(options_gsa,'load_mh',0); + +if options_gsa.redform, + options_gsa.pprior=1; + options_gsa.ppost=0; +end + +if ~(exist('stab_map_','file')==6 | exist('stab_map_','file')==2), + dynare_root = strrep(which('dynare.m'),'dynare.m',''); + gsa_path = [dynare_root 'gsa']; + if exist(gsa_path) + addpath(gsa_path,path) + else + disp('Download Dynare sensitivity routines at:') + disp('http://eemc.jrc.ec.europa.eu/softwareDYNARE-Dowload.htm') + disp(' ' ) + error('GSA routines missing!') + end +end + + +if options_gsa.morris==1 | options_gsa.morris==3, + if ~options_gsa.identification, + options_gsa.redform=1; + end + options_gsa.pprior=1; + options_gsa.ppost=0; + %options_gsa.stab=1; + options_gsa.glue=0; + options_gsa.rmse=0; + options_gsa.load_rmse=0; + options_gsa.alpha2_stab=1; + options_gsa.ksstat=1; + if options_gsa.morris==3, + options_gsa = set_default_option(options_gsa,'Nsam',256); + OutputDirectoryName = CheckPath('GSA/IDENTIF'); + else + OutputDirectoryName = CheckPath('GSA/SCREEN'); + end +else + OutputDirectoryName = CheckPath('GSA'); +end + +options_.opt_gsa = options_gsa; + +if (options_gsa.load_stab | options_gsa.load_rmse | options_gsa.load_redform) ... + & options_gsa.pprior, + filetoload=[OutputDirectoryName '/' fname_ '_prior.mat']; + if isempty(ls(filetoload)), + disp([filetoload,' not found!']) + disp(['You asked to load a non existent analysis']) + %options_gsa.load_stab=0; + return, + else + if isempty(strmatch('bkpprior',who('-file', filetoload),'exact')), + disp('Warning! Missing prior info for saved sample') % trap for files previous + disp('The saved files are generated with previous version of GSA package') % trap for files previous + else + load(filetoload,'bkpprior'), + if any(bayestopt_.pshape~=bkpprior.pshape) | ... + any(bayestopt_.p1~=bkpprior.p1) | ... + any(bayestopt_.p2~=bkpprior.p2) | ... + any(bayestopt_.p3(~isnan(bayestopt_.p3))~=bkpprior.p3(~isnan(bkpprior.p3))) | ... + any(bayestopt_.p4(~isnan(bayestopt_.p4))~=bkpprior.p4(~isnan(bkpprior.p4))), + disp('WARNING!') + disp('The saved sample has different priors w.r.t. to current ones!!') + disp('') + disp('Press ENTER to continue') + pause; + end + end + end +end + +if options_gsa.stab & ~options_gsa.ppost, + x0 = stab_map_(OutputDirectoryName); +end + +% reduced form +% redform_map(namendo, namlagendo, namexo, icomp, pprior, ilog, threshold) +options_gsa = set_default_option(options_gsa,'logtrans_redform',0); +options_gsa = set_default_option(options_gsa,'threshold_redform',[]); +options_gsa = set_default_option(options_gsa,'ksstat_redform',0.1); +options_gsa = set_default_option(options_gsa,'alpha2_redform',0.3); +options_gsa = set_default_option(options_gsa,'namendo',[]); +options_gsa = set_default_option(options_gsa,'namlagendo',[]); +options_gsa = set_default_option(options_gsa,'namexo',[]); + +options_.opt_gsa = options_gsa; +if options_gsa.identification, + map_ident_(OutputDirectoryName); +end + +if options_gsa.redform & ~isempty(options_gsa.namendo) ... + & ~options_gsa.ppost, + if strmatch(':',options_gsa.namendo,'exact'), + options_gsa.namendo=M_.endo_names; + end + if strmatch(':',options_gsa.namexo,'exact'), + options_gsa.namexo=M_.exo_names; + end + if strmatch(':',options_gsa.namlagendo,'exact'), + options_gsa.namlagendo=M_.endo_names; + end + options_.opt_gsa = options_gsa; + if options_gsa.morris==1, + redform_screen(OutputDirectoryName); + else + % check existence of the SS_ANOVA toolbox + if ~(exist('gsa_sdp','file')==6 | exist('gsa_sdp','file')==2), + disp('Download Mapping routines at:') + disp('http://eemc.jrc.ec.europa.eu/softwareDYNARE-Dowload.htm') + disp(' ' ) + error('Mapping routines missing!') + end + + redform_map(OutputDirectoryName); + end +end +% RMSE mapping +% function [rmse_MC, ixx] = filt_mc_(vvarvecm, loadSA, pfilt, alpha, alpha2) +options_gsa = set_default_option(options_gsa,'rmse',0); +options_gsa = set_default_option(options_gsa,'lik_only',0); +options_gsa = set_default_option(options_gsa,'var_rmse',options_.varobs); +options_gsa = set_default_option(options_gsa,'pfilt_rmse',0.1); +options_gsa = set_default_option(options_gsa,'istart_rmse',options_.presample+1); +options_gsa = set_default_option(options_gsa,'alpha_rmse',0.002); +options_gsa = set_default_option(options_gsa,'alpha2_rmse',1); +options_.opt_gsa = options_gsa; +if options_gsa.rmse, + if ~options_gsa.ppost + if options_gsa.pprior + a=whos('-file',[OutputDirectoryName,'/',fname_,'_prior'],'logpo2'); + else + a=whos('-file',[OutputDirectoryName,'/',fname_,'_mc'],'logpo2'); + end + if isempty(a), + dynare_MC([],OutputDirectoryName); + options_gsa.load_rmse=0; + % else + % if options_gsa.load_rmse==0, + % disp('You already saved a MC filter/smoother analysis ') + % disp('Do you want to overwrite ?') + % pause; + % if options_gsa.pprior + % delete([OutputDirectoryName,'/',fname_,'_prior_*.mat']) + % else + % delete([OutputDirectoryName,'/',fname_,'_mc_*.mat']) + % end + % dynare_MC([],OutputDirectoryName); + % options_gsa.load_rmse=0; + % end + + end + end + clear a; + filt_mc_(OutputDirectoryName); +end + + +if options_gsa.glue, + dr_ = oo_.dr; + if options_gsa.ppost + load([OutputDirectoryName,'/',fname_,'_post']); + DirectoryName = CheckPath('metropolis'); + else + if options_gsa.pprior + load([OutputDirectoryName,'/',fname_,'_prior']); + else + load([OutputDirectoryName,'/',fname_,'_mc']); + end + end + if ~exist('x'), + disp(['No RMSE analysis is available for current options']) + disp(['No GLUE file prepared']) + return, + end + nruns=size(x,1); + gend = options_.nobs; + rawdata = read_variables(options_.datafile,options_.varobs,[],options_.xls_sheet,options_.xls_range); + rawdata = rawdata(options_.first_obs:options_.first_obs+gend-1,:); + if options_.loglinear == 1 + rawdata = log(rawdata); + end + if options_.prefilter == 1 + %data = transpose(rawdata-ones(gend,1)*bayestopt_.mean_varobs); + data = transpose(rawdata-ones(gend,1)*mean(rawdata,1)); + else + data = transpose(rawdata); + end + + Obs.data = data; + Obs.time = [1:gend]; + Obs.num = gend; + for j=1:size(options_.varobs,1) + Obs.name{j} = deblank(options_.varobs(j,:)); + vj=deblank(options_.varobs(j,:)); + + jxj = strmatch(vj,lgy_(dr_.order_var,:),'exact'); + js = strmatch(vj,lgy_,'exact'); + if ~options_gsa.ppost + % y0=zeros(gend+1,nruns); + % nb = size(stock_filter,3); + % y0 = squeeze(stock_filter(:,jxj,:)) + ... + % kron(stock_ys(js,:),ones(size(stock_filter,1),1)); + % Out(j).data = y0'; + % Out(j).time = [1:size(y0,1)]; + Out(j).data = jxj; + Out(j).time = [pwd,'/',OutputDirectoryName]; + else + Out(j).data = jxj; + Out(j).time = [pwd,'/',DirectoryName]; + end + Out(j).name = vj; + Out(j).ini = 'yes'; + Lik(j).name = ['rmse_',vj]; + Lik(j).ini = 'yes'; + Lik(j).isam = 1; + Lik(j).data = rmse_MC(:,j)'; + + if ~options_gsa.ppost + % y0 = squeeze(stock_smooth(:,jxj,:)) + ... + % kron(stock_ys(js,:),ones(size(stock_smooth,1),1)); + % Out1(j).name = vj; + % Out1(j).ini = 'yes'; + % Out1(j).time = [1:size(y0,1)]; + % Out1(j).data = y0'; + Out1=Out; + else + Out1=Out; + end + ismoo(j)=jxj; + + end + jsmoo = size(options_.varobs,1); + for j=1:M_.endo_nbr, + if ~ismember(j,ismoo), + jsmoo=jsmoo+1; + vj=deblank(M_.endo_names(dr_.order_var(j),:)); + if ~options_gsa.ppost + % y0 = squeeze(stock_smooth(:,j,:)) + ... + % kron(stock_ys(j,:),ones(size(stock_smooth,1),1)); + % Out1(jsmoo).time = [1:size(y0,1)]; + % Out1(jsmoo).data = y0'; + Out1(jsmoo).data = j; + Out1(jsmoo).time = [pwd,'/',OutputDirectoryName]; + else + Out1(jsmoo).data = j; + Out1(jsmoo).time = [pwd,'/',DirectoryName]; + end + Out1(jsmoo).name = vj; + Out1(jsmoo).ini = 'yes'; + end + end + tit(M_.exo_names_orig_ord,:) = M_.exo_names; + for j=1:M_.exo_nbr, + Exo(j).name = deblank(tit(j,:)); + end + if ~options_gsa.ppost + Lik(size(options_.varobs,1)+1).name = 'logpo'; + Lik(size(options_.varobs,1)+1).ini = 'yes'; + Lik(size(options_.varobs,1)+1).isam = 1; + Lik(size(options_.varobs,1)+1).data = -logpo2; + end + Sam.name = bayestopt_.name; + Sam.dim = [size(x) 0]; + Sam.data = [x]; + + Rem.id = 'Original'; + Rem.ind= [1:size(x,1)]; + + Info.dynare=M_.fname; + Info.order_var=dr_.order_var; + Out=Out1; + if options_gsa.ppost + % Info.dynare=M_.fname; + % Info.order_var=dr_.order_var; + % Out=Out1; + Info.TypeofSample='post'; + save([OutputDirectoryName,'/',fname_,'_glue_post'], 'Out', 'Sam', 'Lik', 'Obs', 'Rem','Info', 'Exo') + %save([fname_,'_post_glue_smooth'], 'Out', 'Sam', 'Lik', 'Obs', 'Rem','Info') + + else + if options_gsa.pprior + Info.TypeofSample='prior'; + save([OutputDirectoryName,'/',fname_,'_glue_prior'], 'Out', 'Sam', 'Lik', 'Obs', 'Rem','Info', 'Exo') + % save([OutputDirectoryName,'/',fname_,'_prior_glue'], 'Out', 'Sam', 'Lik', 'Obs', 'Rem') + % Out=Out1; + % save([OutputDirectoryName,'/',fname_,'_prior_glue_smooth'], 'Out', 'Sam', 'Lik', 'Obs', 'Rem') + else + Info.TypeofSample='mc'; + save([OutputDirectoryName,'/',fname_,'_glue_mc'], 'Out', 'Sam', 'Lik', 'Obs', 'Rem','Info', 'Exo') + % save([OutputDirectoryName,'/',fname_,'_mc_glue'], 'Out', 'Sam', 'Lik', 'Obs', 'Rem') + % Out=Out1; + % save([OutputDirectoryName,'/',fname_,'_mc_glue_smooth'], 'Out', 'Sam', 'Lik', 'Obs', 'Rem') + end + end + +end diff --git a/matlab/dynare_solve.m b/matlab/dynare_solve.m index 2dfc5735be..34a410eebe 100644 --- a/matlab/dynare_solve.m +++ b/matlab/dynare_solve.m @@ -33,15 +33,15 @@ function [x,info] = dynare_solve(func,x,jacobian_flag,varargin) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global options_ - - options_ = set_default_option(options_,'solve_algo',2); - info = 0; - if options_.solve_algo == 0 +global options_ + +options_ = set_default_option(options_,'solve_algo',2); +info = 0; +if options_.solve_algo == 0 if exist('OCTAVE_VERSION') || isempty(ver('optim')) - % Note that fsolve() exists under Octave, but has a different syntax - % So we fail for the moment under Octave, until we add the corresponding code - error('DYNARE_SOLVE: you can''t use solve_algo=0 since you don''t have Matlab''s Optimization Toolbox') + % Note that fsolve() exists under Octave, but has a different syntax + % So we fail for the moment under Octave, until we add the corresponding code + error('DYNARE_SOLVE: you can''t use solve_algo=0 since you don''t have Matlab''s Optimization Toolbox') end options=optimset('fsolve'); options.MaxFunEvals = 50000; @@ -49,81 +49,81 @@ function [x,info] = dynare_solve(func,x,jacobian_flag,varargin) options.TolFun=1e-8; options.Display = 'iter'; if jacobian_flag - options.Jacobian = 'on'; + options.Jacobian = 'on'; else - options.Jacobian = 'off'; + options.Jacobian = 'off'; end [x,fval,exitval,output] = fsolve(func,x,options,varargin{:}); if exitval > 0 - info = 0; + info = 0; else - info = 1; + info = 1; end - elseif options_.solve_algo == 1 +elseif options_.solve_algo == 1 nn = size(x,1); [x,info]=solve1(func,x,1:nn,1:nn,jacobian_flag,1,varargin{:}); - elseif options_.solve_algo == 2 || options_.solve_algo == 4 +elseif options_.solve_algo == 2 || options_.solve_algo == 4 nn = size(x,1) ; tolf = options_.solve_tolf ; if jacobian_flag - [fvec,fjac] = feval(func,x,varargin{:}); + [fvec,fjac] = feval(func,x,varargin{:}); else - fvec = feval(func,x,varargin{:}); - fjac = zeros(nn,nn) ; + fvec = feval(func,x,varargin{:}); + fjac = zeros(nn,nn) ; end i = find(~isfinite(fvec)); if ~isempty(i) - disp(['STEADY: numerical initial values incompatible with the following' ... - ' equations']) - disp(i') - error('exiting ...') + disp(['STEADY: numerical initial values incompatible with the following' ... + ' equations']) + disp(i') + error('exiting ...') end if max(abs(fvec)) < tolf - return ; + return ; end if ~jacobian_flag - fjac = zeros(nn,nn) ; - dh = max(abs(x),options_.gstep*ones(nn,1))*eps^(1/3); - for j = 1:nn - xdh = x ; - xdh(j) = xdh(j)+dh(j) ; - fjac(:,j) = (feval(func,xdh,varargin{:}) - fvec)./dh(j) ; - end + fjac = zeros(nn,nn) ; + dh = max(abs(x),options_.gstep*ones(nn,1))*eps^(1/3); + for j = 1:nn + xdh = x ; + xdh(j) = xdh(j)+dh(j) ; + fjac(:,j) = (feval(func,xdh,varargin{:}) - fvec)./dh(j) ; + end end [j1,j2,r,s] = dmperm(fjac); if options_.debug - disp(['DYNARE_SOLVE (solve_algo=2|4): number of blocks = ' num2str(length(r))]); + disp(['DYNARE_SOLVE (solve_algo=2|4): number of blocks = ' num2str(length(r))]); end % Activate bad conditioning flag for solve_algo = 2, but not for solve_algo = 4 bad_cond_flag = (options_.solve_algo == 2); for i=length(r)-1:-1:1 - if options_.debug - disp(['DYNARE_SOLVE (solve_algo=2|4): solving block ' num2str(i) ', of size ' num2str(r(i+1)-r(i)) ]); - end - [x,info]=solve1(func,x,j1(r(i):r(i+1)-1),j2(r(i):r(i+1)-1),jacobian_flag, bad_cond_flag, varargin{:}); - if info - return - end + if options_.debug + disp(['DYNARE_SOLVE (solve_algo=2|4): solving block ' num2str(i) ', of size ' num2str(r(i+1)-r(i)) ]); + end + [x,info]=solve1(func,x,j1(r(i):r(i+1)-1),j2(r(i):r(i+1)-1),jacobian_flag, bad_cond_flag, varargin{:}); + if info + return + end end fvec = feval(func,x,varargin{:}); if max(abs(fvec)) > tolf [x,info]=solve1(func,x,1:nn,1:nn,jacobian_flag, bad_cond_flag, varargin{:}); end - elseif options_.solve_algo == 3 +elseif options_.solve_algo == 3 if jacobian_flag - [x,info] = csolve(func,x,func,1e-6,500,varargin{:}); + [x,info] = csolve(func,x,func,1e-6,500,varargin{:}); else - [x,info] = csolve(func,x,[],1e-6,500,varargin{:}); + [x,info] = csolve(func,x,[],1e-6,500,varargin{:}); end - else +else error('DYNARE_SOLVE: option solve_algo must be one of [0,1,2,3,4]') - end +end diff --git a/matlab/dynare_squeeze.m b/matlab/dynare_squeeze.m index ae4d4b721a..b01be342ff 100644 --- a/matlab/dynare_squeeze.m +++ b/matlab/dynare_squeeze.m @@ -18,19 +18,19 @@ function B = dynare_squeeze(A); % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - sizA = size(A); - dimA = length(sizA); - switch dimA - case 1 +sizA = size(A); +dimA = length(sizA); +switch dimA + case 1 + B = A; + case 2 + if sizA(1)==1 + B = transpose(A); + elseif sizA(2)==1 + B = A(:,1); + else B = A; - case 2 - if sizA(1)==1 - B = transpose(A); - elseif sizA(2)==1 - B = A(:,1); - else - B = A; - end - otherwise - B = squeeze(A); - end \ No newline at end of file + end + otherwise + B = squeeze(A); +end \ No newline at end of file diff --git a/matlab/dynasave.m b/matlab/dynasave.m index bcb35bf69b..d9666f77cf 100644 --- a/matlab/dynasave.m +++ b/matlab/dynasave.m @@ -29,22 +29,22 @@ function dynasave(s,var_list) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ oo_ +global M_ oo_ - if size(var_list,1) == 0 +if size(var_list,1) == 0 var_list = M_.endo_names(1:M_.orig_endo_nbr, :); - end +end - n = size(var_list,1); - ivar=zeros(n,1); - for i=1:n - i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact'); - if isempty(i_tmp) +n = size(var_list,1); +ivar=zeros(n,1); +for i=1:n + i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact'); + if isempty(i_tmp) error (['One of the specified variables does not exist']) ; - else + else ivar(i) = i_tmp; - end end +end % dyn2vec(var_list(1),var_list(1)); eval([var_list(1) '=oo_.endo_simul(ivar(1),:)'';']) diff --git a/matlab/dynatype.m b/matlab/dynatype.m index 9ce527b9d9..35276028f4 100644 --- a/matlab/dynatype.m +++ b/matlab/dynatype.m @@ -35,24 +35,24 @@ global M_ oo_ fid=fopen(s,'w') ; if size(var_list,1) == 0 - var_list = M_.endo_names(1:M_.orig_endo_nbr,:); + var_list = M_.endo_names(1:M_.orig_endo_nbr,:); end n = size(var_list,1); - ivar=zeros(n,1); - for i=1:n +ivar=zeros(n,1); +for i=1:n i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact'); if isempty(i_tmp) - error (['One of the specified variables does not exist']) ; + error (['One of the specified variables does not exist']) ; else - ivar(i) = i_tmp; + ivar(i) = i_tmp; end - end +end for i = 1:n - fprintf(fid,M_.endo_names(ivar(i),:),'\n') ; - fprintf(fid,'\n') ; - fprintf(fid,'%15.8g\n',oo_.endo_simul(ivar(i),:)') ; + fprintf(fid,M_.endo_names(ivar(i),:),'\n') ; + fprintf(fid,'\n') ; + fprintf(fid,'%15.8g\n',oo_.endo_simul(ivar(i),:)') ; end fclose(fid) ; diff --git a/matlab/dynsec2hms.m b/matlab/dynsec2hms.m index 1675434b2a..ab75d33d9c 100644 --- a/matlab/dynsec2hms.m +++ b/matlab/dynsec2hms.m @@ -18,8 +18,8 @@ function hms = dynsec2hms(secs) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - secs = round(secs); - s = rem(secs, 60); - m = rem(floor(secs / 60), 60); - h = floor(secs / 3600); - hms = sprintf('%dh%02dm%02ds', h, m, s); \ No newline at end of file +secs = round(secs); +s = rem(secs, 60); +m = rem(floor(secs / 60), 60); +h = floor(secs / 3600); +hms = sprintf('%dh%02dm%02ds', h, m, s); \ No newline at end of file diff --git a/matlab/dyntable.m b/matlab/dyntable.m index 30e93f800a..3564b5b84d 100644 --- a/matlab/dyntable.m +++ b/matlab/dyntable.m @@ -1,5 +1,5 @@ function dyntable(title,headers,labels,values,label_width,val_width, ... - val_precis) + val_precis) % Copyright (C) 2002-2009 Dynare Team % @@ -18,31 +18,31 @@ function dyntable(title,headers,labels,values,label_width,val_width, ... % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global options_ - - if options_.noprint +global options_ + +if options_.noprint return - end +end - label_width = max(size(deblank(strvcat(headers(1,:),labels)),2)+2, ... - label_width); - val_width = max(size(deblank(headers(2:end,:)),2)+2,val_width); - label_fmt = sprintf('%%-%ds',label_width); - header_fmt = sprintf('%%-%ds',val_width); - val_fmt = sprintf('%%%d.%df',val_width,val_precis); - if length(title) > 0 +label_width = max(size(deblank(strvcat(headers(1,:),labels)),2)+2, ... + label_width); +val_width = max(size(deblank(headers(2:end,:)),2)+2,val_width); +label_fmt = sprintf('%%-%ds',label_width); +header_fmt = sprintf('%%-%ds',val_width); +val_fmt = sprintf('%%%d.%df',val_width,val_precis); +if length(title) > 0 disp(sprintf('\n\n%s\n',title)); - end - if length(headers) > 0 +end +if length(headers) > 0 hh = sprintf(label_fmt,headers(1,:)); hh = [hh char(32*ones(1,floor(val_width/4)))]; for i=2:size(headers,1) - hh = [hh sprintf(header_fmt,headers(i,:))]; + hh = [hh sprintf(header_fmt,headers(i,:))]; end disp(hh); - end - for i=1:size(values,1) +end +for i=1:size(values,1) disp([sprintf(label_fmt,labels(i,:)) sprintf(val_fmt,values(i,:))]); - end - +end + % 10/30/02 MJ \ No newline at end of file diff --git a/matlab/erase_compiled_function.m b/matlab/erase_compiled_function.m index 5832c77d14..376776864e 100644 --- a/matlab/erase_compiled_function.m +++ b/matlab/erase_compiled_function.m @@ -1,24 +1,24 @@ -function erase_compiled_function(func) -% erase compiled function with name 'func' - -% Copyright (C) 2006-2009 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 <http://www.gnu.org/licenses/>. - - if exist([func '.' mexext]) - clear(func) - delete([func '.' mexext]) - end +function erase_compiled_function(func) +% erase compiled function with name 'func' + +% Copyright (C) 2006-2009 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 <http://www.gnu.org/licenses/>. + +if exist([func '.' mexext]) + clear(func) + delete([func '.' mexext]) +end diff --git a/matlab/evaluate_likelihood.m b/matlab/evaluate_likelihood.m index 8d3efed076..1e375bf619 100644 --- a/matlab/evaluate_likelihood.m +++ b/matlab/evaluate_likelihood.m @@ -17,7 +17,7 @@ function [llik,parameters] = evaluate_likelihood(parameters) % [1] This function cannot evaluate the likelihood of a dsge-var model... % [2] This function use persistent variables for the dataset and the description of the missing observations. Consequently, if this function % is called more than once (by changing the value of parameters) the sample *must not* change. - + % Copyright (C) 2009 Dynare Team % % This file is part of Dynare. @@ -34,109 +34,109 @@ function [llik,parameters] = evaluate_likelihood(parameters) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - global options_ M_ bayestopt_ oo_ - - persistent load_data - persistent gend data data_index number_of_observations no_more_missing_observations - - if nargin==0 - parameters = 'posterior mode'; + +global options_ M_ bayestopt_ oo_ + +persistent load_data +persistent gend data data_index number_of_observations no_more_missing_observations + +if nargin==0 + parameters = 'posterior mode'; +end + +if ischar(parameters) + switch parameters + case 'posterior mode' + parameters = get_posterior_parameters('mode'); + case 'posterior mean' + parameters = get_posterior_parameters('mean'); + case 'posterior median' + parameters = get_posterior_parameters('median'); + case 'prior mode' + parameters = bayestopt_.p5(:); + case 'prior mean' + parameters = bayestopt_.p1; + otherwise + disp('eval_likelihood:: If the input argument is a string, then it has to be equal to:') + disp(' ''posterior mode'', ') + disp(' ''posterior mean'', ') + disp(' ''posterior median'', ') + disp(' ''prior mode'' or') + disp(' ''prior mean''.') + error end - - if ischar(parameters) - switch parameters - case 'posterior mode' - parameters = get_posterior_parameters('mode'); - case 'posterior mean' - parameters = get_posterior_parameters('mean'); - case 'posterior median' - parameters = get_posterior_parameters('median'); - case 'prior mode' - parameters = bayestopt_.p5(:); - case 'prior mean' - parameters = bayestopt_.p1; - otherwise - disp('eval_likelihood:: If the input argument is a string, then it has to be equal to:') - disp(' ''posterior mode'', ') - disp(' ''posterior mean'', ') - disp(' ''posterior median'', ') - disp(' ''prior mode'' or') - disp(' ''prior mean''.') - error +end + +if isempty(load_data) + % Get the data. + n_varobs = size(options_.varobs,1); + rawdata = read_variables(options_.datafile,options_.varobs,[],options_.xls_sheet,options_.xls_range); + options_ = set_default_option(options_,'nobs',size(rawdata,1)-options_.first_obs+1); + gend = options_.nobs; + rawdata = rawdata(options_.first_obs:options_.first_obs+gend-1,:); + % Transform the data. + if options_.loglinear + if ~options_.logdata + rawdata = log(rawdata); end end - - if isempty(load_data) - % Get the data. - n_varobs = size(options_.varobs,1); - rawdata = read_variables(options_.datafile,options_.varobs,[],options_.xls_sheet,options_.xls_range); - options_ = set_default_option(options_,'nobs',size(rawdata,1)-options_.first_obs+1); - gend = options_.nobs; - rawdata = rawdata(options_.first_obs:options_.first_obs+gend-1,:); - % Transform the data. - if options_.loglinear - if ~options_.logdata - rawdata = log(rawdata); + % Test if the data set is real. + if ~isreal(rawdata) + error('There are complex values in the data! Probably a wrong transformation') + end + % Detrend the data. + options_.missing_data = any(any(isnan(rawdata))); + if options_.prefilter == 1 + if options_.missing_data + bayestopt_.mean_varobs = zeros(n_varobs,1); + for variable=1:n_varobs + rdx = find(~isnan(rawdata(:,variable))); + m = mean(rawdata(rdx,variable)); + rawdata(rdx,variable) = rawdata(rdx,variable)-m; + bayestopt_.mean_varobs(variable) = m; end + else + bayestopt_.mean_varobs = mean(rawdata,1)'; + rawdata = rawdata-repmat(bayestopt_.mean_varobs',gend,1); end - % Test if the data set is real. - if ~isreal(rawdata) - error('There are complex values in the data! Probably a wrong transformation') - end - % Detrend the data. - options_.missing_data = any(any(isnan(rawdata))); - if options_.prefilter == 1 - if options_.missing_data - bayestopt_.mean_varobs = zeros(n_varobs,1); - for variable=1:n_varobs - rdx = find(~isnan(rawdata(:,variable))); - m = mean(rawdata(rdx,variable)); - rawdata(rdx,variable) = rawdata(rdx,variable)-m; - bayestopt_.mean_varobs(variable) = m; - end + end + data = transpose(rawdata); + % Handle the missing observations. + [data_index,number_of_observations,no_more_missing_observations] = describe_missing_data(data,gend,n_varobs); + missing_value = ~(number_of_observations == gend*n_varobs); + % Determine if a constant is needed. + if options_.steadystate_flag% if the *_steadystate.m file is provided. + [ys,tchek] = feval([M_.fname '_steadystate'],... + [zeros(M_.exo_nbr,1);... + oo_.exo_det_steady_state]); + if size(ys,1) < M_.endo_nbr + if length(M_.aux_vars) > 0 + ys = add_auxiliary_variables_to_steadystate(ys,M_.aux_vars,... + M_.fname,... + zeros(M_.exo_nbr,1),... + oo_.exo_det_steady_state,... + M_.params); else - bayestopt_.mean_varobs = mean(rawdata,1)'; - rawdata = rawdata-repmat(bayestopt_.mean_varobs',gend,1); + error([M_.fname '_steadystate.m doesn''t match the model']); end end - data = transpose(rawdata); - % Handle the missing observations. - [data_index,number_of_observations,no_more_missing_observations] = describe_missing_data(data,gend,n_varobs); - missing_value = ~(number_of_observations == gend*n_varobs); - % Determine if a constant is needed. - if options_.steadystate_flag% if the *_steadystate.m file is provided. - [ys,tchek] = feval([M_.fname '_steadystate'],... - [zeros(M_.exo_nbr,1);... - oo_.exo_det_steady_state]); - if size(ys,1) < M_.endo_nbr - if length(M_.aux_vars) > 0 - ys = add_auxiliary_variables_to_steadystate(ys,M_.aux_vars,... - M_.fname,... - zeros(M_.exo_nbr,1),... - oo_.exo_det_steady_state,... - M_.params); - else - error([M_.fname '_steadystate.m doesn''t match the model']); - end - end - oo_.steady_state = ys; - else% if the steady state file is not provided. - [dd,info] = resol(oo_.steady_state,0); - oo_.steady_state = dd.ys; clear('dd'); - end - if all(abs(oo_.steady_state(bayestopt_.mfys))<1e-9) - options_.noconstant = 1; - else - options_.noconstant = 0; - end - load_data = 1; + oo_.steady_state = ys; + else% if the steady state file is not provided. + [dd,info] = resol(oo_.steady_state,0); + oo_.steady_state = dd.ys; clear('dd'); + end + if all(abs(oo_.steady_state(bayestopt_.mfys))<1e-9) + options_.noconstant = 1; + else + options_.noconstant = 0; end - - pshape_original = bayestopt_.pshape; - bayestopt_.pshape = Inf(size(bayestopt_.pshape)); - clear('priordens')% - - llik = -DsgeLikelihood(parameters,gend,data,data_index,number_of_observations,no_more_missing_observations); - - bayestopt_.pshape = pshape_original; \ No newline at end of file + load_data = 1; +end + +pshape_original = bayestopt_.pshape; +bayestopt_.pshape = Inf(size(bayestopt_.pshape)); +clear('priordens')% + +llik = -DsgeLikelihood(parameters,gend,data,data_index,number_of_observations,no_more_missing_observations); + +bayestopt_.pshape = pshape_original; \ No newline at end of file diff --git a/matlab/evaluate_posterior_kernel.m b/matlab/evaluate_posterior_kernel.m index c3eb15983d..96ccac8d5d 100644 --- a/matlab/evaluate_posterior_kernel.m +++ b/matlab/evaluate_posterior_kernel.m @@ -33,9 +33,9 @@ function lpkern = evaluate_posterior_kernel(parameters,llik) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - [ldens,parameters] = evaluate_prior(parameters); - if nargin==1 - llik = evaluate_likelihood(parameters); - end - lpkern = ldens+llik; \ No newline at end of file + +[ldens,parameters] = evaluate_prior(parameters); +if nargin==1 + llik = evaluate_likelihood(parameters); +end +lpkern = ldens+llik; \ No newline at end of file diff --git a/matlab/evaluate_prior.m b/matlab/evaluate_prior.m index 6319eb17d5..db24e28ac2 100644 --- a/matlab/evaluate_prior.m +++ b/matlab/evaluate_prior.m @@ -32,34 +32,34 @@ function [ldens,parameters] = evaluate_prior(parameters) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - global bayestopt_ - - if nargin==0 - parameters = 'posterior mode'; - end - - if ischar(parameters) - switch parameters - case 'posterior mode' - parameters = get_posterior_parameters('mode'); - case 'posterior mean' - parameters = get_posterior_parameters('mean'); - case 'posterior median' - parameters = get_posterior_parameters('median'); - case 'prior mode' - parameters = bayestopt_.p5(:); - case 'prior mean' - parameters = bayestopt_.p1; - otherwise - disp('eval_prior:: If the input argument is a string, then it has to be equal to:') - disp(' ''posterior mode'', ') - disp(' ''posterior mean'', ') - disp(' ''posterior median'', ') - disp(' ''prior mode'' or') - disp(' ''prior mean''.') - error - end + +global bayestopt_ + +if nargin==0 + parameters = 'posterior mode'; +end + +if ischar(parameters) + switch parameters + case 'posterior mode' + parameters = get_posterior_parameters('mode'); + case 'posterior mean' + parameters = get_posterior_parameters('mean'); + case 'posterior median' + parameters = get_posterior_parameters('median'); + case 'prior mode' + parameters = bayestopt_.p5(:); + case 'prior mean' + parameters = bayestopt_.p1; + otherwise + disp('eval_prior:: If the input argument is a string, then it has to be equal to:') + disp(' ''posterior mode'', ') + disp(' ''posterior mean'', ') + disp(' ''posterior median'', ') + disp(' ''prior mode'' or') + disp(' ''prior mean''.') + error end - clear('priordens'); - ldens = priordens(parameters, bayestopt_.pshape, bayestopt_.p6, bayestopt_.p7, bayestopt_.p3, bayestopt_.p4); \ No newline at end of file +end +clear('priordens'); +ldens = priordens(parameters, bayestopt_.pshape, bayestopt_.p6, bayestopt_.p7, bayestopt_.p3, bayestopt_.p4); \ No newline at end of file diff --git a/matlab/extended_path.m b/matlab/extended_path.m index 2506b823df..d9ee33f84b 100644 --- a/matlab/extended_path.m +++ b/matlab/extended_path.m @@ -1,136 +1,136 @@ function time_series = extended_path(initial_conditions,sample_size,init) % Stochastic simulation of a non linear DSGE model using the Extended Path method (Fair and Taylor 1983). A time - % series of size T is obtained by solving T perfect foresight models. - % - % INPUTS - % o initial_conditions [double] m*nlags array, where m is the number of endogenous variables in the model and - % nlags is the maximum number of lags. - % o sample_size [integer] scalar, size of the sample to be simulated. - % - % OUTPUTS - % o time_series [double] m*sample_size array, the simulations. - % - % ALGORITHM - % - % SPECIAL REQUIREMENTS - - % Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. - global M_ oo_ options_ - - % Set default initial conditions. - if isempty(initial_conditions) - initial_conditions = repmat(oo_.steady_state,1,M_.maximum_lag); - end - - % Copy sample_size to periods. - options_.periods = sample_size; - - % Initialize the exogenous variables. - make_ex_; - - % Initialize the endogenous variables. - make_y_; - - % Initialize the output array. - time_series = NaN(M_.endo_nbr,sample_size+1); - - % Set the covariance matrix of the structural innovations. - variances = diag(M_.Sigma_e); - positive_var_indx = find(variances>0); - covariance_matrix = M_.Sigma_e(positive_var_indx,positive_var_indx); - number_of_structural_innovations = length(covariance_matrix); - covariance_matrix_upper_cholesky = chol(covariance_matrix); - - tdx = M_.maximum_lag+1; - norme = 0; +% series of size T is obtained by solving T perfect foresight models. +% +% INPUTS +% o initial_conditions [double] m*nlags array, where m is the number of endogenous variables in the model and +% nlags is the maximum number of lags. +% o sample_size [integer] scalar, size of the sample to be simulated. +% +% OUTPUTS +% o time_series [double] m*sample_size array, the simulations. +% +% ALGORITHM +% +% SPECIAL REQUIREMENTS + +% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. +global M_ oo_ options_ + +% Set default initial conditions. +if isempty(initial_conditions) + initial_conditions = repmat(oo_.steady_state,1,M_.maximum_lag); +end + +% Copy sample_size to periods. +options_.periods = sample_size; + +% Initialize the exogenous variables. +make_ex_; + +% Initialize the endogenous variables. +make_y_; + +% Initialize the output array. +time_series = NaN(M_.endo_nbr,sample_size+1); + +% Set the covariance matrix of the structural innovations. +variances = diag(M_.Sigma_e); +positive_var_indx = find(variances>0); +covariance_matrix = M_.Sigma_e(positive_var_indx,positive_var_indx); +number_of_structural_innovations = length(covariance_matrix); +covariance_matrix_upper_cholesky = chol(covariance_matrix); + +tdx = M_.maximum_lag+1; +norme = 0; + +% Set verbose option +verbose = 0; + +for t=1:sample_size + shocks = exp(randn(1,number_of_structural_innovations)*covariance_matrix_upper_cholesky-.5*variances(positive_var_indx)'); + oo_.exo_simul(tdx,positive_var_indx) = shocks; + info = perfect_foresight_simulation; + time = info.time; + if verbose + t + info + end + if ~info.convergence + info = homotopic_steps(tdx,positive_var_indx,shocks,norme,.2); + if verbose + norme + info + end + else + norme = sqrt(sum((shocks-1).^2,2)); + end + if ~info.convergence + error('I am not able to simulate this model!') + end + info.time = info.time+time; + time_series(:,t+1) = oo_.endo_simul(:,tdx); + oo_.endo_simul(:,1:end-1) = oo_.endo_simul(:,2:end); + oo_.endo_simul(:,end) = oo_.steady_state; +end + - % Set verbose option - verbose = 0; - - for t=1:sample_size - shocks = exp(randn(1,number_of_structural_innovations)*covariance_matrix_upper_cholesky-.5*variances(positive_var_indx)'); - oo_.exo_simul(tdx,positive_var_indx) = shocks; - info = perfect_foresight_simulation; - time = info.time; - if verbose - t - info - end - if ~info.convergence - info = homotopic_steps(tdx,positive_var_indx,shocks,norme,.2); - if verbose - norme - info - end - else - norme = sqrt(sum((shocks-1).^2,2)); - end - if ~info.convergence - error('I am not able to simulate this model!') - end - info.time = info.time+time; - time_series(:,t+1) = oo_.endo_simul(:,tdx); - oo_.endo_simul(:,1:end-1) = oo_.endo_simul(:,2:end); - oo_.endo_simul(:,end) = oo_.steady_state; - end - - function info = homotopic_steps(tdx,positive_var_indx,shocks,init_weight,step) - global oo_ - weight = init_weight; - verbose = 0; - iter = 0; - time = 0; - reduce_step = 0; - while iter<=100 && weight<=1 - iter = iter+1; - old_weight = weight; - weight = weight+step; - oo_.exo_simul(tdx,positive_var_indx) = weight*shocks+(1-weight); - info = perfect_foresight_simulation; - time = time+info.time; +global oo_ +weight = init_weight; +verbose = 0; +iter = 0; +time = 0; +reduce_step = 0; +while iter<=100 && weight<=1 + iter = iter+1; + old_weight = weight; + weight = weight+step; + oo_.exo_simul(tdx,positive_var_indx) = weight*shocks+(1-weight); + info = perfect_foresight_simulation; + time = time+info.time; + if verbose + [iter,step] + [info.iterations.time,info.iterations.error] + end + if ~info.convergence if verbose - [iter,step] - [info.iterations.time,info.iterations.error] + disp('Reduce step size!') end - if ~info.convergence + reduce_step = 1; + break + else + if length(info.iterations.error)<5 if verbose - disp('Reduce step size!') - end - reduce_step = 1; - break - else - if length(info.iterations.error)<5 - if verbose - disp('Increase step size!') - end - step = step*1.5; + disp('Increase step size!') end + step = step*1.5; end end - if reduce_step - step=step/1.5; - info = homotopic_steps(tdx,positive_var_indx,shocks,old_weight,step); - time = time+info.time; - elseif weight<1 && iter<100 - oo_.exo_simul(tdx,positive_var_indx) = shocks; - info = perfect_foresight_simulation; - info.time = info.time+time; - else - info.time = time; - end \ No newline at end of file +end +if reduce_step + step=step/1.5; + info = homotopic_steps(tdx,positive_var_indx,shocks,old_weight,step); + time = time+info.time; +elseif weight<1 && iter<100 + oo_.exo_simul(tdx,positive_var_indx) = shocks; + info = perfect_foresight_simulation; + info.time = info.time+time; +else + info.time = time; +end \ No newline at end of file diff --git a/matlab/fMessageStatus.m b/matlab/fMessageStatus.m index c11f0d23ab..ca7e4c9b31 100644 --- a/matlab/fMessageStatus.m +++ b/matlab/fMessageStatus.m @@ -1,33 +1,33 @@ -function fMessageStatus(prtfrc, njob, waitbarString, waitbarTitle, Parallel, MasterName, DyMo) - -% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. - -global funcName - -if nargin<5, - Parallel.Local=1; -end - -save(['comp_status_',funcName,int2str(njob),'.mat'],'prtfrc','njob','waitbarString','waitbarTitle'); -if Parallel.Local==0, - if isunix, - system(['scp comp_status_',funcName,int2str(njob),'.mat ',Parallel.user,'@',MasterName,':',DyMo]); - else - copyfile(['comp_status_',funcName,int2str(njob),'.mat'],['\\',MasterName,'\',DyMo(1),'$\',DyMo(4:end),'\']); - end -end +function fMessageStatus(prtfrc, njob, waitbarString, waitbarTitle, Parallel, MasterName, DyMo) + +% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. + +global funcName + +if nargin<5, + Parallel.Local=1; +end + +save(['comp_status_',funcName,int2str(njob),'.mat'],'prtfrc','njob','waitbarString','waitbarTitle'); +if Parallel.Local==0, + if isunix, + system(['scp comp_status_',funcName,int2str(njob),'.mat ',Parallel.user,'@',MasterName,':',DyMo]); + else + copyfile(['comp_status_',funcName,int2str(njob),'.mat'],['\\',MasterName,'\',DyMo(1),'$\',DyMo(4:end),'\']); + end +end diff --git a/matlab/fParallel.m b/matlab/fParallel.m index 869eca22be..c8d3200201 100644 --- a/matlab/fParallel.m +++ b/matlab/fParallel.m @@ -1,116 +1,116 @@ -function fParallel(fblck,nblck,whoiam,ThisMatlab,fname) -% In a parallelization context, this function is launched on slave -% machines, and acts as a wrapper around the function containing the -% computing task itself. -% -% INPUTS -% fblck [int] index number of the first thread to run in this -% MATLAB instance -% nblck [int] index number of the first thread to run in this -% MATLAB instance -% whoiam [int] index number of this CPU among all CPUs in the -% cluster -% ThisMatlab [int] index number of this slave machine in the cluster -% (entry in options_.parallel) -% fname [string] function to be run, containing the computing task - -% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. - -global funcName - -funcName=fname; - -warning off; -diary off; - -delete( [fname,'_',int2str(whoiam),'.log']); - -diary( [fname,'_',int2str(whoiam),'.log']); - - -% configure dynare environment -dynareroot = dynare_config(); - -% Load input data -load( [fname,'_input']) - -if exist('fGlobalVar'), - globalVars = fieldnames(fGlobalVar); - for j=1:length(globalVars), - eval(['global ',globalVars{j},';']) - end - struct2local(fGlobalVar); -end - -% On UNIX, mount the master working directory through SSH FS -if isunix & Parallel(ThisMatlab).Local==0, - system(['mkdir ~/MasterRemoteMirror_',fname,'_',int2str(whoiam)]); - system(['sshfs ',Parallel(ThisMatlab).user,'@',fInputVar.MasterName,':/',fInputVar.DyMo,' ~/MasterRemoteMirror_',fname,'_',int2str(whoiam)]); -end - -% Special hack for MH directory -if isfield(fInputVar,'MhDirectoryName') & Parallel(ThisMatlab).Local==0, - if isunix, - fInputVar.MhDirectoryName = ['~/MasterRemoteMirror_',fname,'_',int2str(whoiam),'/',fInputVar.MhDirectoryName]; - else - fInputVar.MhDirectoryName = ['\\',fInputVar.MasterName,'\',fInputVar.DyMo(1),'$\',fInputVar.DyMo(4:end),'\',fInputVar.MhDirectoryName]; - end -end - -fInputVar.Parallel = Parallel; -% Launch the routine to be run in parallel -tic, -fOutputVar = feval(fname, fInputVar ,fblck, nblck, whoiam, ThisMatlab); -toc, -if isfield(fOutputVar,'OutputFileName'), - OutputFileName = fOutputVar.OutputFileName; -else - OutputFileName = ''; -end - -if(whoiam) - - % Save the output result - save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' ) - - % Inform the master that the job is finished, and transfer the output data - if Parallel(ThisMatlab).Local - delete(['P_',fname,'_',int2str(whoiam),'End.txt']); - else - if isunix, - for j=1:size(OutputFileName,1), - system(['scp ',OutputFileName{j,1},OutputFileName{j,2},' ',Parallel(ThisMatlab).user,'@',fInputVar.MasterName,':',fInputVar.DyMo,'/',OutputFileName{j,1}]); - end - system(['scp ',fname,'_output_',int2str(whoiam),'.mat ',Parallel(ThisMatlab).user,'@',fInputVar.MasterName,':',fInputVar.DyMo]); - system(['ssh ',Parallel(ThisMatlab).user,'@',fInputVar.MasterName,' rm -f ',fInputVar.DyMo,'/P_',fname,'_',int2str(whoiam),'End.txt']); - system(['fusermount -u ~/MasterRemoteMirror_',fname,'_',int2str(whoiam)]); - system(['rm -r ~/MasterRemoteMirror_',fname,'_',int2str(whoiam)]); - else - for j=1:size(OutputFileName,1), - copyfile([OutputFileName{j,1},OutputFileName{j,2}],['\\',fInputVar.MasterName,'\',fInputVar.DyMo(1),'$\',fInputVar.DyMo(4:end),'\',OutputFileName{j,1}]) - end - copyfile([fname,'_output_',int2str(whoiam),'.mat'],['\\',fInputVar.MasterName,'\',fInputVar.DyMo(1),'$\',fInputVar.DyMo(4:end)]); - delete(['\\',fInputVar.MasterName,'\',fInputVar.DyMo(1),'$\',fInputVar.DyMo(4:end),'\P_',fname,'_',int2str(whoiam),'End.txt']); - end - end -end - -disp(['fParallel ',int2str(whoiam),' completed.']) -diary off; - -exit; +function fParallel(fblck,nblck,whoiam,ThisMatlab,fname) +% In a parallelization context, this function is launched on slave +% machines, and acts as a wrapper around the function containing the +% computing task itself. +% +% INPUTS +% fblck [int] index number of the first thread to run in this +% MATLAB instance +% nblck [int] index number of the first thread to run in this +% MATLAB instance +% whoiam [int] index number of this CPU among all CPUs in the +% cluster +% ThisMatlab [int] index number of this slave machine in the cluster +% (entry in options_.parallel) +% fname [string] function to be run, containing the computing task + +% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. + +global funcName + +funcName=fname; + +warning off; +diary off; + +delete( [fname,'_',int2str(whoiam),'.log']); + +diary( [fname,'_',int2str(whoiam),'.log']); + + +% configure dynare environment +dynareroot = dynare_config(); + +% Load input data +load( [fname,'_input']) + +if exist('fGlobalVar'), + globalVars = fieldnames(fGlobalVar); + for j=1:length(globalVars), + eval(['global ',globalVars{j},';']) + end + struct2local(fGlobalVar); +end + +% On UNIX, mount the master working directory through SSH FS +if isunix & Parallel(ThisMatlab).Local==0, + system(['mkdir ~/MasterRemoteMirror_',fname,'_',int2str(whoiam)]); + system(['sshfs ',Parallel(ThisMatlab).user,'@',fInputVar.MasterName,':/',fInputVar.DyMo,' ~/MasterRemoteMirror_',fname,'_',int2str(whoiam)]); +end + +% Special hack for MH directory +if isfield(fInputVar,'MhDirectoryName') & Parallel(ThisMatlab).Local==0, + if isunix, + fInputVar.MhDirectoryName = ['~/MasterRemoteMirror_',fname,'_',int2str(whoiam),'/',fInputVar.MhDirectoryName]; + else + fInputVar.MhDirectoryName = ['\\',fInputVar.MasterName,'\',fInputVar.DyMo(1),'$\',fInputVar.DyMo(4:end),'\',fInputVar.MhDirectoryName]; + end +end + +fInputVar.Parallel = Parallel; +% Launch the routine to be run in parallel +tic, +fOutputVar = feval(fname, fInputVar ,fblck, nblck, whoiam, ThisMatlab); +toc, +if isfield(fOutputVar,'OutputFileName'), + OutputFileName = fOutputVar.OutputFileName; +else + OutputFileName = ''; +end + +if(whoiam) + + % Save the output result + save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' ) + + % Inform the master that the job is finished, and transfer the output data + if Parallel(ThisMatlab).Local + delete(['P_',fname,'_',int2str(whoiam),'End.txt']); + else + if isunix, + for j=1:size(OutputFileName,1), + system(['scp ',OutputFileName{j,1},OutputFileName{j,2},' ',Parallel(ThisMatlab).user,'@',fInputVar.MasterName,':',fInputVar.DyMo,'/',OutputFileName{j,1}]); + end + system(['scp ',fname,'_output_',int2str(whoiam),'.mat ',Parallel(ThisMatlab).user,'@',fInputVar.MasterName,':',fInputVar.DyMo]); + system(['ssh ',Parallel(ThisMatlab).user,'@',fInputVar.MasterName,' rm -f ',fInputVar.DyMo,'/P_',fname,'_',int2str(whoiam),'End.txt']); + system(['fusermount -u ~/MasterRemoteMirror_',fname,'_',int2str(whoiam)]); + system(['rm -r ~/MasterRemoteMirror_',fname,'_',int2str(whoiam)]); + else + for j=1:size(OutputFileName,1), + copyfile([OutputFileName{j,1},OutputFileName{j,2}],['\\',fInputVar.MasterName,'\',fInputVar.DyMo(1),'$\',fInputVar.DyMo(4:end),'\',OutputFileName{j,1}]) + end + copyfile([fname,'_output_',int2str(whoiam),'.mat'],['\\',fInputVar.MasterName,'\',fInputVar.DyMo(1),'$\',fInputVar.DyMo(4:end)]); + delete(['\\',fInputVar.MasterName,'\',fInputVar.DyMo(1),'$\',fInputVar.DyMo(4:end),'\P_',fname,'_',int2str(whoiam),'End.txt']); + end + end +end + +disp(['fParallel ',int2str(whoiam),' completed.']) +diary off; + +exit; diff --git a/matlab/f_var.m b/matlab/f_var.m index e3debafd99..5b5138a7cc 100644 --- a/matlab/f_var.m +++ b/matlab/f_var.m @@ -17,6 +17,6 @@ function b=f_var(x,a,nx) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - x=reshape(x,nx,nx); - b=x-a*x*a'; - b=b(:); \ No newline at end of file +x=reshape(x,nx,nx); +b=x-a*x*a'; +b=b(:); \ No newline at end of file diff --git a/matlab/ffill.m b/matlab/ffill.m index 646f2f2576..a933bd58ea 100644 --- a/matlab/ffill.m +++ b/matlab/ffill.m @@ -35,19 +35,19 @@ function [a,b] = ffill(x,ixc,y) xc = size(x,1) ; if isempty(y) - b = [ixc; 0]; - a = [x zeros(size(x,1),1)]; + b = [ixc; 0]; + a = [x zeros(size(x,1),1)]; else - yc = size(y,1) ; - b = [ixc;yc] ; + yc = size(y,1) ; + b = [ixc;yc] ; - if xc > yc - a = [x [y;zeros(xc-yc,size(y,2))]] ; - elseif yc > xc - a = [[x;zeros(yc-xc,size(x,2))] y] ; - else - a = [x y] ; - end + if xc > yc + a = [x [y;zeros(xc-yc,size(y,2))]] ; + elseif yc > xc + a = [[x;zeros(yc-xc,size(x,2))] y] ; + else + a = [x y] ; + end end diff --git a/matlab/forcst.m b/matlab/forcst.m index 29726d62f2..f996f785bb 100644 --- a/matlab/forcst.m +++ b/matlab/forcst.m @@ -33,56 +33,55 @@ function [yf,int_width]=forcst(dr,y0,horizon,var_list) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - global M_ oo_ options_ - - make_ex_; - yf = simult_(y0,dr,zeros(horizon,M_.exo_nbr),1); - nstatic = dr.nstatic; - npred = dr.npred; - nc = size(dr.ghx,2); - endo_nbr = M_.endo_nbr; - inv_order_var = dr.inv_order_var; - [A,B] = kalman_transition_matrix(dr,nstatic+(1:npred),1:nc,dr.transition_auxiliary_variables,M_.exo_nbr); - - if size(var_list,1) == 0 - var_list = M_.endo_names(1:M_.orig_endo_nbr,:); - end - nvar = size(var_list,1); - ivar=zeros(nvar,1); - for i=1:nvar - i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact'); - if isempty(i_tmp) - disp(var_list(i,:)); - error (['One of the variable specified does not exist']) ; - else - ivar(i) = i_tmp; - end - end - ghx1 = dr.ghx(inv_order_var(ivar),:); - ghu1 = dr.ghu(inv_order_var(ivar),:); +global M_ oo_ options_ + +make_ex_; +yf = simult_(y0,dr,zeros(horizon,M_.exo_nbr),1); +nstatic = dr.nstatic; +npred = dr.npred; +nc = size(dr.ghx,2); +endo_nbr = M_.endo_nbr; +inv_order_var = dr.inv_order_var; +[A,B] = kalman_transition_matrix(dr,nstatic+(1:npred),1:nc,dr.transition_auxiliary_variables,M_.exo_nbr); - sigma_u = B*M_.Sigma_e*B'; - sigma_u1 = ghu1*M_.Sigma_e*ghu1'; - sigma_y = 0; - - for i=1:horizon - sigma_y1 = ghx1*sigma_y*ghx1'+sigma_u1; - var_yf(i,:) = diag(sigma_y1)'; - if i == horizon - break - end - sigma_u = A*sigma_u*A'; - sigma_y = sigma_y+sigma_u; +if size(var_list,1) == 0 + var_list = M_.endo_names(1:M_.orig_endo_nbr,:); +end +nvar = size(var_list,1); +ivar=zeros(nvar,1); +for i=1:nvar + i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact'); + if isempty(i_tmp) + disp(var_list(i,:)); + error (['One of the variable specified does not exist']) ; + else + ivar(i) = i_tmp; end +end + +ghx1 = dr.ghx(inv_order_var(ivar),:); +ghu1 = dr.ghu(inv_order_var(ivar),:); - fact = norminv((1-options_.conf_sig)/2,0,1); - - int_width = zeros(horizon,M_.endo_nbr); - for i=1:nvar - int_width(:,i) = fact*sqrt(var_yf(:,i)); +sigma_u = B*M_.Sigma_e*B'; +sigma_u1 = ghu1*M_.Sigma_e*ghu1'; +sigma_y = 0; + +for i=1:horizon + sigma_y1 = ghx1*sigma_y*ghx1'+sigma_u1; + var_yf(i,:) = diag(sigma_y1)'; + if i == horizon + break end + sigma_u = A*sigma_u*A'; + sigma_y = sigma_y+sigma_u; +end + +fact = norminv((1-options_.conf_sig)/2,0,1); + +int_width = zeros(horizon,M_.endo_nbr); +for i=1:nvar + int_width(:,i) = fact*sqrt(var_yf(:,i)); +end - yf = yf(ivar,:); - \ No newline at end of file +yf = yf(ivar,:); diff --git a/matlab/forcst2.m b/matlab/forcst2.m index 0abfcbd863..460c31b87e 100644 --- a/matlab/forcst2.m +++ b/matlab/forcst2.m @@ -1,60 +1,60 @@ -function yf=forcst2(y0,horizon,dr,n) - -% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. - - global M_ options_ - - Sigma_e_ = M_.Sigma_e; - endo_nbr = M_.endo_nbr; - exo_nbr = M_.exo_nbr; - ykmin_ = M_.maximum_endo_lag; - - order = options_.order; - seed = options_.simul_seed; - - k1 = [ykmin_:-1:1]; - k2 = dr.kstate(find(dr.kstate(:,2) <= ykmin_+1),[1 2]); - k2 = k2(:,1)+(ykmin_+1-k2(:,2))*endo_nbr; - - it_ = ykmin_ + 1 ; - - % eliminate shocks with 0 variance - i_exo_var = setdiff([1:exo_nbr],find(diag(Sigma_e_) == 0)); - nxs = length(i_exo_var); - - chol_S = chol(Sigma_e_(i_exo_var,i_exo_var)); - - if ~isempty(Sigma_e_) - e = randn(nxs,n,horizon); - end - - B1 = dr.ghu(:,i_exo_var)*chol_S'; - - yf = zeros(endo_nbr,horizon+ykmin_,n); - yf(:,1:ykmin_,:,:) = repmat(y0,[1,1,n]); - - j = ykmin_*endo_nbr; - for i=ykmin_+(1:horizon) - tempx1 = reshape(yf(:,k1,:),[j,n]); - tempx = tempx1(k2,:); - yf(:,i,:) = dr.ghx*tempx+B1*squeeze(e(:,:,i-ykmin_)); - k1 = k1+1; - end - - yf(dr.order_var,:,:) = yf; - yf=permute(yf,[2 1 3]); +function yf=forcst2(y0,horizon,dr,n) + +% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. + +global M_ options_ + +Sigma_e_ = M_.Sigma_e; +endo_nbr = M_.endo_nbr; +exo_nbr = M_.exo_nbr; +ykmin_ = M_.maximum_endo_lag; + +order = options_.order; +seed = options_.simul_seed; + +k1 = [ykmin_:-1:1]; +k2 = dr.kstate(find(dr.kstate(:,2) <= ykmin_+1),[1 2]); +k2 = k2(:,1)+(ykmin_+1-k2(:,2))*endo_nbr; + +it_ = ykmin_ + 1 ; + +% eliminate shocks with 0 variance +i_exo_var = setdiff([1:exo_nbr],find(diag(Sigma_e_) == 0)); +nxs = length(i_exo_var); + +chol_S = chol(Sigma_e_(i_exo_var,i_exo_var)); + +if ~isempty(Sigma_e_) + e = randn(nxs,n,horizon); +end + +B1 = dr.ghu(:,i_exo_var)*chol_S'; + +yf = zeros(endo_nbr,horizon+ykmin_,n); +yf(:,1:ykmin_,:,:) = repmat(y0,[1,1,n]); + +j = ykmin_*endo_nbr; +for i=ykmin_+(1:horizon) + tempx1 = reshape(yf(:,k1,:),[j,n]); + tempx = tempx1(k2,:); + yf(:,i,:) = dr.ghx*tempx+B1*squeeze(e(:,:,i-ykmin_)); + k1 = k1+1; +end + +yf(dr.order_var,:,:) = yf; +yf=permute(yf,[2 1 3]); diff --git a/matlab/forcst2a.m b/matlab/forcst2a.m index a0d9133065..a3bbf66fc2 100644 --- a/matlab/forcst2a.m +++ b/matlab/forcst2a.m @@ -1,46 +1,46 @@ -function yf=forcst2a(y0,dr,e) - -% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. - - global M_ options_ - - Sigma_e_ = M_.Sigma_e; - endo_nbr = M_.endo_nbr; - exo_nbr = M_.exo_nbr; - ykmin_ = M_.maximum_endo_lag; - - horizon = size(e,1); - options_ = set_default_option(options_,'simul_seed',0); - order = options_.order; - - k1 = [ykmin_:-1:1]; - k2 = dr.kstate(find(dr.kstate(:,2) <= ykmin_+1),[1 2]); - k2 = k2(:,1)+(ykmin_+1-k2(:,2))*endo_nbr; - - yf = zeros(horizon+ykmin_,endo_nbr); - yf(1:ykmin_,:) = y0'; - - j = ykmin_*endo_nbr; - for i=ykmin_+(1:horizon) - tempx = yf(k1,:)'; - yf(i,:) = tempx(k2)'*dr.ghx'; - k1 = k1+1; - end - - yf(:,dr.order_var) = yf; - +function yf=forcst2a(y0,dr,e) + +% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. + +global M_ options_ + +Sigma_e_ = M_.Sigma_e; +endo_nbr = M_.endo_nbr; +exo_nbr = M_.exo_nbr; +ykmin_ = M_.maximum_endo_lag; + +horizon = size(e,1); +options_ = set_default_option(options_,'simul_seed',0); +order = options_.order; + +k1 = [ykmin_:-1:1]; +k2 = dr.kstate(find(dr.kstate(:,2) <= ykmin_+1),[1 2]); +k2 = k2(:,1)+(ykmin_+1-k2(:,2))*endo_nbr; + +yf = zeros(horizon+ykmin_,endo_nbr); +yf(1:ykmin_,:) = y0'; + +j = ykmin_*endo_nbr; +for i=ykmin_+(1:horizon) + tempx = yf(k1,:)'; + yf(i,:) = tempx(k2)'*dr.ghx'; + k1 = k1+1; +end + +yf(:,dr.order_var) = yf; + diff --git a/matlab/forcst_unc.m b/matlab/forcst_unc.m index a3d2880689..94f72750f2 100644 --- a/matlab/forcst_unc.m +++ b/matlab/forcst_unc.m @@ -1,153 +1,153 @@ -function forcst_unc(y0,var_list) -% function [mean,intval1,intval2]=forcst_unc(y0,var_list) -% computes forecasts with parameter uncertainty -% -% INPUTS -% y0: matrix of initial values -% var_list: list of variables to be forecasted -% -% OUTPUTS -% none -% -% ALGORITHM -% uses antithetic draws for the shocks -% -% SPECIAL REQUIREMENTS -% None. - -% Copyright (C) 2006-2009 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 <http://www.gnu.org/licenses/>. - - global M_ options_ oo_ estim_params_ bayestopt_ - - % setting up estim_params_ - [xparam1,estim_params_,bayestopt_,lb,ub] = set_prior(estim_params_,M_); - - options_.TeX = 0; - options_.nograph = 0; - plot_priors(bayestopt_,M_,options_); - - % workspace initialization - if isempty(var_list) - var_list = M_.endo_names(1:M_.orig_endo_nbr,:); - end - n = size(var_list,1); - - periods = options_.forecast; - exo_nbr = M_.exo_nbr; - replic = options_.replic; - order = options_.order; - maximum_lag = M_.maximum_lag; - % params = prior_draw(1); - params = rndprior(bayestopt_); - set_parameters(params); - % eliminate shocks with 0 variance - i_exo_var = setdiff([1:exo_nbr],find(diag(M_.Sigma_e) == 0)); - nx = length(i_exo_var); - - ex0 = zeros(periods,exo_nbr); - yf1 = zeros(periods+M_.maximum_lag,n,replic); - - % loops on parameter values - m1 = 0; - m2 = 0; - for i=1:replic - % draw parameter values from the prior - % params = prior_draw(0); - params = rndprior(bayestopt_); - set_parameters(params); - % solve the model - [dr,info] = resol(oo_.steady_state,0); - % discard problematic cases - if info - continue - end - % compute forecast with zero shocks - m1 = m1+1; - yf1(:,:,m1) = simult_(y0,dr,ex0,order)'; - % compute forecast with antithetic shocks - chol_S = chol(M_.Sigma_e(i_exo_var,i_exo_var)); - ex(:,i_exo_var) = randn(periods,nx)*chol_S; - m2 = m2+1; - yf2(:,:,m2) = simult_(y0,dr,ex,order)'; - m2 = m2+1; - yf2(:,:,m2) = simult_(y0,dr,-ex,order)'; - end - - oo_.forecast.accept_rate = (replic-m1)/replic; - - if options_.noprint == 0 & m1 < replic - disp(' ') - disp(' ') - disp('FORECASTING WITH PARAMETER UNCERTAINTY:') - disp(sprintf(['The model couldn''t be solved for %f%% of the parameter' ... - ' values'],100*oo_.forecast.accept_rate)) - disp(' ') - disp(' ') - end - - % compute moments - yf1 = yf1(:,:,1:m1); - yf2 = yf2(:,:,1:m2); - - yf_mean = mean(yf1,3); - - yf1 = sort(yf1,3); - yf2 = sort(yf2,3); - - sig_lev = options_.conf_sig; - k1 = round((0.5+[-sig_lev, sig_lev]/2)*replic); - % make sure that lower bound is at least the first element - if k1(2) == 0 - k1(2) = 1; - end - k2 = round((1+[-sig_lev, sig_lev])*replic); - % make sure that lower bound is at least the first element - if k2(2) == 0 - k2(2) = 1; - end - - % compute shock uncertainty around forecast with mean prior - set_parameters(bayestopt_.p1); - [dr,info] = resol(oo_.steady_state,0); - [yf3,yf3_intv] = forcst(dr,y0,periods,var_list); - yf3_1 = yf3'-[zeros(maximum_lag,n); yf3_intv]; - yf3_2 = yf3'+[zeros(maximum_lag,n); yf3_intv]; - - % graphs - - dynare_graph_init('Forecasts type I',n,{'b-' 'g-' 'g-' 'r-' 'r-'}); - for i=1:n - dynare_graph([yf_mean(:,i) squeeze(yf1(:,i,k1)) squeeze(yf2(:,i,k2))],... - var_list(i,:)); - end - dynare_graph_close; - - dynare_graph_init('Forecasts type II',n,{'b-' 'k-' 'k-' 'r-' 'r-'}); - for i=1:n - dynare_graph([yf_mean(:,i) yf3_1(:,i) yf3_2(:,i) squeeze(yf2(:,i,k2))],... - var_list(i,:)); - end - dynare_graph_close; - - - % saving results - save_results(yf_mean,'oo_.forecast.mean.',var_list); - save_results(yf1(:,:,k1(1)),'oo_.forecast.HPDinf.',var_list); - save_results(yf1(:,:,k1(2)),'oo_.forecast.HPDsup.',var_list); - save_results(yf2(:,:,k2(1)),'oo_.forecast.HPDTotalinf.',var_list); - save_results(yf2(:,:,k2(2)),'oo_.forecast.HPDTotalsup.',var_list); \ No newline at end of file +function forcst_unc(y0,var_list) +% function [mean,intval1,intval2]=forcst_unc(y0,var_list) +% computes forecasts with parameter uncertainty +% +% INPUTS +% y0: matrix of initial values +% var_list: list of variables to be forecasted +% +% OUTPUTS +% none +% +% ALGORITHM +% uses antithetic draws for the shocks +% +% SPECIAL REQUIREMENTS +% None. + +% Copyright (C) 2006-2009 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 <http://www.gnu.org/licenses/>. + +global M_ options_ oo_ estim_params_ bayestopt_ + +% setting up estim_params_ +[xparam1,estim_params_,bayestopt_,lb,ub] = set_prior(estim_params_,M_); + +options_.TeX = 0; +options_.nograph = 0; +plot_priors(bayestopt_,M_,options_); + +% workspace initialization +if isempty(var_list) + var_list = M_.endo_names(1:M_.orig_endo_nbr,:); +end +n = size(var_list,1); + +periods = options_.forecast; +exo_nbr = M_.exo_nbr; +replic = options_.replic; +order = options_.order; +maximum_lag = M_.maximum_lag; +% params = prior_draw(1); +params = rndprior(bayestopt_); +set_parameters(params); +% eliminate shocks with 0 variance +i_exo_var = setdiff([1:exo_nbr],find(diag(M_.Sigma_e) == 0)); +nx = length(i_exo_var); + +ex0 = zeros(periods,exo_nbr); +yf1 = zeros(periods+M_.maximum_lag,n,replic); + +% loops on parameter values +m1 = 0; +m2 = 0; +for i=1:replic + % draw parameter values from the prior + % params = prior_draw(0); + params = rndprior(bayestopt_); + set_parameters(params); + % solve the model + [dr,info] = resol(oo_.steady_state,0); + % discard problematic cases + if info + continue + end + % compute forecast with zero shocks + m1 = m1+1; + yf1(:,:,m1) = simult_(y0,dr,ex0,order)'; + % compute forecast with antithetic shocks + chol_S = chol(M_.Sigma_e(i_exo_var,i_exo_var)); + ex(:,i_exo_var) = randn(periods,nx)*chol_S; + m2 = m2+1; + yf2(:,:,m2) = simult_(y0,dr,ex,order)'; + m2 = m2+1; + yf2(:,:,m2) = simult_(y0,dr,-ex,order)'; +end + +oo_.forecast.accept_rate = (replic-m1)/replic; + +if options_.noprint == 0 & m1 < replic + disp(' ') + disp(' ') + disp('FORECASTING WITH PARAMETER UNCERTAINTY:') + disp(sprintf(['The model couldn''t be solved for %f%% of the parameter' ... + ' values'],100*oo_.forecast.accept_rate)) + disp(' ') + disp(' ') +end + +% compute moments +yf1 = yf1(:,:,1:m1); +yf2 = yf2(:,:,1:m2); + +yf_mean = mean(yf1,3); + +yf1 = sort(yf1,3); +yf2 = sort(yf2,3); + +sig_lev = options_.conf_sig; +k1 = round((0.5+[-sig_lev, sig_lev]/2)*replic); +% make sure that lower bound is at least the first element +if k1(2) == 0 + k1(2) = 1; +end +k2 = round((1+[-sig_lev, sig_lev])*replic); +% make sure that lower bound is at least the first element +if k2(2) == 0 + k2(2) = 1; +end + +% compute shock uncertainty around forecast with mean prior +set_parameters(bayestopt_.p1); +[dr,info] = resol(oo_.steady_state,0); +[yf3,yf3_intv] = forcst(dr,y0,periods,var_list); +yf3_1 = yf3'-[zeros(maximum_lag,n); yf3_intv]; +yf3_2 = yf3'+[zeros(maximum_lag,n); yf3_intv]; + +% graphs + +dynare_graph_init('Forecasts type I',n,{'b-' 'g-' 'g-' 'r-' 'r-'}); +for i=1:n + dynare_graph([yf_mean(:,i) squeeze(yf1(:,i,k1)) squeeze(yf2(:,i,k2))],... + var_list(i,:)); +end +dynare_graph_close; + +dynare_graph_init('Forecasts type II',n,{'b-' 'k-' 'k-' 'r-' 'r-'}); +for i=1:n + dynare_graph([yf_mean(:,i) yf3_1(:,i) yf3_2(:,i) squeeze(yf2(:,i,k2))],... + var_list(i,:)); +end +dynare_graph_close; + + +% saving results +save_results(yf_mean,'oo_.forecast.mean.',var_list); +save_results(yf1(:,:,k1(1)),'oo_.forecast.HPDinf.',var_list); +save_results(yf1(:,:,k1(2)),'oo_.forecast.HPDsup.',var_list); +save_results(yf2(:,:,k2(1)),'oo_.forecast.HPDTotalinf.',var_list); +save_results(yf2(:,:,k2(2)),'oo_.forecast.HPDTotalsup.',var_list); \ No newline at end of file diff --git a/matlab/forecast.m b/matlab/forecast.m index 109866142f..4580249e4f 100644 --- a/matlab/forecast.m +++ b/matlab/forecast.m @@ -1,142 +1,142 @@ -function info = forecast(var_list,task) -% function forecast(var_list,task) -% computes mean forecast for a given value of the parameters -% computes also confidence band for the forecast -% -% INPUTS -% var_list: list of variables (character matrix) -% task: indicates how to initialize the forecast -% either 'simul' or 'smoother' -% OUTPUTS -% nothing is returned but the procedure saves output -% in oo_.forecast.Mean -% oo_.forecast.HPDinf -% oo_.forecast.HPDsup -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2003-2009 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 <http://www.gnu.org/licenses/>. - - global options_ dr_ oo_ M_ - - info = 0; - - old_options = options_; - - maximum_lag = M_.maximum_lag; - - - endo_names = M_.endo_names; - if isempty(var_list) - var_list = endo_names(1:M_.orig_endo_nbr, :); - end - i_var = []; - for i = 1:size(var_list) - tmp = strmatch(var_list(i,:),endo_names,'exact'); - if isempty(tmp) - error([var_list(i,:) ' isn''t and endogenous variable']) - end - i_var = [i_var; tmp]; - end - - n_var = length(i_var); - - trend = 0; - switch task - case 'simul' - horizon = options_.periods; - if horizon == 0 - horizon = 5; - end - if size(oo_.endo_simul,2) < maximum_lag - y0 = repmat(oo_.steady_state,1,maximum_lag); - else - y0 = oo_.endo_simul(:,1:maximum_lag); - end - case 'smoother' - horizon = options_.forecast; - y_smoothed = oo_.SmoothedVariables; - y0 = zeros(M_.endo_nbr,maximum_lag); - for i = 1:M_.endo_nbr - v_name = deblank(M_.endo_names(i,:)); - y0(i,:) = y_smoothed.(v_name)(end-maximum_lag+1:end)+oo_.dr.ys(i); - end - gend = options_.nobs; - if isfield(oo_.Smoother,'TrendCoeffs') - var_obs = options_.varobs; - endo_names = M_.endo_names; - order_var = oo_.dr.order_var; - i_var_obs = []; - trend_coeffs = []; - for i=1:size(var_obs,1) - tmp = strmatch(var_obs(i,:),endo_names(i_var,:),'exact'); - if ~isempty(tmp) - i_var_obs = [ i_var_obs; tmp]; - trend_coeffs = [trend_coeffs; oo_.Smoother.TrendCoeffs(i)]; - end - end - trend = trend_coeffs*(gend+(1-M_.maximum_lag:horizon)); - end - global bayestopt_ - if isfield(bayestopt_,'mean_varobs') - trend = trend + repmat(bayestopt_.mean_varobs,1,horizon+M_.maximum_lag); - end - otherwise - error('Wrong flag value') - end - - if M_.exo_det_nbr == 0 - [yf,int_width] = forcst(oo_.dr,y0,horizon,var_list); - else - exo_det_length = size(oo_.exo_det_simul,1)-M_.maximum_lag; - if horizon > exo_det_length - ex = zeros(horizon,M_.exo_nbr); - oo_.exo_det_simul = [ oo_.exo_det_simul;... - repmat(oo_.exo_det_steady_state',... - horizon- ... - exo_det_length,1)]; - elseif horizon < exo_det_length - ex = zeros(exo_det_length,M_.exo_nbr); - end - [yf,int_width] = simultxdet(y0,ex,oo_.exo_det_simul,... - options_.order,var_list,M_,oo_,options_); - end - - if ~isscalar(trend) - yf(i_var_obs,:) = yf(i_var_obs,:) + trend; - end - - for i=1:n_var - eval(['oo_.forecast.Mean.' var_list(i,:) '= yf(' int2str(i) ',maximum_lag+1:end)'';']); - eval(['oo_.forecast.HPDinf.' var_list(i,:) '= yf(' int2str(i) ',maximum_lag+1:end)''-' ... - ' int_width(:,' int2str(i) ');']); - eval(['oo_.forecast.HPDsup.' var_list(i,:) '= yf(' int2str(i) ',maximum_lag+1:end)''+' ... - ' int_width(:,' int2str(i) ');']); - end - - for i=1:M_.exo_det_nbr - eval(['oo_.forecast.Exogenous.' M_.exo_det_names(i,:) '= oo_.exo_det_simul(:,' int2str(i) ');']); - end - - if options_.nograph == 0 - forecast_graphs(var_list); - end - - options_ = old_options; - +function info = forecast(var_list,task) +% function forecast(var_list,task) +% computes mean forecast for a given value of the parameters +% computes also confidence band for the forecast +% +% INPUTS +% var_list: list of variables (character matrix) +% task: indicates how to initialize the forecast +% either 'simul' or 'smoother' +% OUTPUTS +% nothing is returned but the procedure saves output +% in oo_.forecast.Mean +% oo_.forecast.HPDinf +% oo_.forecast.HPDsup +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2003-2009 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 <http://www.gnu.org/licenses/>. + +global options_ dr_ oo_ M_ + +info = 0; + +old_options = options_; + +maximum_lag = M_.maximum_lag; + + +endo_names = M_.endo_names; +if isempty(var_list) + var_list = endo_names(1:M_.orig_endo_nbr, :); +end +i_var = []; +for i = 1:size(var_list) + tmp = strmatch(var_list(i,:),endo_names,'exact'); + if isempty(tmp) + error([var_list(i,:) ' isn''t and endogenous variable']) + end + i_var = [i_var; tmp]; +end + +n_var = length(i_var); + +trend = 0; +switch task + case 'simul' + horizon = options_.periods; + if horizon == 0 + horizon = 5; + end + if size(oo_.endo_simul,2) < maximum_lag + y0 = repmat(oo_.steady_state,1,maximum_lag); + else + y0 = oo_.endo_simul(:,1:maximum_lag); + end + case 'smoother' + horizon = options_.forecast; + y_smoothed = oo_.SmoothedVariables; + y0 = zeros(M_.endo_nbr,maximum_lag); + for i = 1:M_.endo_nbr + v_name = deblank(M_.endo_names(i,:)); + y0(i,:) = y_smoothed.(v_name)(end-maximum_lag+1:end)+oo_.dr.ys(i); + end + gend = options_.nobs; + if isfield(oo_.Smoother,'TrendCoeffs') + var_obs = options_.varobs; + endo_names = M_.endo_names; + order_var = oo_.dr.order_var; + i_var_obs = []; + trend_coeffs = []; + for i=1:size(var_obs,1) + tmp = strmatch(var_obs(i,:),endo_names(i_var,:),'exact'); + if ~isempty(tmp) + i_var_obs = [ i_var_obs; tmp]; + trend_coeffs = [trend_coeffs; oo_.Smoother.TrendCoeffs(i)]; + end + end + trend = trend_coeffs*(gend+(1-M_.maximum_lag:horizon)); + end + global bayestopt_ + if isfield(bayestopt_,'mean_varobs') + trend = trend + repmat(bayestopt_.mean_varobs,1,horizon+M_.maximum_lag); + end + otherwise + error('Wrong flag value') +end + +if M_.exo_det_nbr == 0 + [yf,int_width] = forcst(oo_.dr,y0,horizon,var_list); +else + exo_det_length = size(oo_.exo_det_simul,1)-M_.maximum_lag; + if horizon > exo_det_length + ex = zeros(horizon,M_.exo_nbr); + oo_.exo_det_simul = [ oo_.exo_det_simul;... + repmat(oo_.exo_det_steady_state',... + horizon- ... + exo_det_length,1)]; + elseif horizon < exo_det_length + ex = zeros(exo_det_length,M_.exo_nbr); + end + [yf,int_width] = simultxdet(y0,ex,oo_.exo_det_simul,... + options_.order,var_list,M_,oo_,options_); +end + +if ~isscalar(trend) + yf(i_var_obs,:) = yf(i_var_obs,:) + trend; +end + +for i=1:n_var + eval(['oo_.forecast.Mean.' var_list(i,:) '= yf(' int2str(i) ',maximum_lag+1:end)'';']); + eval(['oo_.forecast.HPDinf.' var_list(i,:) '= yf(' int2str(i) ',maximum_lag+1:end)''-' ... + ' int_width(:,' int2str(i) ');']); + eval(['oo_.forecast.HPDsup.' var_list(i,:) '= yf(' int2str(i) ',maximum_lag+1:end)''+' ... + ' int_width(:,' int2str(i) ');']); +end + +for i=1:M_.exo_det_nbr + eval(['oo_.forecast.Exogenous.' M_.exo_det_names(i,:) '= oo_.exo_det_simul(:,' int2str(i) ');']); +end + +if options_.nograph == 0 + forecast_graphs(var_list); +end + +options_ = old_options; + diff --git a/matlab/forecast_graphs.m b/matlab/forecast_graphs.m index aba7f08ad3..806112f97c 100644 --- a/matlab/forecast_graphs.m +++ b/matlab/forecast_graphs.m @@ -1,95 +1,95 @@ -function forecast_graphs(var_list) - -% Copyright (C) 2008-2009 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 <http://www.gnu.org/licenses/>. - - global M_ oo_ options_ - - nc = 4; - nr = 3; - exo_nbr = M_.exo_nbr; - endo_names = M_.endo_names; - fname = M_.fname; -% $$$ varobs = options_.varobs; -% $$$ y = oo_.SmoothedVariables; -% $$$ ys = oo_.dr.ys; -% $$$ gend = size(y,2); - yf = oo_.forecast.Mean; - hpdinf = oo_.forecast.HPDinf; - hpdsup = oo_.forecast.HPDsup; - if isempty(var_list) - varlist = endo_names(1:M_.orig_endo_nbr,:); - end - i_var = []; - for i = 1:size(var_list) - tmp = strmatch(var_list(i,:),endo_names,'exact'); - if isempty(tmp) - error([var_list(i,:) ' isn''t and endogenous variable']) - end - i_var = [i_var; tmp]; - end - nvar = length(i_var); - -% $$$ % build trend for smoothed variables if necessary -% $$$ trend = zeros(size(varobs,1),10); -% $$$ if isfield(oo_.Smoother,'TrendCoeffs') -% $$$ trend_coeffs = oo_.Smoother.TrendCoeffs; -% $$$ trend = trend_coeffs*(gend-9:gend); -% $$$ end - - % create subdirectory <fname>/graphs if id doesn't exist - if ~exist(fname, 'dir') - mkdir('.',fname); - end - if ~exist([fname '/graphs']) - mkdir(fname,'graphs'); - end - - m = 1; - n_fig = 1; - figure('Name','Forecasts (I)') - for j= 1:nvar - if m > nc*nr; - eval(['print -depsc ' fname '/graphs/forcst' int2str(n_fig) ... - '.eps;']) - n_fig =n_fig+1; - eval(['figure(''Name'',''Forecast (' int2str(n_fig) ')'');']); - m = 1; - end - subplot(nr,nc,m); - vn = deblank(endo_names(i_var(j),:)); - obs = 0; -% $$$ k = strmatch(vn,varobs,'exact'); -% $$$ if ~isempty(k) -% $$$ yy = y.(vn)(end-9:end) + repmat(ys(i_var(j)),10,1)+trend(k,:)'; -% $$$ plot(yy); -% $$$ hold on -% $$$ obs = 10; -% $$$ end - plot([NaN(obs,1); yf.(vn)]); - hold on - plot([NaN(obs,1); hpdinf.(vn)]); - hold on - plot([NaN(obs,1); hpdsup.(vn)]); - title(vn,'Interpreter','none'); - hold off - m = m + 1; - end - - if m > 1 - eval(['print -deps ' fname '/graphs/forcst' int2str(n_fig) '.eps;']) - end \ No newline at end of file +function forecast_graphs(var_list) + +% Copyright (C) 2008-2009 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 <http://www.gnu.org/licenses/>. + +global M_ oo_ options_ + +nc = 4; +nr = 3; +exo_nbr = M_.exo_nbr; +endo_names = M_.endo_names; +fname = M_.fname; +% $$$ varobs = options_.varobs; +% $$$ y = oo_.SmoothedVariables; +% $$$ ys = oo_.dr.ys; +% $$$ gend = size(y,2); +yf = oo_.forecast.Mean; +hpdinf = oo_.forecast.HPDinf; +hpdsup = oo_.forecast.HPDsup; +if isempty(var_list) + varlist = endo_names(1:M_.orig_endo_nbr,:); +end +i_var = []; +for i = 1:size(var_list) + tmp = strmatch(var_list(i,:),endo_names,'exact'); + if isempty(tmp) + error([var_list(i,:) ' isn''t and endogenous variable']) + end + i_var = [i_var; tmp]; +end +nvar = length(i_var); + +% $$$ % build trend for smoothed variables if necessary +% $$$ trend = zeros(size(varobs,1),10); +% $$$ if isfield(oo_.Smoother,'TrendCoeffs') +% $$$ trend_coeffs = oo_.Smoother.TrendCoeffs; +% $$$ trend = trend_coeffs*(gend-9:gend); +% $$$ end + +% create subdirectory <fname>/graphs if id doesn't exist +if ~exist(fname, 'dir') + mkdir('.',fname); +end +if ~exist([fname '/graphs']) + mkdir(fname,'graphs'); +end + +m = 1; +n_fig = 1; +figure('Name','Forecasts (I)') +for j= 1:nvar + if m > nc*nr; + eval(['print -depsc ' fname '/graphs/forcst' int2str(n_fig) ... + '.eps;']) + n_fig =n_fig+1; + eval(['figure(''Name'',''Forecast (' int2str(n_fig) ')'');']); + m = 1; + end + subplot(nr,nc,m); + vn = deblank(endo_names(i_var(j),:)); + obs = 0; +% $$$ k = strmatch(vn,varobs,'exact'); +% $$$ if ~isempty(k) +% $$$ yy = y.(vn)(end-9:end) + repmat(ys(i_var(j)),10,1)+trend(k,:)'; +% $$$ plot(yy); +% $$$ hold on +% $$$ obs = 10; +% $$$ end + plot([NaN(obs,1); yf.(vn)]); + hold on + plot([NaN(obs,1); hpdinf.(vn)]); + hold on + plot([NaN(obs,1); hpdsup.(vn)]); + title(vn,'Interpreter','none'); + hold off + m = m + 1; +end + +if m > 1 + eval(['print -deps ' fname '/graphs/forcst' int2str(n_fig) '.eps;']) +end \ No newline at end of file diff --git a/matlab/formdata.m b/matlab/formdata.m index 65aac17451..b19345704d 100644 --- a/matlab/formdata.m +++ b/matlab/formdata.m @@ -1,79 +1,79 @@ -function formdata(fname,date) -% function formdata(fname,date) -% store endogenous and exogenous variables in a "FRM" TROLL text format file -% INPUT -% fname: name of the FRM file -% date: the date of first observation (i.e. 2007A for an annual dataset) -% OUTPUT -% none -% ALGORITHM -% none -% SPECIAL REQUIREMENT -% none - -% Copyright (C) 2007-2008 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 <http://www.gnu.org/licenses/>. - - global M_ oo_ - fid = fopen([fname '_endo.frm'],'w'); - n=size(oo_.endo_simul,1); - t=size(oo_.endo_simul,2); - SN=upper(cellstr(M_.endo_names)); - for i=1:n - str=strvcat(SN(i)); - fprintf(fid,'USER: x x DATAFILE: x %s\n',str); - fprintf(fid,'PER: 1 YEAR: %s FRAC: 1 NOBS: %d CLINES: 0 DLINES: ???\n',date,t); - fprintf(fid,'%10.5f %10.5f %10.5f %10.5f\n',reshape(oo_.endo_simul(i,1:floor(t/4)*4),floor(t/4),4)); - if(floor(t/4)*4<t) - switch(t-floor(t/4)*4) - case 1 - fprintf(fid,'%10.5f\n',oo_.endo_simul(i,floor(t/4)*4+1:t)); - case 2 - fprintf(fid,'%10.5f %10.5f\n',oo_.endo_simul(i,floor(t/4)*4+1:t)); - case 3 - fprintf(fid,'%10.5f %10.5f %10.5f\n',oo_.endo_simul(i,floor(t/4)*4+1:t)); - end; - %else - % fprintf(fid,'\n'); - end; - end; - fclose(fid); - - fid = fopen([fname '_exo.frm'],'w'); - n=size(oo_.exo_simul,2); - t=size(oo_.exo_simul,1); - SN=upper(cellstr(M_.exo_names)); - for i=1:n - str=strvcat(SN(i)); - fprintf(fid,'USER: x x DATAFILE: x %s\n',str); - fprintf(fid,'PER: 1 YEAR: %s FRAC: 1 NOBS: %d CLINES: 0 DLINES: ???\n',date,t); - fprintf(fid,'%10.5f %10.5f %10.5f %10.5f\n',reshape(oo_.exo_simul(1:floor(t/4)*4,i),floor(t/4),4)); - if(floor(t/4)*4<t) - switch(t-floor(t/4)*4) - case 1 - fprintf(fid,'%10.5f\n',oo_.exo_simul(floor(t/4)*4+1:t,i)'); - case 2 - fprintf(fid,'%10.5f %10.5f\n',oo_.exo_simul(floor(t/4)*4+1:t,i)'); - case 3 - fprintf(fid,'%10.5f %10.5f %10.5f\n',oo_.exo_simul(floor(t/4)*4+1:t,i)'); - end; - %else - % fprintf(fid,'\n'); - end; - end; - fclose(fid); +function formdata(fname,date) +% function formdata(fname,date) +% store endogenous and exogenous variables in a "FRM" TROLL text format file +% INPUT +% fname: name of the FRM file +% date: the date of first observation (i.e. 2007A for an annual dataset) +% OUTPUT +% none +% ALGORITHM +% none +% SPECIAL REQUIREMENT +% none + +% Copyright (C) 2007-2008 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 <http://www.gnu.org/licenses/>. + +global M_ oo_ +fid = fopen([fname '_endo.frm'],'w'); +n=size(oo_.endo_simul,1); +t=size(oo_.endo_simul,2); +SN=upper(cellstr(M_.endo_names)); +for i=1:n + str=strvcat(SN(i)); + fprintf(fid,'USER: x x DATAFILE: x %s\n',str); + fprintf(fid,'PER: 1 YEAR: %s FRAC: 1 NOBS: %d CLINES: 0 DLINES: ???\n',date,t); + fprintf(fid,'%10.5f %10.5f %10.5f %10.5f\n',reshape(oo_.endo_simul(i,1:floor(t/4)*4),floor(t/4),4)); + if(floor(t/4)*4<t) + switch(t-floor(t/4)*4) + case 1 + fprintf(fid,'%10.5f\n',oo_.endo_simul(i,floor(t/4)*4+1:t)); + case 2 + fprintf(fid,'%10.5f %10.5f\n',oo_.endo_simul(i,floor(t/4)*4+1:t)); + case 3 + fprintf(fid,'%10.5f %10.5f %10.5f\n',oo_.endo_simul(i,floor(t/4)*4+1:t)); + end; + %else + % fprintf(fid,'\n'); + end; +end; +fclose(fid); + +fid = fopen([fname '_exo.frm'],'w'); +n=size(oo_.exo_simul,2); +t=size(oo_.exo_simul,1); +SN=upper(cellstr(M_.exo_names)); +for i=1:n + str=strvcat(SN(i)); + fprintf(fid,'USER: x x DATAFILE: x %s\n',str); + fprintf(fid,'PER: 1 YEAR: %s FRAC: 1 NOBS: %d CLINES: 0 DLINES: ???\n',date,t); + fprintf(fid,'%10.5f %10.5f %10.5f %10.5f\n',reshape(oo_.exo_simul(1:floor(t/4)*4,i),floor(t/4),4)); + if(floor(t/4)*4<t) + switch(t-floor(t/4)*4) + case 1 + fprintf(fid,'%10.5f\n',oo_.exo_simul(floor(t/4)*4+1:t,i)'); + case 2 + fprintf(fid,'%10.5f %10.5f\n',oo_.exo_simul(floor(t/4)*4+1:t,i)'); + case 3 + fprintf(fid,'%10.5f %10.5f %10.5f\n',oo_.exo_simul(floor(t/4)*4+1:t,i)'); + end; + %else + % fprintf(fid,'\n'); + end; +end; +fclose(fid); return; \ No newline at end of file diff --git a/matlab/ftest.m b/matlab/ftest.m index 498921d628..58cbf6c2aa 100644 --- a/matlab/ftest.m +++ b/matlab/ftest.m @@ -20,13 +20,13 @@ function ftest (s1,s2) global nvx nvy x y lag1 if size(s1,1) ~= 2 - error ('Sp�cifiez deux fichiers pour la comparaison.') ; + error ('Sp�cifiez deux fichiers pour la comparaison.') ; end for i = 1:2 - if ~ isempty(find(abs(s1(i,:)) == 46)) - error ('Entrez les noms de fichiers sans extensions.') ; - end + if ~ isempty(find(abs(s1(i,:)) == 46)) + error ('Entrez les noms de fichiers sans extensions.') ; + end end s1 = [s1 [' ';' ']] ; @@ -54,28 +54,28 @@ fclose(fid) ; nvy = setstr(nvy) ; if size(x,1) ~= size(y,1) - error ('FTEST: The two files don''t have the same number of variables.'); + error ('FTEST: The two files don''t have the same number of variables.'); end for i = 1:size(x,1) - if ~ strcmp(nvx(i,:),nvy(i,:)) - error ('FTEST: The two files don''t have the same variables.') ; - end + if ~ strcmp(nvx(i,:),nvy(i,:)) + error ('FTEST: The two files don''t have the same variables.') ; + end end if nnz(lag1 - lag2) > 0 - error ('FTEST: Leads and lags aren''t the same in both files.') ; + error ('FTEST: Leads and lags aren''t the same in both files.') ; end j = zeros(size(s2,1),1); for i=1:size(s2,1) - k = strmatch(s2(i,:),nvx,'exact') ; - if isempty(k) - t = ['FTEST: Variable ' s2(i) 'doesn''t exist'] ; - error (t) ; - else - j(i) =k; - end + k = strmatch(s2(i,:),nvx,'exact') ; + if isempty(k) + t = ['FTEST: Variable ' s2(i) 'doesn''t exist'] ; + error (t) ; + else + j(i) =k; + end end y = y(j,:) ; diff --git a/matlab/gcompare.m b/matlab/gcompare.m index d0f6f780ef..bed6a03870 100644 --- a/matlab/gcompare.m +++ b/matlab/gcompare.m @@ -32,20 +32,20 @@ ix = [1-lag1(1):size(x,2)-lag1(1)]' ; i = [lag1(1):size(ix,1)-lag1(2)+1]' ; if options_.smpl == 0 - i = [M_.maximum_lag:size(y,2)]' ; + i = [M_.maximum_lag:size(y,2)]' ; else - i = [options_.smpl(1):options_.smpl(2)]' ; + i = [options_.smpl(1):options_.smpl(2)]' ; end for k = 1:size(x,1) - figure ; - plot (ix(i),x(k,i),ix(i),y(k,i)) ; - xlabel (['Periods']) ; - title (['Variable ' s2(k,:)]) ; - l = min(i) + 1; - ll = max(i) - 1 ; - text (l,x(k,l),s1(1,:)) ; - text (ll,y(k,ll),s1(2,:)) ; + figure ; + plot (ix(i),x(k,i),ix(i),y(k,i)) ; + xlabel (['Periods']) ; + title (['Variable ' s2(k,:)]) ; + l = min(i) + 1; + ll = max(i) - 1 ; + text (l,x(k,l),s1(1,:)) ; + text (ll,y(k,ll),s1(2,:)) ; end % 06/18/01 MJ corrected treatment of options_.smpl diff --git a/matlab/generalized_cholesky2.m b/matlab/generalized_cholesky2.m index 4c81f2899b..8c1f8ef9a6 100644 --- a/matlab/generalized_cholesky2.m +++ b/matlab/generalized_cholesky2.m @@ -47,10 +47,10 @@ norm_A = max(sum(abs(A))'); gamm = max(abs(diag(A))); delta = max([eps*norm_A;eps]); Pprod = eye(n); - + if n > 2; for k = 1,n-2; - if min((diag(A(k+1:n,k+1:n))' - A(k,k+1:n).^2/A(k,k))') < tau*gamm ... + if min((diag(A(k+1:n,k+1:n))' - A(k,k+1:n).^2/A(k,k))') < tau*gamm ... & min(eig(A((k+1):n,(k+1):n))) < 0; [tmp,dmax] = max(diag(A(k:n,k:n))); if A(k+dmax-1,k+dmax-1) > A(k,k); @@ -61,23 +61,23 @@ if n > 2; A = P*A*P; L = P*L*P; Pprod = P*Pprod; - end; - g = zeros(n-(k-1),1); - for i=k:n; + end; + g = zeros(n-(k-1),1); + for i=k:n; if i == 1; - sum1 = 0; + sum1 = 0; else; - sum1 = sum(abs(A(i,k:(i-1)))'); - end; + sum1 = sum(abs(A(i,k:(i-1)))'); + end; if i == n; - sum2 = 0; + sum2 = 0; else; sum2 = sum(abs(A((i+1):n,i))); - end; + end; g(i-k+1) = A(i,i) - sum1 - sum2; - end; - [tmp,gmax] = max(g); - if gmax ~= k; + end; + [tmp,gmax] = max(g); + if gmax ~= k; P = eye(n); Ptemp = P(k,:); P(k,:) = P(k+dmax-1,:); @@ -85,32 +85,32 @@ if n > 2; A = P*A*P; L = P*L*P; Pprod = P*Pprod; - end; - normj = sum(abs(A(k+1:n,k))); - delta = max([0;deltaprev;-A(k,k)+normj;-A(k,k)+tau*gamm]); - if delta > 0; - A(k,k) = A(k,k) + delta; - deltaprev = delta; - end; - end; - A(k,k) = sqrt(A(k,k)); - L(k,k) = A(k,k); - for i=k+1:n; + end; + normj = sum(abs(A(k+1:n,k))); + delta = max([0;deltaprev;-A(k,k)+normj;-A(k,k)+tau*gamm]); + if delta > 0; + A(k,k) = A(k,k) + delta; + deltaprev = delta; + end; + end; + A(k,k) = sqrt(A(k,k)); + L(k,k) = A(k,k); + for i=k+1:n; if L(k,k) > eps; A(i,k) = A(i,k)/L(k,k); end; - L(i,k) = A(i,k); + L(i,k) = A(i,k); A(i,k+1:i) = A(i,k+1:i) - L(i,k)*L(k+1:i,k)'; if A(i,i) < 0; A(i,i) = 0; end; - end; + end; end; end; A(n-1,n) = A(n,n-1); eigvals = eig(A(n-1:n,n-1:n)); dlist = [ 0 ; deltaprev ;... - -min(eigvals)+tau*max((inv(1-tau)*max(eigvals)-min(eigvals))|gamm) ]; + -min(eigvals)+tau*max((inv(1-tau)*max(eigvals)-min(eigvals))|gamm) ]; if dlist(1) > dlist(2); delta = dlist(1); else; diff --git a/matlab/gensylv/sylvester3.m b/matlab/gensylv/sylvester3.m index a4af35a73c..505988aaae 100644 --- a/matlab/gensylv/sylvester3.m +++ b/matlab/gensylv/sylvester3.m @@ -18,55 +18,55 @@ function x=sylvester3(a,b,c,d) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - n = size(a,1); - m = size(c,1); - if n == 1 +n = size(a,1); +m = size(c,1); +if n == 1 x=d./(a*ones(1,m)+b*c); return - end - if m == 1 +end +if m == 1 x = (a+c*b)\d; return; - end - x=zeros(n,m); - [u,t]=schur(c); - if exist('OCTAVE_VERSION') +end +x=zeros(n,m); +[u,t]=schur(c); +if exist('OCTAVE_VERSION') [aa,bb,qq,zz]=qz(full(a),full(b)); d=qq'*d*u; - else +else [aa,bb,qq,zz]=qz(full(a),full(b),'real'); % available in Matlab version 6.0 d=qq*d*u; - end - i = 1; - while i < m +end +i = 1; +while i < m if t(i+1,i) == 0 - if i == 1 - c = zeros(n,1); - else - c = bb*(x(:,1:i-1)*t(1:i-1,i)); - end - x(:,i)=(aa+bb*t(i,i))\(d(:,i)-c); - i = i+1; + if i == 1 + c = zeros(n,1); + else + c = bb*(x(:,1:i-1)*t(1:i-1,i)); + end + x(:,i)=(aa+bb*t(i,i))\(d(:,i)-c); + i = i+1; else - if i == n - c = zeros(n,1); - c1 = zeros(n,1); - else - c = bb*(x(:,1:i-1)*t(1:i-1,i)); - c1 = bb*(x(:,1:i-1)*t(1:i-1,i+1)); - end - z = [aa+bb*t(i,i) bb*t(i+1,i); bb*t(i,i+1) aa+bb*t(i+1,i+1)]... - \[d(:,i)-c;d(:,i+1)-c1]; - x(:,i) = z(1:n); - x(:,i+1) = z(n+1:end); - i = i + 2; + if i == n + c = zeros(n,1); + c1 = zeros(n,1); + else + c = bb*(x(:,1:i-1)*t(1:i-1,i)); + c1 = bb*(x(:,1:i-1)*t(1:i-1,i+1)); + end + z = [aa+bb*t(i,i) bb*t(i+1,i); bb*t(i,i+1) aa+bb*t(i+1,i+1)]... + \[d(:,i)-c;d(:,i+1)-c1]; + x(:,i) = z(1:n); + x(:,i+1) = z(n+1:end); + i = i + 2; end - end - if i == m +end +if i == m c = bb*(x(:,1:m-1)*t(1:m-1,m)); x(:,m)=(aa+bb*t(m,m))\(d(:,m)-c); - end - x=zz*x*u'; - +end +x=zz*x*u'; + % 01/25/03 MJ corrected bug for i==m (sign of c in x determination) % 01/31/03 MJ added 'real' to qz call diff --git a/matlab/gensylv/sylvester3a.m b/matlab/gensylv/sylvester3a.m index fa796c00d9..d4f88f2fa6 100644 --- a/matlab/gensylv/sylvester3a.m +++ b/matlab/gensylv/sylvester3a.m @@ -18,17 +18,17 @@ function x=sylvester3a(x0,a,b,c,d) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - a_1 = inv(a); - b = a_1*b; - d = a_1*d; - e = 1; - iter = 1; - while e > 1e-8 & iter < 500 +a_1 = inv(a); +b = a_1*b; +d = a_1*d; +e = 1; +iter = 1; +while e > 1e-8 & iter < 500 x = d-b*x0*c; e = max(max(abs(x-x0))); x0 = x; iter = iter + 1; - end - if iter == 500 +end +if iter == 500 warning('sylvester3a : Only accuracy of %10.8f is achieved after 500 iterations') - end \ No newline at end of file +end \ No newline at end of file diff --git a/matlab/gensylv/sylvester3mr.m b/matlab/gensylv/sylvester3mr.m index 24c7adeb59..463db37971 100644 --- a/matlab/gensylv/sylvester3mr.m +++ b/matlab/gensylv/sylvester3mr.m @@ -18,83 +18,83 @@ function x=sylvester3mr(a,b,c,d) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - n = size(a,1); - m = size(c,1); - if length(size(d))==2, +n = size(a,1); +m = size(c,1); +if length(size(d))==2, x=sylvester3(a,b,c,d); return - end - p = size(d,3); - if n == 1 +end +p = size(d,3); +if n == 1 for j=1:p, - x(:,:,j)=d(:,:,j)./(a*ones(1,m)+b*c); + x(:,:,j)=d(:,:,j)./(a*ones(1,m)+b*c); end return - end - if m == 1 +end +if m == 1 invacb = inv(a+c*b); x = invacb*d; return; - end - x=zeros(n,m,p); - [u,t]=schur(c); - if exist('OCTAVE_VERSION') +end +x=zeros(n,m,p); +[u,t]=schur(c); +if exist('OCTAVE_VERSION') [aa,bb,qq,zz]=qz(full(a),full(b)); for j=1:p, - d(:,:,j)=qq'*d(:,:,j)*u; + d(:,:,j)=qq'*d(:,:,j)*u; end - else +else [aa,bb,qq,zz]=qz(full(a),full(b),'real'); % available in Matlab version 6.0 for j=1:p, - d(:,:,j)=qq*d(:,:,j)*u; + d(:,:,j)=qq*d(:,:,j)*u; end - end - i = 1; - c = zeros(n,1,p); - while i < m +end +i = 1; +c = zeros(n,1,p); +while i < m if t(i+1,i) == 0 - if i == 1 - c = zeros(n,1,p); - else - for j=1:p, - c(:,:,j) = bb*(x(:,1:i-1,j)*t(1:i-1,i)); + if i == 1 + c = zeros(n,1,p); + else + for j=1:p, + c(:,:,j) = bb*(x(:,1:i-1,j)*t(1:i-1,i)); + end end - end -% aabbtinv = inv(aa+bb*t(i,i)); -% x(:,i,:)=aabbtinv*squeeze(d(:,i,:)-c); - x(:,i,:)=(aa+bb*t(i,i))\squeeze(d(:,i,:)-c); - i = i+1; + % aabbtinv = inv(aa+bb*t(i,i)); + % x(:,i,:)=aabbtinv*squeeze(d(:,i,:)-c); + x(:,i,:)=(aa+bb*t(i,i))\squeeze(d(:,i,:)-c); + i = i+1; else - if i == n - c = zeros(n,1,p); - c1 = zeros(n,1,p); - else - for j=1:p, - c(:,:,j) = bb*(x(:,1:i-1,j)*t(1:i-1,i)); - c1(:,:,j) = bb*(x(:,1:i-1,j)*t(1:i-1,i+1)); + if i == n + c = zeros(n,1,p); + c1 = zeros(n,1,p); + else + for j=1:p, + c(:,:,j) = bb*(x(:,1:i-1,j)*t(1:i-1,i)); + c1(:,:,j) = bb*(x(:,1:i-1,j)*t(1:i-1,i+1)); + end end - end -% bigmatinv = inv([aa+bb*t(i,i) bb*t(i+1,i); bb*t(i,i+1) aa+bb*t(i+1,i+1)]); -% z = bigmatinv * squeeze([d(:,i,:)-c;d(:,i+1,:)-c1]); - bigmat = ([aa+bb*t(i,i) bb*t(i+1,i); bb*t(i,i+1) aa+bb*t(i+1,i+1)]); - z = bigmat\squeeze([d(:,i,:)-c;d(:,i+1,:)-c1]); - x(:,i,:) = z(1:n,:); - x(:,i+1,:) = z(n+1:end,:); - i = i + 2; + % bigmatinv = inv([aa+bb*t(i,i) bb*t(i+1,i); bb*t(i,i+1) aa+bb*t(i+1,i+1)]); + % z = bigmatinv * squeeze([d(:,i,:)-c;d(:,i+1,:)-c1]); + bigmat = ([aa+bb*t(i,i) bb*t(i+1,i); bb*t(i,i+1) aa+bb*t(i+1,i+1)]); + z = bigmat\squeeze([d(:,i,:)-c;d(:,i+1,:)-c1]); + x(:,i,:) = z(1:n,:); + x(:,i+1,:) = z(n+1:end,:); + i = i + 2; end - end - if i == m - for j=1:p, - c(:,:,j) = bb*(x(:,1:m-1,j)*t(1:m-1,m)); - end -% aabbtinv = inv(aa+bb*t(m,m)); -% x(:,m,:)=aabbtinv*squeeze(d(:,m,:)-c); - aabbt = (aa+bb*t(m,m)); +end +if i == m + for j=1:p, + c(:,:,j) = bb*(x(:,1:m-1,j)*t(1:m-1,m)); + end + % aabbtinv = inv(aa+bb*t(m,m)); + % x(:,m,:)=aabbtinv*squeeze(d(:,m,:)-c); + aabbt = (aa+bb*t(m,m)); x(:,m,:)=aabbt\squeeze(d(:,m,:)-c); - end - for j=1:p, +end +for j=1:p, x(:,:,j)=zz*x(:,:,j)*u'; - end - +end + % 01/25/03 MJ corrected bug for i==m (sign of c in x determination) % 01/31/03 MJ added 'real' to qz call diff --git a/matlab/getH.m b/matlab/getH.m index fe99ec8078..5d3b06efa7 100644 --- a/matlab/getH.m +++ b/matlab/getH.m @@ -1,320 +1,320 @@ -function [H, dA, dOm, Hss, info] = getH(A, B, M_,oo_,kronflag,indx,indexo) - -% computes derivative of reduced form linear model w.r.t. deep params -% -% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. - -if nargin<3 | isempty(kronflag), kronflag = 0; end -if nargin<4 | isempty(indx), indx = [1:M_.param_nbr];, end, -if nargin<5 | isempty(indexo), indexo = [];, end, - - -[I,J]=find(M_.lead_lag_incidence'); -yy0=oo_.dr.ys(I); -% yy0=[]; -% for j=1:size(M_.lead_lag_incidence,1); -% yy0 = [ yy0; oo_.dr.ys(find(M_.lead_lag_incidence(j,:)))]; -% end -[df, gp] = feval([M_.fname,'_params_derivs'],yy0, oo_.exo_steady_state', M_.params, 1); -[residual, g1 ] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', M_.params,1); - -[residual, g1, g2 ] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', M_.params,1); -[residual, gg1] = feval([M_.fname,'_static'],oo_.dr.ys, oo_.exo_steady_state', M_.params); -% df = feval([M_.fname,'_model_derivs'],yy0, oo_.exo_steady_state', M_.params, 1); -dyssdtheta = -gg1\df; -Hss = dyssdtheta(oo_.dr.order_var,indx); -dyssdtheta = dyssdtheta(I,:); -[nr, nc]=size(g2); -nc = sqrt(nc); -ns = max(max(M_.lead_lag_incidence)); -gp2 = gp*0; -for j=1:nr, - [I J]=ind2sub([nc nc],find(g2(j,:))); - for i=1:nc, - is = find(I==i); - is = is(find(J(is)<=ns)); - if ~isempty(is), - g20=full(g2(j,find(g2(j,:)))); - gp2(j,i,:)=g20(is)*dyssdtheta(J(is),:); - end - end -end - - -gp = gp+gp2; -gp = gp(:,:,indx); -param_nbr = length(indx); - -% order_var = [oo_.dr.order_var; ... -% [size(oo_dr.ghx,2)+1:size(oo_dr.ghx,2)+size(oo_.dr.transition_auxiliary_variables,1)]' ]; -% [A(order_var,order_var),B(order_var,:)]=dynare_resolve; -% [A,B,ys,info]=dynare_resolve; -% if info(1) > 0 -% H = []; -% A0 = []; -% B0 = []; -% dA = []; -% dOm = []; -% return -% end - -m = size(A,1); -n = size(B,2); - - - -klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1; -k1 = M_.lead_lag_incidence(find([1:klen] ~= M_.maximum_endo_lag+1),:); -a = g1(:,nonzeros(k1')); -da = gp(:,nonzeros(k1'),:); -kstate = oo_.dr.kstate; - -GAM1 = zeros(M_.endo_nbr,M_.endo_nbr); -Dg1 = zeros(M_.endo_nbr,M_.endo_nbr,param_nbr); -% nf = find(M_.lead_lag_incidence(M_.maximum_endo_lag+2,:)); -% GAM1(:, nf) = -g1(:,M_.lead_lag_incidence(M_.maximum_endo_lag+2,nf)); - -k = find(kstate(:,2) == M_.maximum_endo_lag+2 & kstate(:,3)); -GAM1(:, kstate(k,1)) = -a(:,kstate(k,3)); -Dg1(:, kstate(k,1), :) = -da(:,kstate(k,3),:); -k = find(kstate(:,2) > M_.maximum_endo_lag+2 & kstate(:,3)); -kk = find(kstate(:,2) > M_.maximum_endo_lag+2 & ~kstate(:,3)); -nauxe = 0; -if ~isempty(k), -ax(:,k)= -a(:,kstate(k,3)); -ax(:,kk)= 0; -dax(:,k,:)= -da(:,kstate(k,3),:); -dax(:,kk,:)= 0; -nauxe=size(ax,2); -GAM1 = [ax GAM1]; -Dg1 = cat(2,dax,Dg1); -clear ax -end - - -[junk,cols_b,cols_j] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+1, ... - oo_.dr.order_var)); -GAM0 = zeros(M_.endo_nbr,M_.endo_nbr); -Dg0 = zeros(M_.endo_nbr,M_.endo_nbr,param_nbr); -GAM0(:,cols_b) = g1(:,cols_j); -Dg0(:,cols_b,:) = gp(:,cols_j,:); -% GAM0 = g1(:,M_.lead_lag_incidence(M_.maximum_endo_lag+1,:)); - - -k = find(kstate(:,2) == M_.maximum_endo_lag+1 & kstate(:,4)); -GAM2 = zeros(M_.endo_nbr,M_.endo_nbr); -Dg2 = zeros(M_.endo_nbr,M_.endo_nbr,param_nbr); -% nb = find(M_.lead_lag_incidence(1,:)); -% GAM2(:, nb) = -g1(:,M_.lead_lag_incidence(1,nb)); -GAM2(:, kstate(k,1)) = -a(:,kstate(k,4)); -Dg2(:, kstate(k,1), :) = -da(:,kstate(k,4),:); -naux = 0; -k = find(kstate(:,2) < M_.maximum_endo_lag+1 & kstate(:,4)); -kk = find(kstate(:,2) < M_.maximum_endo_lag+1 ); -if ~isempty(k), -ax(:,k)= -a(:,kstate(k,4)); -ax = ax(:,kk); -dax(:,k,:)= -da(:,kstate(k,4),:); -dax = dax(:,kk,:); -naux = size(ax,2); -GAM2 = [GAM2 ax]; -Dg2 = cat(2,Dg2,dax); -end - -GAM0 = blkdiag(GAM0,eye(naux)); -Dg0 = cat(1,Dg0,zeros(naux+nauxe,M_.endo_nbr,param_nbr)); -Dg0 = cat(2,Dg0,zeros(m+nauxe,naux,param_nbr)); -Dg0 = cat(2,zeros(m+nauxe,nauxe,param_nbr),Dg0); - -GAM2 = [GAM2 ; A(M_.endo_nbr+1:end,:)]; -Dg2 = cat(1,Dg2,zeros(naux+nauxe,m,param_nbr)); -Dg2 = cat(2,zeros(m+nauxe,nauxe,param_nbr),Dg2); -GAM2 = [zeros(m+nauxe,nauxe) [GAM2; zeros(nauxe,m)]]; -GAM0 = [[zeros(m,nauxe);(eye(nauxe))] [GAM0; zeros(nauxe,m)]]; - -GAM3 = -g1(:,length(yy0)+1:end); -% GAM3 = -g1(oo_.dr.order_var,length(yy0)+1:end); -GAM3 = [GAM3; zeros(naux+nauxe,size(GAM3,2))]; -% Dg3 = -gp(oo_.dr.order_var,length(yy0)+1:end,:); -Dg3 = -gp(:,length(yy0)+1:end,:); -Dg3 = cat(1,Dg3,zeros(naux+nauxe,size(GAM3,2),param_nbr)); - -auxe = zeros(0,1); -k0 = kstate(find(kstate(:,2) >= M_.maximum_endo_lag+2),:);; -i0 = find(k0(:,2) == M_.maximum_endo_lag+2); -for i=M_.maximum_endo_lag+3:M_.maximum_endo_lag+2+M_.maximum_endo_lead, - i1 = find(k0(:,2) == i); - n1 = size(i1,1); - j = zeros(n1,1); - for j1 = 1:n1 - j(j1) = find(k0(i0,1)==k0(i1(j1),1)); - end - auxe = [auxe; i0(j)]; - i0 = i1; -end -auxe = [(1:size(auxe,1))' auxe(end:-1:1)]; -n_ir1 = size(auxe,1); -nr = m + n_ir1; -GAM1 = [[GAM1 zeros(size(GAM1,1),naux)]; zeros(naux+nauxe,m+nauxe)]; -GAM1(m+1:end,:) = sparse(auxe(:,1),auxe(:,2),ones(n_ir1,1),n_ir1,nr); -Dg1 = cat(2,Dg1,zeros(M_.endo_nbr,naux,param_nbr)); -Dg1 = cat(1,Dg1,zeros(naux+nauxe,m+nauxe,param_nbr)); - -Ax = A; -A1 = A; -Bx = B; -B1 = B; -for j=1:M_.maximum_endo_lead-1, - A1 = A1*A; - B1 = A*B1; - k = find(kstate(:,2) == M_.maximum_endo_lag+2+j ); - Ax = [A1(kstate(k,1),:); Ax]; - Bx = [B1(kstate(k,1),:); Bx]; -end -Ax = [zeros(m+nauxe,nauxe) Ax]; -A0 = A; -A=Ax; clear Ax A1; -B0=B; -B = Bx; clear Bx B1; - -m = size(A,1); -n = size(B,2); - -% Dg1 = zeros(m,m,param_nbr); -% Dg1(:, nf, :) = -gp(:,M_.lead_lag_incidence(3,nf),:); - -% Dg0 = gp(:,M_.lead_lag_incidence(2,:),:); - -% Dg2 = zeros(m,m,param_nbr); -% Dg2(:, nb, :) = -gp(:,M_.lead_lag_incidence(1,nb),:); - -% Dg3 = -gp(:,length(yy0)+1:end,:); - -if kronflag==1, % kronecker products - Dg0=reshape(Dg0,m^2,param_nbr); - Dg1=reshape(Dg1,m^2,param_nbr); - Dg2=reshape(Dg2,m^2,param_nbr); - Dg3=reshape(Dg3,m*n,param_nbr); - Om = B*B'; - Im = eye(m); - Dm = duplication(m); - DmPl = inv(Dm'*Dm)*Dm'; - Kmm = commutation(m,m); - Kmn = commutation(m,n); - - - Da = [eye(m^2),zeros(m^2,m*(m+1)/2)]; - Dom = [zeros(m*(m+1)/2,m^2),eye(m*(m+1)/2)]; - - - Df1Dtau = ( kron(Im,GAM0) - kron(A',GAM1) - kron(Im,GAM1*A) )*Da; - - Df1Dthet = kron(A',Im)*Dg0 - kron( (A')^2,Im)*Dg1 - Dg2; - - Df2Dtau = DmPl*( kron(GAM0,GAM0) - kron(GAM0,GAM1*A) - kron(GAM1*A,GAM0) + kron(GAM1*A,GAM1*A) )*Dm*Dom - ... - DmPl*( kron(GAM0*Om,GAM1) + kron(GAM1,GAM0*Om)*Kmm - kron(GAM1*A*Om,GAM1) - kron(GAM1,GAM1*A*Om)*Kmm )*Da; - - - Df2Dthet = DmPl*( kron(GAM0*Om,Im) + kron(Im,GAM0*Om)*Kmm - kron(Im,GAM1*A*Om)*Kmm - kron(GAM1*A*Om,Im) )*Dg0 - ... - DmPl*( kron(GAM0*Om*A',Im) + kron(Im,GAM0*Om*A')*Kmm - kron(Im,GAM1*A*Om*A')*Kmm - kron(GAM1*A*Om*A',Im) )*Dg1 -... - DmPl*( kron(GAM3,Im) + kron(Im,GAM3)*Kmn )*Dg3; - - - DfDtau = [Df1Dtau;Df2Dtau]; - DfDthet = [Df1Dthet;Df2Dthet]; - - H = -DfDtau\DfDthet; - x = reshape(H(1:m*m,:),m,m,param_nbr); - y = reshape(Dm*H(m*m+1:end,:),m,m,param_nbr); - x = x(nauxe+1:end,nauxe+1:end,:); - y = y(nauxe+1:end,nauxe+1:end,:); - m = size(y,1); - x = reshape(x,m*m,param_nbr); - Dm = duplication(m); - DmPl = inv(Dm'*Dm)*Dm'; - y = DmPl*reshape(y,m*m,param_nbr); - H = [x;y]; - - H = [ [zeros(M_.endo_nbr,length(indexo)) Hss]; H]; - -elseif kronflag==-1, % perturbation - fun = 'thet2tau'; - params0 = M_.params; - H = fdjac(fun,[sqrt(diag(M_.Sigma_e(indexo,indexo))); M_.params(indx)],indx,indexo); - assignin('base','M_', M_); - assignin('base','oo_', oo_); - -else % generalized sylvester equation - - % solves a*x+b*x*c=d - a = (GAM0-GAM1*A); - inva = inv(a); - b = -GAM1; - c = A; - elem = zeros(m,m,param_nbr); - d = elem; - for j=1:param_nbr, - elem(:,:,j) = (Dg0(:,:,j)-Dg1(:,:,j)*A); - d(:,:,j) = Dg2(:,:,j)-elem(:,:,j)*A; - end - xx=sylvester3mr(a,b,c,d); - if ~isempty(indexo), - dSig = zeros(M_.exo_nbr,M_.exo_nbr); - for j=1:length(indexo) - dSig(indexo(j),indexo(j)) = 2*sqrt(M_.Sigma_e(indexo(j),indexo(j))); - y = B*dSig*B'; - y = y(nauxe+1:end,nauxe+1:end); - H(:,j) = [zeros((m-nauxe)^2,1); vech(y)]; - if nargout>1, - dOm(:,:,j) = y; - end - dSig(indexo(j),indexo(j)) = 0; - end - end - for j=1:param_nbr, - x = xx(:,:,j); - y = inva * (Dg3(:,:,j)-(elem(:,:,j)-GAM1*x)*B); - y = y*M_.Sigma_e*B'+B*M_.Sigma_e*y'; - x = x(nauxe+1:end,nauxe+1:end); - y = y(nauxe+1:end,nauxe+1:end); - if nargout>1, - dA(:,:,j+length(indexo)) = x; - dOm(:,:,j+length(indexo)) = y; - end - H(:,j+length(indexo)) = [x(:); vech(y)]; - end -% for j=1:param_nbr, -% disp(['Derivatives w.r.t. ',M_.param_names(indx(j),:),', ',int2str(j),'/',int2str(param_nbr)]) -% elem = (Dg0(:,:,j)-Dg1(:,:,j)*A); -% d = Dg2(:,:,j)-elem*A; -% x=sylvester3(a,b,c,d); -% % x=sylvester3a(x,a,b,c,d); -% y = inva * (Dg3(:,:,j)-(elem-GAM1*x)*B); -% y = y*B'+B*y'; -% x = x(nauxe+1:end,nauxe+1:end); -% y = y(nauxe+1:end,nauxe+1:end); -% H(:,j) = [x(:); vech(y)]; -% end - H = [[zeros(M_.endo_nbr,length(indexo)) Hss]; H]; - -end - - -return - - +function [H, dA, dOm, Hss, info] = getH(A, B, M_,oo_,kronflag,indx,indexo) + +% computes derivative of reduced form linear model w.r.t. deep params +% +% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. + +if nargin<3 | isempty(kronflag), kronflag = 0; end +if nargin<4 | isempty(indx), indx = [1:M_.param_nbr];, end, +if nargin<5 | isempty(indexo), indexo = [];, end, + + +[I,J]=find(M_.lead_lag_incidence'); +yy0=oo_.dr.ys(I); +% yy0=[]; +% for j=1:size(M_.lead_lag_incidence,1); +% yy0 = [ yy0; oo_.dr.ys(find(M_.lead_lag_incidence(j,:)))]; +% end +[df, gp] = feval([M_.fname,'_params_derivs'],yy0, oo_.exo_steady_state', M_.params, 1); +[residual, g1 ] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', M_.params,1); + +[residual, g1, g2 ] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', M_.params,1); +[residual, gg1] = feval([M_.fname,'_static'],oo_.dr.ys, oo_.exo_steady_state', M_.params); +% df = feval([M_.fname,'_model_derivs'],yy0, oo_.exo_steady_state', M_.params, 1); +dyssdtheta = -gg1\df; +Hss = dyssdtheta(oo_.dr.order_var,indx); +dyssdtheta = dyssdtheta(I,:); +[nr, nc]=size(g2); +nc = sqrt(nc); +ns = max(max(M_.lead_lag_incidence)); +gp2 = gp*0; +for j=1:nr, + [I J]=ind2sub([nc nc],find(g2(j,:))); + for i=1:nc, + is = find(I==i); + is = is(find(J(is)<=ns)); + if ~isempty(is), + g20=full(g2(j,find(g2(j,:)))); + gp2(j,i,:)=g20(is)*dyssdtheta(J(is),:); + end + end +end + + +gp = gp+gp2; +gp = gp(:,:,indx); +param_nbr = length(indx); + +% order_var = [oo_.dr.order_var; ... +% [size(oo_dr.ghx,2)+1:size(oo_dr.ghx,2)+size(oo_.dr.transition_auxiliary_variables,1)]' ]; +% [A(order_var,order_var),B(order_var,:)]=dynare_resolve; +% [A,B,ys,info]=dynare_resolve; +% if info(1) > 0 +% H = []; +% A0 = []; +% B0 = []; +% dA = []; +% dOm = []; +% return +% end + +m = size(A,1); +n = size(B,2); + + + +klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1; +k1 = M_.lead_lag_incidence(find([1:klen] ~= M_.maximum_endo_lag+1),:); +a = g1(:,nonzeros(k1')); +da = gp(:,nonzeros(k1'),:); +kstate = oo_.dr.kstate; + +GAM1 = zeros(M_.endo_nbr,M_.endo_nbr); +Dg1 = zeros(M_.endo_nbr,M_.endo_nbr,param_nbr); +% nf = find(M_.lead_lag_incidence(M_.maximum_endo_lag+2,:)); +% GAM1(:, nf) = -g1(:,M_.lead_lag_incidence(M_.maximum_endo_lag+2,nf)); + +k = find(kstate(:,2) == M_.maximum_endo_lag+2 & kstate(:,3)); +GAM1(:, kstate(k,1)) = -a(:,kstate(k,3)); +Dg1(:, kstate(k,1), :) = -da(:,kstate(k,3),:); +k = find(kstate(:,2) > M_.maximum_endo_lag+2 & kstate(:,3)); +kk = find(kstate(:,2) > M_.maximum_endo_lag+2 & ~kstate(:,3)); +nauxe = 0; +if ~isempty(k), + ax(:,k)= -a(:,kstate(k,3)); + ax(:,kk)= 0; + dax(:,k,:)= -da(:,kstate(k,3),:); + dax(:,kk,:)= 0; + nauxe=size(ax,2); + GAM1 = [ax GAM1]; + Dg1 = cat(2,dax,Dg1); + clear ax +end + + +[junk,cols_b,cols_j] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+1, ... + oo_.dr.order_var)); +GAM0 = zeros(M_.endo_nbr,M_.endo_nbr); +Dg0 = zeros(M_.endo_nbr,M_.endo_nbr,param_nbr); +GAM0(:,cols_b) = g1(:,cols_j); +Dg0(:,cols_b,:) = gp(:,cols_j,:); +% GAM0 = g1(:,M_.lead_lag_incidence(M_.maximum_endo_lag+1,:)); + + +k = find(kstate(:,2) == M_.maximum_endo_lag+1 & kstate(:,4)); +GAM2 = zeros(M_.endo_nbr,M_.endo_nbr); +Dg2 = zeros(M_.endo_nbr,M_.endo_nbr,param_nbr); +% nb = find(M_.lead_lag_incidence(1,:)); +% GAM2(:, nb) = -g1(:,M_.lead_lag_incidence(1,nb)); +GAM2(:, kstate(k,1)) = -a(:,kstate(k,4)); +Dg2(:, kstate(k,1), :) = -da(:,kstate(k,4),:); +naux = 0; +k = find(kstate(:,2) < M_.maximum_endo_lag+1 & kstate(:,4)); +kk = find(kstate(:,2) < M_.maximum_endo_lag+1 ); +if ~isempty(k), + ax(:,k)= -a(:,kstate(k,4)); + ax = ax(:,kk); + dax(:,k,:)= -da(:,kstate(k,4),:); + dax = dax(:,kk,:); + naux = size(ax,2); + GAM2 = [GAM2 ax]; + Dg2 = cat(2,Dg2,dax); +end + +GAM0 = blkdiag(GAM0,eye(naux)); +Dg0 = cat(1,Dg0,zeros(naux+nauxe,M_.endo_nbr,param_nbr)); +Dg0 = cat(2,Dg0,zeros(m+nauxe,naux,param_nbr)); +Dg0 = cat(2,zeros(m+nauxe,nauxe,param_nbr),Dg0); + +GAM2 = [GAM2 ; A(M_.endo_nbr+1:end,:)]; +Dg2 = cat(1,Dg2,zeros(naux+nauxe,m,param_nbr)); +Dg2 = cat(2,zeros(m+nauxe,nauxe,param_nbr),Dg2); +GAM2 = [zeros(m+nauxe,nauxe) [GAM2; zeros(nauxe,m)]]; +GAM0 = [[zeros(m,nauxe);(eye(nauxe))] [GAM0; zeros(nauxe,m)]]; + +GAM3 = -g1(:,length(yy0)+1:end); +% GAM3 = -g1(oo_.dr.order_var,length(yy0)+1:end); +GAM3 = [GAM3; zeros(naux+nauxe,size(GAM3,2))]; +% Dg3 = -gp(oo_.dr.order_var,length(yy0)+1:end,:); +Dg3 = -gp(:,length(yy0)+1:end,:); +Dg3 = cat(1,Dg3,zeros(naux+nauxe,size(GAM3,2),param_nbr)); + +auxe = zeros(0,1); +k0 = kstate(find(kstate(:,2) >= M_.maximum_endo_lag+2),:);; +i0 = find(k0(:,2) == M_.maximum_endo_lag+2); +for i=M_.maximum_endo_lag+3:M_.maximum_endo_lag+2+M_.maximum_endo_lead, + i1 = find(k0(:,2) == i); + n1 = size(i1,1); + j = zeros(n1,1); + for j1 = 1:n1 + j(j1) = find(k0(i0,1)==k0(i1(j1),1)); + end + auxe = [auxe; i0(j)]; + i0 = i1; +end +auxe = [(1:size(auxe,1))' auxe(end:-1:1)]; +n_ir1 = size(auxe,1); +nr = m + n_ir1; +GAM1 = [[GAM1 zeros(size(GAM1,1),naux)]; zeros(naux+nauxe,m+nauxe)]; +GAM1(m+1:end,:) = sparse(auxe(:,1),auxe(:,2),ones(n_ir1,1),n_ir1,nr); +Dg1 = cat(2,Dg1,zeros(M_.endo_nbr,naux,param_nbr)); +Dg1 = cat(1,Dg1,zeros(naux+nauxe,m+nauxe,param_nbr)); + +Ax = A; +A1 = A; +Bx = B; +B1 = B; +for j=1:M_.maximum_endo_lead-1, + A1 = A1*A; + B1 = A*B1; + k = find(kstate(:,2) == M_.maximum_endo_lag+2+j ); + Ax = [A1(kstate(k,1),:); Ax]; + Bx = [B1(kstate(k,1),:); Bx]; +end +Ax = [zeros(m+nauxe,nauxe) Ax]; +A0 = A; +A=Ax; clear Ax A1; +B0=B; +B = Bx; clear Bx B1; + +m = size(A,1); +n = size(B,2); + +% Dg1 = zeros(m,m,param_nbr); +% Dg1(:, nf, :) = -gp(:,M_.lead_lag_incidence(3,nf),:); + +% Dg0 = gp(:,M_.lead_lag_incidence(2,:),:); + +% Dg2 = zeros(m,m,param_nbr); +% Dg2(:, nb, :) = -gp(:,M_.lead_lag_incidence(1,nb),:); + +% Dg3 = -gp(:,length(yy0)+1:end,:); + +if kronflag==1, % kronecker products + Dg0=reshape(Dg0,m^2,param_nbr); + Dg1=reshape(Dg1,m^2,param_nbr); + Dg2=reshape(Dg2,m^2,param_nbr); + Dg3=reshape(Dg3,m*n,param_nbr); + Om = B*B'; + Im = eye(m); + Dm = duplication(m); + DmPl = inv(Dm'*Dm)*Dm'; + Kmm = commutation(m,m); + Kmn = commutation(m,n); + + + Da = [eye(m^2),zeros(m^2,m*(m+1)/2)]; + Dom = [zeros(m*(m+1)/2,m^2),eye(m*(m+1)/2)]; + + + Df1Dtau = ( kron(Im,GAM0) - kron(A',GAM1) - kron(Im,GAM1*A) )*Da; + + Df1Dthet = kron(A',Im)*Dg0 - kron( (A')^2,Im)*Dg1 - Dg2; + + Df2Dtau = DmPl*( kron(GAM0,GAM0) - kron(GAM0,GAM1*A) - kron(GAM1*A,GAM0) + kron(GAM1*A,GAM1*A) )*Dm*Dom - ... + DmPl*( kron(GAM0*Om,GAM1) + kron(GAM1,GAM0*Om)*Kmm - kron(GAM1*A*Om,GAM1) - kron(GAM1,GAM1*A*Om)*Kmm )*Da; + + + Df2Dthet = DmPl*( kron(GAM0*Om,Im) + kron(Im,GAM0*Om)*Kmm - kron(Im,GAM1*A*Om)*Kmm - kron(GAM1*A*Om,Im) )*Dg0 - ... + DmPl*( kron(GAM0*Om*A',Im) + kron(Im,GAM0*Om*A')*Kmm - kron(Im,GAM1*A*Om*A')*Kmm - kron(GAM1*A*Om*A',Im) )*Dg1 -... + DmPl*( kron(GAM3,Im) + kron(Im,GAM3)*Kmn )*Dg3; + + + DfDtau = [Df1Dtau;Df2Dtau]; + DfDthet = [Df1Dthet;Df2Dthet]; + + H = -DfDtau\DfDthet; + x = reshape(H(1:m*m,:),m,m,param_nbr); + y = reshape(Dm*H(m*m+1:end,:),m,m,param_nbr); + x = x(nauxe+1:end,nauxe+1:end,:); + y = y(nauxe+1:end,nauxe+1:end,:); + m = size(y,1); + x = reshape(x,m*m,param_nbr); + Dm = duplication(m); + DmPl = inv(Dm'*Dm)*Dm'; + y = DmPl*reshape(y,m*m,param_nbr); + H = [x;y]; + + H = [ [zeros(M_.endo_nbr,length(indexo)) Hss]; H]; + +elseif kronflag==-1, % perturbation + fun = 'thet2tau'; + params0 = M_.params; + H = fdjac(fun,[sqrt(diag(M_.Sigma_e(indexo,indexo))); M_.params(indx)],indx,indexo); + assignin('base','M_', M_); + assignin('base','oo_', oo_); + +else % generalized sylvester equation + + % solves a*x+b*x*c=d + a = (GAM0-GAM1*A); + inva = inv(a); + b = -GAM1; + c = A; + elem = zeros(m,m,param_nbr); + d = elem; + for j=1:param_nbr, + elem(:,:,j) = (Dg0(:,:,j)-Dg1(:,:,j)*A); + d(:,:,j) = Dg2(:,:,j)-elem(:,:,j)*A; + end + xx=sylvester3mr(a,b,c,d); + if ~isempty(indexo), + dSig = zeros(M_.exo_nbr,M_.exo_nbr); + for j=1:length(indexo) + dSig(indexo(j),indexo(j)) = 2*sqrt(M_.Sigma_e(indexo(j),indexo(j))); + y = B*dSig*B'; + y = y(nauxe+1:end,nauxe+1:end); + H(:,j) = [zeros((m-nauxe)^2,1); vech(y)]; + if nargout>1, + dOm(:,:,j) = y; + end + dSig(indexo(j),indexo(j)) = 0; + end + end + for j=1:param_nbr, + x = xx(:,:,j); + y = inva * (Dg3(:,:,j)-(elem(:,:,j)-GAM1*x)*B); + y = y*M_.Sigma_e*B'+B*M_.Sigma_e*y'; + x = x(nauxe+1:end,nauxe+1:end); + y = y(nauxe+1:end,nauxe+1:end); + if nargout>1, + dA(:,:,j+length(indexo)) = x; + dOm(:,:,j+length(indexo)) = y; + end + H(:,j+length(indexo)) = [x(:); vech(y)]; + end + % for j=1:param_nbr, + % disp(['Derivatives w.r.t. ',M_.param_names(indx(j),:),', ',int2str(j),'/',int2str(param_nbr)]) + % elem = (Dg0(:,:,j)-Dg1(:,:,j)*A); + % d = Dg2(:,:,j)-elem*A; + % x=sylvester3(a,b,c,d); + % % x=sylvester3a(x,a,b,c,d); + % y = inva * (Dg3(:,:,j)-(elem-GAM1*x)*B); + % y = y*B'+B*y'; + % x = x(nauxe+1:end,nauxe+1:end); + % y = y(nauxe+1:end,nauxe+1:end); + % H(:,j) = [x(:); vech(y)]; + % end + H = [[zeros(M_.endo_nbr,length(indexo)) Hss]; H]; + +end + + +return + + diff --git a/matlab/getJJ.m b/matlab/getJJ.m index 2c5f7aabc9..d2f9f8a753 100644 --- a/matlab/getJJ.m +++ b/matlab/getJJ.m @@ -1,139 +1,139 @@ -function [JJ, H, gam] = getJJ(A, B, M_,oo_,options_,kronflag,indx,indexo,mf,nlags,useautocorr) - -% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. - -if nargin<7 | isempty(indx), indx = [1:M_.param_nbr];, end, -if nargin<8 | isempty(indexo), indexo = [];, end, -if nargin<10 | isempty(nlags), nlags=3; end, -if nargin<11 | isempty(useautocorr), useautocorr=0; end, - - if useautocorr, - warning('off','MATLAB:divideByZero') - end -if kronflag == -1, - fun = 'thet2tau'; - params0 = M_.params; - JJ = fdjac(fun,[sqrt(diag(M_.Sigma_e(indexo,indexo))); M_.params(indx)],indx,indexo,1,mf,nlags,useautocorr); - M_.params = params0; - params0 = M_.params; - H = fdjac(fun,[sqrt(diag(M_.Sigma_e(indexo,indexo))); M_.params(indx)],indx,indexo,0,mf,nlags,useautocorr); - M_.params = params0; - assignin('base','M_', M_); - assignin('base','oo_', oo_); -else - [H, dA, dOm, dYss] = getH(A, B, M_,oo_,kronflag,indx,indexo); -% if isempty(H), -% JJ = []; -% GAM = []; -% return -% end - m = length(A); - - GAM = lyapunov_symm(A,B*M_.Sigma_e*B',options_.qz_criterium,options_.lyapunov_complex_threshold,1); - k = find(abs(GAM) < 1e-12); - GAM(k) = 0; -% if useautocorr, - sdy = sqrt(diag(GAM)); - sy = sdy*sdy'; -% end - -% BB = dOm*0; -% for j=1:length(indx), -% BB(:,:,j)= dA(:,:,j)*GAM*A'+A*GAM*dA(:,:,j)'+dOm(:,:,j); -% end -% XX = lyapunov_symm_mr(A,BB,options_.qz_criterium,options_.lyapunov_complex_threshold,0); - for j=1:length(indexo), - dum = lyapunov_symm(A,dOm(:,:,j),options_.qz_criterium,options_.lyapunov_complex_threshold,2); -% dum = XX(:,:,j); - k = find(abs(dum) < 1e-12); - dum(k) = 0; - if useautocorr - dsy = 1/2./sdy.*diag(dum); - dsy = dsy*sdy'+sdy*dsy'; - dum1=dum; - dum1 = (dum1.*sy-dsy.*GAM)./(sy.*sy); - dum1 = dum1-diag(diag(dum1))+diag(diag(dum)); - dumm = vech(dum1(mf,mf)); - else - dumm = vech(dum(mf,mf)); - end - for i=1:nlags, - dum1 = A^i*dum; - if useautocorr - dum1 = (dum1.*sy-dsy.*(A^i*GAM))./(sy.*sy); - end - dumm = [dumm; vec(dum1(mf,mf))]; - end - JJ(:,j) = dumm; - end - nexo = length(indexo); - for j=1:length(indx), - dum = lyapunov_symm(A,dA(:,:,j+nexo)*GAM*A'+A*GAM*dA(:,:,j+nexo)'+dOm(:,:,j+nexo),options_.qz_criterium,options_.lyapunov_complex_threshold,2); -% dum = XX(:,:,j); - k = find(abs(dum) < 1e-12); - dum(k) = 0; - if useautocorr - dsy = 1/2./sdy.*diag(dum); - dsy = dsy*sdy'+sdy*dsy'; - dum1=dum; - dum1 = (dum1.*sy-dsy.*GAM)./(sy.*sy); - dum1 = dum1-diag(diag(dum1))+diag(diag(dum)); - dumm = vech(dum1(mf,mf)); - else - dumm = vech(dum(mf,mf)); - end - for i=1:nlags, - dum1 = A^i*dum; - for ii=1:i, - dum1 = dum1 + A^(ii-1)*dA(:,:,j+nexo)*A^(i-ii)*GAM; - end - if useautocorr - dum1 = (dum1.*sy-dsy.*(A^i*GAM))./(sy.*sy); - end - dumm = [dumm; vec(dum1(mf,mf))]; - end - JJ(:,j+nexo) = dumm; - end - - JJ = [ [zeros(length(mf),nexo) dYss(mf,:)]; JJ]; - - if nargout >2, -% sy=sy(mf,mf); - options_.ar=nlags; - [GAM,stationary_vars] = th_autocovariances(oo_.dr,oo_.dr.order_var(mf),M_,options_); - sy=sqrt(diag(GAM{1})); - sy=sy*sy'; - if useautocorr, - sy=sy-diag(diag(sy))+eye(length(mf)); - GAM{1}=GAM{1}./sy; - else - for j=1:nlags, - GAM{j+1}=GAM{j+1}.*sy; - end - end - gam = vech(GAM{1}); - for j=1:nlags, - gam = [gam; vec(GAM{j+1})]; - end - end - gam = [oo_.dr.ys(oo_.dr.order_var(mf)); gam]; -end - - if useautocorr, - warning('on','MATLAB:divideByZero') - end \ No newline at end of file +function [JJ, H, gam] = getJJ(A, B, M_,oo_,options_,kronflag,indx,indexo,mf,nlags,useautocorr) + +% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. + +if nargin<7 | isempty(indx), indx = [1:M_.param_nbr];, end, +if nargin<8 | isempty(indexo), indexo = [];, end, +if nargin<10 | isempty(nlags), nlags=3; end, +if nargin<11 | isempty(useautocorr), useautocorr=0; end, + +if useautocorr, + warning('off','MATLAB:divideByZero') +end +if kronflag == -1, + fun = 'thet2tau'; + params0 = M_.params; + JJ = fdjac(fun,[sqrt(diag(M_.Sigma_e(indexo,indexo))); M_.params(indx)],indx,indexo,1,mf,nlags,useautocorr); + M_.params = params0; + params0 = M_.params; + H = fdjac(fun,[sqrt(diag(M_.Sigma_e(indexo,indexo))); M_.params(indx)],indx,indexo,0,mf,nlags,useautocorr); + M_.params = params0; + assignin('base','M_', M_); + assignin('base','oo_', oo_); +else + [H, dA, dOm, dYss] = getH(A, B, M_,oo_,kronflag,indx,indexo); + % if isempty(H), + % JJ = []; + % GAM = []; + % return + % end + m = length(A); + + GAM = lyapunov_symm(A,B*M_.Sigma_e*B',options_.qz_criterium,options_.lyapunov_complex_threshold,1); + k = find(abs(GAM) < 1e-12); + GAM(k) = 0; + % if useautocorr, + sdy = sqrt(diag(GAM)); + sy = sdy*sdy'; + % end + + % BB = dOm*0; + % for j=1:length(indx), + % BB(:,:,j)= dA(:,:,j)*GAM*A'+A*GAM*dA(:,:,j)'+dOm(:,:,j); + % end + % XX = lyapunov_symm_mr(A,BB,options_.qz_criterium,options_.lyapunov_complex_threshold,0); + for j=1:length(indexo), + dum = lyapunov_symm(A,dOm(:,:,j),options_.qz_criterium,options_.lyapunov_complex_threshold,2); + % dum = XX(:,:,j); + k = find(abs(dum) < 1e-12); + dum(k) = 0; + if useautocorr + dsy = 1/2./sdy.*diag(dum); + dsy = dsy*sdy'+sdy*dsy'; + dum1=dum; + dum1 = (dum1.*sy-dsy.*GAM)./(sy.*sy); + dum1 = dum1-diag(diag(dum1))+diag(diag(dum)); + dumm = vech(dum1(mf,mf)); + else + dumm = vech(dum(mf,mf)); + end + for i=1:nlags, + dum1 = A^i*dum; + if useautocorr + dum1 = (dum1.*sy-dsy.*(A^i*GAM))./(sy.*sy); + end + dumm = [dumm; vec(dum1(mf,mf))]; + end + JJ(:,j) = dumm; + end + nexo = length(indexo); + for j=1:length(indx), + dum = lyapunov_symm(A,dA(:,:,j+nexo)*GAM*A'+A*GAM*dA(:,:,j+nexo)'+dOm(:,:,j+nexo),options_.qz_criterium,options_.lyapunov_complex_threshold,2); + % dum = XX(:,:,j); + k = find(abs(dum) < 1e-12); + dum(k) = 0; + if useautocorr + dsy = 1/2./sdy.*diag(dum); + dsy = dsy*sdy'+sdy*dsy'; + dum1=dum; + dum1 = (dum1.*sy-dsy.*GAM)./(sy.*sy); + dum1 = dum1-diag(diag(dum1))+diag(diag(dum)); + dumm = vech(dum1(mf,mf)); + else + dumm = vech(dum(mf,mf)); + end + for i=1:nlags, + dum1 = A^i*dum; + for ii=1:i, + dum1 = dum1 + A^(ii-1)*dA(:,:,j+nexo)*A^(i-ii)*GAM; + end + if useautocorr + dum1 = (dum1.*sy-dsy.*(A^i*GAM))./(sy.*sy); + end + dumm = [dumm; vec(dum1(mf,mf))]; + end + JJ(:,j+nexo) = dumm; + end + + JJ = [ [zeros(length(mf),nexo) dYss(mf,:)]; JJ]; + + if nargout >2, + % sy=sy(mf,mf); + options_.ar=nlags; + [GAM,stationary_vars] = th_autocovariances(oo_.dr,oo_.dr.order_var(mf),M_,options_); + sy=sqrt(diag(GAM{1})); + sy=sy*sy'; + if useautocorr, + sy=sy-diag(diag(sy))+eye(length(mf)); + GAM{1}=GAM{1}./sy; + else + for j=1:nlags, + GAM{j+1}=GAM{j+1}.*sy; + end + end + gam = vech(GAM{1}); + for j=1:nlags, + gam = [gam; vec(GAM{j+1})]; + end + end + gam = [oo_.dr.ys(oo_.dr.order_var(mf)); gam]; +end + +if useautocorr, + warning('on','MATLAB:divideByZero') +end \ No newline at end of file diff --git a/matlab/get_date_of_a_file.m b/matlab/get_date_of_a_file.m index b980eea6a5..76ee70c906 100644 --- a/matlab/get_date_of_a_file.m +++ b/matlab/get_date_of_a_file.m @@ -18,11 +18,11 @@ function [d1,d2] = get_date_of_a_file(filename) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - info = dir(filename); - if isempty(info) - error(['get_date_of_a_file:: I''m not able to find ' filename '!']) - end - d1 = info.datenum; - if nargout>1 - d2 = info.date; - end \ No newline at end of file +info = dir(filename); +if isempty(info) + error(['get_date_of_a_file:: I''m not able to find ' filename '!']) +end +d1 = info.datenum; +if nargout>1 + d2 = info.date; +end \ No newline at end of file diff --git a/matlab/get_moments_size.m b/matlab/get_moments_size.m index d65fc063f7..d02c6ca403 100644 --- a/matlab/get_moments_size.m +++ b/matlab/get_moments_size.m @@ -1,45 +1,45 @@ -function s=get_moments_size(options) -% function PosteriorFilterSmootherAndForecast(Y,gend, type) -% Computes posterior filter smoother and forecasts -% -% INPUTS -% options: structure of Dynare options -% -% OUTPUTS -% s: size of moments for a given model and options -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. - - global M_ - - n = size(options.varlist,1); - - if n == 0 - n = M_.endo_nbr; - end - - n2 = n*n; - - s = n; % mean - s = s + n; % std errors - s = s + n2; % variance - s = s + n2; % correlations - s = s + options.ar*n2; % auto-correlations \ No newline at end of file +function s=get_moments_size(options) +% function PosteriorFilterSmootherAndForecast(Y,gend, type) +% Computes posterior filter smoother and forecasts +% +% INPUTS +% options: structure of Dynare options +% +% OUTPUTS +% s: size of moments for a given model and options +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. + +global M_ + +n = size(options.varlist,1); + +if n == 0 + n = M_.endo_nbr; +end + +n2 = n*n; + +s = n; % mean +s = s + n; % std errors +s = s + n2; % variance +s = s + n2; % correlations +s = s + options.ar*n2; % auto-correlations \ No newline at end of file diff --git a/matlab/get_name_of_the_last_mh_file.m b/matlab/get_name_of_the_last_mh_file.m index 3a33664506..8089c870c3 100644 --- a/matlab/get_name_of_the_last_mh_file.m +++ b/matlab/get_name_of_the_last_mh_file.m @@ -10,7 +10,7 @@ function [mhname,info] = get_name_of_the_last_mh_file(M_) % metropolis hastings matches the name of the name of the last mh % file. Otherwise info is equal to zero (a likely reason for this is % that the mcmc simulations were not completed). - + % Copyright (C) 2008-2009 Dynare Team % % This file is part of Dynare. @@ -28,26 +28,26 @@ function [mhname,info] = get_name_of_the_last_mh_file(M_) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - mhname = []; - info = 1; - - MhDirectoryName = CheckPath('metropolis'); - - load([ MhDirectoryName '/' M_.fname '_mh_history.mat']) ; - mh_number = record.LastFileNumber ; - bk_number = record.Nblck ; - clear('record') ; - predicted_mhname = [ MhDirectoryName '/' M_.fname '_mh' int2str(mh_number) '_blck' int2str(bk_number) '.mat' ] ; - - AllMhFiles = dir([MhDirectoryName '/' M_.fname '_mh*_blck*' ]); - idx = 1; - for i=2:size(AllMhFiles) - if AllMhFiles(i).datenum>AllMhFiles(i-1).datenum - idx = i; - end +mhname = []; +info = 1; + +MhDirectoryName = CheckPath('metropolis'); + +load([ MhDirectoryName '/' M_.fname '_mh_history.mat']) ; +mh_number = record.LastFileNumber ; +bk_number = record.Nblck ; +clear('record') ; +predicted_mhname = [ MhDirectoryName '/' M_.fname '_mh' int2str(mh_number) '_blck' int2str(bk_number) '.mat' ] ; + +AllMhFiles = dir([MhDirectoryName '/' M_.fname '_mh*_blck*' ]); +idx = 1; +for i=2:size(AllMhFiles) + if AllMhFiles(i).datenum>AllMhFiles(i-1).datenum + idx = i; end - mhname = [ MhDirectoryName '/' AllMhFiles(idx).name]; - - if ~strcmpi(mhname,predicted_mhname) - info = 0; - end \ No newline at end of file +end +mhname = [ MhDirectoryName '/' AllMhFiles(idx).name]; + +if ~strcmpi(mhname,predicted_mhname) + info = 0; +end \ No newline at end of file diff --git a/matlab/get_param_by_name.m b/matlab/get_param_by_name.m index 6fac0ccbb5..d1e6793933 100644 --- a/matlab/get_param_by_name.m +++ b/matlab/get_param_by_name.m @@ -1,39 +1,39 @@ -function x = get_param_by_name(pname) -% function x = get_param_by_name(pname) -% returns the value of a parameter identified by its name -% -% INPUTS: -% pname: parameter name -% -% OUTPUTS -% x: parameter value -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. - - global M_ - - i = strmatch(pname,M_.param_names,'exact'); - - if isempty(i) - error(sprintf('Can''t find parameter %s', pname)) - end - - x = M_.params(i); +function x = get_param_by_name(pname) +% function x = get_param_by_name(pname) +% returns the value of a parameter identified by its name +% +% INPUTS: +% pname: parameter name +% +% OUTPUTS +% x: parameter value +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. + +global M_ + +i = strmatch(pname,M_.param_names,'exact'); + +if isempty(i) + error(sprintf('Can''t find parameter %s', pname)) +end + +x = M_.params(i); diff --git a/matlab/get_posterior_parameters.m b/matlab/get_posterior_parameters.m index 79fdf3e810..7fcf936a0c 100644 --- a/matlab/get_posterior_parameters.m +++ b/matlab/get_posterior_parameters.m @@ -1,89 +1,89 @@ -function xparam = get_posterior_parameters(type) - -% function xparam = get_posterior_parameters(type) -% Selects (estimated) parameters (posterior mode or posterior mean). -% -% INPUTS -% o type [char] = 'mode' or 'mean'. -% -% OUTPUTS -% o xparam vector of estimated parameters -% -% SPECIAL REQUIREMENTS -% None. - -% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. - -global estim_params_ oo_ options_ M_ - -nvx = estim_params_.nvx; -nvn = estim_params_.nvn; -ncx = estim_params_.ncx; -ncn = estim_params_.ncn; -np = estim_params_.np; - -xparam = zeros(nvx+nvn+ncx+ncn+np,1); - -m = 1; -for i=1:nvx - k1 = estim_params_.var_exo(i,1); - name1 = deblank(M_.exo_names(k1,:)); - xparam(m) = eval(['oo_.posterior_' type '.shocks_std.' name1]); - M_.Sigma_e(k1,k1) = xparam(m)^2; - m = m+1; -end - -for i=1:nvn - k1 = estim_params_.var_endo(i,1); - name1 = deblank(options_.varobs(k1,:)); - xparam(m) = eval(['oo_.posterior_' type '.measurement_errors_std.' name1]); - m = m+1; -end - -for i=1:ncx - k1 = estim_params_.corrx(i,1); - k2 = estim_params_.corrx(i,2); - name1 = deblank(M_.exo_names(k1,:)); - name2 = deblank(M_.exo_names(k2,:)); - xparam(m) = eval(['oo_.posterior_' type '.shocks_corr.' name1 '_' name2]); - M_.Sigma_e(k1,k2) = xparam(m); - M_.Sigma_e(k2,k1) = xparam(m); - m = m+1; -end - -for i=1:ncn - k1 = estim_params_.corrn(i,1); - k2 = estim_params_.corrn(i,2); - name1 = deblank(options_.varobs(k1,:)); - name2 = deblank(options_.varobs(k2,:)); - xparam(m) = eval(['oo_.posterior_' type '.measurement_errors_corr.' name1 '_' name2]); - m = m+1; -end - -FirstDeep = m; - -for i=1:np - name1 = deblank(M_.param_names(estim_params_.param_vals(i,1),:)); - xparam(m) = eval(['oo_.posterior_' type '.parameters.' name1]); - assignin('base',name1,xparam(m));% Useless with version 4 (except maybe for users) - m = m+1; -end - -if np - M_.params(estim_params_.param_vals(:,1)) = xparam(FirstDeep:end); +function xparam = get_posterior_parameters(type) + +% function xparam = get_posterior_parameters(type) +% Selects (estimated) parameters (posterior mode or posterior mean). +% +% INPUTS +% o type [char] = 'mode' or 'mean'. +% +% OUTPUTS +% o xparam vector of estimated parameters +% +% SPECIAL REQUIREMENTS +% None. + +% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. + +global estim_params_ oo_ options_ M_ + +nvx = estim_params_.nvx; +nvn = estim_params_.nvn; +ncx = estim_params_.ncx; +ncn = estim_params_.ncn; +np = estim_params_.np; + +xparam = zeros(nvx+nvn+ncx+ncn+np,1); + +m = 1; +for i=1:nvx + k1 = estim_params_.var_exo(i,1); + name1 = deblank(M_.exo_names(k1,:)); + xparam(m) = eval(['oo_.posterior_' type '.shocks_std.' name1]); + M_.Sigma_e(k1,k1) = xparam(m)^2; + m = m+1; +end + +for i=1:nvn + k1 = estim_params_.var_endo(i,1); + name1 = deblank(options_.varobs(k1,:)); + xparam(m) = eval(['oo_.posterior_' type '.measurement_errors_std.' name1]); + m = m+1; +end + +for i=1:ncx + k1 = estim_params_.corrx(i,1); + k2 = estim_params_.corrx(i,2); + name1 = deblank(M_.exo_names(k1,:)); + name2 = deblank(M_.exo_names(k2,:)); + xparam(m) = eval(['oo_.posterior_' type '.shocks_corr.' name1 '_' name2]); + M_.Sigma_e(k1,k2) = xparam(m); + M_.Sigma_e(k2,k1) = xparam(m); + m = m+1; +end + +for i=1:ncn + k1 = estim_params_.corrn(i,1); + k2 = estim_params_.corrn(i,2); + name1 = deblank(options_.varobs(k1,:)); + name2 = deblank(options_.varobs(k2,:)); + xparam(m) = eval(['oo_.posterior_' type '.measurement_errors_corr.' name1 '_' name2]); + m = m+1; +end + +FirstDeep = m; + +for i=1:np + name1 = deblank(M_.param_names(estim_params_.param_vals(i,1),:)); + xparam(m) = eval(['oo_.posterior_' type '.parameters.' name1]); + assignin('base',name1,xparam(m));% Useless with version 4 (except maybe for users) + m = m+1; +end + +if np + M_.params(estim_params_.param_vals(:,1)) = xparam(FirstDeep:end); end \ No newline at end of file diff --git a/matlab/get_prior_info.m b/matlab/get_prior_info.m index 352e866033..ce4e508287 100644 --- a/matlab/get_prior_info.m +++ b/matlab/get_prior_info.m @@ -26,152 +26,152 @@ function get_prior_info(info) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global options_ M_ estim_params_ oo_ - - if ~nargin - info = 0; - end +global options_ M_ estim_params_ oo_ - M_.dname = M_.fname; - - [xparam1,estim_params_,bayestopt_,lb,ub,M_] = set_prior(estim_params_,M_,options_); - plot_priors(bayestopt_,M_,options_); - - PriorNames = { 'Beta' , 'Gamma' , 'Gaussian' , 'Inverted Gamma' , 'Uniform' , 'Inverted Gamma -- 2' }; - - if size(M_.param_names,1)==size(M_.param_names_tex,1)% All the parameters have a TeX name. - fidTeX = fopen('priors_data.tex','w+'); - % Column 1: a string for the name of the prior distribution. - % Column 2: the prior mean. - % Column 3: the prior standard deviation. - % Column 4: the lower bound of the prior density support. - % Column 5: the upper bound of the prior density support. - % Column 6: the lower bound of the interval containing 80% of the prior mass. - % Column 7: the upper bound of the interval containing 80% of the prior mass. - prior_trunc_backup = options_.prior_trunc ; - options_.prior_trunc = (1-options_.prior_interval)/2 ; - PriorIntervals = prior_bounds(bayestopt_) ; - options_.prior_trunc = prior_trunc_backup ; - for i=1:size(bayestopt_.name,1) - [tmp,TexName] = get_the_name(i,1); - PriorShape = PriorNames{ bayestopt_.pshape(i) }; - PriorMean = bayestopt_.p1(i); - PriorStandardDeviation = bayestopt_.p2(i); - switch bayestopt_.pshape(i) - case { 1 , 5 } - LowerBound = bayestopt_.p3(i); - UpperBound = bayestopt_.p4(i); - case { 2 , 4 , 6 } +if ~nargin + info = 0; +end + +M_.dname = M_.fname; + +[xparam1,estim_params_,bayestopt_,lb,ub,M_] = set_prior(estim_params_,M_,options_); +plot_priors(bayestopt_,M_,options_); + +PriorNames = { 'Beta' , 'Gamma' , 'Gaussian' , 'Inverted Gamma' , 'Uniform' , 'Inverted Gamma -- 2' }; + +if size(M_.param_names,1)==size(M_.param_names_tex,1)% All the parameters have a TeX name. + fidTeX = fopen('priors_data.tex','w+'); + % Column 1: a string for the name of the prior distribution. + % Column 2: the prior mean. + % Column 3: the prior standard deviation. + % Column 4: the lower bound of the prior density support. + % Column 5: the upper bound of the prior density support. + % Column 6: the lower bound of the interval containing 80% of the prior mass. + % Column 7: the upper bound of the interval containing 80% of the prior mass. + prior_trunc_backup = options_.prior_trunc ; + options_.prior_trunc = (1-options_.prior_interval)/2 ; + PriorIntervals = prior_bounds(bayestopt_) ; + options_.prior_trunc = prior_trunc_backup ; + for i=1:size(bayestopt_.name,1) + [tmp,TexName] = get_the_name(i,1); + PriorShape = PriorNames{ bayestopt_.pshape(i) }; + PriorMean = bayestopt_.p1(i); + PriorStandardDeviation = bayestopt_.p2(i); + switch bayestopt_.pshape(i) + case { 1 , 5 } + LowerBound = bayestopt_.p3(i); + UpperBound = bayestopt_.p4(i); + case { 2 , 4 , 6 } + LowerBound = bayestopt_.p3(i); + UpperBound = '$\infty$'; + case 3 + if isinf(bayestopt_.p3(i)) + LowerBound = '$-\infty$'; + else LowerBound = bayestopt_.p3(i); + end + if isinf(bayestopt_.p4(i)) UpperBound = '$\infty$'; - case 3 - if isinf(bayestopt_.p3(i)) - LowerBound = '$-\infty$'; - else - LowerBound = bayestopt_.p3(i); - end - if isinf(bayestopt_.p4(i)) - UpperBound = '$\infty$'; - else - UpperBound = bayestopt_.p4(i); - end - otherwise - error('get_prior_info:: Dynare bug!') + else + UpperBound = bayestopt_.p4(i); end - format_string = build_format_string(bayestopt_,i); - fprintf(fidTeX,format_string, ... - TexName, ... - PriorShape, ... - PriorMean, ... - PriorStandardDeviation, ... - LowerBound, ... - UpperBound, ... - PriorIntervals(i,1), ... - PriorIntervals(i,2) ); + otherwise + error('get_prior_info:: Dynare bug!') end - fclose(fidTeX); + format_string = build_format_string(bayestopt_,i); + fprintf(fidTeX,format_string, ... + TexName, ... + PriorShape, ... + PriorMean, ... + PriorStandardDeviation, ... + LowerBound, ... + UpperBound, ... + PriorIntervals(i,1), ... + PriorIntervals(i,2) ); end - - M_.dname = M_.fname; + fclose(fidTeX); +end - if info==1% Prior simulations (BK). - results = prior_sampler(0,M_,bayestopt_,options_,oo_); - % Display prior mass info - disp(['Prior mass = ' num2str(results.prior.mass)]) - disp(['BK indeterminacy share = ' num2str(results.bk.indeterminacy_share)]) - disp(['BK unstability share = ' num2str(results.bk.unstability_share)]) - disp(['BK singularity share = ' num2str(results.bk.singularity_share)]) - disp(['Complex jacobian share = ' num2str(results.jacobian.problem_share)]) - disp(['mjdgges crash share = ' num2str(results.dll.problem_share)]) - disp(['Steady state problem share = ' num2str(results.ss.problem_share)]) - disp(['Complex steady state share = ' num2str(results.ss.complex_share)]) - disp(['Analytical steady state problem share = ' num2str(results.ass.problem_share)]) - end - - if info==2% Prior optimization. - % Initialize to the prior mode if possible - k = find(~isnan(bayestopt_.p5)); - xparam1(k) = bayestopt_.p5(k); - % Pertubation of the initial condition. - look_for_admissible_initial_condition = 1; - scale = 1.0; - iter = 0; - while look_for_admissible_initial_condition - xinit = xparam1+scale*randn(size(xparam1)); - if all(xinit>bayestopt_.p3) && all(xinit<bayestopt_.p4) - look_for_admissible_initial_condition = 0; +M_.dname = M_.fname; + +if info==1% Prior simulations (BK). + results = prior_sampler(0,M_,bayestopt_,options_,oo_); + % Display prior mass info + disp(['Prior mass = ' num2str(results.prior.mass)]) + disp(['BK indeterminacy share = ' num2str(results.bk.indeterminacy_share)]) + disp(['BK unstability share = ' num2str(results.bk.unstability_share)]) + disp(['BK singularity share = ' num2str(results.bk.singularity_share)]) + disp(['Complex jacobian share = ' num2str(results.jacobian.problem_share)]) + disp(['mjdgges crash share = ' num2str(results.dll.problem_share)]) + disp(['Steady state problem share = ' num2str(results.ss.problem_share)]) + disp(['Complex steady state share = ' num2str(results.ss.complex_share)]) + disp(['Analytical steady state problem share = ' num2str(results.ass.problem_share)]) +end + +if info==2% Prior optimization. + % Initialize to the prior mode if possible + k = find(~isnan(bayestopt_.p5)); + xparam1(k) = bayestopt_.p5(k); + % Pertubation of the initial condition. + look_for_admissible_initial_condition = 1; + scale = 1.0; + iter = 0; + while look_for_admissible_initial_condition + xinit = xparam1+scale*randn(size(xparam1)); + if all(xinit>bayestopt_.p3) && all(xinit<bayestopt_.p4) + look_for_admissible_initial_condition = 0; + else + if iter == 2000; + scale = scale/1.1; + iter = 0; else - if iter == 2000; - scale = scale/1.1; - iter = 0; - else - iter = iter+1; - end + iter = iter+1; end end - % Maximization - [xparams,lpd,hessian] = ... - maximize_prior_density(xinit, bayestopt_.pshape, ... - bayestopt_.p6, ... - bayestopt_.p7, ... - bayestopt_.p3, ... - bayestopt_.p4); - % Display the results. - disp(' ') - disp(' ') - disp('------------------') - disp('PRIOR OPTIMIZATION') - disp('------------------') + end + % Maximization + [xparams,lpd,hessian] = ... + maximize_prior_density(xinit, bayestopt_.pshape, ... + bayestopt_.p6, ... + bayestopt_.p7, ... + bayestopt_.p3, ... + bayestopt_.p4); + % Display the results. + disp(' ') + disp(' ') + disp('------------------') + disp('PRIOR OPTIMIZATION') + disp('------------------') + disp(' ') + for i = 1:length(xparams) + disp(['deep parameter ' int2str(i) ': ' get_the_name(i,0) '.']) + disp([' Initial condition ....... ' num2str(xinit(i)) '.']) + disp([' Prior mode .............. ' num2str(bayestopt_.p5(i)) '.']) + disp([' Optimized prior mode .... ' num2str(xparams(i)) '.']) disp(' ') - for i = 1:length(xparams) - disp(['deep parameter ' int2str(i) ': ' get_the_name(i,0) '.']) - disp([' Initial condition ....... ' num2str(xinit(i)) '.']) - disp([' Prior mode .............. ' num2str(bayestopt_.p5(i)) '.']) - disp([' Optimized prior mode .... ' num2str(xparams(i)) '.']) - disp(' ') - end end - - if info==3% Prior simulations (2nd order moments). - oo_ = compute_moments_varendo('prior',options_,M_,oo_); - end +end + +if info==3% Prior simulations (2nd order moments). + oo_ = compute_moments_varendo('prior',options_,M_,oo_); +end + - function format_string = build_format_string(bayestopt,i) - format_string = ['%s & %s & %6.4f &']; - if isinf(bayestopt.p2(i)) - format_string = [ format_string , ' %s &']; - else - format_string = [ format_string , ' %6.4f &']; - end - if isinf(bayestopt.p3(i)) - format_string = [ format_string , ' %s &']; - else - format_string = [ format_string , ' %6.4f &']; - end - if isinf(bayestopt.p4(i)) - format_string = [ format_string , ' %s &']; - else - format_string = [ format_string , ' %6.4f &']; - end - format_string = [ format_string , ' %6.4f & %6.4f \\\\ \n']; \ No newline at end of file +format_string = ['%s & %s & %6.4f &']; +if isinf(bayestopt.p2(i)) + format_string = [ format_string , ' %s &']; +else + format_string = [ format_string , ' %6.4f &']; +end +if isinf(bayestopt.p3(i)) + format_string = [ format_string , ' %s &']; +else + format_string = [ format_string , ' %6.4f &']; +end +if isinf(bayestopt.p4(i)) + format_string = [ format_string , ' %s &']; +else + format_string = [ format_string , ' %6.4f &']; +end +format_string = [ format_string , ' %6.4f & %6.4f \\\\ \n']; \ No newline at end of file diff --git a/matlab/get_variance_of_endogenous_variables.m b/matlab/get_variance_of_endogenous_variables.m index 77db2c5f72..2e3bbd4394 100644 --- a/matlab/get_variance_of_endogenous_variables.m +++ b/matlab/get_variance_of_endogenous_variables.m @@ -1,64 +1,64 @@ -function [vx1,i_ns] = get_variance_of_endogenous_variables(dr,i_var) - -% function [vx1,i_ns] = get_variance_of_endogenous_variables(dr,i_var) -% Gets the variance of a variables subset -% -% INPUTS -% dr: structure of decisions rules for stochastic simulations -% i_var: indices of a variables list -% -% OUTPUTS -% vx1: variance-covariance matrix -% i_ns: non-stationary variables indices for which the variance has -% been calculated -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2003-2008 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 <http://www.gnu.org/licenses/>. - - global M_ options_ - - endo_nbr = M_.endo_nbr; - - Sigma_e = M_.Sigma_e; - - nstatic = dr.nstatic; - npred = dr.npred; - ghx = dr.ghx(i_var,:); - ghu = dr.ghu(i_var,:); - nc = size(ghx,2); - n = length(i_var); - - [A,B] = kalman_transition_matrix(dr,nstatic+(1:npred),1:nc,dr.transition_auxiliary_variables,M_.exo_nbr); - - [vx,u] = lyapunov_symm(A,B*Sigma_e*B',options_.qz_criterium,options_.lyapunov_complex_threshold); - - if size(u,2) > 0 - i_stat_0 = find(any(abs(A*u) < options_.Schur_vec_tol,2)); - i_stat = find(any(abs(ghx*u) < options_.Schur_vec_tol,2)); - - ghx = ghx(i_stat,:); - ghu = ghu(i_stat,:); - else - i_stat = (1:n)'; - end - - vx1 = Inf*ones(n,n); - vx1(i_stat,i_stat) = ghx(:,i_stat_0)*vx(i_stat_0,i_stat_0)*ghx(:,i_stat_0)'+ghu*Sigma_e*ghu'; - +function [vx1,i_ns] = get_variance_of_endogenous_variables(dr,i_var) + +% function [vx1,i_ns] = get_variance_of_endogenous_variables(dr,i_var) +% Gets the variance of a variables subset +% +% INPUTS +% dr: structure of decisions rules for stochastic simulations +% i_var: indices of a variables list +% +% OUTPUTS +% vx1: variance-covariance matrix +% i_ns: non-stationary variables indices for which the variance has +% been calculated +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2003-2008 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 <http://www.gnu.org/licenses/>. + +global M_ options_ + +endo_nbr = M_.endo_nbr; + +Sigma_e = M_.Sigma_e; + +nstatic = dr.nstatic; +npred = dr.npred; +ghx = dr.ghx(i_var,:); +ghu = dr.ghu(i_var,:); +nc = size(ghx,2); +n = length(i_var); + +[A,B] = kalman_transition_matrix(dr,nstatic+(1:npred),1:nc,dr.transition_auxiliary_variables,M_.exo_nbr); + +[vx,u] = lyapunov_symm(A,B*Sigma_e*B',options_.qz_criterium,options_.lyapunov_complex_threshold); + +if size(u,2) > 0 + i_stat_0 = find(any(abs(A*u) < options_.Schur_vec_tol,2)); + i_stat = find(any(abs(ghx*u) < options_.Schur_vec_tol,2)); + + ghx = ghx(i_stat,:); + ghu = ghu(i_stat,:); +else + i_stat = (1:n)'; +end + +vx1 = Inf*ones(n,n); +vx1(i_stat,i_stat) = ghx(:,i_stat_0)*vx(i_stat_0,i_stat_0)*ghx(:,i_stat_0)'+ghu*Sigma_e*ghu'; + diff --git a/matlab/global_initialization.m b/matlab/global_initialization.m index 89021f92fc..70914a0fe3 100644 --- a/matlab/global_initialization.m +++ b/matlab/global_initialization.m @@ -28,256 +28,256 @@ function global_initialization() % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global oo_ M_ options_ +global oo_ M_ options_ - options_.terminal_condition = 0; - options_.rplottype = 0; - options_.smpl = 0; - options_.dynatol = 0.00001; - options_.maxit_ = 10; - options_.slowc = 1; - options_.timing = 0; - options_.gstep = 1e-2; - options_.scalv = 1; - options_.debug = 0; - options_.initval_file = 0; - options_.Schur_vec_tol = 1e-11; % used to find nonstationary variables - % in Schur decomposition of the - % transition matrix - options_.qz_criterium = 1.000001; - options_.lyapunov_complex_threshold = 1e-15; - options_.solve_tolf = eps^(1/3); - options_.solve_tolx = eps^(2/3); - options_.solve_maxit = 500; - options_.deterministic_simulation_initialization = 0; +options_.terminal_condition = 0; +options_.rplottype = 0; +options_.smpl = 0; +options_.dynatol = 0.00001; +options_.maxit_ = 10; +options_.slowc = 1; +options_.timing = 0; +options_.gstep = 1e-2; +options_.scalv = 1; +options_.debug = 0; +options_.initval_file = 0; +options_.Schur_vec_tol = 1e-11; % used to find nonstationary variables + % in Schur decomposition of the + % transition matrix +options_.qz_criterium = 1.000001; +options_.lyapunov_complex_threshold = 1e-15; +options_.solve_tolf = eps^(1/3); +options_.solve_tolx = eps^(2/3); +options_.solve_maxit = 500; +options_.deterministic_simulation_initialization = 0; - % steady state file - if exist([M_.fname '_steadystate.m'],'file') +% steady state file +if exist([M_.fname '_steadystate.m'],'file') options_.steadystate_flag = 1; - else +else options_.steadystate_flag = 0; - end - options_.steadystate_partial = []; +end +options_.steadystate_partial = []; - % subset of the estimated deep parameters - options_.ParamSubSet = 'None'; +% subset of the estimated deep parameters +options_.ParamSubSet = 'None'; - % bvar-dsge - options_.bvar_dsge = 0; - options_.varlag = 4; +% bvar-dsge +options_.bvar_dsge = 0; +options_.varlag = 4; - % Optimization algorithm [6] gmhmaxlik - options_.Opt6Iter = 2; - options_.Opt6Numb = 5000; +% Optimization algorithm [6] gmhmaxlik +options_.Opt6Iter = 2; +options_.Opt6Numb = 5000; - % Graphics - options_.graphics.nrows = 3; - options_.graphics.ncols = 3; - options_.graphics.line_types = {'b-'}; - options_.graphics.line_width = 1; - options_.nograph = 0; - options_.XTick = []; - options_.XTickLabel = []; +% Graphics +options_.graphics.nrows = 3; +options_.graphics.ncols = 3; +options_.graphics.line_types = {'b-'}; +options_.graphics.line_width = 1; +options_.nograph = 0; +options_.XTick = []; +options_.XTickLabel = []; - % IRFs & other stoch_simul output - options_.irf = 40; - options_.relative_irf = 0; - options_.ar = 5; - options_.simul_seed = []; - options_.hp_filter = 0; - options_.hp_ngrid = 512; - options_.nomoments = 0; - options_.nocorr = 0; - options_.periods = 0; - options_.noprint = 0; - options_.SpectralDensity = 0; +% IRFs & other stoch_simul output +options_.irf = 40; +options_.relative_irf = 0; +options_.ar = 5; +options_.simul_seed = []; +options_.hp_filter = 0; +options_.hp_ngrid = 512; +options_.nomoments = 0; +options_.nocorr = 0; +options_.periods = 0; +options_.noprint = 0; +options_.SpectralDensity = 0; - % TeX output - options_.TeX = 0; +% TeX output +options_.TeX = 0; - % Exel - options_.xls_sheet = ''; - options_.xls_range = ''; +% Exel +options_.xls_sheet = ''; +options_.xls_range = ''; - % Prior draws - options_.forecast = 0; +% Prior draws +options_.forecast = 0; - % Model - options_.linear = 0; +% Model +options_.linear = 0; - % Deterministic simulation - options_.stack_solve_algo = 0; - options_.markowitz = 0.5; - options_.minimal_solving_periods = 1; - - % Solution - options_.order = 2; - options_.solve_algo = 2; - options_.linear = 0; - options_.replic = 50; - options_.drop = 100; - % if mjdgges.dll (or .mexw32 or ....) doesn't exist, matlab/qz is added to the path. - % There exists now qz/mjdgges.m that contains the calls to the old Sims code - % Hence, if mjdgges.m is visible exist(...)==2, - % this means that the DLL isn't avaiable and use_qzdiv is set to 1 - if exist('mjdgges')==2 - options_.use_qzdiv = 1; - else - options_.use_qzdiv = 0; - end - options_.aim_solver = 0; % i.e. by default do not use G.Anderson's AIM solver, use mjdgges instead - options_.k_order_solver=0; % by default do not use k_order_perturbation but mjdgges - options_.partial_information = 0; - options_.conditional_variance_decomposition = []; - - % Ramsey policy - options_.planner_discount = 1.0; - options_.ramsey_policy = 0; - options_.timeless = 0; - - % estimation - options_.Harvey_scale_factor = 10; - options_.MaxNumberOfBytes = 1e6; - options_.MaximumNumberOfMegaBytes = 111; - options_.PosteriorSampleSize = 1000; - options_.bayesian_irf = 0; - options_.bayesian_th_moments = 0; - options_.diffuse_d = []; - options_.diffuse_filter = 0; - options_.filter_step_ahead = []; - options_.filtered_vars = 0; - options_.first_obs = 1; - options_.kalman_algo = 0; - options_.kalman_tol = 1e-12; - options_.riccati_tol = 1e-6; - options_.lik_algo = 1; - options_.lik_init = 1; - options_.load_mh_file = 0; - options_.logdata = 0; - options_.loglinear = 0; - options_.mh_conf_sig = 0.90; - options_.prior_interval = 0.90; - options_.mh_drop = 0.5; - options_.mh_jscale = 0.2; - options_.mh_init_scale = 2*options_.mh_jscale; - options_.mh_mode = 1; - options_.mh_nblck = 2; - options_.mh_recover = 0; - options_.mh_replic = 20000; - options_.mode_check = 0; - options_.mode_check_nolik = 0; - options_.mode_compute = 4; - options_.mode_file = ''; - options_.moments_varendo = 0; - options_.nk = 1; - options_.noconstant = 0; - options_.nodiagnostic = 0; - options_.posterior_mode_estimation = 1; - options_.prefilter = 0; - options_.presample = 0; - options_.prior_trunc = 1e-10; - options_.smoother = 0; - options_.student_degrees_of_freedom = 3; - options_.subdraws = []; - options_.unit_root_vars = []; - options_.use_mh_covariance_matrix = 0; - options_.gradient_method = 2; - options_.posterior_sampling_method = 'random_walk_metropolis_hastings'; - options_.proposal_distribution = 'rand_multivariate_normal'; - options_.student_degrees_of_freedom = 3; - options_.trace_plot_ma = 200; - options_.mh_autocorrelation_function_size = 30; - options_.plot_priors = 1; - options_.cova_compute = 1; - options_.parallel = 0; - options_.number_of_grid_points_for_kde = 2^9; - quarter = 1; - years = [1 2 3 4 5 10 20 30 40 50]; - options_.conditional_variance_decomposition_dates = zeros(1,length(years)); - for i=1:length(years) - options_.conditional_variance_decomposition_dates(i) = ... - (years(i)-1)*4+quarter; - end - % Misc - options_.conf_sig = 0.6; - oo_.exo_simul = []; - oo_.endo_simul = []; - oo_.dr = []; - oo_.exo_steady_state = []; - oo_.exo_det_steady_state = []; - oo_.exo_det_simul = []; +% Deterministic simulation +options_.stack_solve_algo = 0; +options_.markowitz = 0.5; +options_.minimal_solving_periods = 1; - M_.params = []; - - % Variance matrix for measurement errors - M_.H = 0; +% Solution +options_.order = 2; +options_.solve_algo = 2; +options_.linear = 0; +options_.replic = 50; +options_.drop = 100; +% if mjdgges.dll (or .mexw32 or ....) doesn't exist, matlab/qz is added to the path. +% There exists now qz/mjdgges.m that contains the calls to the old Sims code +% Hence, if mjdgges.m is visible exist(...)==2, +% this means that the DLL isn't avaiable and use_qzdiv is set to 1 +if exist('mjdgges')==2 + options_.use_qzdiv = 1; +else + options_.use_qzdiv = 0; +end +options_.aim_solver = 0; % i.e. by default do not use G.Anderson's AIM solver, use mjdgges instead +options_.k_order_solver=0; % by default do not use k_order_perturbation but mjdgges +options_.partial_information = 0; +options_.conditional_variance_decomposition = []; - % BVAR - M_.bvar = []; +% Ramsey policy +options_.planner_discount = 1.0; +options_.ramsey_policy = 0; +options_.timeless = 0; - % homotopy - options_.homotopy_mode = 0; - options_.homotopy_steps = 1; +% estimation +options_.Harvey_scale_factor = 10; +options_.MaxNumberOfBytes = 1e6; +options_.MaximumNumberOfMegaBytes = 111; +options_.PosteriorSampleSize = 1000; +options_.bayesian_irf = 0; +options_.bayesian_th_moments = 0; +options_.diffuse_d = []; +options_.diffuse_filter = 0; +options_.filter_step_ahead = []; +options_.filtered_vars = 0; +options_.first_obs = 1; +options_.kalman_algo = 0; +options_.kalman_tol = 1e-12; +options_.riccati_tol = 1e-6; +options_.lik_algo = 1; +options_.lik_init = 1; +options_.load_mh_file = 0; +options_.logdata = 0; +options_.loglinear = 0; +options_.mh_conf_sig = 0.90; +options_.prior_interval = 0.90; +options_.mh_drop = 0.5; +options_.mh_jscale = 0.2; +options_.mh_init_scale = 2*options_.mh_jscale; +options_.mh_mode = 1; +options_.mh_nblck = 2; +options_.mh_recover = 0; +options_.mh_replic = 20000; +options_.mode_check = 0; +options_.mode_check_nolik = 0; +options_.mode_compute = 4; +options_.mode_file = ''; +options_.moments_varendo = 0; +options_.nk = 1; +options_.noconstant = 0; +options_.nodiagnostic = 0; +options_.posterior_mode_estimation = 1; +options_.prefilter = 0; +options_.presample = 0; +options_.prior_trunc = 1e-10; +options_.smoother = 0; +options_.student_degrees_of_freedom = 3; +options_.subdraws = []; +options_.unit_root_vars = []; +options_.use_mh_covariance_matrix = 0; +options_.gradient_method = 2; +options_.posterior_sampling_method = 'random_walk_metropolis_hastings'; +options_.proposal_distribution = 'rand_multivariate_normal'; +options_.student_degrees_of_freedom = 3; +options_.trace_plot_ma = 200; +options_.mh_autocorrelation_function_size = 30; +options_.plot_priors = 1; +options_.cova_compute = 1; +options_.parallel = 0; +options_.number_of_grid_points_for_kde = 2^9; +quarter = 1; +years = [1 2 3 4 5 10 20 30 40 50]; +options_.conditional_variance_decomposition_dates = zeros(1,length(years)); +for i=1:length(years) + options_.conditional_variance_decomposition_dates(i) = ... + (years(i)-1)*4+quarter; +end +% Misc +options_.conf_sig = 0.6; +oo_.exo_simul = []; +oo_.endo_simul = []; +oo_.dr = []; +oo_.exo_steady_state = []; +oo_.exo_det_steady_state = []; +oo_.exo_det_simul = []; - % prior analysis - options_.prior_mc = 20000; - options_.prior_analysis_endo_var_list = []; - - % did model undergo block decomposition + minimum feedback set computation ? - options_.block = 0; +M_.params = []; - % model evaluated using a compiled MEX - options_.use_dll = 0; - - % model evaluated using bytecode.dll - options_.bytecode = 0; - - % SWZ SBVAR - options_.ms.freq = 1; - options_.ms.initial_subperiod = 1; - options_.ms.final_subperiod=4; - options_.ms.log_var = [ ]; - options_.ms.forecast = 1; - options_.ms.nlags = 1; - options_.ms.cross_restrictions = 0; - options_.ms.contemp_reduced_form = 0; - options_.ms.real_pseudo_forecast = 0; - options_.ms.bayesian_prior = 1; - options_.ms.dummy_obs = 0; - options_.ms.ncsk = 0; - options_.ms.nstd = 6; - options_.ms.ninv = 1000; - options_.ms.indxparr = 1; - options_.ms.indxovr = 0; - options_.ms.aband = 1; - options_.ms.indxap = 1; - options_.ms.apband = 1; - options_.ms.indximf = 1; - options_.ms.imfband = 1; - options_.ms.indxfore = 0; - options_.ms.foreband = 0; - options_.ms.indxgforhat = 1; - options_.ms.indxgimfhat = 1; - options_.ms.indxestima = 1; - options_.ms.indxgdls = 1; - options_.ms.cms =0; - options_.ms.ncms = 0; - options_.ms.eq_cms = 1; - options_.ms.cnum = 0; - options_.ms.banact = 1; - options_.ms.nstates = 2; - options_.ms.indxscalesstates = 0; - options_.ms.alpha = 1.0; - options_.ms.beta = 1.0; - options_.ms.gsig2_lmd = 50^2; - options_.ms.gsig2_lmdm = 50^2; - options_.ms.q_diag = 0.85; - options_.ms.flat_prior = 0; - options_.ms.create_initialization_file = 1; - options_.ms.estimate_msmodel = 1; - options_.ms.compute_mdd = 1; - options_.ms.compute_probabilities = 1; - options_.ms.print_draws = 1; - options_.ms.n_draws=1000; - options_.ms.thinning_factor=1; - options_.ms.proposal_draws = 100000; +% Variance matrix for measurement errors +M_.H = 0; + +% BVAR +M_.bvar = []; + +% homotopy +options_.homotopy_mode = 0; +options_.homotopy_steps = 1; + +% prior analysis +options_.prior_mc = 20000; +options_.prior_analysis_endo_var_list = []; + +% did model undergo block decomposition + minimum feedback set computation ? +options_.block = 0; + +% model evaluated using a compiled MEX +options_.use_dll = 0; + +% model evaluated using bytecode.dll +options_.bytecode = 0; + +% SWZ SBVAR +options_.ms.freq = 1; +options_.ms.initial_subperiod = 1; +options_.ms.final_subperiod=4; +options_.ms.log_var = [ ]; +options_.ms.forecast = 1; +options_.ms.nlags = 1; +options_.ms.cross_restrictions = 0; +options_.ms.contemp_reduced_form = 0; +options_.ms.real_pseudo_forecast = 0; +options_.ms.bayesian_prior = 1; +options_.ms.dummy_obs = 0; +options_.ms.ncsk = 0; +options_.ms.nstd = 6; +options_.ms.ninv = 1000; +options_.ms.indxparr = 1; +options_.ms.indxovr = 0; +options_.ms.aband = 1; +options_.ms.indxap = 1; +options_.ms.apband = 1; +options_.ms.indximf = 1; +options_.ms.imfband = 1; +options_.ms.indxfore = 0; +options_.ms.foreband = 0; +options_.ms.indxgforhat = 1; +options_.ms.indxgimfhat = 1; +options_.ms.indxestima = 1; +options_.ms.indxgdls = 1; +options_.ms.cms =0; +options_.ms.ncms = 0; +options_.ms.eq_cms = 1; +options_.ms.cnum = 0; +options_.ms.banact = 1; +options_.ms.nstates = 2; +options_.ms.indxscalesstates = 0; +options_.ms.alpha = 1.0; +options_.ms.beta = 1.0; +options_.ms.gsig2_lmd = 50^2; +options_.ms.gsig2_lmdm = 50^2; +options_.ms.q_diag = 0.85; +options_.ms.flat_prior = 0; +options_.ms.create_initialization_file = 1; +options_.ms.estimate_msmodel = 1; +options_.ms.compute_mdd = 1; +options_.ms.compute_probabilities = 1; +options_.ms.print_draws = 1; +options_.ms.n_draws=1000; +options_.ms.thinning_factor=1; +options_.ms.proposal_draws = 100000; diff --git a/matlab/gmhmaxlik.m b/matlab/gmhmaxlik.m index 7a47bfbca8..96b61ba5cb 100644 --- a/matlab/gmhmaxlik.m +++ b/matlab/gmhmaxlik.m @@ -1,279 +1,279 @@ -function [PostMod,PostVar,Scale,PostMean] = ... - gmhmaxlik(ObjFun,xparam1,mh_bounds,num,iScale,info,MeanPar,VarCov,varargin) - -%function [PostMod,PostVar,Scale,PostMean] = ... -%gmhmaxlik(ObjFun,xparam1,mh_bounds,num,iScale,info,MeanPar,VarCov,varargin) -% (Dirty) Global minimization routine of (minus) a likelihood (or posterior density) function. -% -% INPUTS -% o ObjFun [char] string specifying the name of the objective function. -% o xparam1 [double] (p*1) vector of parameters to be estimated. -% o mh_bounds [double] (p*2) matrix defining lower and upper bounds for the parameters. -% o num [integer] scalar specifying the number of MH iterations in step 2. -% o iScale [double] scalar specifying the initial of the jumping distribution's scale parameter. -% o info [char] string, empty or equal to 'LastCall'. -% o MeanPar [double] (p*1) vector specifying the initial posterior mean. -% o VarCov [double] (p*p) matrix specifying the initial posterior covariance matrix. -% o gend [integer] scalar specifying the number of observations ==> varargin{1}. -% o data [double] (T*n) matrix of data ==> varargin{2}. -% -% OUTPUTS -% o PostMod [double] (p*1) vector, evaluation of the posterior mode. -% o PostVar [double] (p*p) matrix, evaluation of the posterior covariance matrix. -% o Scale [double] scalar specifying the scale parameter that should be used in -% an eventual metropolis-hastings algorithm. -% o PostMean [double] (p*1) vector, evaluation of the posterior mean. -% -% ALGORITHM -% Metropolis-Hastings with an constantly updated covariance matrix for -% the jump distribution. The posterior mean, variance and mode are -% updated (in step 2) with the following rules: -% -% \[ -% \mu_t = \mu_{t-1} + \frac{1}{t}\left(\theta_t-\mu_{t-1}\right) -% \] -% -% \[ -% \Sigma_t = \Sigma_{t-1} + \mu_{t-1}\mu_{t-1}'-\mu_{t}\mu_{t}' + -% \frac{1}{t}\left(\theta_t\theta_t'-\Sigma_{t-1}-\mu_{t-1}\mu_{t-1}'\right) -% \] -% -% and -% -% \[ -% \mathrm{mode}_t = \left\{ -% \begin{array}{ll} -% \theta_t, & \hbox{if } p(\theta_t|\mathcal Y) > p(\mathrm{mode}_{t-1}|\mathcal Y) \\ -% \mathrm{mode}_{t-1}, & \hbox{otherwise.} -% \end{array} -% \right. -% \] -% -% where $t$ is the iteration, $\mu_t$ the estimate of the posterior mean -% after $t$ iterations, $\Sigma_t$ the estimate of the posterior -% covariance matrix after $t$ iterations, $\mathrm{mode}_t$ is the -% evaluation of the posterior mode after $t$ iterations and -% $p(\theta_t|\mathcal Y)$ is the posterior density of parameters -% (specified by the user supplied function "fun"). -% -% SPECIAL REQUIREMENTS -% None. - -% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. - -global bayestopt_ estim_params_ options_ - -options_.lik_algo = 1; -npar = length(xparam1); - -NumberOfIterations = num; -MaxNumberOfTuningSimulations = 200000; -MaxNumberOfClimbingSimulations = 200000; -AcceptanceTarget = 1/3; - -CovJump = VarCov; -ModePar = xparam1; - -%% [1] I tune the scale parameter. -hh = waitbar(0,'Tuning of the scale parameter...'); -set(hh,'Name','Tuning of the scale parameter.') -j = 1; jj = 1; -isux = 0; jsux = 0; test = 0; -ix2 = ModePar;% initial condition! -ilogpo2 = - feval(ObjFun,ix2,varargin{:});% initial posterior density -mlogpo2 = ilogpo2; -try - dd = transpose(chol(CovJump)); -catch - dd = eye(length(CovJump)); -end -while j<=MaxNumberOfTuningSimulations - proposal = iScale*dd*randn(npar,1) + ix2; - if all(proposal > mh_bounds(:,1)) & all(proposal < mh_bounds(:,2)) - logpo2 = - feval(ObjFun,proposal,varargin{:}); - else - logpo2 = -inf; - end - % I move if the proposal is enough likely... - if logpo2 > -inf & log(rand) < logpo2 - ilogpo2 - ix2 = proposal; - if logpo2 > mlogpo2 - ModePar = proposal; - mlogpo2 = logpo2; - end - ilogpo2 = logpo2; - isux = isux + 1; - jsux = jsux + 1; - end% ... otherwise I don't move. - prtfrc = j/MaxNumberOfTuningSimulations; - waitbar(prtfrc,hh,sprintf('Acceptation rates: %f [%f]',isux/j,jsux/jj)); - if j/500 == round(j/500) - test1 = jsux/jj; - cfactor = test1/AcceptanceTarget; - if cfactor>0 - iScale = iScale*cfactor; - else - iScale = iScale/10; - end - jsux = 0; jj = 0; - if cfactor>0.90 && cfactor<1.10 - test = test+1; - end - if test>4 - break - end - end - j = j+1; - jj = jj + 1; -end -close(hh); -iScale -%% [2] One block metropolis, I update the covariance matrix of the jumping distribution -hh = waitbar(0,'Metropolis-Hastings...'); -set(hh,'Name','Looking for the posterior covariance...') -j = 1; -isux = 0; -ilogpo2 = - feval(ObjFun,ix2,varargin{:}); -while j<= NumberOfIterations - proposal = iScale*dd*randn(npar,1) + ix2; - if all(proposal > mh_bounds(:,1)) & all(proposal < mh_bounds(:,2)) - logpo2 = - feval(ObjFun,proposal,varargin{:}); - else - logpo2 = -inf; - end - % I move if the proposal is enough likely... - if logpo2 > -inf & log(rand) < logpo2 - ilogpo2 - ix2 = proposal; - if logpo2 > mlogpo2 - ModePar = proposal; - mlogpo2 = logpo2; - end - ilogpo2 = logpo2; - isux = isux + 1; - jsux = jsux + 1; - end% ... otherwise I don't move. - prtfrc = j/NumberOfIterations; - waitbar(prtfrc,hh,sprintf('%f done, acceptation rate %f',prtfrc,isux/j)); - % I update the covariance matrix and the mean: - oldMeanPar = MeanPar; - MeanPar = oldMeanPar + (1/j)*(ix2-oldMeanPar); - CovJump = CovJump + oldMeanPar*oldMeanPar' - MeanPar*MeanPar' + ... - (1/j)*(ix2*ix2' - CovJump - oldMeanPar*oldMeanPar'); - j = j+1; -end -close(hh); -PostVar = CovJump; -PostMean = MeanPar; -%% [3 & 4] I tune the scale parameter (with the new covariance matrix) if -%% this is the last call to the routine, and I climb the hill (without -%% updating the covariance matrix)... -if strcmpi(info,'LastCall') - hh = waitbar(0,'Tuning of the scale parameter...'); - set(hh,'Name','Tuning of the scale parameter.') - j = 1; jj = 1; - isux = 0; jsux = 0; - test = 0; - ilogpo2 = - feval(ObjFun,ix2,varargin{:});% initial posterior density - dd = transpose(chol(CovJump)); - while j<=MaxNumberOfTuningSimulations - proposal = iScale*dd*randn(npar,1) + ix2; - if all(proposal > mh_bounds(:,1)) & all(proposal < mh_bounds(:,2)) - logpo2 = - feval(ObjFun,proposal,varargin{:}); - else - logpo2 = -inf; - end - % I move if the proposal is enough likely... - if logpo2 > -inf & log(rand) < logpo2 - ilogpo2 - ix2 = proposal; - if logpo2 > mlogpo2 - ModePar = proposal; - mlogpo2 = logpo2; - end - ilogpo2 = logpo2; - isux = isux + 1; - jsux = jsux + 1; - end% ... otherwise I don't move. - prtfrc = j/MaxNumberOfTuningSimulations; - waitbar(prtfrc,hh,sprintf('Acceptation rates: %f [%f]',isux/j,jsux/jj)); - if j/1000 == round(j/1000) - test1 = jsux/jj; - cfactor = test1/AcceptanceTarget; - iScale = iScale*cfactor; - jsux = 0; jj = 0; - if cfactor>0.90 && cfactor<1.10 - test = test+1; - end - if test>4 - break - end - end - j = j+1; - jj = jj + 1; - end - close(hh); - Scale = iScale; - iScale - %% - %% Now I climb the hill - %% - climb = 1; - if climb - hh = waitbar(0,' '); - set(hh,'Name','Now I am climbing the hill...') - j = 1; jj = 1; - jsux = 0; - test = 0; - while j<=MaxNumberOfClimbingSimulations - proposal = iScale*dd*randn(npar,1) + ModePar; - if all(proposal > mh_bounds(:,1)) & all(proposal < mh_bounds(:,2)) - logpo2 = - feval(ObjFun,proposal,varargin{:}); - else - logpo2 = -inf; - end - if logpo2 > mlogpo2% I move if the proposal is higher... - ModePar = proposal; - mlogpo2 = logpo2; - jsux = jsux + 1; - end% otherwise I don't move... - prtfrc = j/MaxNumberOfClimbingSimulations; - waitbar(prtfrc,hh,sprintf('%f Jumps / MaxStepSize %f',jsux,sqrt(max(diag(iScale*CovJump))))); - if j/200 == round(j/200) - if jsux<=1 - test = test+1; - else - test = 0; - end - jsux = 0; - jj = 0; - if test>4% If I do not progress enough I reduce the scale parameter - % of the jumping distribution (cooling down the system). - iScale = iScale/1.10; - end - if sqrt(max(diag(iScale*CovJump)))<10^(-4) - break% Steps are too small! - end - end - j = j+1; - jj = jj + 1; - end - close(hh); - end%climb -else - Scale = iScale; -end +function [PostMod,PostVar,Scale,PostMean] = ... + gmhmaxlik(ObjFun,xparam1,mh_bounds,num,iScale,info,MeanPar,VarCov,varargin) + +%function [PostMod,PostVar,Scale,PostMean] = ... +%gmhmaxlik(ObjFun,xparam1,mh_bounds,num,iScale,info,MeanPar,VarCov,varargin) +% (Dirty) Global minimization routine of (minus) a likelihood (or posterior density) function. +% +% INPUTS +% o ObjFun [char] string specifying the name of the objective function. +% o xparam1 [double] (p*1) vector of parameters to be estimated. +% o mh_bounds [double] (p*2) matrix defining lower and upper bounds for the parameters. +% o num [integer] scalar specifying the number of MH iterations in step 2. +% o iScale [double] scalar specifying the initial of the jumping distribution's scale parameter. +% o info [char] string, empty or equal to 'LastCall'. +% o MeanPar [double] (p*1) vector specifying the initial posterior mean. +% o VarCov [double] (p*p) matrix specifying the initial posterior covariance matrix. +% o gend [integer] scalar specifying the number of observations ==> varargin{1}. +% o data [double] (T*n) matrix of data ==> varargin{2}. +% +% OUTPUTS +% o PostMod [double] (p*1) vector, evaluation of the posterior mode. +% o PostVar [double] (p*p) matrix, evaluation of the posterior covariance matrix. +% o Scale [double] scalar specifying the scale parameter that should be used in +% an eventual metropolis-hastings algorithm. +% o PostMean [double] (p*1) vector, evaluation of the posterior mean. +% +% ALGORITHM +% Metropolis-Hastings with an constantly updated covariance matrix for +% the jump distribution. The posterior mean, variance and mode are +% updated (in step 2) with the following rules: +% +% \[ +% \mu_t = \mu_{t-1} + \frac{1}{t}\left(\theta_t-\mu_{t-1}\right) +% \] +% +% \[ +% \Sigma_t = \Sigma_{t-1} + \mu_{t-1}\mu_{t-1}'-\mu_{t}\mu_{t}' + +% \frac{1}{t}\left(\theta_t\theta_t'-\Sigma_{t-1}-\mu_{t-1}\mu_{t-1}'\right) +% \] +% +% and +% +% \[ +% \mathrm{mode}_t = \left\{ +% \begin{array}{ll} +% \theta_t, & \hbox{if } p(\theta_t|\mathcal Y) > p(\mathrm{mode}_{t-1}|\mathcal Y) \\ +% \mathrm{mode}_{t-1}, & \hbox{otherwise.} +% \end{array} +% \right. +% \] +% +% where $t$ is the iteration, $\mu_t$ the estimate of the posterior mean +% after $t$ iterations, $\Sigma_t$ the estimate of the posterior +% covariance matrix after $t$ iterations, $\mathrm{mode}_t$ is the +% evaluation of the posterior mode after $t$ iterations and +% $p(\theta_t|\mathcal Y)$ is the posterior density of parameters +% (specified by the user supplied function "fun"). +% +% SPECIAL REQUIREMENTS +% None. + +% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. + +global bayestopt_ estim_params_ options_ + +options_.lik_algo = 1; +npar = length(xparam1); + +NumberOfIterations = num; +MaxNumberOfTuningSimulations = 200000; +MaxNumberOfClimbingSimulations = 200000; +AcceptanceTarget = 1/3; + +CovJump = VarCov; +ModePar = xparam1; + +%% [1] I tune the scale parameter. +hh = waitbar(0,'Tuning of the scale parameter...'); +set(hh,'Name','Tuning of the scale parameter.') +j = 1; jj = 1; +isux = 0; jsux = 0; test = 0; +ix2 = ModePar;% initial condition! +ilogpo2 = - feval(ObjFun,ix2,varargin{:});% initial posterior density +mlogpo2 = ilogpo2; +try + dd = transpose(chol(CovJump)); +catch + dd = eye(length(CovJump)); +end +while j<=MaxNumberOfTuningSimulations + proposal = iScale*dd*randn(npar,1) + ix2; + if all(proposal > mh_bounds(:,1)) & all(proposal < mh_bounds(:,2)) + logpo2 = - feval(ObjFun,proposal,varargin{:}); + else + logpo2 = -inf; + end + % I move if the proposal is enough likely... + if logpo2 > -inf & log(rand) < logpo2 - ilogpo2 + ix2 = proposal; + if logpo2 > mlogpo2 + ModePar = proposal; + mlogpo2 = logpo2; + end + ilogpo2 = logpo2; + isux = isux + 1; + jsux = jsux + 1; + end% ... otherwise I don't move. + prtfrc = j/MaxNumberOfTuningSimulations; + waitbar(prtfrc,hh,sprintf('Acceptation rates: %f [%f]',isux/j,jsux/jj)); + if j/500 == round(j/500) + test1 = jsux/jj; + cfactor = test1/AcceptanceTarget; + if cfactor>0 + iScale = iScale*cfactor; + else + iScale = iScale/10; + end + jsux = 0; jj = 0; + if cfactor>0.90 && cfactor<1.10 + test = test+1; + end + if test>4 + break + end + end + j = j+1; + jj = jj + 1; +end +close(hh); +iScale +%% [2] One block metropolis, I update the covariance matrix of the jumping distribution +hh = waitbar(0,'Metropolis-Hastings...'); +set(hh,'Name','Looking for the posterior covariance...') +j = 1; +isux = 0; +ilogpo2 = - feval(ObjFun,ix2,varargin{:}); +while j<= NumberOfIterations + proposal = iScale*dd*randn(npar,1) + ix2; + if all(proposal > mh_bounds(:,1)) & all(proposal < mh_bounds(:,2)) + logpo2 = - feval(ObjFun,proposal,varargin{:}); + else + logpo2 = -inf; + end + % I move if the proposal is enough likely... + if logpo2 > -inf & log(rand) < logpo2 - ilogpo2 + ix2 = proposal; + if logpo2 > mlogpo2 + ModePar = proposal; + mlogpo2 = logpo2; + end + ilogpo2 = logpo2; + isux = isux + 1; + jsux = jsux + 1; + end% ... otherwise I don't move. + prtfrc = j/NumberOfIterations; + waitbar(prtfrc,hh,sprintf('%f done, acceptation rate %f',prtfrc,isux/j)); + % I update the covariance matrix and the mean: + oldMeanPar = MeanPar; + MeanPar = oldMeanPar + (1/j)*(ix2-oldMeanPar); + CovJump = CovJump + oldMeanPar*oldMeanPar' - MeanPar*MeanPar' + ... + (1/j)*(ix2*ix2' - CovJump - oldMeanPar*oldMeanPar'); + j = j+1; +end +close(hh); +PostVar = CovJump; +PostMean = MeanPar; +%% [3 & 4] I tune the scale parameter (with the new covariance matrix) if +%% this is the last call to the routine, and I climb the hill (without +%% updating the covariance matrix)... +if strcmpi(info,'LastCall') + hh = waitbar(0,'Tuning of the scale parameter...'); + set(hh,'Name','Tuning of the scale parameter.') + j = 1; jj = 1; + isux = 0; jsux = 0; + test = 0; + ilogpo2 = - feval(ObjFun,ix2,varargin{:});% initial posterior density + dd = transpose(chol(CovJump)); + while j<=MaxNumberOfTuningSimulations + proposal = iScale*dd*randn(npar,1) + ix2; + if all(proposal > mh_bounds(:,1)) & all(proposal < mh_bounds(:,2)) + logpo2 = - feval(ObjFun,proposal,varargin{:}); + else + logpo2 = -inf; + end + % I move if the proposal is enough likely... + if logpo2 > -inf & log(rand) < logpo2 - ilogpo2 + ix2 = proposal; + if logpo2 > mlogpo2 + ModePar = proposal; + mlogpo2 = logpo2; + end + ilogpo2 = logpo2; + isux = isux + 1; + jsux = jsux + 1; + end% ... otherwise I don't move. + prtfrc = j/MaxNumberOfTuningSimulations; + waitbar(prtfrc,hh,sprintf('Acceptation rates: %f [%f]',isux/j,jsux/jj)); + if j/1000 == round(j/1000) + test1 = jsux/jj; + cfactor = test1/AcceptanceTarget; + iScale = iScale*cfactor; + jsux = 0; jj = 0; + if cfactor>0.90 && cfactor<1.10 + test = test+1; + end + if test>4 + break + end + end + j = j+1; + jj = jj + 1; + end + close(hh); + Scale = iScale; + iScale + %% + %% Now I climb the hill + %% + climb = 1; + if climb + hh = waitbar(0,' '); + set(hh,'Name','Now I am climbing the hill...') + j = 1; jj = 1; + jsux = 0; + test = 0; + while j<=MaxNumberOfClimbingSimulations + proposal = iScale*dd*randn(npar,1) + ModePar; + if all(proposal > mh_bounds(:,1)) & all(proposal < mh_bounds(:,2)) + logpo2 = - feval(ObjFun,proposal,varargin{:}); + else + logpo2 = -inf; + end + if logpo2 > mlogpo2% I move if the proposal is higher... + ModePar = proposal; + mlogpo2 = logpo2; + jsux = jsux + 1; + end% otherwise I don't move... + prtfrc = j/MaxNumberOfClimbingSimulations; + waitbar(prtfrc,hh,sprintf('%f Jumps / MaxStepSize %f',jsux,sqrt(max(diag(iScale*CovJump))))); + if j/200 == round(j/200) + if jsux<=1 + test = test+1; + else + test = 0; + end + jsux = 0; + jj = 0; + if test>4% If I do not progress enough I reduce the scale parameter + % of the jumping distribution (cooling down the system). + iScale = iScale/1.10; + end + if sqrt(max(diag(iScale*CovJump)))<10^(-4) + break% Steps are too small! + end + end + j = j+1; + jj = jj + 1; + end + close(hh); + end%climb +else + Scale = iScale; +end PostMod = ModePar; \ No newline at end of file diff --git a/matlab/graph_decomp.m b/matlab/graph_decomp.m index 4e4fa47072..14cfd0d959 100644 --- a/matlab/graph_decomp.m +++ b/matlab/graph_decomp.m @@ -1,82 +1,82 @@ -function []=graph_decomp(z,shock_names,varlist,initial_date) -%function []=graph_decomp(z,varlist,initial_period,freq) - -% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. - - global M_ - % number of components equals number of shocks + 1 (initial conditions) - comp_nbr = size(z,2)-1; - - gend = size(z,3); - freq = initial_date.freq; - initial_period = initial_date.period + initial_date.sub_period/freq; - x = initial_period-1/freq:(1/freq):initial_period+(gend-1)/freq; - - [i_var,nvar] = varlist_indices(varlist); - for j=1:nvar - z1 = squeeze(z(i_var(j),:,:)); - xmin = x(1); - xmax = x(end); - ix = z1 > 0; - ymax = max(sum(z1.*ix)); - ix = z1 < 0; - ymin = min(sum(z1.*ix)); - if ymax-ymin < 1e-6 - continue - end - figure('Name',M_.endo_names(i_var(j),:)); - ax=axes('Position',[0.1 0.1 0.6 0.8]); - axis(ax,[xmin xmax ymin ymax]); - plot(ax,x(2:end),z1(end,:),'k-','LineWidth',2) - hold on; - for i=1:gend - i_1 = i-1; - yp = 0; - ym = 0; - for k = 1:comp_nbr - zz = z1(k,i); - if zz > 0 - fill([x(i) x(i) x(i+1) x(i+1)],[yp yp+zz yp+zz yp],k); - yp = yp+zz; - else - fill([x(i) x(i) x(i+1) x(i+1)],[ym ym+zz ym+zz ym],k); - ym = ym+zz; - end - hold on; - end - end - plot(ax,x(2:end),z1(end,:),'k-','LineWidth',2) - hold off; - - axes('Position',[0.75 0.1 0.2 0.8]); - axis([0 1 0 1]); - axis off; - hold on; - y1 = 0; - height = 1/comp_nbr; - labels = strvcat(shock_names,'Initial values'); - - for j=1:comp_nbr - fill([0 0 0.2 0.2],[y1 y1+0.7*height y1+0.7*height y1],j); - hold on - text(0.3,y1+0.3*height,labels(j,:),'Interpreter','none'); - hold on - y1 = y1 + height; - end - hold off - end \ No newline at end of file +function []=graph_decomp(z,shock_names,varlist,initial_date) +%function []=graph_decomp(z,varlist,initial_period,freq) + +% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. + +global M_ +% number of components equals number of shocks + 1 (initial conditions) +comp_nbr = size(z,2)-1; + +gend = size(z,3); +freq = initial_date.freq; +initial_period = initial_date.period + initial_date.sub_period/freq; +x = initial_period-1/freq:(1/freq):initial_period+(gend-1)/freq; + +[i_var,nvar] = varlist_indices(varlist); +for j=1:nvar + z1 = squeeze(z(i_var(j),:,:)); + xmin = x(1); + xmax = x(end); + ix = z1 > 0; + ymax = max(sum(z1.*ix)); + ix = z1 < 0; + ymin = min(sum(z1.*ix)); + if ymax-ymin < 1e-6 + continue + end + figure('Name',M_.endo_names(i_var(j),:)); + ax=axes('Position',[0.1 0.1 0.6 0.8]); + axis(ax,[xmin xmax ymin ymax]); + plot(ax,x(2:end),z1(end,:),'k-','LineWidth',2) + hold on; + for i=1:gend + i_1 = i-1; + yp = 0; + ym = 0; + for k = 1:comp_nbr + zz = z1(k,i); + if zz > 0 + fill([x(i) x(i) x(i+1) x(i+1)],[yp yp+zz yp+zz yp],k); + yp = yp+zz; + else + fill([x(i) x(i) x(i+1) x(i+1)],[ym ym+zz ym+zz ym],k); + ym = ym+zz; + end + hold on; + end + end + plot(ax,x(2:end),z1(end,:),'k-','LineWidth',2) + hold off; + + axes('Position',[0.75 0.1 0.2 0.8]); + axis([0 1 0 1]); + axis off; + hold on; + y1 = 0; + height = 1/comp_nbr; + labels = strvcat(shock_names,'Initial values'); + + for j=1:comp_nbr + fill([0 0 0.2 0.2],[y1 y1+0.7*height y1+0.7*height y1],j); + hold on + text(0.3,y1+0.3*height,labels(j,:),'Interpreter','none'); + hold on + y1 = y1 + height; + end + hold off +end \ No newline at end of file diff --git a/matlab/hessian.m b/matlab/hessian.m index 9dfd5174b1..9c2d81e71f 100644 --- a/matlab/hessian.m +++ b/matlab/hessian.m @@ -1,80 +1,80 @@ -function hessian_mat = hessian(func,x,gstep,varargin) -% function hessian_mat = hessian(func,x,varargin) -% Computes second order partial derivatives -% -% INPUTS -% func [string] name of the function -% x [double] vector, the Hessian of "func" is evaluated at x. -% gstep [double] scalar, size of epsilon. -% varargin [void] list of additional arguments for "func". -% -% OUTPUTS -% hessian_mat [double] Hessian matrix -% -% ALGORITHM -% Uses Abramowitz and Stegun (1965) formulas 25.3.24 and 25.3.27 p. 884 -% -% SPECIAL REQUIREMENTS -% none -% - -% Copyright (C) 2001-2007 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 <http://www.gnu.org/licenses/>. - - func = str2func(func); - n=size(x,1); - h1=max(abs(x),sqrt(gstep)*ones(n,1))*eps^(1/6); - h_1=h1; - xh1=x+h1; - h1=xh1-x; - xh1=x-h_1; - h_1=x-xh1; - xh1=x; - f0=feval(func,x,varargin{:}); - f1=zeros(size(f0,1),n); - f_1=f1; - for i=1:n - xh1(i)=x(i)+h1(i); - f1(:,i)=feval(func,xh1,varargin{:}); - xh1(i)=x(i)-h_1(i); - f_1(:,i)=feval(func,xh1,varargin{:}); - xh1(i)=x(i); - i=i+1; - end - xh_1=xh1; - hessian_mat = zeros(size(f0,1),n*n); - for i=1:n - if i > 1 - k=[i:n:n*(i-1)]; - hessian_mat(:,(i-1)*n+1:(i-1)*n+i-1)=hessian_mat(:,k); - end - hessian_mat(:,(i-1)*n+i)=(f1(:,i)+f_1(:,i)-2*f0)./(h1(i)*h_1(i)); - temp=f1+f_1-f0*ones(1,n); - for j=i+1:n - xh1(i)=x(i)+h1(i); - xh1(j)=x(j)+h_1(j); - xh_1(i)=x(i)-h1(i); - xh_1(j)=x(j)-h_1(j); - hessian_mat(:,(i-1)*n+j)=-(-feval(func,xh1,varargin{:})-feval(func,xh_1,varargin{:})+temp(:,i)+temp(:,j))./(2*h1(i)*h_1(j)); - xh1(i)=x(i); - xh1(j)=x(j); - xh_1(i)=x(i); - xh_1(j)=x(j); - j=j+1; - end - i=i+1; - end \ No newline at end of file +function hessian_mat = hessian(func,x,gstep,varargin) +% function hessian_mat = hessian(func,x,varargin) +% Computes second order partial derivatives +% +% INPUTS +% func [string] name of the function +% x [double] vector, the Hessian of "func" is evaluated at x. +% gstep [double] scalar, size of epsilon. +% varargin [void] list of additional arguments for "func". +% +% OUTPUTS +% hessian_mat [double] Hessian matrix +% +% ALGORITHM +% Uses Abramowitz and Stegun (1965) formulas 25.3.24 and 25.3.27 p. 884 +% +% SPECIAL REQUIREMENTS +% none +% + +% Copyright (C) 2001-2007 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 <http://www.gnu.org/licenses/>. + +func = str2func(func); +n=size(x,1); +h1=max(abs(x),sqrt(gstep)*ones(n,1))*eps^(1/6); +h_1=h1; +xh1=x+h1; +h1=xh1-x; +xh1=x-h_1; +h_1=x-xh1; +xh1=x; +f0=feval(func,x,varargin{:}); +f1=zeros(size(f0,1),n); +f_1=f1; +for i=1:n + xh1(i)=x(i)+h1(i); + f1(:,i)=feval(func,xh1,varargin{:}); + xh1(i)=x(i)-h_1(i); + f_1(:,i)=feval(func,xh1,varargin{:}); + xh1(i)=x(i); + i=i+1; +end +xh_1=xh1; +hessian_mat = zeros(size(f0,1),n*n); +for i=1:n + if i > 1 + k=[i:n:n*(i-1)]; + hessian_mat(:,(i-1)*n+1:(i-1)*n+i-1)=hessian_mat(:,k); + end + hessian_mat(:,(i-1)*n+i)=(f1(:,i)+f_1(:,i)-2*f0)./(h1(i)*h_1(i)); + temp=f1+f_1-f0*ones(1,n); + for j=i+1:n + xh1(i)=x(i)+h1(i); + xh1(j)=x(j)+h_1(j); + xh_1(i)=x(i)-h1(i); + xh_1(j)=x(j)-h_1(j); + hessian_mat(:,(i-1)*n+j)=-(-feval(func,xh1,varargin{:})-feval(func,xh_1,varargin{:})+temp(:,i)+temp(:,j))./(2*h1(i)*h_1(j)); + xh1(i)=x(i); + xh1(j)=x(j); + xh_1(i)=x(i); + xh_1(j)=x(j); + j=j+1; + end + i=i+1; +end \ No newline at end of file diff --git a/matlab/homotopy1.m b/matlab/homotopy1.m index 23347677a5..e2f9b20143 100644 --- a/matlab/homotopy1.m +++ b/matlab/homotopy1.m @@ -1,81 +1,81 @@ -function homotopy1(values, step_nbr) -% function homotopy1(values, step_nbr) -% -% Implements homotopy (mode 1) for steady-state computation. -% The multi-dimensional vector going from the set of initial values -% to the set of final values is divided in as many sub-vectors as -% there are steps, and the problem is solved as many times. -% -% INPUTS -% values: a matrix with 4 columns, representing the content of -% homotopy_setup block, with one variable per line. -% Column 1 is variable type (1 for exogenous, 2 for -% exogenous deterministic, 4 for parameters) -% Column 2 is symbol integer identifier. -% Column 3 is initial value, and column 4 is final value. -% Column 3 can contain NaNs, in which case previous -% initialization of variable will be used as initial value. -% step_nbr: number of steps for homotopy -% -% OUTPUTS -% none -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2008-2009 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 <http://www.gnu.org/licenses/>. - - global M_ oo_ options_ - - nv = size(values, 1); - - ip = find(values(:,1) == 4); % Parameters - ix = find(values(:,1) == 1); % Exogenous - ixd = find(values(:,1) == 2); % Exogenous deterministic - - if length([ip; ix; ixd]) ~= nv - error('HOMOTOPY mode 1: incorrect variable types specified') - end - - % Construct vector of starting values, using previously initialized values - % when initial value has not been given in homotopy_setup block - oldvalues = values(:,3); - ipn = find(values(:,1) == 4 & isnan(oldvalues)); - oldvalues(ipn) = M_.params(values(ipn, 2)); - ixn = find(values(:,1) == 1 & isnan(oldvalues)); - oldvalues(ixn) = oo_.exo_steady_state(values(ixn, 2)); - ixdn = find(values(:,1) == 2 & isnan(oldvalues)); - oldvalues(ixdn) = oo_.exo_det_steady_state(values(ixdn, 2)); - - if any(oldvalues == values(:,4)) - error('HOMOTOPY mode 1: initial and final values should be different') - end - - points = zeros(nv, step_nbr+1); - for i = 1:nv - points(i,:) = oldvalues(i):(values(i,4)-oldvalues(i))/step_nbr:values(i,4); - end - - for i=1:step_nbr+1 - disp([ 'HOMOTOPY mode 1: computing step ' int2str(i-1) '/' int2str(step_nbr) '...' ]) - M_.params(values(ip,2)) = points(ip,i); - oo_.exo_steady_state(values(ix,2)) = points(ix,i); - oo_.exo_det_steady_state(values(ixd,2)) = points(ixd,i); - - steady_; - end +function homotopy1(values, step_nbr) +% function homotopy1(values, step_nbr) +% +% Implements homotopy (mode 1) for steady-state computation. +% The multi-dimensional vector going from the set of initial values +% to the set of final values is divided in as many sub-vectors as +% there are steps, and the problem is solved as many times. +% +% INPUTS +% values: a matrix with 4 columns, representing the content of +% homotopy_setup block, with one variable per line. +% Column 1 is variable type (1 for exogenous, 2 for +% exogenous deterministic, 4 for parameters) +% Column 2 is symbol integer identifier. +% Column 3 is initial value, and column 4 is final value. +% Column 3 can contain NaNs, in which case previous +% initialization of variable will be used as initial value. +% step_nbr: number of steps for homotopy +% +% OUTPUTS +% none +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2008-2009 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 <http://www.gnu.org/licenses/>. + +global M_ oo_ options_ + +nv = size(values, 1); + +ip = find(values(:,1) == 4); % Parameters +ix = find(values(:,1) == 1); % Exogenous +ixd = find(values(:,1) == 2); % Exogenous deterministic + +if length([ip; ix; ixd]) ~= nv + error('HOMOTOPY mode 1: incorrect variable types specified') +end + +% Construct vector of starting values, using previously initialized values +% when initial value has not been given in homotopy_setup block +oldvalues = values(:,3); +ipn = find(values(:,1) == 4 & isnan(oldvalues)); +oldvalues(ipn) = M_.params(values(ipn, 2)); +ixn = find(values(:,1) == 1 & isnan(oldvalues)); +oldvalues(ixn) = oo_.exo_steady_state(values(ixn, 2)); +ixdn = find(values(:,1) == 2 & isnan(oldvalues)); +oldvalues(ixdn) = oo_.exo_det_steady_state(values(ixdn, 2)); + +if any(oldvalues == values(:,4)) + error('HOMOTOPY mode 1: initial and final values should be different') +end + +points = zeros(nv, step_nbr+1); +for i = 1:nv + points(i,:) = oldvalues(i):(values(i,4)-oldvalues(i))/step_nbr:values(i,4); +end + +for i=1:step_nbr+1 + disp([ 'HOMOTOPY mode 1: computing step ' int2str(i-1) '/' int2str(step_nbr) '...' ]) + M_.params(values(ip,2)) = points(ip,i); + oo_.exo_steady_state(values(ix,2)) = points(ix,i); + oo_.exo_det_steady_state(values(ixd,2)) = points(ixd,i); + + steady_; +end diff --git a/matlab/homotopy2.m b/matlab/homotopy2.m index 50095c8ed0..5e5332e008 100644 --- a/matlab/homotopy2.m +++ b/matlab/homotopy2.m @@ -42,65 +42,64 @@ function homotopy2(values, step_nbr) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ oo_ options_ +global M_ oo_ options_ - nv = size(values, 1); - - oldvalues = values(:,3); - - % Initialize all variables with initial value, or the reverse... - for i = 1:nv +nv = size(values, 1); + +oldvalues = values(:,3); + +% Initialize all variables with initial value, or the reverse... +for i = 1:nv switch values(i,1) - case 1 - if isnan(oldvalues(i)) - oldvalues(i) = oo_.exo_steady_state(values(i,2)); - else - oo_.exo_steady_state(values(i,2)) = oldvalues(i); - end - case 2 - if isnan(oldvalues(i)) - oldvalues(i) = oo_.exo_det_steady_state(values(i,2)); - else - oo_.exo_det_steady_state(values(i,2)) = oldvalues(i); - end - case 4 - if isnan(oldvalues(i)) - oldvalues(i) = M_.params(values(i,2)); - else - M_.params(values(i,2)) = oldvalues(i); - end - otherwise - error('HOMOTOPY mode 2: incorrect variable types specified') + case 1 + if isnan(oldvalues(i)) + oldvalues(i) = oo_.exo_steady_state(values(i,2)); + else + oo_.exo_steady_state(values(i,2)) = oldvalues(i); + end + case 2 + if isnan(oldvalues(i)) + oldvalues(i) = oo_.exo_det_steady_state(values(i,2)); + else + oo_.exo_det_steady_state(values(i,2)) = oldvalues(i); + end + case 4 + if isnan(oldvalues(i)) + oldvalues(i) = M_.params(values(i,2)); + else + M_.params(values(i,2)) = oldvalues(i); + end + otherwise + error('HOMOTOPY mode 2: incorrect variable types specified') end - end +end - if any(oldvalues == values(:,4)) +if any(oldvalues == values(:,4)) error('HOMOTOPY mode 2: initial and final values should be different') - end - - % Actually do the homotopy - for i = 1:nv +end + +% Actually do the homotopy +for i = 1:nv switch values(i,1) - case 1 - varname = M_.exo_names(values(i,2), :); - case 2 - varname = M_.exo_det_names(values(i,2), :); - case 4 - varname = M_.param_names(values(i,2), :); + case 1 + varname = M_.exo_names(values(i,2), :); + case 2 + varname = M_.exo_det_names(values(i,2), :); + case 4 + varname = M_.param_names(values(i,2), :); end for v = oldvalues(i):(values(i,4)-oldvalues(i))/step_nbr:values(i,4) - switch values(i,1) - case 1 - oo_.exo_steady_state(values(i,2)) = v; - case 2 - oo_.exo_det_steady_state(values(i,2)) = v; - case 4 - M_.params(values(i,2)) = v; - end + switch values(i,1) + case 1 + oo_.exo_steady_state(values(i,2)) = v; + case 2 + oo_.exo_det_steady_state(values(i,2)) = v; + case 4 + M_.params(values(i,2)) = v; + end - disp([ 'HOMOTOPY mode 2: lauching solver with ' deblank(varname) ' = ' num2str(v) ' ...']) - - steady_; + disp([ 'HOMOTOPY mode 2: lauching solver with ' deblank(varname) ' = ' num2str(v) ' ...']) + + steady_; end - end - \ No newline at end of file +end diff --git a/matlab/homotopy3.m b/matlab/homotopy3.m index 6cd4d98b4f..902cabb195 100644 --- a/matlab/homotopy3.m +++ b/matlab/homotopy3.m @@ -1,125 +1,125 @@ -function homotopy3(values, step_nbr) -% function homotopy3(values, step_nbr) -% -% Implements homotopy (mode 3) for steady-state computation. -% Tries first the most extreme values. If it fails to compute the steady -% state, the interval between initial and desired values is divided by two -% for each parameter. Every time that it is impossible to find a steady -% state, the previous interval is divided by two. When one succeed to find -% a steady state, the previous interval is multiplied by two. -% -% INPUTS -% values: a matrix with 4 columns, representing the content of -% homotopy_setup block, with one variable per line. -% Column 1 is variable type (1 for exogenous, 2 for -% exogenous deterministic, 4 for parameters) -% Column 2 is symbol integer identifier. -% Column 3 is initial value, and column 4 is final value. -% Column 3 can contain NaNs, in which case previous -% initialization of variable will be used as initial value. -% step_nbr: maximum number of steps to try before aborting -% -% OUTPUTS -% none -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2008-2009 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 <http://www.gnu.org/licenses/>. - - global M_ oo_ options_ - - tol = 1e-8; - - nv = size(values,1); - - ip = find(values(:,1) == 4); % Parameters - ix = find(values(:,1) == 1); % Exogenous - ixd = find(values(:,1) == 2); % Exogenous deterministic - - if length([ip; ix; ixd]) ~= nv - error('HOMOTOPY mode 3: incorrect variable types specified') - end - - % Construct vector of starting values, using previously initialized values - % when initial value has not been given in homotopy_setup block - oldvalues = values(:,3); - ipn = find(values(:,1) == 4 & isnan(oldvalues)); - oldvalues(ipn) = M_.params(values(ipn, 2)); - ixn = find(values(:,1) == 1 & isnan(oldvalues)); - oldvalues(ixn) = oo_.exo_steady_state(values(ixn, 2)); - ixdn = find(values(:,1) == 2 & isnan(oldvalues)); - oldvalues(ixdn) = oo_.exo_det_steady_state(values(ixdn, 2)); - - targetvalues = values(:,4); - - if min(abs(targetvalues - oldvalues)) < tol - error('HOMOTOPY mode 3: distance between initial and final values should be at least %e for all variables', tol) - end - iplus = find(targetvalues > oldvalues); - iminus = find(targetvalues < oldvalues); - - curvalues = oldvalues; - inc = (targetvalues-oldvalues)/2; - kplus = []; - kminus = []; - - disp('HOMOTOPY mode 3: launching solver at initial point...') - - iter = 1; - while iter < step_nbr - - M_.params(values(ip,2)) = curvalues(ip); - oo_.exo_steady_state(values(ix,2)) = curvalues(ix); - oo_.exo_det_steady_state(values(ixd,2)) = curvalues(ixd); - - old_ss = oo_.steady_state; - - try - steady_; - - if length([kplus; kminus]) == nv - return - end - if iter == 1 - disp('HOMOTOPY mode 3: successful step, now jumping to final point...') - else - disp('HOMOTOPY mode 3: successful step, now multiplying increment by 2...') - end - oldvalues = curvalues; - inc = 2*inc; - catch E - disp(E.message) - disp('HOMOTOPY mode 3: failed step, now dividing increment by 2...') - inc = inc/2; - oo_.steady_state = old_ss; - end - - curvalues = oldvalues + inc; - kplus = find(curvalues(iplus) >= targetvalues(iplus)); - curvalues(iplus(kplus)) = targetvalues(iplus(kplus)); - kminus = find(curvalues(iminus) <= targetvalues(iminus)); - curvalues(iminus(kminus)) = targetvalues(iminus(kminus)); - - if max(abs(inc)) < tol - error('HOMOTOPY mode 3: failed, increment has become too small') - end - - iter = iter + 1; - end - error('HOMOTOPY mode 3: failed, maximum iterations reached') +function homotopy3(values, step_nbr) +% function homotopy3(values, step_nbr) +% +% Implements homotopy (mode 3) for steady-state computation. +% Tries first the most extreme values. If it fails to compute the steady +% state, the interval between initial and desired values is divided by two +% for each parameter. Every time that it is impossible to find a steady +% state, the previous interval is divided by two. When one succeed to find +% a steady state, the previous interval is multiplied by two. +% +% INPUTS +% values: a matrix with 4 columns, representing the content of +% homotopy_setup block, with one variable per line. +% Column 1 is variable type (1 for exogenous, 2 for +% exogenous deterministic, 4 for parameters) +% Column 2 is symbol integer identifier. +% Column 3 is initial value, and column 4 is final value. +% Column 3 can contain NaNs, in which case previous +% initialization of variable will be used as initial value. +% step_nbr: maximum number of steps to try before aborting +% +% OUTPUTS +% none +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2008-2009 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 <http://www.gnu.org/licenses/>. + +global M_ oo_ options_ + +tol = 1e-8; + +nv = size(values,1); + +ip = find(values(:,1) == 4); % Parameters +ix = find(values(:,1) == 1); % Exogenous +ixd = find(values(:,1) == 2); % Exogenous deterministic + +if length([ip; ix; ixd]) ~= nv + error('HOMOTOPY mode 3: incorrect variable types specified') +end + +% Construct vector of starting values, using previously initialized values +% when initial value has not been given in homotopy_setup block +oldvalues = values(:,3); +ipn = find(values(:,1) == 4 & isnan(oldvalues)); +oldvalues(ipn) = M_.params(values(ipn, 2)); +ixn = find(values(:,1) == 1 & isnan(oldvalues)); +oldvalues(ixn) = oo_.exo_steady_state(values(ixn, 2)); +ixdn = find(values(:,1) == 2 & isnan(oldvalues)); +oldvalues(ixdn) = oo_.exo_det_steady_state(values(ixdn, 2)); + +targetvalues = values(:,4); + +if min(abs(targetvalues - oldvalues)) < tol + error('HOMOTOPY mode 3: distance between initial and final values should be at least %e for all variables', tol) +end +iplus = find(targetvalues > oldvalues); +iminus = find(targetvalues < oldvalues); + +curvalues = oldvalues; +inc = (targetvalues-oldvalues)/2; +kplus = []; +kminus = []; + +disp('HOMOTOPY mode 3: launching solver at initial point...') + +iter = 1; +while iter < step_nbr + + M_.params(values(ip,2)) = curvalues(ip); + oo_.exo_steady_state(values(ix,2)) = curvalues(ix); + oo_.exo_det_steady_state(values(ixd,2)) = curvalues(ixd); + + old_ss = oo_.steady_state; + + try + steady_; + + if length([kplus; kminus]) == nv + return + end + if iter == 1 + disp('HOMOTOPY mode 3: successful step, now jumping to final point...') + else + disp('HOMOTOPY mode 3: successful step, now multiplying increment by 2...') + end + oldvalues = curvalues; + inc = 2*inc; + catch E + disp(E.message) + disp('HOMOTOPY mode 3: failed step, now dividing increment by 2...') + inc = inc/2; + oo_.steady_state = old_ss; + end + + curvalues = oldvalues + inc; + kplus = find(curvalues(iplus) >= targetvalues(iplus)); + curvalues(iplus(kplus)) = targetvalues(iplus(kplus)); + kminus = find(curvalues(iminus) <= targetvalues(iminus)); + curvalues(iminus(kminus)) = targetvalues(iminus(kminus)); + + if max(abs(inc)) < tol + error('HOMOTOPY mode 3: failed, increment has become too small') + end + + iter = iter + 1; +end +error('HOMOTOPY mode 3: failed, maximum iterations reached') diff --git a/matlab/identification_checks.m b/matlab/identification_checks.m index 29c9d3c439..376c3b449c 100644 --- a/matlab/identification_checks.m +++ b/matlab/identification_checks.m @@ -1,145 +1,145 @@ -function [McoH, McoJ, PcoH, PcoJ, condH, condJ, eH, eJ, ind01, ind02, indnoH, indnoJ] = identification_checks(H,JJ, bayestopt_) - -% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. - -% My suggestion is to have the following steps for identification check in -% dynare: - -% 1. check rank of H at theta -npar = size(H,2); -indnoH = {}; -indnoJ = {}; -ind1 = find(vnorm(H)~=0); -H1 = H(:,ind1); -covH = H1'*H1; -sdH = sqrt(diag(covH)); -sdH = sdH*sdH'; -[e1,e2] = eig( (H1'*H1)./sdH ); -eH = zeros(npar,npar); -% eH(ind1,:) = e1; -eH(ind1,length(find(vnorm(H)==0))+1:end) = e1; -eH(find(vnorm(H)==0),1:length(find(vnorm(H)==0)))=eye(length(find(vnorm(H)==0))); -condH = cond(H1); -% condH = cond(H1'*H1); - -ind2 = find(vnorm(JJ)~=0); -JJ1 = JJ(:,ind2); -covJJ = JJ1'*JJ1; -sdJJ = sqrt(diag(covJJ)); -sdJJ = sdJJ*sdJJ'; -[ee1,ee2] = eig( (JJ1'*JJ1)./sdJJ ); -% eJ = NaN(npar,length(ind2)); -eJ = zeros(npar,npar); -eJ(ind2,length(find(vnorm(JJ)==0))+1:end) = ee1; -eJ(find(vnorm(JJ)==0),1:length(find(vnorm(JJ)==0)))=eye(length(find(vnorm(JJ)==0))); -% condJ = cond(JJ1'*JJ1); -condJ = cond(JJ1); - -if rank(H)<npar - ixno = 0; - % - find out which parameters are involved, - % using something like the vnorm and the eigenvalue decomposition of H; -% disp('Some parameters are NOT identified in the model: H rank deficient') -% disp(' ') - if length(ind1)<npar, - ixno = ixno + 1; - indnoH(ixno) = {find(~ismember([1:npar],ind1))}; -% disp('Not identified params') -% disp(bayestopt_.name(indnoH{1})) -% disp(' ') - end - e0 = find(abs(diag(e2))<eps); - for j=1:length(e0), - ixno = ixno + 1; - indnoH(ixno) = {ind1(find(e1(:,e0(j))))}; -% disp('Perfectly collinear parameters') -% disp(bayestopt_.name(indnoH{ixno})) -% disp(' ') - end -else % rank(H)==length(theta), go to 2 - % 2. check rank of J -% disp('All parameters are identified at theta in the model (rank of H)') -% disp(' ') -end - -if rank(JJ)<npar - ixno = 0; - % - find out which parameters are involved -% disp('Some parameters are NOT identified by the moments included in J') -% disp(' ') - if length(ind2)<npar, - ixno = ixno + 1; - indnoJ(ixno) = {find(~ismember([1:npar],ind2))}; - end - ee0 = find(abs(diag(ee2))<eps); - for j=1:length(ee0), - ixno = ixno + 1; - indnoJ(ixno) = {ind2(find(ee1(:,ee0(j))))}; -% disp('Perfectly collinear parameters in moments J') -% disp(bayestopt_.name(indnoJ{ixno})) -% disp(' ') - end -else %rank(J)==length(theta) => -% disp('All parameters are identified at theta by the moments included in J') -end - - -% rank(H1)==size(H1,2) -% rank(JJ1)==size(JJ1,2) - -% to find near linear dependence problems I use - -McoH = NaN(npar,1); -McoJ = NaN(npar,1); -for ii = 1:size(H1,2); - McoH(ind1(ii),:) = [cosn([H1(:,ii),H1(:,find([1:1:size(H1,2)]~=ii))])]; -end -for ii = 1:size(JJ1,2); - McoJ(ind2(ii),:) = [cosn([JJ1(:,ii),JJ1(:,find([1:1:size(JJ1,2)]~=ii))])]; -end - -% format long % some are nearly 1 -% McoJ - - -% here there is no exact linear dependence, but there are several -% near-dependencies, mostly due to strong pairwise colliniearities, which can -% be checked using - -PcoH = NaN(npar,npar); -PcoJ = NaN(npar,npar); -for ii = 1:size(H1,2); - for jj = 1:size(H1,2); - PcoH(ind1(ii),ind1(jj)) = [cosn([H1(:,ii),H1(:,jj)])]; - end -end - -for ii = 1:size(JJ1,2); - for jj = 1:size(JJ1,2); - PcoJ(ind2(ii),ind2(jj)) = [cosn([JJ1(:,ii),JJ1(:,jj)])]; - end -end - -ind01 = zeros(npar,1); -ind02 = zeros(npar,1); -ind01(ind1) = 1; -ind02(ind2) = 1; - - - - +function [McoH, McoJ, PcoH, PcoJ, condH, condJ, eH, eJ, ind01, ind02, indnoH, indnoJ] = identification_checks(H,JJ, bayestopt_) + +% Copyright (C) 2008 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 <http://www.gnu.org/licenses/>. + +% My suggestion is to have the following steps for identification check in +% dynare: + +% 1. check rank of H at theta +npar = size(H,2); +indnoH = {}; +indnoJ = {}; +ind1 = find(vnorm(H)~=0); +H1 = H(:,ind1); +covH = H1'*H1; +sdH = sqrt(diag(covH)); +sdH = sdH*sdH'; +[e1,e2] = eig( (H1'*H1)./sdH ); +eH = zeros(npar,npar); +% eH(ind1,:) = e1; +eH(ind1,length(find(vnorm(H)==0))+1:end) = e1; +eH(find(vnorm(H)==0),1:length(find(vnorm(H)==0)))=eye(length(find(vnorm(H)==0))); +condH = cond(H1); +% condH = cond(H1'*H1); + +ind2 = find(vnorm(JJ)~=0); +JJ1 = JJ(:,ind2); +covJJ = JJ1'*JJ1; +sdJJ = sqrt(diag(covJJ)); +sdJJ = sdJJ*sdJJ'; +[ee1,ee2] = eig( (JJ1'*JJ1)./sdJJ ); +% eJ = NaN(npar,length(ind2)); +eJ = zeros(npar,npar); +eJ(ind2,length(find(vnorm(JJ)==0))+1:end) = ee1; +eJ(find(vnorm(JJ)==0),1:length(find(vnorm(JJ)==0)))=eye(length(find(vnorm(JJ)==0))); +% condJ = cond(JJ1'*JJ1); +condJ = cond(JJ1); + +if rank(H)<npar + ixno = 0; + % - find out which parameters are involved, + % using something like the vnorm and the eigenvalue decomposition of H; + % disp('Some parameters are NOT identified in the model: H rank deficient') + % disp(' ') + if length(ind1)<npar, + ixno = ixno + 1; + indnoH(ixno) = {find(~ismember([1:npar],ind1))}; + % disp('Not identified params') + % disp(bayestopt_.name(indnoH{1})) + % disp(' ') + end + e0 = find(abs(diag(e2))<eps); + for j=1:length(e0), + ixno = ixno + 1; + indnoH(ixno) = {ind1(find(e1(:,e0(j))))}; + % disp('Perfectly collinear parameters') + % disp(bayestopt_.name(indnoH{ixno})) + % disp(' ') + end +else % rank(H)==length(theta), go to 2 + % 2. check rank of J + % disp('All parameters are identified at theta in the model (rank of H)') + % disp(' ') +end + +if rank(JJ)<npar + ixno = 0; + % - find out which parameters are involved + % disp('Some parameters are NOT identified by the moments included in J') + % disp(' ') + if length(ind2)<npar, + ixno = ixno + 1; + indnoJ(ixno) = {find(~ismember([1:npar],ind2))}; + end + ee0 = find(abs(diag(ee2))<eps); + for j=1:length(ee0), + ixno = ixno + 1; + indnoJ(ixno) = {ind2(find(ee1(:,ee0(j))))}; + % disp('Perfectly collinear parameters in moments J') + % disp(bayestopt_.name(indnoJ{ixno})) + % disp(' ') + end +else %rank(J)==length(theta) => + % disp('All parameters are identified at theta by the moments included in J') +end + + +% rank(H1)==size(H1,2) +% rank(JJ1)==size(JJ1,2) + +% to find near linear dependence problems I use + +McoH = NaN(npar,1); +McoJ = NaN(npar,1); +for ii = 1:size(H1,2); + McoH(ind1(ii),:) = [cosn([H1(:,ii),H1(:,find([1:1:size(H1,2)]~=ii))])]; +end +for ii = 1:size(JJ1,2); + McoJ(ind2(ii),:) = [cosn([JJ1(:,ii),JJ1(:,find([1:1:size(JJ1,2)]~=ii))])]; +end + +% format long % some are nearly 1 +% McoJ + + +% here there is no exact linear dependence, but there are several +% near-dependencies, mostly due to strong pairwise colliniearities, which can +% be checked using + +PcoH = NaN(npar,npar); +PcoJ = NaN(npar,npar); +for ii = 1:size(H1,2); + for jj = 1:size(H1,2); + PcoH(ind1(ii),ind1(jj)) = [cosn([H1(:,ii),H1(:,jj)])]; + end +end + +for ii = 1:size(JJ1,2); + for jj = 1:size(JJ1,2); + PcoJ(ind2(ii),ind2(jj)) = [cosn([JJ1(:,ii),JJ1(:,jj)])]; + end +end + +ind01 = zeros(npar,1); +ind02 = zeros(npar,1); +ind01(ind1) = 1; +ind02(ind2) = 1; + + + + diff --git a/matlab/imcforecast.m b/matlab/imcforecast.m index 99e9f0131d..5d91ae99ba 100644 --- a/matlab/imcforecast.m +++ b/matlab/imcforecast.m @@ -48,7 +48,7 @@ global options_ oo_ M_ bayestopt_ if isfield(options_cond_fcst,'parameter_set') || isempty(options_cond_fcst.parameter_set) options_cond_fcst.parameter_set = 'posterior_mode'; end - + if ischar(options_cond_fcst.parameter_set) switch options_cond_fcst.parameter_set case 'posterior_mode' diff --git a/matlab/independent_metropolis_hastings.m b/matlab/independent_metropolis_hastings.m index 7153c923cd..8d7db127e2 100644 --- a/matlab/independent_metropolis_hastings.m +++ b/matlab/independent_metropolis_hastings.m @@ -50,19 +50,19 @@ load([MhDirectoryName '/' ModelName '_mh_history.mat'],'record'); localVars = struct('TargetFun', TargetFun, ... - 'ProposalFun', ProposalFun, ... - 'xparam1', xparam1, ... - 'vv', vv, ... - 'mh_bounds', mh_bounds, ... - 'ix2', ix2, ... - 'ilogpo2', ilogpo2, ... - 'ModelName', ModelName, ... - 'fline', fline, ... - 'npar', npar, ... - 'nruns', nruns, ... - 'NewFile', NewFile, ... - 'MAX_nruns', MAX_nruns, ... - 'd', d); + 'ProposalFun', ProposalFun, ... + 'xparam1', xparam1, ... + 'vv', vv, ... + 'mh_bounds', mh_bounds, ... + 'ix2', ix2, ... + 'ilogpo2', ilogpo2, ... + 'ModelName', ModelName, ... + 'fline', fline, ... + 'npar', npar, ... + 'nruns', nruns, ... + 'NewFile', NewFile, ... + 'MAX_nruns', MAX_nruns, ... + 'd', d); localVars.InitSizeArray=InitSizeArray; localVars.record=record; localVars.varargin=varargin; @@ -77,10 +77,10 @@ if isnumeric(options_.parallel),% | isunix, % for the moment exclude unix platfo else % global variables for parallel routines globalVars = struct('M_',M_, ... - 'options_', options_, ... - 'bayestopt_', bayestopt_, ... - 'estim_params_', estim_params_, ... - 'oo_', oo_); + 'options_', options_, ... + 'bayestopt_', bayestopt_, ... + 'estim_params_', estim_params_, ... + 'oo_', oo_); % which files have to be copied to run remotely NamFileInput(1,:) = {'',[ModelName '_static.m']}; @@ -91,17 +91,17 @@ else if (options_.load_mh_file~=0) & any(fline>1) , NamFileInput(length(NamFileInput)+1,:)={[M_.dname '/metropolis/'],[ModelName '_mh' int2str(NewFile(1)) '_blck*.mat']}; end - + % from where to get back results -% NamFileOutput(1,:) = {[M_.dname,'/metropolis/'],'*.*'}; + % NamFileOutput(1,:) = {[M_.dname,'/metropolis/'],'*.*'}; [fout, nBlockPerCPU, totCPU] = masterParallel(options_.parallel, fblck, nblck,NamFileInput,'independent_metropolis_hastings_core', localVars, globalVars); for j=1:totCPU, - offset = sum(nBlockPerCPU(1:j-1))+fblck-1; - record.LastLogLiK(offset+1:sum(nBlockPerCPU(1:j)))=fout(j).record.LastLogLiK(offset+1:sum(nBlockPerCPU(1:j))); - record.LastParameters(offset+1:sum(nBlockPerCPU(1:j)),:)=fout(j).record.LastParameters(offset+1:sum(nBlockPerCPU(1:j)),:); - record.AcceptationRates(offset+1:sum(nBlockPerCPU(1:j)))=fout(j).record.AcceptationRates(offset+1:sum(nBlockPerCPU(1:j))); - record.Seeds(offset+1:sum(nBlockPerCPU(1:j)))=fout(j).record.Seeds(offset+1:sum(nBlockPerCPU(1:j))); + offset = sum(nBlockPerCPU(1:j-1))+fblck-1; + record.LastLogLiK(offset+1:sum(nBlockPerCPU(1:j)))=fout(j).record.LastLogLiK(offset+1:sum(nBlockPerCPU(1:j))); + record.LastParameters(offset+1:sum(nBlockPerCPU(1:j)),:)=fout(j).record.LastParameters(offset+1:sum(nBlockPerCPU(1:j)),:); + record.AcceptationRates(offset+1:sum(nBlockPerCPU(1:j)))=fout(j).record.AcceptationRates(offset+1:sum(nBlockPerCPU(1:j))); + record.Seeds(offset+1:sum(nBlockPerCPU(1:j)))=fout(j).record.Seeds(offset+1:sum(nBlockPerCPU(1:j))); end end @@ -109,7 +109,7 @@ end irun = fout(1).irun; NewFile = fout(1).NewFile; - + % ComptationalTime=toc, % record.Seeds.Normal = randn('state'); diff --git a/matlab/independent_metropolis_hastings_core.m b/matlab/independent_metropolis_hastings_core.m index f585268ae8..ca7cbad5e8 100644 --- a/matlab/independent_metropolis_hastings_core.m +++ b/matlab/independent_metropolis_hastings_core.m @@ -1,189 +1,189 @@ -function myoutput = independent_metropolis_hastings_core(myinputs,fblck,nblck,whoiam, ThisMatlab) - -% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. - -if nargin<4, - whoiam=0; -end - - -global bayestopt_ estim_params_ options_ M_ oo_ - -struct2local(myinputs); - - -MhDirectoryName = CheckPath('metropolis'); - -OpenOldFile = ones(nblck,1); -if strcmpi(ProposalFun,'rand_multivariate_normal') - n = npar; - ProposalDensity = 'multivariate_normal_pdf'; -elseif strcmpi(ProposalFun,'rand_multivariate_student') - n = options_.student_degrees_of_freedom; - ProposalDensity = 'multivariate_student_pdf'; -end -% load([MhDirectoryName '/' ModelName '_mh_history.mat'],'record'); -%%%% -%%%% NOW i run the (nblck-fblck+1) metropolis-hastings chains -%%%% -jscale = diag(bayestopt_.jscale); - -jloop=0; - -for b = fblck:nblck, - jloop=jloop+1; - randn('state',record.Seeds(b).Normal); - rand('state',record.Seeds(b).Unifor); - if (options_.load_mh_file~=0) & (fline(b)>1) & OpenOldFile(b) - load(['./' MhDirectoryName '/' ModelName '_mh' int2str(NewFile(b)) ... - '_blck' int2str(b) '.mat']) - x2 = [x2;zeros(InitSizeArray(b)-fline(b)+1,npar)]; - logpo2 = [logpo2;zeros(InitSizeArray(b)-fline(b)+1,1)]; - OpenOldFile(b) = 0; - else - x2 = zeros(InitSizeArray(b),npar); - logpo2 = zeros(InitSizeArray(b),1); - end - if exist('OCTAVE_VERSION') - diary off; - elseif whoiam -% keyboard; - waitbarString = ['Please wait... Metropolis-Hastings (' int2str(b) '/' int2str(options_.mh_nblck) ')...']; -% waitbarTitle=['Metropolis-Hastings ',options_.parallel(ThisMatlab).PcName]; - if options_.parallel(ThisMatlab).Local, - waitbarTitle=['Local ']; - else - waitbarTitle=[options_.parallel(ThisMatlab).PcName]; - end - fMessageStatus(0,whoiam,waitbarString, waitbarTitle, options_.parallel(ThisMatlab), MasterName, DyMo); - else, - hh = waitbar(0,['Please wait... Metropolis-Hastings (' int2str(b) '/' int2str(options_.mh_nblck) ')...']); - set(hh,'Name','Metropolis-Hastings'); - - end - isux = 0; - jsux = 0; - irun = fline(b); - j = 1; - while j <= nruns(b) - par = feval(ProposalFun, xparam1, d * jscale, n); - if all( par(:) > mh_bounds(:,1) ) & all( par(:) < mh_bounds(:,2) ) - try - logpost = - feval(TargetFun, par(:),varargin{:}); - catch, - logpost = -inf; - end - else - logpost = -inf; - end - r = logpost - ilogpo2(b) + ... - log(feval(ProposalDensity, ix2(b,:), xparam1, d * jscale, n)) - ... - log(feval(ProposalDensity, par, xparam1, d * jscale, n)); - if (logpost > -inf) && (log(rand) < r) - x2(irun,:) = par; - ix2(b,:) = par; - logpo2(irun) = logpost; - ilogpo2(b) = logpost; - isux = isux + 1; - jsux = jsux + 1; - else - x2(irun,:) = ix2(b,:); - logpo2(irun) = ilogpo2(b); - end - prtfrc = j/nruns(b); - if exist('OCTAVE_VERSION') - if mod(j, 10) == 0, - printf('MH: Computing Metropolis-Hastings (chain %d/%d): %3.f%% done, acception rate: %3.f%%\r', b, nblck, 100 * prtfrc, 100 * isux / j); - end - if mod(j,50)==0 & whoiam, -% keyboard; - waitbarString = [ '(' int2str(b) '/' int2str(options_.mh_nblck) '), ' sprintf('accept. %3.f%%%%', 100 * isux/j)]; - fMessageStatus(prtfrc,whoiam,waitbarString, '', options_.parallel(ThisMatlab), MasterName, DyMo) - end - else - if mod(j, 3)==0 & ~whoiam - waitbar(prtfrc,hh,[ '(' int2str(b) '/' int2str(options_.mh_nblck) ') ' sprintf('%f done, acceptation rate %f',prtfrc,isux/j)]); - elseif mod(j,50)==0 & whoiam, -% keyboard; - waitbarString = [ '(' int2str(b) '/' int2str(options_.mh_nblck) ') ' sprintf('%f done, acceptation rate %f',prtfrc,isux/j)]; - fMessageStatus(prtfrc,whoiam,waitbarString, waitbarTitle, options_.parallel(ThisMatlab), MasterName, DyMo) - end - end - - if (irun == InitSizeArray(b)) | (j == nruns(b)) % Now I save the simulations - save([MhDirectoryName '/' ModelName '_mh' int2str(NewFile(b)) '_blck' int2str(b) '.mat'],'x2','logpo2'); - fidlog = fopen([MhDirectoryName '/metropolis.log'],'a'); - fprintf(fidlog,['\n']); - fprintf(fidlog,['%% Mh' int2str(NewFile(b)) 'Blck' int2str(b) ' (' datestr(now,0) ')\n']); - fprintf(fidlog,' \n'); - fprintf(fidlog,[' Number of simulations.: ' int2str(length(logpo2)) '\n']); - fprintf(fidlog,[' Acceptation rate......: ' num2str(jsux/length(logpo2)) '\n']); - fprintf(fidlog,[' Posterior mean........:\n']); - for i=1:length(x2(1,:)) - fprintf(fidlog,[' params:' int2str(i) ': ' num2str(mean(x2(:,i))) '\n']); - end - fprintf(fidlog,[' log2po:' num2str(mean(logpo2)) '\n']); - fprintf(fidlog,[' Minimum value.........:\n']);; - for i=1:length(x2(1,:)) - fprintf(fidlog,[' params:' int2str(i) ': ' num2str(min(x2(:,i))) '\n']); - end - fprintf(fidlog,[' log2po:' num2str(min(logpo2)) '\n']); - fprintf(fidlog,[' Maximum value.........:\n']); - for i=1:length(x2(1,:)) - fprintf(fidlog,[' params:' int2str(i) ': ' num2str(max(x2(:,i))) '\n']); - end - fprintf(fidlog,[' log2po:' num2str(max(logpo2)) '\n']); - fprintf(fidlog,' \n'); - fclose(fidlog); - jsux = 0; - if j == nruns(b) % I record the last draw... - record.LastParameters(b,:) = x2(end,:); - record.LastLogLiK(b) = logpo2(end); - end - % size of next file in chain b - InitSizeArray(b) = min(nruns(b)-j,MAX_nruns); - % initialization of next file if necessary - if InitSizeArray(b) - x2 = zeros(InitSizeArray(b),npar); - logpo2 = zeros(InitSizeArray(b),1); - NewFile(b) = NewFile(b) + 1; - irun = 0; - end - end - j=j+1; - irun = irun + 1; - end% End of the simulations for one mh-block. - record.AcceptationRates(b) = isux/j; - if exist('OCTAVE_VERSION') - printf('\n'); - diary on; - elseif ~whoiam - close(hh); - end - record.Seeds(b).Normal = randn('state'); - record.Seeds(b).Unifor = rand('state'); - OutputFileName(jloop,:) = {[MhDirectoryName,filesep], [ModelName '_mh*_blck' int2str(b) '.mat']}; -end% End of the loop over the mh-blocks. - - -myoutput.record = record; -myoutput.irun = irun; -myoutput.NewFile = NewFile; -myoutput.OutputFileName = OutputFileName; - - +function myoutput = independent_metropolis_hastings_core(myinputs,fblck,nblck,whoiam, ThisMatlab) + +% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. + +if nargin<4, + whoiam=0; +end + + +global bayestopt_ estim_params_ options_ M_ oo_ + +struct2local(myinputs); + + +MhDirectoryName = CheckPath('metropolis'); + +OpenOldFile = ones(nblck,1); +if strcmpi(ProposalFun,'rand_multivariate_normal') + n = npar; + ProposalDensity = 'multivariate_normal_pdf'; +elseif strcmpi(ProposalFun,'rand_multivariate_student') + n = options_.student_degrees_of_freedom; + ProposalDensity = 'multivariate_student_pdf'; +end +% load([MhDirectoryName '/' ModelName '_mh_history.mat'],'record'); +%%%% +%%%% NOW i run the (nblck-fblck+1) metropolis-hastings chains +%%%% +jscale = diag(bayestopt_.jscale); + +jloop=0; + +for b = fblck:nblck, + jloop=jloop+1; + randn('state',record.Seeds(b).Normal); + rand('state',record.Seeds(b).Unifor); + if (options_.load_mh_file~=0) & (fline(b)>1) & OpenOldFile(b) + load(['./' MhDirectoryName '/' ModelName '_mh' int2str(NewFile(b)) ... + '_blck' int2str(b) '.mat']) + x2 = [x2;zeros(InitSizeArray(b)-fline(b)+1,npar)]; + logpo2 = [logpo2;zeros(InitSizeArray(b)-fline(b)+1,1)]; + OpenOldFile(b) = 0; + else + x2 = zeros(InitSizeArray(b),npar); + logpo2 = zeros(InitSizeArray(b),1); + end + if exist('OCTAVE_VERSION') + diary off; + elseif whoiam + % keyboard; + waitbarString = ['Please wait... Metropolis-Hastings (' int2str(b) '/' int2str(options_.mh_nblck) ')...']; + % waitbarTitle=['Metropolis-Hastings ',options_.parallel(ThisMatlab).PcName]; + if options_.parallel(ThisMatlab).Local, + waitbarTitle=['Local ']; + else + waitbarTitle=[options_.parallel(ThisMatlab).PcName]; + end + fMessageStatus(0,whoiam,waitbarString, waitbarTitle, options_.parallel(ThisMatlab), MasterName, DyMo); + else, + hh = waitbar(0,['Please wait... Metropolis-Hastings (' int2str(b) '/' int2str(options_.mh_nblck) ')...']); + set(hh,'Name','Metropolis-Hastings'); + + end + isux = 0; + jsux = 0; + irun = fline(b); + j = 1; + while j <= nruns(b) + par = feval(ProposalFun, xparam1, d * jscale, n); + if all( par(:) > mh_bounds(:,1) ) & all( par(:) < mh_bounds(:,2) ) + try + logpost = - feval(TargetFun, par(:),varargin{:}); + catch, + logpost = -inf; + end + else + logpost = -inf; + end + r = logpost - ilogpo2(b) + ... + log(feval(ProposalDensity, ix2(b,:), xparam1, d * jscale, n)) - ... + log(feval(ProposalDensity, par, xparam1, d * jscale, n)); + if (logpost > -inf) && (log(rand) < r) + x2(irun,:) = par; + ix2(b,:) = par; + logpo2(irun) = logpost; + ilogpo2(b) = logpost; + isux = isux + 1; + jsux = jsux + 1; + else + x2(irun,:) = ix2(b,:); + logpo2(irun) = ilogpo2(b); + end + prtfrc = j/nruns(b); + if exist('OCTAVE_VERSION') + if mod(j, 10) == 0, + printf('MH: Computing Metropolis-Hastings (chain %d/%d): %3.f%% done, acception rate: %3.f%%\r', b, nblck, 100 * prtfrc, 100 * isux / j); + end + if mod(j,50)==0 & whoiam, + % keyboard; + waitbarString = [ '(' int2str(b) '/' int2str(options_.mh_nblck) '), ' sprintf('accept. %3.f%%%%', 100 * isux/j)]; + fMessageStatus(prtfrc,whoiam,waitbarString, '', options_.parallel(ThisMatlab), MasterName, DyMo) + end + else + if mod(j, 3)==0 & ~whoiam + waitbar(prtfrc,hh,[ '(' int2str(b) '/' int2str(options_.mh_nblck) ') ' sprintf('%f done, acceptation rate %f',prtfrc,isux/j)]); + elseif mod(j,50)==0 & whoiam, + % keyboard; + waitbarString = [ '(' int2str(b) '/' int2str(options_.mh_nblck) ') ' sprintf('%f done, acceptation rate %f',prtfrc,isux/j)]; + fMessageStatus(prtfrc,whoiam,waitbarString, waitbarTitle, options_.parallel(ThisMatlab), MasterName, DyMo) + end + end + + if (irun == InitSizeArray(b)) | (j == nruns(b)) % Now I save the simulations + save([MhDirectoryName '/' ModelName '_mh' int2str(NewFile(b)) '_blck' int2str(b) '.mat'],'x2','logpo2'); + fidlog = fopen([MhDirectoryName '/metropolis.log'],'a'); + fprintf(fidlog,['\n']); + fprintf(fidlog,['%% Mh' int2str(NewFile(b)) 'Blck' int2str(b) ' (' datestr(now,0) ')\n']); + fprintf(fidlog,' \n'); + fprintf(fidlog,[' Number of simulations.: ' int2str(length(logpo2)) '\n']); + fprintf(fidlog,[' Acceptation rate......: ' num2str(jsux/length(logpo2)) '\n']); + fprintf(fidlog,[' Posterior mean........:\n']); + for i=1:length(x2(1,:)) + fprintf(fidlog,[' params:' int2str(i) ': ' num2str(mean(x2(:,i))) '\n']); + end + fprintf(fidlog,[' log2po:' num2str(mean(logpo2)) '\n']); + fprintf(fidlog,[' Minimum value.........:\n']);; + for i=1:length(x2(1,:)) + fprintf(fidlog,[' params:' int2str(i) ': ' num2str(min(x2(:,i))) '\n']); + end + fprintf(fidlog,[' log2po:' num2str(min(logpo2)) '\n']); + fprintf(fidlog,[' Maximum value.........:\n']); + for i=1:length(x2(1,:)) + fprintf(fidlog,[' params:' int2str(i) ': ' num2str(max(x2(:,i))) '\n']); + end + fprintf(fidlog,[' log2po:' num2str(max(logpo2)) '\n']); + fprintf(fidlog,' \n'); + fclose(fidlog); + jsux = 0; + if j == nruns(b) % I record the last draw... + record.LastParameters(b,:) = x2(end,:); + record.LastLogLiK(b) = logpo2(end); + end + % size of next file in chain b + InitSizeArray(b) = min(nruns(b)-j,MAX_nruns); + % initialization of next file if necessary + if InitSizeArray(b) + x2 = zeros(InitSizeArray(b),npar); + logpo2 = zeros(InitSizeArray(b),1); + NewFile(b) = NewFile(b) + 1; + irun = 0; + end + end + j=j+1; + irun = irun + 1; + end% End of the simulations for one mh-block. + record.AcceptationRates(b) = isux/j; + if exist('OCTAVE_VERSION') + printf('\n'); + diary on; + elseif ~whoiam + close(hh); + end + record.Seeds(b).Normal = randn('state'); + record.Seeds(b).Unifor = rand('state'); + OutputFileName(jloop,:) = {[MhDirectoryName,filesep], [ModelName '_mh*_blck' int2str(b) '.mat']}; +end% End of the loop over the mh-blocks. + + +myoutput.record = record; +myoutput.irun = irun; +myoutput.NewFile = NewFile; +myoutput.OutputFileName = OutputFileName; + + diff --git a/matlab/indnv.m b/matlab/indnv.m index be3dbd0ca1..8345b87f40 100644 --- a/matlab/indnv.m +++ b/matlab/indnv.m @@ -33,12 +33,12 @@ function a=indnv(x,y) a = zeros(size(x)) ; for i = 1:size(x,1) - j = find( x(i) == y ); - if isempty(j) - a(i) = NaN; - else - a(i) = j; - end + j = find( x(i) == y ); + if isempty(j) + a(i) = NaN; + else + a(i) = j; + end end diff --git a/matlab/initial_estimation_checks.m b/matlab/initial_estimation_checks.m index 83f1a85955..6e0ad2aadb 100644 --- a/matlab/initial_estimation_checks.m +++ b/matlab/initial_estimation_checks.m @@ -30,43 +30,43 @@ function initial_estimation_checks(xparam1,gend,data,data_index,number_of_observ % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global dr1_test bayestopt_ estim_params_ options_ oo_ M_ +global dr1_test bayestopt_ estim_params_ options_ oo_ M_ - nv = size(data,1); - if nv-size(options_.varobs,1) +nv = size(data,1); +if nv-size(options_.varobs,1) disp(' ') disp(['Declared number of observed variables = ' int2str(size(options_.varobs,1))]) disp(['Number of variables in the database = ' int2str(nv)]) disp(' ') error(['Estimation can''t take place because the declared number of observed' ... 'variables doesn''t match the number of variables in the database.']) - end - if nv > M_.exo_nbr+estim_params_.nvn +end +if nv > M_.exo_nbr+estim_params_.nvn error(['Estimation can''t take place because there are less shocks than' ... 'observed variables']) - end - if (number_of_observations==gend*nv)% No missing observations... - k = find(all(~isnan(data),2)); - r = rank(data(unique(k),:)); - if r < nv - error(['Estimation can''t take place because the data are perfectly' ... - ' correlated']); - end - end - - if ~isempty(strmatch('dsge_prior_weight',M_.param_names)) +end +if (number_of_observations==gend*nv)% No missing observations... + k = find(all(~isnan(data),2)); + r = rank(data(unique(k),:)); + if r < nv + error(['Estimation can''t take place because the data are perfectly' ... + ' correlated']); + end +end + +if ~isempty(strmatch('dsge_prior_weight',M_.param_names)) [fval,cost_flag,info] = DsgeVarLikelihood(xparam1,gend); - else +else [fval,cost_flag,ys,trend_coeff,info] = DsgeLikelihood(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations); - end +end - % when their is an analytical steadystate, check that the values - % returned by *_steadystate match with the static model - if options_.steadystate_flag +% when their is an analytical steadystate, check that the values +% returned by *_steadystate match with the static model +if options_.steadystate_flag [ys,check] = feval([M_.fname '_steadystate'],... - oo_.steady_state,... - [oo_.exo_steady_state; ... - oo_.exo_det_steady_state]); + oo_.steady_state,... + [oo_.exo_steady_state; ... + oo_.exo_det_steady_state]); if size(ys,1) < M_.endo_nbr if length(M_.aux_vars) > 0 ys = add_auxiliary_variables_to_steadystate(ys,M_.aux_vars,... @@ -83,28 +83,28 @@ function initial_estimation_checks(xparam1,gend,data,data_index,number_of_observ % steady state. check1 = 0; if isfield(options_,'unit_root_vars') & options_.diffuse_filter == 0 - if isempty(options_.unit_root_vars) - check1 = max(abs(feval([M_.fname '_static'],... - oo_.steady_state,... - [oo_.exo_steady_state; ... - oo_.exo_det_steady_state], M_.params))) > options_.dynatol ; - if check1 - error(['The seadystate values returned by ' M_.fname ... - '_steadystate.m don''t solve the static model!' ]) - end - end + if isempty(options_.unit_root_vars) + check1 = max(abs(feval([M_.fname '_static'],... + oo_.steady_state,... + [oo_.exo_steady_state; ... + oo_.exo_det_steady_state], M_.params))) > options_.dynatol ; + if check1 + error(['The seadystate values returned by ' M_.fname ... + '_steadystate.m don''t solve the static model!' ]) + end + end end - end - - if info(1) > 0 - disp('Error in computing likelihood for initial parameter values') - print_info(info, options_.noprint) - end - - if any(abs(oo_.steady_state(bayestopt_.mfys))>1e-9) & (options_.prefilter==1) - disp(['You are trying to estimate a model with a non zero steady state for the observed endogenous']) - disp(['variables using demeaned data!']) - error('You should change something in your mod file...') - end - - disp(['Initial value of the log posterior (or likelihood): ' num2str(-fval)]); +end + +if info(1) > 0 + disp('Error in computing likelihood for initial parameter values') + print_info(info, options_.noprint) +end + +if any(abs(oo_.steady_state(bayestopt_.mfys))>1e-9) & (options_.prefilter==1) + disp(['You are trying to estimate a model with a non zero steady state for the observed endogenous']) + disp(['variables using demeaned data!']) + error('You should change something in your mod file...') +end + +disp(['Initial value of the log posterior (or likelihood): ' num2str(-fval)]); diff --git a/matlab/initialize_from_mode.m b/matlab/initialize_from_mode.m index b5900801f0..7cdfe662ff 100644 --- a/matlab/initialize_from_mode.m +++ b/matlab/initialize_from_mode.m @@ -31,73 +31,72 @@ function estim_params_ = initialize_from_mode(fname,M_,estim_params_) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - load(fname,'xparam1','parameter_names'); - - endo_names = M_.endo_names; - exo_names = M_.exo_names; - param_names = M_.param_names; - param_vals = estim_params_.param_vals; - var_exo = estim_params_.var_exo; - var_endo = estim_params_.var_endo; - corrx = estim_params_.corrx; - corrn = estim_params_.corrn; - for i=1:length(parameter_names) - name = parameter_names{i}; - k1 = strmatch(name,param_names,'exact'); + +load(fname,'xparam1','parameter_names'); + +endo_names = M_.endo_names; +exo_names = M_.exo_names; +param_names = M_.param_names; +param_vals = estim_params_.param_vals; +var_exo = estim_params_.var_exo; +var_endo = estim_params_.var_endo; +corrx = estim_params_.corrx; +corrn = estim_params_.corrn; +for i=1:length(parameter_names) + name = parameter_names{i}; + k1 = strmatch(name,param_names,'exact'); + if ~isempty(k1) + k2 = find(param_vals(:,1) == k1); + if ~isempty(k2) + estim_params_.param_vals(k2,2) = xparam1(i); + end + M_.params(i) = xparam1(i); + continue + end + k3 = strfind(name,','); + if isempty(k3) + k1 = strmatch(name,exo_names,'exact'); if ~isempty(k1) - k2 = find(param_vals(:,1) == k1); + k2 = find(var_exo(:,1) == k1); if ~isempty(k2) - estim_params_.param_vals(k2,2) = xparam1(i); + estim_params_.var_exo(k2,2) = xparam1(i); end - M_.params(i) = xparam1(i); + M_.Sigma_e(k1,k1) = xparam1(i)^2; continue end - k3 = strfind(name,','); - if isempty(k3) - k1 = strmatch(name,exo_names,'exact'); - if ~isempty(k1) - k2 = find(var_exo(:,1) == k1); - if ~isempty(k2) - estim_params_.var_exo(k2,2) = xparam1(i); - end - M_.Sigma_e(k1,k1) = xparam1(i)^2; - continue - end - k1 = strmatch(name,endo_names,'exact'); - if ~isempty(k1) - k2 = find(var_endo(:,1) == k1); - if ~isempty(k2) - estim_params_.var_endo(k2,2) = xparam1(i); - end - M_.H(k1,k1) = xparam1(i)^2; - continue + k1 = strmatch(name,endo_names,'exact'); + if ~isempty(k1) + k2 = find(var_endo(:,1) == k1); + if ~isempty(k2) + estim_params_.var_endo(k2,2) = xparam1(i); end - else - k1 = strmatch(name(1:k3-1),exo_names,'exact'); - k1a = strmatch(name(k3+1:end),exo_names,'exact'); - if ~isempty(k1) & ~isempty(k1a) - k2 = find(corrx(:,1) == k1 & corrx(:,2) == k1a); - if ~isempty(k2) - estim_params_.corrx(k2,3) = xparam1(i); - end - M_.Sigma_e(k1,k1a) = xparam1(i)*sqrt(M_.Sigma_e(k1,k1)+M_.Sigma_e(k1a,k1a)); - M_.Sigma_e(k1a,k1) = M_.Sigma_e(k1,k1a); - continue + M_.H(k1,k1) = xparam1(i)^2; + continue + end + else + k1 = strmatch(name(1:k3-1),exo_names,'exact'); + k1a = strmatch(name(k3+1:end),exo_names,'exact'); + if ~isempty(k1) & ~isempty(k1a) + k2 = find(corrx(:,1) == k1 & corrx(:,2) == k1a); + if ~isempty(k2) + estim_params_.corrx(k2,3) = xparam1(i); end - k1 = strmatch(name(1:k3-1),endo_names,'exact'); - k1a = strmatch(name(k3+1:end),endo_names,'exact'); - if ~isempty(k1) & ~isempty(k1a) - k2 = find(corrn(:,1) == k1 & corrn(:,2) == k1a); - if ~isempty(k2) - estim_params_.corrn(k2,3) = xparam1(i); - end - M_.H(k1,k1a) = xparam1(i)*sqrt(M_.H(k1,k1)+M_.H(k1a,k1a)); - M_.H(k1a,k1) = M_.H(k1,k1a); - continue + M_.Sigma_e(k1,k1a) = xparam1(i)*sqrt(M_.Sigma_e(k1,k1)+M_.Sigma_e(k1a,k1a)); + M_.Sigma_e(k1a,k1) = M_.Sigma_e(k1,k1a); + continue + end + k1 = strmatch(name(1:k3-1),endo_names,'exact'); + k1a = strmatch(name(k3+1:end),endo_names,'exact'); + if ~isempty(k1) & ~isempty(k1a) + k2 = find(corrn(:,1) == k1 & corrn(:,2) == k1a); + if ~isempty(k2) + estim_params_.corrn(k2,3) = xparam1(i); end + M_.H(k1,k1a) = xparam1(i)*sqrt(M_.H(k1,k1)+M_.H(k1a,k1a)); + M_.H(k1a,k1) = M_.H(k1,k1a); + continue end - error([name 'doesn''t exist in this model']) end - - \ No newline at end of file + error([name 'doesn''t exist in this model']) +end + diff --git a/matlab/initvalf.m b/matlab/initvalf.m index f581a04328..0dbbe59cd9 100644 --- a/matlab/initvalf.m +++ b/matlab/initvalf.m @@ -30,46 +30,46 @@ function initvalf(fname_) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ oo_ options_ +global M_ oo_ options_ - series_ = 1; - if exist(fname_) == 2 - eval(fname_); - elseif exist([fname_ '.xls']) == 2 - [data_,names_v_]=xlsread([fname_ '.xls']); - series_ = 0; - elseif exist([fname_ '.mat']) == 2 - load(fname_); - end - - options_.initval_file = 1; - oo_.endo_simul = []; - oo_.exo_simul = []; - - for i_=1:size(M_.endo_names,1) +series_ = 1; +if exist(fname_) == 2 + eval(fname_); +elseif exist([fname_ '.xls']) == 2 + [data_,names_v_]=xlsread([fname_ '.xls']); + series_ = 0; +elseif exist([fname_ '.mat']) == 2 + load(fname_); +end + +options_.initval_file = 1; +oo_.endo_simul = []; +oo_.exo_simul = []; + +for i_=1:size(M_.endo_names,1) if series_ == 1 - x_ = eval(M_.endo_names(i_,:)); - oo_.endo_simul = [oo_.endo_simul; x_']; + x_ = eval(M_.endo_names(i_,:)); + oo_.endo_simul = [oo_.endo_simul; x_']; else - k_ = strmatch(upper(M_.endo_names(i_,:)),names_v_,'exact'); - if isempty(k_) - error(['INITVAL_FILE: ' M_.endo_names(i_,:) ' not found']) - end - x_ = data_(:,k_); - oo_.endo_simul = [oo_.endo_simul; x_']; + k_ = strmatch(upper(M_.endo_names(i_,:)),names_v_,'exact'); + if isempty(k_) + error(['INITVAL_FILE: ' M_.endo_names(i_,:) ' not found']) + end + x_ = data_(:,k_); + oo_.endo_simul = [oo_.endo_simul; x_']; end - end - - for i_=1:size(M_.exo_names,1) +end + +for i_=1:size(M_.exo_names,1) if series_ == 1 - x_ = eval(M_.exo_names(i_,:) ); - oo_.exo_simul = [oo_.exo_simul x_]; + x_ = eval(M_.exo_names(i_,:) ); + oo_.exo_simul = [oo_.exo_simul x_]; else - k_ = strmatch(upper(M_.exo_names(i_,:)),names_v_,'exact'); - if isempty(k_) - error(['INITVAL_FILE: ' M_.exo_names(i_,:) ' not found']) - end - x_ = data_(:,k_); - oo_.exo_simul = [oo_.exo_simul x_]; + k_ = strmatch(upper(M_.exo_names(i_,:)),names_v_,'exact'); + if isempty(k_) + error(['INITVAL_FILE: ' M_.exo_names(i_,:) ' not found']) + end + x_ = data_(:,k_); + oo_.exo_simul = [oo_.exo_simul x_]; end - end +end diff --git a/matlab/irf.m b/matlab/irf.m index 91d7fa3cb3..fcfa9d3c69 100644 --- a/matlab/irf.m +++ b/matlab/irf.m @@ -34,19 +34,19 @@ function y = irf(dr, e1, long, drop, replic, iorder) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ oo_ options_ +global M_ oo_ options_ - temps = repmat(dr.ys,1,M_.maximum_lag); - y = 0; - - if iorder == 1 +temps = repmat(dr.ys,1,M_.maximum_lag); +y = 0; + +if iorder == 1 y1 = repmat(dr.ys,1,long); ex2 = zeros(long,M_.exo_nbr); ex2(1,:) = e1'; y2 = simult_(temps,dr,ex2,iorder); y = y2(:,M_.maximum_lag+1:end)-y1; - else +else % eliminate shocks with 0 variance i_exo_var = setdiff([1:M_.exo_nbr],find(diag(M_.Sigma_e) == 0 )); nxs = length(i_exo_var); @@ -54,13 +54,13 @@ function y = irf(dr, e1, long, drop, replic, iorder) ex2 = ex1; chol_S = chol(M_.Sigma_e(i_exo_var,i_exo_var)); for j = 1: replic - randn('seed',j); - ex1(:,i_exo_var) = randn(long+drop,nxs)*chol_S; - ex2 = ex1; - ex2(drop+1,:) = ex2(drop+1,:)+e1'; - y1 = simult_(temps,dr,ex1,iorder); - y2 = simult_(temps,dr,ex2,iorder); - y = y+(y2(:,M_.maximum_lag+drop+1:end)-y1(:,M_.maximum_lag+drop+1:end)); + randn('seed',j); + ex1(:,i_exo_var) = randn(long+drop,nxs)*chol_S; + ex2 = ex1; + ex2(drop+1,:) = ex2(drop+1,:)+e1'; + y1 = simult_(temps,dr,ex1,iorder); + y2 = simult_(temps,dr,ex2,iorder); + y = y+(y2(:,M_.maximum_lag+drop+1:end)-y1(:,M_.maximum_lag+drop+1:end)); end y=y/replic; - end +end diff --git a/matlab/isconst.m b/matlab/isconst.m index 9bcea59bdb..28d306f1f7 100644 --- a/matlab/isconst.m +++ b/matlab/isconst.m @@ -26,7 +26,7 @@ function aa = isconst(y) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/> - aa = 0; - if all(abs(y(2:end)-y(1:end-1))<1e-10) - aa = 1; - end \ No newline at end of file +aa = 0; +if all(abs(y(2:end)-y(1:end-1))<1e-10) + aa = 1; +end \ No newline at end of file diff --git a/matlab/isint.m b/matlab/isint.m index ddc44ba710..111fc21e40 100644 --- a/matlab/isint.m +++ b/matlab/isint.m @@ -14,7 +14,7 @@ function [b,c,d] = isint(a) % % NOTES % p+q is equal to the product of m by n. - + % Copyright (C) 2009 Dynare Team % % This file is part of Dynare. @@ -32,10 +32,10 @@ function [b,c,d] = isint(a) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - [m,n] = size(a); - b = abs(fix(a)-a)<1e-15; - - if nargout>1 - c = find(b==1); - d = find(b==0); - end \ No newline at end of file +[m,n] = size(a); +b = abs(fix(a)-a)<1e-15; + +if nargout>1 + c = find(b==1); + d = find(b==0); +end \ No newline at end of file diff --git a/matlab/ispd.m b/matlab/ispd.m index 99cc181be2..874be5808b 100644 --- a/matlab/ispd.m +++ b/matlab/ispd.m @@ -33,8 +33,8 @@ m = length(A);% I do not test for a square matrix... test = 1; for i=1:m - if ( det( A(1:i, 1:i) ) < 2.0*eps ) - test = 0; - break - end + if ( det( A(1:i, 1:i) ) < 2.0*eps ) + test = 0; + break + end end \ No newline at end of file diff --git a/matlab/k_order_pert.m b/matlab/k_order_pert.m index 56ab80f16c..33efb45408 100644 --- a/matlab/k_order_pert.m +++ b/matlab/k_order_pert.m @@ -1,81 +1,81 @@ function [dr,info] = k_order_pert(dr,M,options,oo) - - info = 0; - - M.var_order_endo_names = M.endo_names(dr.order_var,:); - order = options.order; - - switch(order) - case 1 - [g_0, g_1] = k_order_perturbation(dr,0,M,options, oo , ['.' ... - mexext]); - dr.g_1 = g_1; - case 2 - [g_0, g_1, g_2] = k_order_perturbation(dr,0,M,options, oo , ['.' ... - mexext]); - dr.g_0 = g_0; - dr.g_1 = g_1; - dr.g_2 = g_2; - case 3 - [g_0, g_1, g_2, g_3] = k_order_perturbation(dr,0,M,options, oo , ['.' ... - mexext]); - dr.g_0 = g_0; - dr.g_1 = g_1; - dr.g_2 = g_2; - dr.g_3 = g_3; - otherwise - error('order > 3 isn''t implemented') - end - - npred = dr.npred; - - dr.ghx = g_1(:,1:npred); - dr.ghu = g_1(:,npred+1:end); +info = 0; + +M.var_order_endo_names = M.endo_names(dr.order_var,:); + +order = options.order; + +switch(order) + case 1 + [g_0, g_1] = k_order_perturbation(dr,0,M,options, oo , ['.' ... + mexext]); + dr.g_1 = g_1; + case 2 + [g_0, g_1, g_2] = k_order_perturbation(dr,0,M,options, oo , ['.' ... + mexext]); + dr.g_0 = g_0; + dr.g_1 = g_1; + dr.g_2 = g_2; + case 3 + [g_0, g_1, g_2, g_3] = k_order_perturbation(dr,0,M,options, oo , ['.' ... + mexext]); + dr.g_0 = g_0; + dr.g_1 = g_1; + dr.g_2 = g_2; + dr.g_3 = g_3; + otherwise + error('order > 3 isn''t implemented') +end + +npred = dr.npred; + +dr.ghx = g_1(:,1:npred); +dr.ghu = g_1(:,npred+1:end); + +if options.loglinear == 1 + k = find(dr.kstate(:,2) <= M.maximum_endo_lag+1); + klag = dr.kstate(k,[1 2]); + k1 = dr.order_var; - if options.loglinear == 1 - k = find(dr.kstate(:,2) <= M.maximum_endo_lag+1); - klag = dr.kstate(k,[1 2]); - k1 = dr.order_var; - - dr.ghx = repmat(1./dr.ys(k1),1,size(dr.ghx,2)).*dr.ghx.* ... - repmat(dr.ys(k1(klag(:,1)))',size(dr.ghx,1),1); - dr.ghu = repmat(1./dr.ys(k1),1,size(dr.ghu,2)).*dr.ghu; - end + dr.ghx = repmat(1./dr.ys(k1),1,size(dr.ghx,2)).*dr.ghx.* ... + repmat(dr.ys(k1(klag(:,1)))',size(dr.ghx,1),1); + dr.ghu = repmat(1./dr.ys(k1),1,size(dr.ghu,2)).*dr.ghu; +end - if order > 1 - dr.ghs2 = 2*g_0; - endo_nbr = M.endo_nbr; - exo_nbr = M.exo_nbr; - s0 = 0; - s1 = 0; - ghxx=zeros(endo_nbr, npred^2); - ghxu=zeros(endo_nbr, npred*exo_nbr); - ghuu=zeros(endo_nbr, exo_nbr^2); - for i=1:size(g_2,2) - if s0 < npred & s1 < npred - ghxx(:,s0*npred+s1+1) = 2*g_2(:,i); - if s1 > s0 - ghxx(:,s1*npred+s0+1) = 2*g_2(:,i); - end - elseif s0 < npred & s1 < npred+exo_nbr - ghxu(:,(s0*exo_nbr+s1-npred+1)) = 2*g_2(:,i); - elseif s0 < npred+exo_nbr & s1 < npred+exo_nbr - ghuu(:,(s0-npred)*exo_nbr+s1-npred +1) = 2*g_2(:,i); - if s1 > s0 - ghuu(:,(s1-npred)*exo_nbr+s0-npred+1) = 2*g_2(:,i); - end - else - error('dr1:k_order_perturbation:g_2','Unaccounted columns in g_2'); +if order > 1 + dr.ghs2 = 2*g_0; + endo_nbr = M.endo_nbr; + exo_nbr = M.exo_nbr; + s0 = 0; + s1 = 0; + ghxx=zeros(endo_nbr, npred^2); + ghxu=zeros(endo_nbr, npred*exo_nbr); + ghuu=zeros(endo_nbr, exo_nbr^2); + for i=1:size(g_2,2) + if s0 < npred & s1 < npred + ghxx(:,s0*npred+s1+1) = 2*g_2(:,i); + if s1 > s0 + ghxx(:,s1*npred+s0+1) = 2*g_2(:,i); end - s1 = s1+1; - if s1 == npred+exo_nbr - s0 = s0+1; - s1 = s0; + elseif s0 < npred & s1 < npred+exo_nbr + ghxu(:,(s0*exo_nbr+s1-npred+1)) = 2*g_2(:,i); + elseif s0 < npred+exo_nbr & s1 < npred+exo_nbr + ghuu(:,(s0-npred)*exo_nbr+s1-npred +1) = 2*g_2(:,i); + if s1 > s0 + ghuu(:,(s1-npred)*exo_nbr+s0-npred+1) = 2*g_2(:,i); end - end % for loop - dr.ghxx = ghxx; - dr.ghxu = ghxu; - dr.ghuu = ghuu; - end - + else + error('dr1:k_order_perturbation:g_2','Unaccounted columns in g_2'); + end + s1 = s1+1; + if s1 == npred+exo_nbr + s0 = s0+1; + s1 = s0; + end + end % for loop + dr.ghxx = ghxx; + dr.ghxu = ghxu; + dr.ghuu = ghuu; +end + diff --git a/matlab/kalman/build_selection_matrix.m b/matlab/kalman/build_selection_matrix.m index bd47b72c16..573c719fdb 100644 --- a/matlab/kalman/build_selection_matrix.m +++ b/matlab/kalman/build_selection_matrix.m @@ -18,7 +18,7 @@ function Z = build_selection_matrix(mf,m,p) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - Z = zeros(p,m); - for i=1:p - Z(i,mf(i)) = 1; - end \ No newline at end of file +Z = zeros(p,m); +for i=1:p + Z(i,mf(i)) = 1; +end \ No newline at end of file diff --git a/matlab/kalman/likelihood/diffuse_kalman_filter.m b/matlab/kalman/likelihood/diffuse_kalman_filter.m index 1b27edc766..031fa16bfa 100644 --- a/matlab/kalman/likelihood/diffuse_kalman_filter.m +++ b/matlab/kalman/likelihood/diffuse_kalman_filter.m @@ -39,106 +39,106 @@ function [LIK, lik] = diffuse_kalman_filter(T,R,Q,H,Pinf,Pstar,Y,start,Z,kalman_ % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - [pp,smpl] = size(Y); - mm = size(T,2); - a = zeros(mm,1); - dF = 1; - QQ = R*Q*transpose(R); - t = 0; - oldK = 0; - lik = zeros(smpl,1); - LIK = Inf; + +[pp,smpl] = size(Y); +mm = size(T,2); +a = zeros(mm,1); +dF = 1; +QQ = R*Q*transpose(R); +t = 0; +oldK = 0; +lik = zeros(smpl,1); +LIK = Inf; % lik(smpl+1) = smpl*pp*log(2*pi); - notsteady = 1; - reste = 0; - - while rank(Pinf,kalman_tol) && (t<smpl) - t = t+1; - v = Y(:,t)-Z*a; - Finf = Z*Pinf*Z' ; - if rcond(Finf) < kalman_tol - if ~all(abs(Finf(:)) < kalman_tol) - % The univariate diffuse kalman filter should be used. - return - else - Fstar = Z*Pstar*Z' + H; - if rcond(Fstar) < kalman_tol - if ~all(abs(Fstar(:))<kalman_tol) - % The univariate diffuse kalman filter should be used. - return - else - a = T*a; - Pstar = T*Pstar*transpose(T)+QQ; - Pinf = T*Pinf*transpose(T); - end - else - iFstar = inv(Fstar); - dFstar = det(Fstar); - Kstar = Pstar*Z'*iFstar; - lik(t) = log(dFstar) + v'*iFstar*v; - Pinf = T*Pinf*transpose(T); - Pstar = T*(Pstar-Pstar*Z'*Kstar')*T'+QQ; - a = T*(a+Kstar*v); - end - end - else - lik(t) = log(det(Finf)); - iFinf = inv(Finf); - Kinf = Pinf*Z'*iFinf; - Fstar = Z*Pstar*Z' + H; - Kstar = (Pstar*Z'-Kinf*Fstar)*iFinf; - Pstar = T*(Pstar-Pstar*Z'*Kinf'-Pinf*Z'*Kstar')*T'+QQ; - Pinf = T*(Pinf-Pinf*Z'*Kinf')*T'; - a = T*(a+Kinf*v); - end - end - - if t == smpl - error(['There isn''t enough information to estimate the initial conditions of the nonstationary variables']); - end - - F_singular = 1; - while notsteady && (t<smpl) - t = t+1; - v = Y(:,t)-Z*a; - F = Z*Pstar*Z' + H; - oldPstar = Pstar; - dF = det(F); - if rcond(F) < kalman_tol - if ~all(abs(F(:))<kalman_tol) - return - else - a = T*a; - Pstar = T*Pstar*T'+QQ; - end - else - F_singular = 0; - iF = inv(F); - lik(t) = log(dF)+v'*iF*v; - K = Pstar*Z'*iF; - a = T*(a+K*v); - Pstar = T*(Pstar-K*Z*Pstar)*T'+QQ; - end - notsteady = ~(max(max(abs(K-oldK)))<riccati_tol); - oldK = K; - end - - if F_singular == 1 - error(['The variance of the forecast error remains singular until the end of the sample']) - end - - if t < smpl - t0 = t; - while t<smpl - t = t+1; - v = Y(:,t)-Z*a; - a = T*(a+K*v); - lik(t) = v'*iF*v; - end - lik(t0:smpl) = lik(t0:smpl) + log(dF); - end - - lik = (lik + pp*log(2*pi))/2; - - LIK = sum(lik(start:end)); % Minus the log-likelihood. \ No newline at end of file +notsteady = 1; +reste = 0; + +while rank(Pinf,kalman_tol) && (t<smpl) + t = t+1; + v = Y(:,t)-Z*a; + Finf = Z*Pinf*Z' ; + if rcond(Finf) < kalman_tol + if ~all(abs(Finf(:)) < kalman_tol) + % The univariate diffuse kalman filter should be used. + return + else + Fstar = Z*Pstar*Z' + H; + if rcond(Fstar) < kalman_tol + if ~all(abs(Fstar(:))<kalman_tol) + % The univariate diffuse kalman filter should be used. + return + else + a = T*a; + Pstar = T*Pstar*transpose(T)+QQ; + Pinf = T*Pinf*transpose(T); + end + else + iFstar = inv(Fstar); + dFstar = det(Fstar); + Kstar = Pstar*Z'*iFstar; + lik(t) = log(dFstar) + v'*iFstar*v; + Pinf = T*Pinf*transpose(T); + Pstar = T*(Pstar-Pstar*Z'*Kstar')*T'+QQ; + a = T*(a+Kstar*v); + end + end + else + lik(t) = log(det(Finf)); + iFinf = inv(Finf); + Kinf = Pinf*Z'*iFinf; + Fstar = Z*Pstar*Z' + H; + Kstar = (Pstar*Z'-Kinf*Fstar)*iFinf; + Pstar = T*(Pstar-Pstar*Z'*Kinf'-Pinf*Z'*Kstar')*T'+QQ; + Pinf = T*(Pinf-Pinf*Z'*Kinf')*T'; + a = T*(a+Kinf*v); + end +end + +if t == smpl + error(['There isn''t enough information to estimate the initial conditions of the nonstationary variables']); +end + +F_singular = 1; +while notsteady && (t<smpl) + t = t+1; + v = Y(:,t)-Z*a; + F = Z*Pstar*Z' + H; + oldPstar = Pstar; + dF = det(F); + if rcond(F) < kalman_tol + if ~all(abs(F(:))<kalman_tol) + return + else + a = T*a; + Pstar = T*Pstar*T'+QQ; + end + else + F_singular = 0; + iF = inv(F); + lik(t) = log(dF)+v'*iF*v; + K = Pstar*Z'*iF; + a = T*(a+K*v); + Pstar = T*(Pstar-K*Z*Pstar)*T'+QQ; + end + notsteady = ~(max(max(abs(K-oldK)))<riccati_tol); + oldK = K; +end + +if F_singular == 1 + error(['The variance of the forecast error remains singular until the end of the sample']) +end + +if t < smpl + t0 = t; + while t<smpl + t = t+1; + v = Y(:,t)-Z*a; + a = T*(a+K*v); + lik(t) = v'*iF*v; + end + lik(t0:smpl) = lik(t0:smpl) + log(dF); +end + +lik = (lik + pp*log(2*pi))/2; + +LIK = sum(lik(start:end)); % Minus the log-likelihood. \ No newline at end of file diff --git a/matlab/kalman/likelihood/kalman_filter.m b/matlab/kalman/likelihood/kalman_filter.m index 98fe065eeb..cfdaeee915 100644 --- a/matlab/kalman/likelihood/kalman_filter.m +++ b/matlab/kalman/likelihood/kalman_filter.m @@ -42,59 +42,59 @@ function [LIK, lik] = kalman_filter(T,R,Q,H,P,Y,start,mf,kalman_tol,riccati_tol) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - smpl = size(Y,2); % Sample size. - mm = size(T,2); % Number of state variables. - pp = size(Y,1); % Maximum number of observed variables. - a = zeros(mm,1); % State vector. - dF = 1; % det(F). - QQ = R*Q*transpose(R); % Variance of R times the vector of structural innovations. - t = 0; % Initialization of the time index. - lik = zeros(smpl,1); % Initialization of the vector gathering the densities. - LIK = Inf; % Default value of the log likelihood. - oldK = 0; - notsteady = 1; % Steady state flag. - F_singular = 1; +smpl = size(Y,2); % Sample size. +mm = size(T,2); % Number of state variables. +pp = size(Y,1); % Maximum number of observed variables. +a = zeros(mm,1); % State vector. +dF = 1; % det(F). +QQ = R*Q*transpose(R); % Variance of R times the vector of structural innovations. +t = 0; % Initialization of the time index. +lik = zeros(smpl,1); % Initialization of the vector gathering the densities. +LIK = Inf; % Default value of the log likelihood. +oldK = 0; +notsteady = 1; % Steady state flag. +F_singular = 1; - while notsteady & t<smpl - t = t+1; - v = Y(:,t)-a(mf); - F = P(mf,mf) + H; - if rcond(F) < kalman_tol - if ~all(abs(F(:))<kalman_tol) - return - else - a = T*a; - P = T*P*transpose(T)+QQ; - end +while notsteady & t<smpl + t = t+1; + v = Y(:,t)-a(mf); + F = P(mf,mf) + H; + if rcond(F) < kalman_tol + if ~all(abs(F(:))<kalman_tol) + return else - F_singular = 0; - dF = det(F); - iF = inv(F); - lik(t) = log(dF)+transpose(v)*iF*v; - K = P(:,mf)*iF; - a = T*(a+K*v); - P = T*(P-K*P(mf,:))*transpose(T)+QQ; + a = T*a; + P = T*P*transpose(T)+QQ; end - notsteady = max(max(abs(K-oldK))) > riccati_tol; - oldK = K; + else + F_singular = 0; + dF = det(F); + iF = inv(F); + lik(t) = log(dF)+transpose(v)*iF*v; + K = P(:,mf)*iF; + a = T*(a+K*v); + P = T*(P-K*P(mf,:))*transpose(T)+QQ; end + notsteady = max(max(abs(K-oldK))) > riccati_tol; + oldK = K; +end - if F_singular - error('The variance of the forecast error remains singular until the end of the sample') +if F_singular + error('The variance of the forecast error remains singular until the end of the sample') +end + +if t < smpl + t0 = t+1; + while t < smpl + t = t+1; + v = Y(:,t)-a(mf); + a = T*(a+K*v); + lik(t) = transpose(v)*iF*v; end + lik(t0:smpl) = lik(t0:smpl) + log(dF); +end - if t < smpl - t0 = t+1; - while t < smpl - t = t+1; - v = Y(:,t)-a(mf); - a = T*(a+K*v); - lik(t) = transpose(v)*iF*v; - end - lik(t0:smpl) = lik(t0:smpl) + log(dF); - end - - % adding log-likelihhod constants - lik = (lik + pp*log(2*pi))/2; +% adding log-likelihhod constants +lik = (lik + pp*log(2*pi))/2; - LIK = sum(lik(start:end)); % Minus the log-likelihood. \ No newline at end of file +LIK = sum(lik(start:end)); % Minus the log-likelihood. \ No newline at end of file diff --git a/matlab/kalman/likelihood/missing_observations_diffuse_kalman_filter.m b/matlab/kalman/likelihood/missing_observations_diffuse_kalman_filter.m index bc13e8e53b..18c70dd569 100644 --- a/matlab/kalman/likelihood/missing_observations_diffuse_kalman_filter.m +++ b/matlab/kalman/likelihood/missing_observations_diffuse_kalman_filter.m @@ -1,5 +1,5 @@ function [LIK, lik] = missing_observations_diffuse_kalman_filter(T,R,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol,... - data_index,number_of_observations,no_more_missing_observations) + data_index,number_of_observations,no_more_missing_observations) % Computes the diffuse likelihood of a state space model. % % INPUTS @@ -44,131 +44,131 @@ function [LIK, lik] = missing_observations_diffuse_kalman_filter(T,R,Q,H,Pinf,Ps % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - [pp,smpl] = size(Y); - mm = size(T,2); - a = zeros(mm,1); - dF = 1; - QQ = R*Q*transpose(R); - t = 0; - oldK = 0; - lik = zeros(smpl,1); - LIK = Inf; - notsteady = 1; - - while rank(Pinf,kalman_tol) && (t<smpl) - t = t+1; - d_index = data_index{t}; - if isempty(d_index) - a = T*a; - Pstar = T*Pstar*transpose(T)+QQ; - Pinf = T*Pinf*transpose(T); - else - ZZ = Z(d_index,:); - v = Y(d_index,t)-ZZ*a; - Finf = ZZ*Pinf*ZZ'; - if rcond(Finf) < kalman_tol - if ~all(abs(Finf(:)) < kalman_tol) - % The univariate diffuse kalman filter shoudl be used. - return - else - if ~isscalar(H) % => Errors in the measurement equation. - Fstar = ZZ*Pstar*ZZ' + H(d_index,d_index); - else% => - % case 1. No errors in the measurement (H=0) and more than one variable is observed in this state space model. - % case 2. Errors in the measurement equation, but only one variable is observed in this state-space model. - Fstar = ZZ*Pstar*ZZ' + H; - end - if rcond(Fstar) < kalman_tol - if ~all(abs(Fstar(:))<kalman_tol) - % The univariate diffuse kalman filter should be used. - return - else - a = T*a; - Pstar = T*Pstar*transpose(T)+QQ; - Pinf = T*Pinf*transpose(T); - end - else - iFstar = inv(Fstar); - dFstar = det(Fstar); - Kstar = Pstar*ZZ'*iFstar; - lik(t) = log(dFstar) + v'*iFstar*v + length(d_index)*log(2*pi); - Pinf = T*Pinf*transpose(T); - Pstar = T*(Pstar-Pstar*ZZ'*Kstar')*T'+QQ; - a = T*(a+Kstar*v); - end - end - else - lik(t) = log(det(Finf)); - iFinf = inv(Finf); - Kinf = Pinf*ZZ'*iFinf; - Fstar = ZZ*Pstar*ZZ' + H; - Kstar = (Pstar*ZZ'-Kinf*Fstar)*iFinf; - Pstar = T*(Pstar-Pstar*ZZ'*Kinf'-Pinf*ZZ'*Kstar')*T'+QQ; - Pinf = T*(Pinf-Pinf*ZZ'*Kinf')*T'; - a = T*(a+Kinf*v); - end - end - end - - if t == smpl - error(['There isn''t enough information to estimate the initial conditions of the nonstationary variables']); - end - - F_singular = 1; - while notsteady && (t<smpl) - t = t+1; - d_index = data_index{t}; - if isempty(d_index) - a = T*a; - Pstar = T*Pstar*transpose(T)+QQ; - else - ZZ = Z(d_index,:); - v = Y(d_index,t)-ZZ*a; - if ~isscalar(H) % => Errors in the measurement equation. - F = ZZ*Pstar*ZZ' + H(d_index,d_index); - else% => - % case 1. No errors in the measurement (H=0) and more than one variable is observed in this state space model. - % case 2. Errors in the measurement equation, but only one variable is observed in this state-space model. - F = ZZ*Pstar*ZZ' + H; - end - dF = det(F); - if rcond(F) < kalman_tol - if ~all(abs(F(:))<kalman_tol) - return - else - a = T*a; - Pstar = T*Pstar*T'+QQ; - end - else - F_singular = 0; - iF = inv(F); - lik(t) = log(dF) + v'*iF*v + length(d_index)*log(2*pi); - K = Pstar*ZZ'*iF; - a = T*(a+K*v); - Pstar = T*(Pstar-K*ZZ*Pstar)*T'+QQ; - end - if t>no_more_missing_observations - notsteady = max(max(abs(K-oldK)))>riccati_tol; - oldK = K; - end - end - end - - if F_singular == 1 - error(['The variance of the forecast error remains singular until the end of the sample']) - end - - if t < smpl - t0 = t; - while t<smpl - t = t+1; - v = Y(:,t)-Z*a; - a = T*(a+K*v); - lik(t) = v'*iF*v; - end - lik(t0:smpl) = lik(t0:smpl) + log(dF) + pp*log(2*pi); - end - - lik = lik/2; - - LIK = sum(lik(start:end));% Minus the log-likelihood. \ No newline at end of file +[pp,smpl] = size(Y); +mm = size(T,2); +a = zeros(mm,1); +dF = 1; +QQ = R*Q*transpose(R); +t = 0; +oldK = 0; +lik = zeros(smpl,1); +LIK = Inf; +notsteady = 1; + +while rank(Pinf,kalman_tol) && (t<smpl) + t = t+1; + d_index = data_index{t}; + if isempty(d_index) + a = T*a; + Pstar = T*Pstar*transpose(T)+QQ; + Pinf = T*Pinf*transpose(T); + else + ZZ = Z(d_index,:); + v = Y(d_index,t)-ZZ*a; + Finf = ZZ*Pinf*ZZ'; + if rcond(Finf) < kalman_tol + if ~all(abs(Finf(:)) < kalman_tol) + % The univariate diffuse kalman filter shoudl be used. + return + else + if ~isscalar(H) % => Errors in the measurement equation. + Fstar = ZZ*Pstar*ZZ' + H(d_index,d_index); + else% => + % case 1. No errors in the measurement (H=0) and more than one variable is observed in this state space model. + % case 2. Errors in the measurement equation, but only one variable is observed in this state-space model. + Fstar = ZZ*Pstar*ZZ' + H; + end + if rcond(Fstar) < kalman_tol + if ~all(abs(Fstar(:))<kalman_tol) + % The univariate diffuse kalman filter should be used. + return + else + a = T*a; + Pstar = T*Pstar*transpose(T)+QQ; + Pinf = T*Pinf*transpose(T); + end + else + iFstar = inv(Fstar); + dFstar = det(Fstar); + Kstar = Pstar*ZZ'*iFstar; + lik(t) = log(dFstar) + v'*iFstar*v + length(d_index)*log(2*pi); + Pinf = T*Pinf*transpose(T); + Pstar = T*(Pstar-Pstar*ZZ'*Kstar')*T'+QQ; + a = T*(a+Kstar*v); + end + end + else + lik(t) = log(det(Finf)); + iFinf = inv(Finf); + Kinf = Pinf*ZZ'*iFinf; + Fstar = ZZ*Pstar*ZZ' + H; + Kstar = (Pstar*ZZ'-Kinf*Fstar)*iFinf; + Pstar = T*(Pstar-Pstar*ZZ'*Kinf'-Pinf*ZZ'*Kstar')*T'+QQ; + Pinf = T*(Pinf-Pinf*ZZ'*Kinf')*T'; + a = T*(a+Kinf*v); + end + end +end + +if t == smpl + error(['There isn''t enough information to estimate the initial conditions of the nonstationary variables']); +end + +F_singular = 1; +while notsteady && (t<smpl) + t = t+1; + d_index = data_index{t}; + if isempty(d_index) + a = T*a; + Pstar = T*Pstar*transpose(T)+QQ; + else + ZZ = Z(d_index,:); + v = Y(d_index,t)-ZZ*a; + if ~isscalar(H) % => Errors in the measurement equation. + F = ZZ*Pstar*ZZ' + H(d_index,d_index); + else% => + % case 1. No errors in the measurement (H=0) and more than one variable is observed in this state space model. + % case 2. Errors in the measurement equation, but only one variable is observed in this state-space model. + F = ZZ*Pstar*ZZ' + H; + end + dF = det(F); + if rcond(F) < kalman_tol + if ~all(abs(F(:))<kalman_tol) + return + else + a = T*a; + Pstar = T*Pstar*T'+QQ; + end + else + F_singular = 0; + iF = inv(F); + lik(t) = log(dF) + v'*iF*v + length(d_index)*log(2*pi); + K = Pstar*ZZ'*iF; + a = T*(a+K*v); + Pstar = T*(Pstar-K*ZZ*Pstar)*T'+QQ; + end + if t>no_more_missing_observations + notsteady = max(max(abs(K-oldK)))>riccati_tol; + oldK = K; + end + end +end + +if F_singular == 1 + error(['The variance of the forecast error remains singular until the end of the sample']) +end + +if t < smpl + t0 = t; + while t<smpl + t = t+1; + v = Y(:,t)-Z*a; + a = T*(a+K*v); + lik(t) = v'*iF*v; + end + lik(t0:smpl) = lik(t0:smpl) + log(dF) + pp*log(2*pi); +end + +lik = lik/2; + +LIK = sum(lik(start:end));% Minus the log-likelihood. \ No newline at end of file diff --git a/matlab/kalman/likelihood/missing_observations_kalman_filter.m b/matlab/kalman/likelihood/missing_observations_kalman_filter.m index 11dcfa832e..97a22839fa 100644 --- a/matlab/kalman/likelihood/missing_observations_kalman_filter.m +++ b/matlab/kalman/likelihood/missing_observations_kalman_filter.m @@ -28,7 +28,7 @@ function [LIK, lik] = missing_observations_kalman_filter(T,R,Q,H,P,Y,start,mf,k % % NOTES % The vector "lik" is used to evaluate the jacobian of the likelihood. - + % Copyright (C) 2004-2008 Dynare Team % % This file is part of Dynare. @@ -45,74 +45,74 @@ function [LIK, lik] = missing_observations_kalman_filter(T,R,Q,H,P,Y,start,mf,k % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - smpl = size(Y,2); % Sample size. - mm = size(T,2); % Number of state variables. - pp = size(Y,1); % Maximum number of observed variables. - a = zeros(mm,1); % State vector. - dF = 1; % det(F). - QQ = R*Q*transpose(R); % Variance of R times the vector of structural innovations. - t = 0; % Initialization of the time index. - lik = zeros(smpl,1); % Initialization of the vector gathering the densities. - LIK = Inf; % Default value of the log likelihood. - oldK = 0; - notsteady = 1; % Steady state flag. - F_singular = 1; - - while notsteady & t<smpl - t = t+1; - d_index = data_index{t}; - if isempty(d_index) - a = T*a; - P = T*P*transpose(T)+QQ; - else - MF = mf(d_index); % Set the selection for observed variables. - v = Y(d_index,t)-a(MF); - if ~isscalar(H) % => Errors in the measurement equation. - F = P(MF,MF) + H(d_index,d_index); - else% => - % case 1. No errors in the measurement (H=0) and more than one variable is observed in this state space model. - % case 2. Errors in the measurement equation, but only one variable is observed in this state-space model. - F = P(MF,MF)+H; - end - if rcond(F) < kalman_tol - if ~all(abs(F(:))<kalman_tol) - return - else - a = T*a; - P = T*P*transpose(T)+QQ; - end + +smpl = size(Y,2); % Sample size. +mm = size(T,2); % Number of state variables. +pp = size(Y,1); % Maximum number of observed variables. +a = zeros(mm,1); % State vector. +dF = 1; % det(F). +QQ = R*Q*transpose(R); % Variance of R times the vector of structural innovations. +t = 0; % Initialization of the time index. +lik = zeros(smpl,1); % Initialization of the vector gathering the densities. +LIK = Inf; % Default value of the log likelihood. +oldK = 0; +notsteady = 1; % Steady state flag. +F_singular = 1; + +while notsteady & t<smpl + t = t+1; + d_index = data_index{t}; + if isempty(d_index) + a = T*a; + P = T*P*transpose(T)+QQ; + else + MF = mf(d_index); % Set the selection for observed variables. + v = Y(d_index,t)-a(MF); + if ~isscalar(H) % => Errors in the measurement equation. + F = P(MF,MF) + H(d_index,d_index); + else% => + % case 1. No errors in the measurement (H=0) and more than one variable is observed in this state space model. + % case 2. Errors in the measurement equation, but only one variable is observed in this state-space model. + F = P(MF,MF)+H; + end + if rcond(F) < kalman_tol + if ~all(abs(F(:))<kalman_tol) + return else - F_singular = 0; - dF = det(F); - iF = inv(F); - lik(t) = log(dF) + transpose(v)*iF*v + length(d_index)*log(2*pi); - K = P(:,MF)*iF; - a = T*(a+K*v); - P = T*(P-K*P(MF,:))*transpose(T)+QQ; - end - if t>no_more_missing_observations - notsteady = max(max(abs(K-oldK)))>riccati_tol; - oldK = K; + a = T*a; + P = T*P*transpose(T)+QQ; end + else + F_singular = 0; + dF = det(F); + iF = inv(F); + lik(t) = log(dF) + transpose(v)*iF*v + length(d_index)*log(2*pi); + K = P(:,MF)*iF; + a = T*(a+K*v); + P = T*(P-K*P(MF,:))*transpose(T)+QQ; end - end - - if F_singular - error('The variance of the forecast error remains singular until the end of the sample') - end - - if t < smpl - t0 = t; - while t < smpl - t = t+1; - v = Y(:,t)-a(mf); - a = T*(a+K*v); - lik(t) = v'*iF*v; + if t>no_more_missing_observations + notsteady = max(max(abs(K-oldK)))>riccati_tol; + oldK = K; end - lik(t0:smpl) = lik(t0:smpl) + log(dF) + pp*log(2*pi); end - - lik = lik/2; +end + +if F_singular + error('The variance of the forecast error remains singular until the end of the sample') +end + +if t < smpl + t0 = t; + while t < smpl + t = t+1; + v = Y(:,t)-a(mf); + a = T*(a+K*v); + lik(t) = v'*iF*v; + end + lik(t0:smpl) = lik(t0:smpl) + log(dF) + pp*log(2*pi); +end + +lik = lik/2; - LIK = sum(lik(start:end)); \ No newline at end of file +LIK = sum(lik(start:end)); \ No newline at end of file diff --git a/matlab/kalman/likelihood/univariate_diffuse_kalman_filter.m b/matlab/kalman/likelihood/univariate_diffuse_kalman_filter.m index 48082fb8d8..360c98c954 100644 --- a/matlab/kalman/likelihood/univariate_diffuse_kalman_filter.m +++ b/matlab/kalman/likelihood/univariate_diffuse_kalman_filter.m @@ -99,7 +99,7 @@ while newRank && (t<smpl) end if (t==smpl) - error(['univariate_diffuse_kalman_filter:: There isn''t enough information to estimate the initial conditions of the nonstationary variables']); + error(['univariate_diffuse_kalman_filter:: There isn''t enough information to estimate the initial conditions of the nonstationary variables']); end while notsteady && (t<smpl) @@ -137,7 +137,7 @@ while t < smpl a = a + Ki*prediction_error/Fi; Pstar = Pstar - Ki*Ki'/Fi; lik(t) = lik(t) + log(Fi) + prediction_error*prediction_error/Fi ... - + l2pi; + + l2pi; end end a = T*a; diff --git a/matlab/kalman/likelihood/univariate_diffuse_kalman_filter_corr.m b/matlab/kalman/likelihood/univariate_diffuse_kalman_filter_corr.m index 7d4b954217..8edcef8548 100644 --- a/matlab/kalman/likelihood/univariate_diffuse_kalman_filter_corr.m +++ b/matlab/kalman/likelihood/univariate_diffuse_kalman_filter_corr.m @@ -148,7 +148,7 @@ while newRank && (t<smpl) end if (t==smpl) - error(['univariate_diffuse_kalman_filter:: There isn''t enough information to estimate the initial conditions of the nonstationary variables']); + error(['univariate_diffuse_kalman_filter:: There isn''t enough information to estimate the initial conditions of the nonstationary variables']); end while notsteady && (t<smpl) @@ -186,7 +186,7 @@ while t < smpl a = a + Ki*prediction_error/Fi; Pstar = Pstar - Ki*Ki'/Fi; lik(t) = lik(t) + log(Fi) + prediction_error*prediction_error/Fi ... - + l2pi; + + l2pi; end end a = T*a; diff --git a/matlab/kalman/likelihood/univariate_kalman_filter_corr.m b/matlab/kalman/likelihood/univariate_kalman_filter_corr.m index 86999fd634..4dacb7216b 100644 --- a/matlab/kalman/likelihood/univariate_kalman_filter_corr.m +++ b/matlab/kalman/likelihood/univariate_kalman_filter_corr.m @@ -1,124 +1,124 @@ -function [LIK, lik] = ... - univariate_kalman_filter_corr(T,R,Q,H,P,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations) -% Computes the likelihood of a stationnary state space model (univariate -% approach + correlated measurement errors). -% -% INPUTS -% T [double] mm*mm transition matrix of the state equation. -% R [double] mm*rr matrix, mapping structural innovations to state variables. -% Q [double] rr*rr covariance matrix of the structural innovations. -% H [double] pp*pp covariance matrix of the measurement error. -% P [double] mm*mm variance-covariance matrix with stationary variables -% Y [double] pp*smpl matrix of (detrended) data, where pp is the maximum number of observed variables. -% start [integer] scalar, likelihood evaluation starts at 'start'. -% Z [integer] pp*mm selection matrix. -% kalman_tol [double] scalar, tolerance parameter (rcond). -% riccati_tol [double] scalar, tolerance parameter (riccati iteration). -% data_index [cell] 1*smpl cell of column vectors of indices. -% number_of_observations [integer] scalar. -% no_more_missing_observations [integer] scalar. -% -% OUTPUTS -% LIK [double] scalar, likelihood -% lik [double] vector, density of observations in each period. -% -% REFERENCES -% See "Filtering and Smoothing of State Vector for Diffuse State Space -% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series -% Analysis, vol. 24(1), pp. 85-98). -% -% NOTES -% The vector "lik" is used to evaluate the jacobian of the likelihood. - -% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. - -pp = size(Y,1); % Number of observed variables -mm = size(T,1); % Number of variables in the state vector. -rr = size(R,2); % Number of structural innovations. -smpl = size(Y,2); % Number of periods in the dataset. -a = zeros(mm+pp,1); % Initial condition of the state vector. -t = 0; -lik = zeros(smpl,1); -notsteady = 1; - -TT = zeros(mm+pp); -TT(1:mm,1:mm) = T; -QQ = zeros(rr+pp); -QQ(1:rr,1:rr) = Q; -QQ(rr+1:end,rr+1:end) = H; -RR = zeros(mm+pp,rr+pp); -RR(1:mm,1:rr) = R; -RR(mm+1:end,rr+1:end) = eye(pp); -PP = zeros(mm+pp); -PP(1:mm,1:mm) = P; -PP(mm+1:end,mm+1:end) = H; -QQQQ = zeros(mm+pp); -RQR = R*Q*R'; -QQQQ(1:mm,1:mm) = RQR; -QQQQ(mm+1:end,mm+1:end) = H; -l2pi = log(2*pi); - -while notsteady && t<smpl - t = t+1; - d_index = data_index{t}; - MF = mf(d_index); - oldPP = PP; - for i=1:length(MF) - prediction_error = Y(d_index(i),t) - a(MF(i)) - a( mm+i ); - Fi = PP(MF(i),MF(i)) + PP(mm+i,mm+i); - if Fi > kalman_tol - lik(t) = lik(t) + log(Fi) + prediction_error*prediction_error/Fi ... - + l2pi; - Ki = sum(PP(:,[MF(i) mm+i]),2)/Fi; - a = a + Ki*prediction_error; - PP = PP - (Ki*Fi)*transpose(Ki); - end - end - a(1:mm) = T*a(1:mm); - a(mm+1:end) = zeros(pp,1); - PP(1:mm,1:mm) = T*PP(1:mm,1:mm)*transpose(T) + RQR; - PP(mm+1:end,1:mm) = zeros(pp,mm); - PP(1:mm,mm+1:end) = zeros(mm,pp); - PP(mm+1:end,mm+1:end) = H; - if t>no_more_missing_observations - notsteady = max(max(abs(PP-oldPP)))>riccati_tol; - end -end - -% Steady state kalman filter. -while t < smpl - PPPP = PP; - t = t+1; - for i=1:pp - prediction_error = Y(i,t) - a(mf(i)) - a(mm+i); - Fi = PPPP(mf(i),mf(i)) + PPPP(mm+i,mm+i); - if Fi > kalman_tol - Ki = ( PPPP(:,mf(i)) + PPPP(:,mm+i) )/Fi; - a = a + Ki*prediction_error; - PPPP = PPPP - (Fi*Ki)*transpose(Ki); - lik(t) = lik(t) + log(Fi) + prediction_error*prediction_error/Fi ... - + l2pi; - end - end - a(1:mm) = T*a(1:mm); - a(mm+1:end) = zeros(pp,1); -end - -lik = lik/2; - +function [LIK, lik] = ... + univariate_kalman_filter_corr(T,R,Q,H,P,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations) +% Computes the likelihood of a stationnary state space model (univariate +% approach + correlated measurement errors). +% +% INPUTS +% T [double] mm*mm transition matrix of the state equation. +% R [double] mm*rr matrix, mapping structural innovations to state variables. +% Q [double] rr*rr covariance matrix of the structural innovations. +% H [double] pp*pp covariance matrix of the measurement error. +% P [double] mm*mm variance-covariance matrix with stationary variables +% Y [double] pp*smpl matrix of (detrended) data, where pp is the maximum number of observed variables. +% start [integer] scalar, likelihood evaluation starts at 'start'. +% Z [integer] pp*mm selection matrix. +% kalman_tol [double] scalar, tolerance parameter (rcond). +% riccati_tol [double] scalar, tolerance parameter (riccati iteration). +% data_index [cell] 1*smpl cell of column vectors of indices. +% number_of_observations [integer] scalar. +% no_more_missing_observations [integer] scalar. +% +% OUTPUTS +% LIK [double] scalar, likelihood +% lik [double] vector, density of observations in each period. +% +% REFERENCES +% See "Filtering and Smoothing of State Vector for Diffuse State Space +% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series +% Analysis, vol. 24(1), pp. 85-98). +% +% NOTES +% The vector "lik" is used to evaluate the jacobian of the likelihood. + +% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. + +pp = size(Y,1); % Number of observed variables +mm = size(T,1); % Number of variables in the state vector. +rr = size(R,2); % Number of structural innovations. +smpl = size(Y,2); % Number of periods in the dataset. +a = zeros(mm+pp,1); % Initial condition of the state vector. +t = 0; +lik = zeros(smpl,1); +notsteady = 1; + +TT = zeros(mm+pp); +TT(1:mm,1:mm) = T; +QQ = zeros(rr+pp); +QQ(1:rr,1:rr) = Q; +QQ(rr+1:end,rr+1:end) = H; +RR = zeros(mm+pp,rr+pp); +RR(1:mm,1:rr) = R; +RR(mm+1:end,rr+1:end) = eye(pp); +PP = zeros(mm+pp); +PP(1:mm,1:mm) = P; +PP(mm+1:end,mm+1:end) = H; +QQQQ = zeros(mm+pp); +RQR = R*Q*R'; +QQQQ(1:mm,1:mm) = RQR; +QQQQ(mm+1:end,mm+1:end) = H; +l2pi = log(2*pi); + +while notsteady && t<smpl + t = t+1; + d_index = data_index{t}; + MF = mf(d_index); + oldPP = PP; + for i=1:length(MF) + prediction_error = Y(d_index(i),t) - a(MF(i)) - a( mm+i ); + Fi = PP(MF(i),MF(i)) + PP(mm+i,mm+i); + if Fi > kalman_tol + lik(t) = lik(t) + log(Fi) + prediction_error*prediction_error/Fi ... + + l2pi; + Ki = sum(PP(:,[MF(i) mm+i]),2)/Fi; + a = a + Ki*prediction_error; + PP = PP - (Ki*Fi)*transpose(Ki); + end + end + a(1:mm) = T*a(1:mm); + a(mm+1:end) = zeros(pp,1); + PP(1:mm,1:mm) = T*PP(1:mm,1:mm)*transpose(T) + RQR; + PP(mm+1:end,1:mm) = zeros(pp,mm); + PP(1:mm,mm+1:end) = zeros(mm,pp); + PP(mm+1:end,mm+1:end) = H; + if t>no_more_missing_observations + notsteady = max(max(abs(PP-oldPP)))>riccati_tol; + end +end + +% Steady state kalman filter. +while t < smpl + PPPP = PP; + t = t+1; + for i=1:pp + prediction_error = Y(i,t) - a(mf(i)) - a(mm+i); + Fi = PPPP(mf(i),mf(i)) + PPPP(mm+i,mm+i); + if Fi > kalman_tol + Ki = ( PPPP(:,mf(i)) + PPPP(:,mm+i) )/Fi; + a = a + Ki*prediction_error; + PPPP = PPPP - (Fi*Ki)*transpose(Ki); + lik(t) = lik(t) + log(Fi) + prediction_error*prediction_error/Fi ... + + l2pi; + end + end + a(1:mm) = T*a(1:mm); + a(mm+1:end) = zeros(pp,1); +end + +lik = lik/2; + LIK = sum(lik(start:end)); \ No newline at end of file diff --git a/matlab/kalman/steady_state_kalman_gain.m b/matlab/kalman/steady_state_kalman_gain.m index 2bede6e0c0..c79ee8e774 100644 --- a/matlab/kalman/steady_state_kalman_gain.m +++ b/matlab/kalman/steady_state_kalman_gain.m @@ -33,7 +33,7 @@ function [K,iF,P] = steady_state_kalman_gain(T,R,Q,H,mf) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - + m = length(T); p = length(mf); Z = build_selection_matrix(mf,m,p); diff --git a/matlab/kalman_transition_matrix.m b/matlab/kalman_transition_matrix.m index f6a306c725..b0152cf181 100644 --- a/matlab/kalman_transition_matrix.m +++ b/matlab/kalman_transition_matrix.m @@ -31,23 +31,23 @@ function [A,B] = kalman_transition_matrix(dr,iv,ic,aux,exo_nbr) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - n_iv = length(iv); - n_ir1 = size(aux,1); - nr = n_iv + n_ir1; - - A = zeros(nr,nr); - i_n_iv = 1:n_iv; - A(i_n_iv,ic) = dr.ghx(iv,:); - if n_ir1 > 0 +n_iv = length(iv); +n_ir1 = size(aux,1); +nr = n_iv + n_ir1; + +A = zeros(nr,nr); + +i_n_iv = 1:n_iv; +A(i_n_iv,ic) = dr.ghx(iv,:); +if n_ir1 > 0 A(n_iv+1:end,:) = sparse(aux(:,1),aux(:,2),ones(n_ir1,1),n_ir1,nr); - end +end - if nargout>1 - B = zeros(nr,exo_nbr); - B(i_n_iv,:) = dr.ghu(iv,:); - end +if nargout>1 + B = zeros(nr,exo_nbr); + B(i_n_iv,:) = dr.ghu(iv,:); +end % $$$ function [A,B] = kalman_transition_matrix(dr) % $$$ global M_ diff --git a/matlab/kronecker/A_times_B_kronecker_C.m b/matlab/kronecker/A_times_B_kronecker_C.m index a0a863937d..3d9b99f639 100644 --- a/matlab/kronecker/A_times_B_kronecker_C.m +++ b/matlab/kronecker/A_times_B_kronecker_C.m @@ -32,7 +32,7 @@ function D = A_times_B_kronecker_C(A,B,C) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - + % Chek number of inputs and outputs. if nargin>3 | nargin<2 error('Two or Three input arguments required!') diff --git a/matlab/lnsrch1.m b/matlab/lnsrch1.m index 592da48deb..592d78c4e0 100644 --- a/matlab/lnsrch1.m +++ b/matlab/lnsrch1.m @@ -40,37 +40,37 @@ function [x,f,fvec,check]=lnsrch1(xold,fold,g,p,stpmax,func,j1,j2,varargin) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global options_ - - alf = 1e-4 ; - tolx = options_.solve_tolx; - alam = 1; - - x = xold; - nn = length(j2); - summ = sqrt(sum(p.*p)) ; - if ~isfinite(summ) +global options_ + +alf = 1e-4 ; +tolx = options_.solve_tolx; +alam = 1; + +x = xold; +nn = length(j2); +summ = sqrt(sum(p.*p)) ; +if ~isfinite(summ) error(['Some element of Newton direction isn''t finite. Jacobian maybe' ... ' singular or there is a problem with initial values']) - end - - if summ > stpmax +end + +if summ > stpmax p=p.*stpmax/summ ; - end +end - slope = g'*p ; - - test = max(abs(p)'./max([abs(xold(j2))';ones(1,nn)])) ; - alamin = tolx/test ; +slope = g'*p ; - if alamin > 0.1 +test = max(abs(p)'./max([abs(xold(j2))';ones(1,nn)])) ; +alamin = tolx/test ; + +if alamin > 0.1 alamin = 0.1; - end - - while 1 +end + +while 1 if alam < alamin - check = 1 ; - return + check = 1 ; + return end x(j2) = xold(j2) + (alam*p) ; @@ -79,49 +79,49 @@ function [x,f,fvec,check]=lnsrch1(xold,fold,g,p,stpmax,func,j1,j2,varargin) f = 0.5*fvec'*fvec ; if any(isnan(fvec)) - alam = alam/2 ; - alam2 = alam ; - f2 = f ; - fold2 = fold ; + alam = alam/2 ; + alam2 = alam ; + f2 = f ; + fold2 = fold ; else - if f <= fold+alf*alam*slope - check = 0; - break ; - else - if alam == 1 - tmplam = -slope/(2*(f-fold-slope)) ; - else - rhs1 = f-fold-alam*slope ; - rhs2 = f2-fold2-alam2*slope ; - a = (rhs1/(alam^2)-rhs2/(alam2^2))/(alam-alam2) ; - b = (-alam2*rhs1/(alam^2)+alam*rhs2/(alam2^2))/(alam-alam2) ; - if a == 0 - tmplam = -slope/(2*b) ; - else - disc = (b^2)-3*a*slope ; - - if disc < 0 - error ('Roundoff problem in nlsearch') ; - else - tmplam = (-b+sqrt(disc))/(3*a) ; - end - - end - - if tmplam > 0.5*alam - tmplam = 0.5*alam; - end - - end - - alam2 = alam ; - f2 = f ; - fold2 = fold ; - alam = max([tmplam;(0.1*alam)]) ; - end + if f <= fold+alf*alam*slope + check = 0; + break ; + else + if alam == 1 + tmplam = -slope/(2*(f-fold-slope)) ; + else + rhs1 = f-fold-alam*slope ; + rhs2 = f2-fold2-alam2*slope ; + a = (rhs1/(alam^2)-rhs2/(alam2^2))/(alam-alam2) ; + b = (-alam2*rhs1/(alam^2)+alam*rhs2/(alam2^2))/(alam-alam2) ; + if a == 0 + tmplam = -slope/(2*b) ; + else + disc = (b^2)-3*a*slope ; + + if disc < 0 + error ('Roundoff problem in nlsearch') ; + else + tmplam = (-b+sqrt(disc))/(3*a) ; + end + + end + + if tmplam > 0.5*alam + tmplam = 0.5*alam; + end + + end + + alam2 = alam ; + f2 = f ; + fold2 = fold ; + alam = max([tmplam;(0.1*alam)]) ; + end end - end +end % 01/14/01 MJ lnsearch is now a separate function % 01/12/03 MJ check for finite summ to avoid infinite loop when Jacobian diff --git a/matlab/lpdfgam.m b/matlab/lpdfgam.m index 7f7690b2a8..0a8505960f 100644 --- a/matlab/lpdfgam.m +++ b/matlab/lpdfgam.m @@ -30,11 +30,11 @@ function ldens = lpdfgam(x,a,b); % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - ldens = -Inf( size(x) ) ; - idx = find( x>0 ); - - if length(a)==1 - ldens(idx) = -gammaln(a) - a*log(b) + (a-1)*log(x(idx)) - x(idx)/b ; - else - ldens(idx) = -gammaln(a(idx)) - a(idx).*log(b(idx)) + (a(idx)-1).*log(x(idx)) - x(idx)./b(idx) ; - end \ No newline at end of file +ldens = -Inf( size(x) ) ; +idx = find( x>0 ); + +if length(a)==1 + ldens(idx) = -gammaln(a) - a*log(b) + (a-1)*log(x(idx)) - x(idx)/b ; +else + ldens(idx) = -gammaln(a(idx)) - a(idx).*log(b(idx)) + (a(idx)-1).*log(x(idx)) - x(idx)./b(idx) ; +end \ No newline at end of file diff --git a/matlab/lpdfgbeta.m b/matlab/lpdfgbeta.m index 75a5e8fecc..33ff3df48a 100644 --- a/matlab/lpdfgbeta.m +++ b/matlab/lpdfgbeta.m @@ -31,11 +31,11 @@ function ldens = lpdfgbeta(x,a,b,aa,bb); % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - ldens = -Inf( size(x) ) ; - idx = find( (x-aa)>0 & (x-bb)<0 ) ; - - if length(a)==1 - ldens(idx) = -betaln(a,b) + (a-1)*log(x(idx)-aa) + (b-1)*log(bb-x(idx)) - (a+b-1)*log(bb-aa) ; - else - ldens(idx) = -betaln(a(idx),b(idx)) + (a(idx)-1).*log(x(idx)-aa(idx)) + (b(idx)-1).*log(bb(idx)-x(idx)) - (a(idx)+b(idx)-1).*log(bb(idx)-aa(idx)); - end \ No newline at end of file +ldens = -Inf( size(x) ) ; +idx = find( (x-aa)>0 & (x-bb)<0 ) ; + +if length(a)==1 + ldens(idx) = -betaln(a,b) + (a-1)*log(x(idx)-aa) + (b-1)*log(bb-x(idx)) - (a+b-1)*log(bb-aa) ; +else + ldens(idx) = -betaln(a(idx),b(idx)) + (a(idx)-1).*log(x(idx)-aa(idx)) + (b(idx)-1).*log(bb(idx)-x(idx)) - (a(idx)+b(idx)-1).*log(bb(idx)-aa(idx)); +end \ No newline at end of file diff --git a/matlab/lpdfig1.m b/matlab/lpdfig1.m index 4b7b061a6c..9c17277a84 100644 --- a/matlab/lpdfig1.m +++ b/matlab/lpdfig1.m @@ -34,11 +34,11 @@ function ldens = lpdfig1(x,s,nu) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - ldens = -Inf( size(x) ) ; - idx = find( x>0 ) ; - - if length(s)==1 - ldens(idx) = log(2) - gammaln(.5*nu) - .5*nu*(log(2)-log(s)) - (nu+1)*log(x(idx)) - .5*s./(x(idx).*x(idx)) ; - else - ldens(idx) = log(2) - gammaln(.5*nu(idx)) - .5*nu(idx).*(log(2)-log(s(idx))) - (nu(idx)+1).*log(x(idx)) - .5*s(idx)./(x(idx).*x(idx)) ; - end \ No newline at end of file +ldens = -Inf( size(x) ) ; +idx = find( x>0 ) ; + +if length(s)==1 + ldens(idx) = log(2) - gammaln(.5*nu) - .5*nu*(log(2)-log(s)) - (nu+1)*log(x(idx)) - .5*s./(x(idx).*x(idx)) ; +else + ldens(idx) = log(2) - gammaln(.5*nu(idx)) - .5*nu(idx).*(log(2)-log(s(idx))) - (nu(idx)+1).*log(x(idx)) - .5*s(idx)./(x(idx).*x(idx)) ; +end \ No newline at end of file diff --git a/matlab/lpdfig2.m b/matlab/lpdfig2.m index 59c4d07c7c..7f95581811 100644 --- a/matlab/lpdfig2.m +++ b/matlab/lpdfig2.m @@ -34,11 +34,11 @@ function ldens = lpdfig2(x,s,nu) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - ldens = -Inf( size(x) ) ; - idx = find( x>0 ) ; - - if length(s)==1 - ldens(idx) = -gammaln(.5*nu) - (.5*nu)*(log(2)-log(s)) - .5*(nu+2)*log(x(idx)) -.5*s./x(idx); - else - ldens(idx) = -gammaln(.5*nu(idx)) - (.5*nu(idx)).*(log(2)-log(s(idx))) - .5*(nu(idx)+2).*log(x(idx)) -.5*s(idx)./x(idx); - end \ No newline at end of file +ldens = -Inf( size(x) ) ; +idx = find( x>0 ) ; + +if length(s)==1 + ldens(idx) = -gammaln(.5*nu) - (.5*nu)*(log(2)-log(s)) - .5*(nu+2)*log(x(idx)) -.5*s./x(idx); +else + ldens(idx) = -gammaln(.5*nu(idx)) - (.5*nu(idx)).*(log(2)-log(s(idx))) - .5*(nu(idx)+2).*log(x(idx)) -.5*s(idx)./x(idx); +end \ No newline at end of file diff --git a/matlab/lyapunov_symm.m b/matlab/lyapunov_symm.m index bb3108fd52..801df633f3 100644 --- a/matlab/lyapunov_symm.m +++ b/matlab/lyapunov_symm.m @@ -1,116 +1,116 @@ -function [x,u] = lyapunov_symm(a,b,qz_criterium,lyapunov_complex_threshold,method) -% Solves the Lyapunov equation x-a*x*a' = b, for b and x symmetric matrices. -% If a has some unit roots, the function computes only the solution of the stable subsystem. -% -% INPUTS: -% a [double] n*n matrix. -% b [double] n*n matrix. -% qz_criterium [double] scalar, unit root threshold for eigenvalues in a. -% lyapunov_complex_threshold [double] scalar, complex block threshold for the upper triangular matrix T. -% method [integer] Scalar, if method=0 [default] then U, T, n and k are not persistent. -% method=1 then U, T, n and k are declared as persistent -% variables and the schur decomposition is triggered. -% method=2 then U, T, n and k are declared as persistent -% variables and the schur decomposition is not performed. -% OUTPUTS -% x: [double] m*m solution matrix of the lyapunov equation, where m is the dimension of the stable subsystem. -% u: [double] Schur vectors associated with unit roots -% -% ALGORITHM -% Uses reordered Schur decomposition -% -% SPECIAL REQUIREMENTS -% None - -% Copyright (C) 2006-2009 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 <http://www.gnu.org/licenses/>. - - if nargin<5 - method = 0; - end - if method - persistent U T k n - else - if exist('U','var') - clear('U','T','k','n') - end - end - - u = []; - - if size(a,1) == 1 - x=b/(1-a*a); - return - end - - if method<2 - [U,T] = schur(a); - e1 = abs(ordeig(T)) > 2-qz_criterium; - k = sum(e1); % Number of unit roots. - n = length(e1)-k; % Number of stationary variables. - if k > 0 - % Selects stable roots - [U,T] = ordschur(U,T,e1); - T = T(k+1:end,k+1:end); - end - end - - B = U(:,k+1:end)'*b*U(:,k+1:end); - - x = zeros(n,n); - i = n; - - while i >= 2 - if abs(T(i,i-1))<lyapunov_complex_threshold - if i == n - c = zeros(n,1); - else - c = T(1:i,:)*(x(:,i+1:end)*T(i,i+1:end)') + ... - T(i,i)*T(1:i,i+1:end)*x(i+1:end,i); - end - q = eye(i)-T(1:i,1:i)*T(i,i); - x(1:i,i) = q\(B(1:i,i)+c); - x(i,1:i-1) = x(1:i-1,i)'; - i = i - 1; - else - if i == n - c = zeros(n,1); - c1 = zeros(n,1); - else - c = T(1:i,:)*(x(:,i+1:end)*T(i,i+1:end)') + ... - T(i,i)*T(1:i,i+1:end)*x(i+1:end,i) + ... - T(i,i-1)*T(1:i,i+1:end)*x(i+1:end,i-1); - c1 = T(1:i,:)*(x(:,i+1:end)*T(i-1,i+1:end)') + ... - T(i-1,i-1)*T(1:i,i+1:end)*x(i+1:end,i-1) + ... - T(i-1,i)*T(1:i,i+1:end)*x(i+1:end,i); - end - q = [ eye(i)-T(1:i,1:i)*T(i,i) , -T(1:i,1:i)*T(i,i-1) ; ... - -T(1:i,1:i)*T(i-1,i) , eye(i)-T(1:i,1:i)*T(i-1,i-1) ]; - z = q\[ B(1:i,i)+c ; B(1:i,i-1) + c1 ]; - x(1:i,i) = z(1:i); - x(1:i,i-1) = z(i+1:end); - x(i,1:i-1) = x(1:i-1,i)'; - x(i-1,1:i-2) = x(1:i-2,i-1)'; - i = i - 2; - end - end - if i == 1 - c = T(1,:)*(x(:,2:end)*T(1,2:end)') + T(1,1)*T(1,2:end)*x(2:end,1); - x(1,1) = (B(1,1)+c)/(1-T(1,1)*T(1,1)); - end - x = U(:,k+1:end)*x*U(:,k+1:end)'; - u = U(:,1:k); \ No newline at end of file +function [x,u] = lyapunov_symm(a,b,qz_criterium,lyapunov_complex_threshold,method) +% Solves the Lyapunov equation x-a*x*a' = b, for b and x symmetric matrices. +% If a has some unit roots, the function computes only the solution of the stable subsystem. +% +% INPUTS: +% a [double] n*n matrix. +% b [double] n*n matrix. +% qz_criterium [double] scalar, unit root threshold for eigenvalues in a. +% lyapunov_complex_threshold [double] scalar, complex block threshold for the upper triangular matrix T. +% method [integer] Scalar, if method=0 [default] then U, T, n and k are not persistent. +% method=1 then U, T, n and k are declared as persistent +% variables and the schur decomposition is triggered. +% method=2 then U, T, n and k are declared as persistent +% variables and the schur decomposition is not performed. +% OUTPUTS +% x: [double] m*m solution matrix of the lyapunov equation, where m is the dimension of the stable subsystem. +% u: [double] Schur vectors associated with unit roots +% +% ALGORITHM +% Uses reordered Schur decomposition +% +% SPECIAL REQUIREMENTS +% None + +% Copyright (C) 2006-2009 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 <http://www.gnu.org/licenses/>. + +if nargin<5 + method = 0; +end +if method + persistent U T k n +else + if exist('U','var') + clear('U','T','k','n') + end +end + +u = []; + +if size(a,1) == 1 + x=b/(1-a*a); + return +end + +if method<2 + [U,T] = schur(a); + e1 = abs(ordeig(T)) > 2-qz_criterium; + k = sum(e1); % Number of unit roots. + n = length(e1)-k; % Number of stationary variables. + if k > 0 + % Selects stable roots + [U,T] = ordschur(U,T,e1); + T = T(k+1:end,k+1:end); + end +end + +B = U(:,k+1:end)'*b*U(:,k+1:end); + +x = zeros(n,n); +i = n; + +while i >= 2 + if abs(T(i,i-1))<lyapunov_complex_threshold + if i == n + c = zeros(n,1); + else + c = T(1:i,:)*(x(:,i+1:end)*T(i,i+1:end)') + ... + T(i,i)*T(1:i,i+1:end)*x(i+1:end,i); + end + q = eye(i)-T(1:i,1:i)*T(i,i); + x(1:i,i) = q\(B(1:i,i)+c); + x(i,1:i-1) = x(1:i-1,i)'; + i = i - 1; + else + if i == n + c = zeros(n,1); + c1 = zeros(n,1); + else + c = T(1:i,:)*(x(:,i+1:end)*T(i,i+1:end)') + ... + T(i,i)*T(1:i,i+1:end)*x(i+1:end,i) + ... + T(i,i-1)*T(1:i,i+1:end)*x(i+1:end,i-1); + c1 = T(1:i,:)*(x(:,i+1:end)*T(i-1,i+1:end)') + ... + T(i-1,i-1)*T(1:i,i+1:end)*x(i+1:end,i-1) + ... + T(i-1,i)*T(1:i,i+1:end)*x(i+1:end,i); + end + q = [ eye(i)-T(1:i,1:i)*T(i,i) , -T(1:i,1:i)*T(i,i-1) ; ... + -T(1:i,1:i)*T(i-1,i) , eye(i)-T(1:i,1:i)*T(i-1,i-1) ]; + z = q\[ B(1:i,i)+c ; B(1:i,i-1) + c1 ]; + x(1:i,i) = z(1:i); + x(1:i,i-1) = z(i+1:end); + x(i,1:i-1) = x(1:i-1,i)'; + x(i-1,1:i-2) = x(1:i-2,i-1)'; + i = i - 2; + end +end +if i == 1 + c = T(1,:)*(x(:,2:end)*T(1,2:end)') + T(1,1)*T(1,2:end)*x(2:end,1); + x(1,1) = (B(1,1)+c)/(1-T(1,1)*T(1,1)); +end +x = U(:,k+1:end)*x*U(:,k+1:end)'; +u = U(:,1:k); \ No newline at end of file diff --git a/matlab/make_ex_.m b/matlab/make_ex_.m index a07dfbbb16..496c89a3a7 100644 --- a/matlab/make_ex_.m +++ b/matlab/make_ex_.m @@ -28,35 +28,35 @@ function make_ex_ % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - global M_ options_ oo_ ex0_ ex_det0_ - - options_ = set_default_option(options_,'periods',0); - - if isempty(oo_.exo_steady_state) + +global M_ options_ oo_ ex0_ ex_det0_ + +options_ = set_default_option(options_,'periods',0); + +if isempty(oo_.exo_steady_state) oo_.exo_steady_state = zeros(M_.exo_nbr,1); - end - if M_.exo_det_nbr > 1 & isempty(oo_.exo_det_steady_state) +end +if M_.exo_det_nbr > 1 & isempty(oo_.exo_det_steady_state) oo_.exo_det_steady_state = zeros(M_.exo_det_nbr,1); - end - if isempty(oo_.exo_simul) +end +if isempty(oo_.exo_simul) if isempty(ex0_) - oo_.exo_simul = repmat(oo_.exo_steady_state',M_.maximum_lag+options_.periods+M_.maximum_lead,1); + oo_.exo_simul = repmat(oo_.exo_steady_state',M_.maximum_lag+options_.periods+M_.maximum_lead,1); else - oo_.exo_simul = [ repmat(ex0_',M_.maximum_lag,1) ; repmat(oo_.exo_steady_state',options_.periods+M_.maximum_lead,1) ]; + oo_.exo_simul = [ repmat(ex0_',M_.maximum_lag,1) ; repmat(oo_.exo_steady_state',options_.periods+M_.maximum_lead,1) ]; end - elseif size(oo_.exo_simul,1) < M_.maximum_lag+M_.maximum_lead+options_.periods +elseif size(oo_.exo_simul,1) < M_.maximum_lag+M_.maximum_lead+options_.periods oo_.exo_simul = [ oo_.exo_simul ; repmat(oo_.exo_steady_state',M_.maximum_lag+options_.periods+M_.maximum_lead-size(oo_.exo_simul,1),1) ]; - end +end - if M_.exo_det_nbr > 0 +if M_.exo_det_nbr > 0 if isempty(oo_.exo_det_simul) - if isempty(ex_det0_) - oo_.exo_det_simul = [ones(M_.maximum_lag+options_.periods+M_.maximum_lead,1)*oo_.exo_det_steady_state']; - else - oo_.exo_det_simul = [ones(M_.maximum_lag,1)*ex_det0_';ones(options_.periods+M_.maximum_lead,1)*oo_.exo_det_steady_state']; - end + if isempty(ex_det0_) + oo_.exo_det_simul = [ones(M_.maximum_lag+options_.periods+M_.maximum_lead,1)*oo_.exo_det_steady_state']; + else + oo_.exo_det_simul = [ones(M_.maximum_lag,1)*ex_det0_';ones(options_.periods+M_.maximum_lead,1)*oo_.exo_det_steady_state']; + end elseif size(oo_.exo_det_simul,1) < M_.maximum_lag+M_.maximum_lead+options_.periods - oo_.exo_det_simul = [oo_.exo_det_simul; ones(M_.maximum_lag+options_.periods+M_.maximum_lead-size(oo_.exo_det_simul,1),1)*oo_.exo_det_steady_state']; + oo_.exo_det_simul = [oo_.exo_det_simul; ones(M_.maximum_lag+options_.periods+M_.maximum_lead-size(oo_.exo_det_simul,1),1)*oo_.exo_det_steady_state']; end - end \ No newline at end of file +end \ No newline at end of file diff --git a/matlab/make_y_.m b/matlab/make_y_.m index b0cba6eb11..1ce426e8ef 100644 --- a/matlab/make_y_.m +++ b/matlab/make_y_.m @@ -29,37 +29,37 @@ function make_y_ % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ options_ oo_ ys0_ - - options_ = set_default_option(options_,'periods',0); - - if isempty(oo_.steady_state) +global M_ options_ oo_ ys0_ + +options_ = set_default_option(options_,'periods',0); + +if isempty(oo_.steady_state) oo_.steady_state = zeros(M_.endo_nbr,1); - end - - if isempty(oo_.endo_simul) +end + +if isempty(oo_.endo_simul) if isempty(ys0_) - oo_.endo_simul = [oo_.steady_state*ones(1,M_.maximum_lag+options_.periods+M_.maximum_lead)]; + oo_.endo_simul = [oo_.steady_state*ones(1,M_.maximum_lag+options_.periods+M_.maximum_lead)]; else - oo_.endo_simul = [ys0_*ones(1,M_.maximum_lag) oo_.steady_state*ones(1,options_.periods+M_.maximum_lead)]; + oo_.endo_simul = [ys0_*ones(1,M_.maximum_lag) oo_.steady_state*ones(1,options_.periods+M_.maximum_lead)]; + end +elseif size(oo_.endo_simul,2) < M_.maximum_lag+M_.maximum_lead+options_.periods + switch options_.deterministic_simulation_initialization + case 0 + oo_.endo_simul = [oo_.endo_simul ... + oo_.steady_state*ones(1,M_.maximum_lag+options_.periods+M_.maximum_lead-size(oo_.endo_simul,2),1)]; + case 1% A linear approximation is used to initiate the solution. + oldopt = options_; + options_.order = 1; + dr = oo_.dr; + dr.ys = oo_.steady_state; + [dr,info,M_,options_,oo_]=dr1(dr,0,M_,options_,oo_); + exogenous_variables = zeros(M_.maximum_lag+options_.periods+M_.maximum_lead-size(oo_.endo_simul,2)+1,0); + y0 = oo_.endo_simul(:,1:M_.maximum_lag); + oo_.endo_simul=simult_(y0,dr,exogenous_variables,1); + options_ = oldopt; + case 2% Homotopic mod: Leave endo_simul as it is. + otherwise + error('Unknown method.') end - elseif size(oo_.endo_simul,2) < M_.maximum_lag+M_.maximum_lead+options_.periods - switch options_.deterministic_simulation_initialization - case 0 - oo_.endo_simul = [oo_.endo_simul ... - oo_.steady_state*ones(1,M_.maximum_lag+options_.periods+M_.maximum_lead-size(oo_.endo_simul,2),1)]; - case 1% A linear approximation is used to initiate the solution. - oldopt = options_; - options_.order = 1; - dr = oo_.dr; - dr.ys = oo_.steady_state; - [dr,info,M_,options_,oo_]=dr1(dr,0,M_,options_,oo_); - exogenous_variables = zeros(M_.maximum_lag+options_.periods+M_.maximum_lead-size(oo_.endo_simul,2)+1,0); - y0 = oo_.endo_simul(:,1:M_.maximum_lag); - oo_.endo_simul=simult_(y0,dr,exogenous_variables,1); - options_ = oldopt; - case 2% Homotopic mod: Leave endo_simul as it is. - otherwise - error('Unknown method.') - end - end \ No newline at end of file +end \ No newline at end of file diff --git a/matlab/marginal_density.m b/matlab/marginal_density.m index b57a08fdca..6e41b76093 100644 --- a/matlab/marginal_density.m +++ b/matlab/marginal_density.m @@ -70,55 +70,55 @@ linee = 0; check_coverage = 1; increase = 1; while check_coverage - for p = 0.1:0.1:0.9; - critval = chi2inv(p,npar); - ifil = FirstLine; - tmp = 0; - for n = FirstMhFile:TotalNumberOfMhFiles - for b=1:nblck - load([ MhDirectoryName '/' M_.fname '_mh' int2str(n) '_blck' int2str(b) '.mat'],'x2','logpo2'); - EndOfFile = size(x2,1); - for i = ifil:EndOfFile - deviation = (x2(i,:)-MU)*invSIGMA*(x2(i,:)-MU)'; - if deviation <= critval - lftheta = -log(p)-(npar*log(2*pi)+log(detSIGMA)+deviation)/2; - tmp = tmp + exp(lftheta - logpo2(i) + lpost_mode); - end - end - end - ifil = 1; + for p = 0.1:0.1:0.9; + critval = chi2inv(p,npar); + ifil = FirstLine; + tmp = 0; + for n = FirstMhFile:TotalNumberOfMhFiles + for b=1:nblck + load([ MhDirectoryName '/' M_.fname '_mh' int2str(n) '_blck' int2str(b) '.mat'],'x2','logpo2'); + EndOfFile = size(x2,1); + for i = ifil:EndOfFile + deviation = (x2(i,:)-MU)*invSIGMA*(x2(i,:)-MU)'; + if deviation <= critval + lftheta = -log(p)-(npar*log(2*pi)+log(detSIGMA)+deviation)/2; + tmp = tmp + exp(lftheta - logpo2(i) + lpost_mode); + end + end + end + ifil = 1; + end + linee = linee + 1; + warning_old_state = warning; + warning off; + marginal(linee,:) = [p, lpost_mode-log(tmp/((TotalNumberOfMhDraws-TODROP)*nblck))]; + warning(warning_old_state); end - linee = linee + 1; - warning_old_state = warning; - warning off; - marginal(linee,:) = [p, lpost_mode-log(tmp/((TotalNumberOfMhDraws-TODROP)*nblck))]; - warning(warning_old_state); - end - if abs((marginal(9,2)-marginal(1,2))/marginal(9,2)) > 0.01 | isinf(marginal(1,2)) - if increase == 1 - disp('MH: The support of the weighting density function is not large enough...') - disp('MH: I increase the variance of this distribution.') - increase = 1.2*increase; - invSIGMA = inv(SIGMA*increase); - detSIGMA = det(SIGMA*increase); - linee = 0; + if abs((marginal(9,2)-marginal(1,2))/marginal(9,2)) > 0.01 | isinf(marginal(1,2)) + if increase == 1 + disp('MH: The support of the weighting density function is not large enough...') + disp('MH: I increase the variance of this distribution.') + increase = 1.2*increase; + invSIGMA = inv(SIGMA*increase); + detSIGMA = det(SIGMA*increase); + linee = 0; + else + disp('MH: Let me try again.') + increase = 1.2*increase; + invSIGMA = inv(SIGMA*increase); + detSIGMA = det(SIGMA*increase); + linee = 0; + if increase > 20 + check_coverage = 0; + clear invSIGMA detSIGMA increase; + disp('MH: There''s probably a problem with the modified harmonic mean estimator.') + end + end else - disp('MH: Let me try again.') - increase = 1.2*increase; - invSIGMA = inv(SIGMA*increase); - detSIGMA = det(SIGMA*increase); - linee = 0; - if increase > 20 - check_coverage = 0; - clear invSIGMA detSIGMA increase; - disp('MH: There''s probably a problem with the modified harmonic mean estimator.') - end - end - else - check_coverage = 0; - clear invSIGMA detSIGMA increase; - disp('MH: Modified harmonic mean estimator, done!') - end + check_coverage = 0; + clear invSIGMA detSIGMA increase; + disp('MH: Modified harmonic mean estimator, done!') + end end oo_.MarginalDensity.ModifiedHarmonicMean = mean(marginal(:,2)); \ No newline at end of file diff --git a/matlab/masterParallel.m b/matlab/masterParallel.m index 471e7dd283..8510c52762 100644 --- a/matlab/masterParallel.m +++ b/matlab/masterParallel.m @@ -1,289 +1,289 @@ -function [fOutVar,nBlockPerCPU, totCPU] = masterParallel(Parallel,fBlock,nBlock,NamFileInput,fname,fInputVar,fGlobalVar) -% Top-level function called on the master computer when parallelizing a task. -% -% The number of parallelized threads will be equal to (nBlock-fBlock+1). -% -% INPUTS -% Parallel [struct vector] copy of options_.parallel -% fBlock [int] index number of the first thread -% (between 1 and nBlock) -% nBlock [int] index number of the last thread -% NamFileInput [cell array] containins the list of input files to be -% copied in the working directory of remote slaves -% 2 columns, as many lines as there are files -% - first column contains directory paths -% - second column contains filenames -% fname [string] name of the function to be parallelized, and -% which will be run on the slaves -% fInputVar [struct] structure containing local variables to be used -% by fName on the slaves -% fGlobalVar [struct] structure containing global variables to be used -% by fName on the slaves -% -% OUTPUT -% fOutVar [struct vector] result of the parallel computation, one -% struct per thread -% nBlockPerCPU [int vector] for each CPU used, indicates the number of -% threads run on that CPU -% totCPU [int] total number of CPU used (can be lower than -% the number of CPU declared in "Parallel", if -% the number of required threads is lower) - -% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. - -totCPU=0; - -% Determine my hostname and my working directory -DyMo=pwd; -fInputVar.DyMo=DyMo; -if isunix, - [tempo, MasterName]=system(['ifconfig | grep ''inet addr:''| grep -v ''127.0.0.1'' | cut -d: -f2 | awk ''{ print $1}''']); -else - [tempo, MasterName]=system('hostname'); -end -MasterName=deblank(MasterName); -fInputVar.MasterName = MasterName; - -% Save input data for use by the slaves -if exist('fGlobalVar'), -save([fname,'_input.mat'],'fInputVar','fGlobalVar') -else -save([fname,'_input.mat'],'fInputVar') -end -save([fname,'_input.mat'],'Parallel','-append') - -% Determine the total number of available CPUs, and the number of threads to run on each CPU -for j=1:length(Parallel), - nCPU(j)=length(Parallel(j).NumCPU); - totCPU=totCPU+nCPU(j); -end - -nCPU=cumsum(nCPU); -offset0 = fBlock-1; -if (nBlock-offset0)>totCPU, - diff = mod((nBlock-offset0),totCPU); - nBlockPerCPU(1:diff) = ceil((nBlock-offset0)/totCPU); - nBlockPerCPU(diff+1:totCPU) = floor((nBlock-offset0)/totCPU); -else - nBlockPerCPU(1:nBlock-offset0)=1; - totCPU = nBlock-offset0; -end - - % Clean up remnants of previous runs - mydelete(['comp_status_',fname,'*.mat']) - mydelete(['P_',fname,'*End.txt']); - - % Create a shell script containing the commands to launch the required tasks on the slaves - fid = fopen('ConcurrentCommand1.bat','w+'); - for j=1:totCPU, - - indPC=min(find(nCPU>=j)); - - if indPC>1 - nCPU0 = nCPU(indPC-1); - else - nCPU0=0; - end - offset = sum(nBlockPerCPU(1:j-1))+offset0; - - fid1=fopen(['P_',fname,'_',int2str(j),'End.txt'],'w+'); - fclose(fid1); - - if Parallel(indPC).Local == 1, % run on the local machine - if isunix, - if exist('OCTAVE_VERSION') - command1=['octave --eval fParallel\(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',\''',fname,'\''\) &']; - else - command1=['matlab -nosplash -nodesktop -minimize -r fParallel\(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',\''',fname,'\''\) &']; - end - else - if exist('OCTAVE_VERSION') - command1=['start /B psexec -W ',DyMo, ' -a ',int2str(Parallel(indPC).NumCPU(j-nCPU0)),' -low octave --eval fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')']; - else - command1=['start /B psexec -W ',DyMo, ' -a ',int2str(Parallel(indPC).NumCPU(j-nCPU0)),' -low matlab -nosplash -nodesktop -minimize -r fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')']; - end - end - else - if isunix, - [tempo, RemoteName]=system(['ssh ',Parallel(indPC).user,'@',Parallel(indPC).PcName,' "ifconfig | grep \''inet addr:\''| grep -v \''127.0.0.1\'' | cut -d: -f2 | awk \''{ print $1}\''"']); - RemoteName=RemoteName(1:end-1); - RemoteFolder = Parallel(indPC).RemoteFolder; - else - RemoteName = Parallel(indPC).PcName; - RemoteFolder = [Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteFolder]; - end - - remoteFlag=1; - - if strcmpi(RemoteName,MasterName), - if ~copyfile(['P_',fname,'_',int2str(j),'End.txt'],RemoteFolder), - remoteFlag=0; - end - end - if remoteFlag, - if j==nCPU0+1, - if isunix, - system(['ssh ',Parallel(indPC).user,'@',Parallel(indPC).PcName,' rm -fr ',Parallel(indPC).RemoteFolder,'/*']); - else - mydelete('*.*',['\\',Parallel(indPC).PcName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteFolder,'\']); - adir=dir(['\\',Parallel(indPC).PcName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteFolder,'\']); - for jdir=3:length(adir) - STATUS = rmdir(['\\',Parallel(indPC).PcName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteFolder,'\',adir(jdir).name],'s'); - if STATUS == 0, - disp(['Warning!: Directory ',adir(jdir).name,' could not be removed from ',Parallel(indPC).PcName,'.']) - end - end - end - - if isunix, - system(['scp ',fname,'_input.mat ',Parallel(indPC).user,'@',Parallel(indPC).PcName,':',Parallel(indPC).RemoteFolder]); - for jfil=1:size(NamFileInput,1) - if ~isempty(NamFileInput{jfil,1}) - system(['ssh ',Parallel(indPC).user,'@',Parallel(indPC).PcName,' mkdir -p ',Parallel(indPC).RemoteFolder,'/',NamFileInput{jfil,1}]) - end - system(['scp ',NamFileInput{jfil,1},NamFileInput{jfil,2},' ',Parallel(indPC).user,'@',Parallel(indPC).PcName,':',Parallel(indPC).RemoteFolder,'/',NamFileInput{jfil,1}]); - end - else - copyfile([fname,'_input.mat'], ['\\',Parallel(indPC).PcName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteFolder]); - for jfil=1:size(NamFileInput,1) - copyfile([NamFileInput{jfil,1},NamFileInput{jfil,2}],['\\',Parallel(indPC).PcName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteFolder,'\',NamFileInput{jfil,1}]) - end - end - end - end - - if isunix, - if exist('OCTAVE_VERSION'), - command1=['ssh ',Parallel(indPC).user,'@',Parallel(indPC).PcName,' "cd ',Parallel(indPC).RemoteFolder, '; octave --eval fParallel\(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',\''',fname,'\''\);" &']; - else - command1=['ssh ',Parallel(indPC).user,'@',Parallel(indPC).PcName,' "cd ',Parallel(indPC).RemoteFolder, '; matlab -nosplash -nodesktop -minimize -r fParallel\(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',\''',fname,'\''\);" &']; - end - else - if ~strcmp(Parallel(indPC).PcName,MasterName), % run on a remote machine - if exist('OCTAVE_VERSION'), - command1=['start /B psexec \\',Parallel(indPC).PcName,' -e -u ',Parallel(indPC).user,' -p ',Parallel(indPC).passwd,' -W ',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteFolder,'\ -a ',int2str(Parallel(indPC).NumCPU(j-nCPU0)), ... - ' -low octave --eval fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')']; - else - command1=['start /B psexec \\',Parallel(indPC).PcName,' -e -u ',Parallel(indPC).user,' -p ',Parallel(indPC).passwd,' -W ',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteFolder,'\ -a ',int2str(Parallel(indPC).NumCPU(j-nCPU0)), ... - ' -low matlab -nosplash -nodesktop -minimize -r fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')']; - end - else % run on the local machine via the network - if exist('OCTAVE_VERSION'), - command1=['start /B psexec \\',Parallel(indPC).PcName,' -e -W ',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteFolder,'\ -a ',int2str(Parallel(indPC).NumCPU(j-nCPU0)), ... - ' -low octave --eval fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')']; - else - command1=['start /B psexec \\',Parallel(indPC).PcName,' -e -W ',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteFolder,'\ -a ',int2str(Parallel(indPC).NumCPU(j-nCPU0)), ... - ' -low matlab -nosplash -nodesktop -minimize -r fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')']; - end - end - end - end - fprintf(fid,'%s\n',command1); - end - - fclose(fid); - - % Run the slaves - if isunix, - system('sh ConcurrentCommand1.bat &'); - pause(1) - else - system('ConcurrentCommand1.bat'); - end - - % Wait for the slaves to finish their job, and display some progress information meanwhile - t0=cputime; - t00=cputime; - hh=NaN(1,nBlock); - if exist('OCTAVE_VERSION'), - diary off; - else - hfigstatus = figure('name',['Parallel ',fname],... - 'MenuBar', 'none', ... - 'NumberTitle','off'); - vspace = 0.1; - ncol = ceil(totCPU/10); - hspace = 0.9/ncol; - for j=1:totCPU, - jrow = mod(j-1,10)+1; - jcol = ceil(j/10); - hstatus(j) = axes('position',[0.05/ncol+(jcol-1)/ncol 0.92-vspace*(jrow-1) 0.9/ncol 0.03], ... - 'box','on','xtick',[],'ytick',[],'xlim',[0 1],'ylim',[0 1]); - end - cumBlockPerCPU = cumsum(nBlockPerCPU); - end - pcerdone = NaN(1,totCPU); - while (1) - waitbarString = ''; - statusString = ''; - pause(1) - stax = dir(['comp_status_',fname,'*.mat']); - for j=1:length(stax), - - try - load(stax(j).name) - pcerdone(j) = prtfrc; - if exist('OCTAVE_VERSION'), - statusString = [statusString, waitbarString, ', %3.f%% done! ']; - else - status_String{j} = waitbarString; - status_Title{j} = waitbarTitle; - idCPU(j) = njob; - end - if prtfrc==1, delete(stax(j).name), end - catch - - end - end - if exist('OCTAVE_VERSION'), - printf([statusString,'\r'], 100 .* pcerdone); - else - figure(hfigstatus), - for j=1:length(stax), - axes(hstatus(idCPU(j))), - hpat = findobj(hstatus(idCPU(j)),'Type','patch'); - if ~isempty(hpat), - set(hpat,'XData',[0 0 pcerdone(j) pcerdone(j)]) - else - patch([0 0 pcerdone(j) pcerdone(j)],[0 1 1 0],'r','EdgeColor','r') - end - title([status_Title{j},' - ',status_String{j}]); - end - end - if isempty(dir(['P_',fname,'_*End.txt'])) - mydelete(['comp_status_',fname,'*.mat']) - if ~exist('OCTAVE_VERSION'), - close(hfigstatus), - else - printf('\n'); - diary on; - end - break - end - end - - % Create return value - for j=1:totCPU, - load([fname,'_output_',int2str(j),'.mat'],'fOutputVar'); - delete([fname,'_output_',int2str(j),'.mat']); - fOutVar(j)=fOutputVar; - end - -% Cleanup -delete([fname,'_input.mat']) -delete ConcurrentCommand1.bat +function [fOutVar,nBlockPerCPU, totCPU] = masterParallel(Parallel,fBlock,nBlock,NamFileInput,fname,fInputVar,fGlobalVar) +% Top-level function called on the master computer when parallelizing a task. +% +% The number of parallelized threads will be equal to (nBlock-fBlock+1). +% +% INPUTS +% Parallel [struct vector] copy of options_.parallel +% fBlock [int] index number of the first thread +% (between 1 and nBlock) +% nBlock [int] index number of the last thread +% NamFileInput [cell array] containins the list of input files to be +% copied in the working directory of remote slaves +% 2 columns, as many lines as there are files +% - first column contains directory paths +% - second column contains filenames +% fname [string] name of the function to be parallelized, and +% which will be run on the slaves +% fInputVar [struct] structure containing local variables to be used +% by fName on the slaves +% fGlobalVar [struct] structure containing global variables to be used +% by fName on the slaves +% +% OUTPUT +% fOutVar [struct vector] result of the parallel computation, one +% struct per thread +% nBlockPerCPU [int vector] for each CPU used, indicates the number of +% threads run on that CPU +% totCPU [int] total number of CPU used (can be lower than +% the number of CPU declared in "Parallel", if +% the number of required threads is lower) + +% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. + +totCPU=0; + +% Determine my hostname and my working directory +DyMo=pwd; +fInputVar.DyMo=DyMo; +if isunix, + [tempo, MasterName]=system(['ifconfig | grep ''inet addr:''| grep -v ''127.0.0.1'' | cut -d: -f2 | awk ''{ print $1}''']); +else + [tempo, MasterName]=system('hostname'); +end +MasterName=deblank(MasterName); +fInputVar.MasterName = MasterName; + +% Save input data for use by the slaves +if exist('fGlobalVar'), + save([fname,'_input.mat'],'fInputVar','fGlobalVar') +else + save([fname,'_input.mat'],'fInputVar') +end +save([fname,'_input.mat'],'Parallel','-append') + +% Determine the total number of available CPUs, and the number of threads to run on each CPU +for j=1:length(Parallel), + nCPU(j)=length(Parallel(j).NumCPU); + totCPU=totCPU+nCPU(j); +end + +nCPU=cumsum(nCPU); +offset0 = fBlock-1; +if (nBlock-offset0)>totCPU, + diff = mod((nBlock-offset0),totCPU); + nBlockPerCPU(1:diff) = ceil((nBlock-offset0)/totCPU); + nBlockPerCPU(diff+1:totCPU) = floor((nBlock-offset0)/totCPU); +else + nBlockPerCPU(1:nBlock-offset0)=1; + totCPU = nBlock-offset0; +end + +% Clean up remnants of previous runs +mydelete(['comp_status_',fname,'*.mat']) +mydelete(['P_',fname,'*End.txt']); + +% Create a shell script containing the commands to launch the required tasks on the slaves +fid = fopen('ConcurrentCommand1.bat','w+'); +for j=1:totCPU, + + indPC=min(find(nCPU>=j)); + + if indPC>1 + nCPU0 = nCPU(indPC-1); + else + nCPU0=0; + end + offset = sum(nBlockPerCPU(1:j-1))+offset0; + + fid1=fopen(['P_',fname,'_',int2str(j),'End.txt'],'w+'); + fclose(fid1); + + if Parallel(indPC).Local == 1, % run on the local machine + if isunix, + if exist('OCTAVE_VERSION') + command1=['octave --eval fParallel\(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',\''',fname,'\''\) &']; + else + command1=['matlab -nosplash -nodesktop -minimize -r fParallel\(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',\''',fname,'\''\) &']; + end + else + if exist('OCTAVE_VERSION') + command1=['start /B psexec -W ',DyMo, ' -a ',int2str(Parallel(indPC).NumCPU(j-nCPU0)),' -low octave --eval fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')']; + else + command1=['start /B psexec -W ',DyMo, ' -a ',int2str(Parallel(indPC).NumCPU(j-nCPU0)),' -low matlab -nosplash -nodesktop -minimize -r fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')']; + end + end + else + if isunix, + [tempo, RemoteName]=system(['ssh ',Parallel(indPC).user,'@',Parallel(indPC).PcName,' "ifconfig | grep \''inet addr:\''| grep -v \''127.0.0.1\'' | cut -d: -f2 | awk \''{ print $1}\''"']); + RemoteName=RemoteName(1:end-1); + RemoteFolder = Parallel(indPC).RemoteFolder; + else + RemoteName = Parallel(indPC).PcName; + RemoteFolder = [Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteFolder]; + end + + remoteFlag=1; + + if strcmpi(RemoteName,MasterName), + if ~copyfile(['P_',fname,'_',int2str(j),'End.txt'],RemoteFolder), + remoteFlag=0; + end + end + if remoteFlag, + if j==nCPU0+1, + if isunix, + system(['ssh ',Parallel(indPC).user,'@',Parallel(indPC).PcName,' rm -fr ',Parallel(indPC).RemoteFolder,'/*']); + else + mydelete('*.*',['\\',Parallel(indPC).PcName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteFolder,'\']); + adir=dir(['\\',Parallel(indPC).PcName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteFolder,'\']); + for jdir=3:length(adir) + STATUS = rmdir(['\\',Parallel(indPC).PcName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteFolder,'\',adir(jdir).name],'s'); + if STATUS == 0, + disp(['Warning!: Directory ',adir(jdir).name,' could not be removed from ',Parallel(indPC).PcName,'.']) + end + end + end + + if isunix, + system(['scp ',fname,'_input.mat ',Parallel(indPC).user,'@',Parallel(indPC).PcName,':',Parallel(indPC).RemoteFolder]); + for jfil=1:size(NamFileInput,1) + if ~isempty(NamFileInput{jfil,1}) + system(['ssh ',Parallel(indPC).user,'@',Parallel(indPC).PcName,' mkdir -p ',Parallel(indPC).RemoteFolder,'/',NamFileInput{jfil,1}]) + end + system(['scp ',NamFileInput{jfil,1},NamFileInput{jfil,2},' ',Parallel(indPC).user,'@',Parallel(indPC).PcName,':',Parallel(indPC).RemoteFolder,'/',NamFileInput{jfil,1}]); + end + else + copyfile([fname,'_input.mat'], ['\\',Parallel(indPC).PcName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteFolder]); + for jfil=1:size(NamFileInput,1) + copyfile([NamFileInput{jfil,1},NamFileInput{jfil,2}],['\\',Parallel(indPC).PcName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteFolder,'\',NamFileInput{jfil,1}]) + end + end + end + end + + if isunix, + if exist('OCTAVE_VERSION'), + command1=['ssh ',Parallel(indPC).user,'@',Parallel(indPC).PcName,' "cd ',Parallel(indPC).RemoteFolder, '; octave --eval fParallel\(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',\''',fname,'\''\);" &']; + else + command1=['ssh ',Parallel(indPC).user,'@',Parallel(indPC).PcName,' "cd ',Parallel(indPC).RemoteFolder, '; matlab -nosplash -nodesktop -minimize -r fParallel\(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',\''',fname,'\''\);" &']; + end + else + if ~strcmp(Parallel(indPC).PcName,MasterName), % run on a remote machine + if exist('OCTAVE_VERSION'), + command1=['start /B psexec \\',Parallel(indPC).PcName,' -e -u ',Parallel(indPC).user,' -p ',Parallel(indPC).passwd,' -W ',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteFolder,'\ -a ',int2str(Parallel(indPC).NumCPU(j-nCPU0)), ... + ' -low octave --eval fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')']; + else + command1=['start /B psexec \\',Parallel(indPC).PcName,' -e -u ',Parallel(indPC).user,' -p ',Parallel(indPC).passwd,' -W ',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteFolder,'\ -a ',int2str(Parallel(indPC).NumCPU(j-nCPU0)), ... + ' -low matlab -nosplash -nodesktop -minimize -r fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')']; + end + else % run on the local machine via the network + if exist('OCTAVE_VERSION'), + command1=['start /B psexec \\',Parallel(indPC).PcName,' -e -W ',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteFolder,'\ -a ',int2str(Parallel(indPC).NumCPU(j-nCPU0)), ... + ' -low octave --eval fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')']; + else + command1=['start /B psexec \\',Parallel(indPC).PcName,' -e -W ',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteFolder,'\ -a ',int2str(Parallel(indPC).NumCPU(j-nCPU0)), ... + ' -low matlab -nosplash -nodesktop -minimize -r fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')']; + end + end + end + end + fprintf(fid,'%s\n',command1); +end + +fclose(fid); + +% Run the slaves +if isunix, + system('sh ConcurrentCommand1.bat &'); + pause(1) +else + system('ConcurrentCommand1.bat'); +end + +% Wait for the slaves to finish their job, and display some progress information meanwhile +t0=cputime; +t00=cputime; +hh=NaN(1,nBlock); +if exist('OCTAVE_VERSION'), + diary off; +else + hfigstatus = figure('name',['Parallel ',fname],... + 'MenuBar', 'none', ... + 'NumberTitle','off'); + vspace = 0.1; + ncol = ceil(totCPU/10); + hspace = 0.9/ncol; + for j=1:totCPU, + jrow = mod(j-1,10)+1; + jcol = ceil(j/10); + hstatus(j) = axes('position',[0.05/ncol+(jcol-1)/ncol 0.92-vspace*(jrow-1) 0.9/ncol 0.03], ... + 'box','on','xtick',[],'ytick',[],'xlim',[0 1],'ylim',[0 1]); + end + cumBlockPerCPU = cumsum(nBlockPerCPU); +end +pcerdone = NaN(1,totCPU); +while (1) + waitbarString = ''; + statusString = ''; + pause(1) + stax = dir(['comp_status_',fname,'*.mat']); + for j=1:length(stax), + + try + load(stax(j).name) + pcerdone(j) = prtfrc; + if exist('OCTAVE_VERSION'), + statusString = [statusString, waitbarString, ', %3.f%% done! ']; + else + status_String{j} = waitbarString; + status_Title{j} = waitbarTitle; + idCPU(j) = njob; + end + if prtfrc==1, delete(stax(j).name), end + catch + + end + end + if exist('OCTAVE_VERSION'), + printf([statusString,'\r'], 100 .* pcerdone); + else + figure(hfigstatus), + for j=1:length(stax), + axes(hstatus(idCPU(j))), + hpat = findobj(hstatus(idCPU(j)),'Type','patch'); + if ~isempty(hpat), + set(hpat,'XData',[0 0 pcerdone(j) pcerdone(j)]) + else + patch([0 0 pcerdone(j) pcerdone(j)],[0 1 1 0],'r','EdgeColor','r') + end + title([status_Title{j},' - ',status_String{j}]); + end + end + if isempty(dir(['P_',fname,'_*End.txt'])) + mydelete(['comp_status_',fname,'*.mat']) + if ~exist('OCTAVE_VERSION'), + close(hfigstatus), + else + printf('\n'); + diary on; + end + break + end +end + +% Create return value +for j=1:totCPU, + load([fname,'_output_',int2str(j),'.mat'],'fOutputVar'); + delete([fname,'_output_',int2str(j),'.mat']); + fOutVar(j)=fOutputVar; +end + +% Cleanup +delete([fname,'_input.mat']) +delete ConcurrentCommand1.bat diff --git a/matlab/matlab_ver_less_than.m b/matlab/matlab_ver_less_than.m index 499ebb3aaa..ff7bebc2b9 100644 --- a/matlab/matlab_ver_less_than.m +++ b/matlab/matlab_ver_less_than.m @@ -35,15 +35,15 @@ function r = matlab_ver_less_than(verstr) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - ver_struct = ver('matlab'); - cur_verstr = ver_struct.Version; - - r = get_ver_numeric(cur_verstr) < get_ver_numeric(verstr); +ver_struct = ver('matlab'); +cur_verstr = ver_struct.Version; + +r = get_ver_numeric(cur_verstr) < get_ver_numeric(verstr); function x = get_ver_numeric(verstr) - nums = sscanf(verstr, '%d.%d.%d')'; - if length(nums) < 3 +nums = sscanf(verstr, '%d.%d.%d')'; +if length(nums) < 3 nums(3) = 0; - end - x = nums * [1; 0.01; 0.0001 ]; +end +x = nums * [1; 0.01; 0.0001 ]; diff --git a/matlab/maximize_prior_density.m b/matlab/maximize_prior_density.m index 5cf2bfe5d9..ca05876833 100644 --- a/matlab/maximize_prior_density.m +++ b/matlab/maximize_prior_density.m @@ -1,5 +1,5 @@ function [xparams,lpd,hessian] = ... - maximize_prior_density(iparams, prior_shape, prior_hyperparameter_1, prior_hyperparameter_2, prior_inf_bound, prior_sup_bound) + maximize_prior_density(iparams, prior_shape, prior_hyperparameter_1, prior_hyperparameter_2, prior_inf_bound, prior_sup_bound) % Maximizes the logged prior density using Chris Sims' optimization routine. % % INPUTS @@ -31,17 +31,16 @@ function [xparams,lpd,hessian] = ... % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - number_of_estimated_parameters = length(iparams); - H0 = 1e-4*eye(number_of_estimated_parameters); - crit = 1e-7; - nit = 1000; - verbose = 2; - gradient_method = 2; - - [lpd,xparams,grad,hessian,itct,fcount,retcodehat] = ... - csminwel('minus_logged_prior_density',iparams,H0,[],crit,nit,gradient_method, ... - prior_shape, prior_hyperparameter_1, prior_hyperparameter_2, prior_inf_bound, prior_sup_bound); - lpd = -lpd; - \ No newline at end of file +number_of_estimated_parameters = length(iparams); +H0 = 1e-4*eye(number_of_estimated_parameters); +crit = 1e-7; +nit = 1000; +verbose = 2; +gradient_method = 2; + +[lpd,xparams,grad,hessian,itct,fcount,retcodehat] = ... + csminwel('minus_logged_prior_density',iparams,H0,[],crit,nit,gradient_method, ... + prior_shape, prior_hyperparameter_1, prior_hyperparameter_2, prior_inf_bound, prior_sup_bound); + +lpd = -lpd; diff --git a/matlab/mcompare.m b/matlab/mcompare.m index abd18b7758..25102664cc 100644 --- a/matlab/mcompare.m +++ b/matlab/mcompare.m @@ -36,34 +36,34 @@ ix = [1-lag1(1):size(x,2)-lag1(1)]' ; i = [lag1(1):size(ix,1)-lag1(2)+1]' ; if size(options_.smpl,1) == 1 - error(['DSAMPLE not specified.']) ; + error(['DSAMPLE not specified.']) ; end if options_.smpl(3) > 0 - if options_.smpl(3) == 2 - if options_.smpl(1)<0 | options_.smpl(2)>size(x,2)-lag1(2) - error ('Wrong sample.') ; - end - i = [options_.smpl(1)+lag1(1):options_.smpl(2)+lag1(1)]' ; - elseif options_.smpl(3) == 1 - if options_.smpl(1)>size(x,2)-lag1(2) - error ('Wrong sample.') ; - end - i = [lag1(1):options_.smpl(1)+lag1(1)]' ; - end + if options_.smpl(3) == 2 + if options_.smpl(1)<0 | options_.smpl(2)>size(x,2)-lag1(2) + error ('Wrong sample.') ; + end + i = [options_.smpl(1)+lag1(1):options_.smpl(2)+lag1(1)]' ; + elseif options_.smpl(3) == 1 + if options_.smpl(1)>size(x,2)-lag1(2) + error ('Wrong sample.') ; + end + i = [lag1(1):options_.smpl(1)+lag1(1)]' ; + end end for k = 1:size(x,1) - figure ; - x1 = x(k,i) ; - y1 = y(k,i) ; - if nnz(x1) < length(x1) - plot(ix(i),(y1-x1)) ; - else - plot(ix(i),(y1-x1)./x1) ; - end - xlabel(['Periods']) ; - title(['Variable ' s2(k)]) ; + figure ; + x1 = x(k,i) ; + y1 = y(k,i) ; + if nnz(x1) < length(x1) + plot(ix(i),(y1-x1)) ; + else + plot(ix(i),(y1-x1)./x1) ; + end + xlabel(['Periods']) ; + title(['Variable ' s2(k)]) ; end return ; diff --git a/matlab/metropolis_draw.m b/matlab/metropolis_draw.m index 1fd32dded6..a7e7b89845 100644 --- a/matlab/metropolis_draw.m +++ b/matlab/metropolis_draw.m @@ -1,70 +1,70 @@ -function [xparams, logpost]=metropolis_draw(init) -% function [xparams, logpost]=metropolis_draw(init) -% Builds draws from metropolis -% -% INPUTS: -% init: scalar equal to 1 (first call) or 0 -% -% OUTPUTS: -% xparams: vector of estimated parameters -% logpost: log of posterior density -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2003-2007 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 <http://www.gnu.org/licenses/>. - - global options_ estim_params_ M_ - persistent mh_nblck NumberOfDraws fname FirstLine FirstMhFile MAX_nruns - - if init - nvx = estim_params_.nvx; - nvn = estim_params_.nvn; - ncx = estim_params_.ncx; - ncn = estim_params_.ncn; - np = estim_params_.np ; - npar = nvx+nvn+ncx+ncn+np; - MhDirectoryName = CheckPath('metropolis'); - fname = [ MhDirectoryName '/' M_.fname]; - load([ fname '_mh_history']); - FirstMhFile = record.KeepedDraws.FirstMhFile; - FirstLine = record.KeepedDraws.FirstLine; - TotalNumberOfMhFiles = sum(record.MhDraws(:,2)); - LastMhFile = TotalNumberOfMhFiles; - TotalNumberOfMhDraws = sum(record.MhDraws(:,1)); - NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws); - MAX_nruns = ceil(options_.MaxNumberOfBytes/(npar+2)/8); - mh_nblck = options_.mh_nblck; - return - end - - ChainNumber = ceil(rand*mh_nblck); - DrawNumber = ceil(rand*NumberOfDraws); - - if DrawNumber <= MAX_nruns-FirstLine+1 - MhFilNumber = FirstMhFile; - MhLine = FirstLine+DrawNumber-1; - else - DrawNumber = DrawNumber-(MAX_nruns-FirstLine+1); - MhFilNumber = FirstMhFile+ceil(DrawNumber/MAX_nruns); - MhLine = DrawNumber-(MhFilNumber-FirstMhFile-1)*MAX_nruns; - end - - load( [ fname '_mh' int2str(MhFilNumber) '_blck' int2str(ChainNumber) '.mat' ],'x2','logpo2'); - xparams = x2(MhLine,:); - logpost= logpo2(MhLine); \ No newline at end of file +function [xparams, logpost]=metropolis_draw(init) +% function [xparams, logpost]=metropolis_draw(init) +% Builds draws from metropolis +% +% INPUTS: +% init: scalar equal to 1 (first call) or 0 +% +% OUTPUTS: +% xparams: vector of estimated parameters +% logpost: log of posterior density +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2003-2007 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 <http://www.gnu.org/licenses/>. + +global options_ estim_params_ M_ +persistent mh_nblck NumberOfDraws fname FirstLine FirstMhFile MAX_nruns + +if init + nvx = estim_params_.nvx; + nvn = estim_params_.nvn; + ncx = estim_params_.ncx; + ncn = estim_params_.ncn; + np = estim_params_.np ; + npar = nvx+nvn+ncx+ncn+np; + MhDirectoryName = CheckPath('metropolis'); + fname = [ MhDirectoryName '/' M_.fname]; + load([ fname '_mh_history']); + FirstMhFile = record.KeepedDraws.FirstMhFile; + FirstLine = record.KeepedDraws.FirstLine; + TotalNumberOfMhFiles = sum(record.MhDraws(:,2)); + LastMhFile = TotalNumberOfMhFiles; + TotalNumberOfMhDraws = sum(record.MhDraws(:,1)); + NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws); + MAX_nruns = ceil(options_.MaxNumberOfBytes/(npar+2)/8); + mh_nblck = options_.mh_nblck; + return +end + +ChainNumber = ceil(rand*mh_nblck); +DrawNumber = ceil(rand*NumberOfDraws); + +if DrawNumber <= MAX_nruns-FirstLine+1 + MhFilNumber = FirstMhFile; + MhLine = FirstLine+DrawNumber-1; +else + DrawNumber = DrawNumber-(MAX_nruns-FirstLine+1); + MhFilNumber = FirstMhFile+ceil(DrawNumber/MAX_nruns); + MhLine = DrawNumber-(MhFilNumber-FirstMhFile-1)*MAX_nruns; +end + +load( [ fname '_mh' int2str(MhFilNumber) '_blck' int2str(ChainNumber) '.mat' ],'x2','logpo2'); +xparams = x2(MhLine,:); +logpost= logpo2(MhLine); \ No newline at end of file diff --git a/matlab/metropolis_hastings_initialization.m b/matlab/metropolis_hastings_initialization.m index 92f23a2746..48112a2add 100644 --- a/matlab/metropolis_hastings_initialization.m +++ b/matlab/metropolis_hastings_initialization.m @@ -1,5 +1,5 @@ function [ ix2, ilogpo2, ModelName, MhDirectoryName, fblck, fline, npar, nblck, nruns, NewFile, MAX_nruns, d ] = ... - metropolis_hastings_initialization(TargetFun, xparam1, vv, mh_bounds, varargin) + metropolis_hastings_initialization(TargetFun, xparam1, vv, mh_bounds, varargin) % Metropolis-Hastings initialization. % % INPUTS @@ -163,11 +163,11 @@ if ~options_.load_mh_file & ~options_.mh_recover % separate initializaton for each chain JSUM = 0; for j=1:nblck, - JSUM = JSUM + sum(100*clock); - randn('state',JSUM); - rand('state',JSUM); - record.Seeds(j).Normal = randn('state'); - record.Seeds(j).Unifor = rand('state'); + JSUM = JSUM + sum(100*clock); + randn('state',JSUM); + rand('state',JSUM); + record.Seeds(j).Normal = randn('state'); + record.Seeds(j).Unifor = rand('state'); end record.InitialParameters = ix2; record.InitialLogLiK = ilogpo2; @@ -182,14 +182,14 @@ if ~options_.load_mh_file & ~options_.mh_recover int2str(AnticipatedNumberOfLinesInTheLastFile) '.\n']); fprintf(fidlog,['\n']); for j = 1:nblck, - fprintf(fidlog,[' Initial seed (randn) for chain number ',int2str(j),':\n']); - for i=1:length(record.Seeds(j).Normal) - fprintf(fidlog,[' ' num2str(record.Seeds(j).Normal(i)') '\n']); - end - fprintf(fidlog,[' Initial seed (rand) for chain number ',int2str(j),':\n']); - for i=1:length(record.Seeds(j).Unifor) - fprintf(fidlog,[' ' num2str(record.Seeds(j).Unifor(i)') '\n']); - end + fprintf(fidlog,[' Initial seed (randn) for chain number ',int2str(j),':\n']); + for i=1:length(record.Seeds(j).Normal) + fprintf(fidlog,[' ' num2str(record.Seeds(j).Normal(i)') '\n']); + end + fprintf(fidlog,[' Initial seed (rand) for chain number ',int2str(j),':\n']); + for i=1:length(record.Seeds(j).Unifor) + fprintf(fidlog,[' ' num2str(record.Seeds(j).Unifor(i)') '\n']); + end end, fprintf(fidlog,' \n'); fclose(fidlog); diff --git a/matlab/mh_autocorrelation_function.m b/matlab/mh_autocorrelation_function.m index a3f3e1aba5..e51d3c185f 100644 --- a/matlab/mh_autocorrelation_function.m +++ b/matlab/mh_autocorrelation_function.m @@ -34,7 +34,7 @@ function mh_autocorrelation_function(options_,M_,estim_params_,type,blck,name1,n % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - + % Cet the column index: if nargin<7 column = name2index(options_, M_, estim_params_, type, name1); diff --git a/matlab/mh_optimal_bandwidth.m b/matlab/mh_optimal_bandwidth.m index 958d358b36..79c11bb2f4 100644 --- a/matlab/mh_optimal_bandwidth.m +++ b/matlab/mh_optimal_bandwidth.m @@ -40,7 +40,7 @@ function optimal_bandwidth = mh_optimal_bandwidth(data,number_of_draws,bandwidth % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - + %% Kernel specifications. if strcmpi(kernel_function,'gaussian') % Kernel definition @@ -104,11 +104,11 @@ if bandwidth == 0; % Rule of thumb bandwidth parameter (Silverman [1986]. h = h*correction^(1/5); elseif bandwidth == -1; % Sheather and Jones [1991] plug-in estimation of the optimal bandwidth parameter. if strcmp(kernel_function,'uniform') | ... - strcmp(kernel_function,'triangle') | ... - strcmp(kernel_function,'epanechnikov') | ... - strcmp(kernel_function,'quartic') - error(['I can''t compute the optimal bandwidth with this kernel...' ... - 'Try the gaussian, triweight or cosinus kernels.']); + strcmp(kernel_function,'triangle') | ... + strcmp(kernel_function,'epanechnikov') | ... + strcmp(kernel_function,'quartic') + error(['I can''t compute the optimal bandwidth with this kernel...' ... + 'Try the gaussian, triweight or cosinus kernels.']); end Itilda4 = 8*7*6*5/(((2*sigma)^9)*sqrt(pi)); g3 = abs(2*correction*k6(0)/(mu21*Itilda4*number_of_draws))^(1/9); @@ -127,9 +127,9 @@ elseif bandwidth == -1; % Sheather and Jones [1991] plug-in estimation of the op elseif bandwidth == -2; % Bump killing... I compute local bandwith parameters in order to remove % spurious bumps introduced by long rejecting periods. if strcmp(kernel_function,'uniform') | ... - strcmp(kernel_function,'triangle') | ... - strcmp(kernel_function,'epanechnikov') | ... - strcmp(kernel_function,'quartic') + strcmp(kernel_function,'triangle') | ... + strcmp(kernel_function,'epanechnikov') | ... + strcmp(kernel_function,'quartic') error(['I can''t compute the optimal bandwidth with this kernel...' ... 'Try the gaussian, triweight or cosinus kernels.']); end diff --git a/matlab/minus_logged_prior_density.m b/matlab/minus_logged_prior_density.m index 92a37b287e..8aafbd9e63 100644 --- a/matlab/minus_logged_prior_density.m +++ b/matlab/minus_logged_prior_density.m @@ -28,5 +28,5 @@ function [f,fake] = minus_logged_prior_density(xparams,pshape,p6,p7,p3,p4) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - fake = 1; - f = - priordens(xparams,pshape,p6,p7,p3,p4); \ No newline at end of file +fake = 1; +f = - priordens(xparams,pshape,p6,p7,p3,p4); \ No newline at end of file diff --git a/matlab/missing/ordeig/ordeig.m b/matlab/missing/ordeig/ordeig.m index f73ce7c7ba..c46e81d597 100644 --- a/matlab/missing/ordeig/ordeig.m +++ b/matlab/missing/ordeig/ordeig.m @@ -1,46 +1,46 @@ -function eigs = ordeig(t) -% function eval = ordeig(t) -% Computes the eigenvalues of a quasi-triangular matrix -% -% INPUTS -% t: quasi-triangular matrix -% -% OUTPUTS -% eigs: eigenvalues -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2003-2008 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 <http://www.gnu.org/licenses/>. - - n = size(t,2); - eigs = zeros(n,1); - i = 1; - while i <= n - if i == n - eigs(n) = t(n,n); - break; - elseif t(i+1,i) == 0 - eigs(i) = t(i,i); - i = i+1; - else - k = i:i+1; - eigs(k) = eig(t(k,k)); - i = i+2; - end - end +function eigs = ordeig(t) +% function eval = ordeig(t) +% Computes the eigenvalues of a quasi-triangular matrix +% +% INPUTS +% t: quasi-triangular matrix +% +% OUTPUTS +% eigs: eigenvalues +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2003-2008 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 <http://www.gnu.org/licenses/>. + +n = size(t,2); +eigs = zeros(n,1); +i = 1; +while i <= n + if i == n + eigs(n) = t(n,n); + break; + elseif t(i+1,i) == 0 + eigs(i) = t(i,i); + i = i+1; + else + k = i:i+1; + eigs(k) = eig(t(k,k)); + i = i+2; + end +end diff --git a/matlab/missing/rows_columns/columns.m b/matlab/missing/rows_columns/columns.m index 95a89b56ad..9c69fdfb8d 100644 --- a/matlab/missing/rows_columns/columns.m +++ b/matlab/missing/rows_columns/columns.m @@ -19,4 +19,4 @@ function c = columns(M) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - c = size(M,2); +c = size(M,2); diff --git a/matlab/missing/rows_columns/rows.m b/matlab/missing/rows_columns/rows.m index c91b071fbc..97aadf84ec 100644 --- a/matlab/missing/rows_columns/rows.m +++ b/matlab/missing/rows_columns/rows.m @@ -19,4 +19,4 @@ function r = rows(x) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - r = size(x,1); +r = size(x,1); diff --git a/matlab/missing/stats/betacdf.m b/matlab/missing/stats/betacdf.m index 3540bef722..a0f9aaabc7 100644 --- a/matlab/missing/stats/betacdf.m +++ b/matlab/missing/stats/betacdf.m @@ -27,38 +27,38 @@ function cdf = betacdf (x, a, b) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if (nargin ~= 3) +if (nargin ~= 3) error ('betacdf: you should provide three arguments'); - end +end - if (~isscalar (a) || ~isscalar(b)) +if (~isscalar (a) || ~isscalar(b)) [retval, x, a, b] = common_size (x, a, b); if (retval > 0) - error ('betacdf: x, a and b must be of common size or scalar'); + error ('betacdf: x, a and b must be of common size or scalar'); end - end +end - sz = size(x); - cdf = zeros (sz); +sz = size(x); +cdf = zeros (sz); - k = find (~(a > 0) | ~(b > 0) | isnan (x)); - if (any (k)) +k = find (~(a > 0) | ~(b > 0) | isnan (x)); +if (any (k)) cdf (k) = NaN; - end +end - k = find ((x >= 1) & (a > 0) & (b > 0)); - if (any (k)) +k = find ((x >= 1) & (a > 0) & (b > 0)); +if (any (k)) cdf (k) = 1; - end +end - k = find ((x > 0) & (x < 1) & (a > 0) & (b > 0)); - if (any (k)) +k = find ((x > 0) & (x < 1) & (a > 0) & (b > 0)); +if (any (k)) if (isscalar (a) && isscalar(b)) - cdf (k) = betainc (x(k), a, b); + cdf (k) = betainc (x(k), a, b); else - cdf (k) = betainc (x(k), a(k), b(k)); + cdf (k) = betainc (x(k), a(k), b(k)); end - end +end end diff --git a/matlab/missing/stats/betainv.m b/matlab/missing/stats/betainv.m index 14c5d13508..54ec63de3f 100644 --- a/matlab/missing/stats/betainv.m +++ b/matlab/missing/stats/betainv.m @@ -27,69 +27,69 @@ function inv = betainv (x, a, b) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if (nargin ~= 3) +if (nargin ~= 3) error ('betainv: you must give three arguments'); - end +end - if (~isscalar (a) || ~isscalar(b)) +if (~isscalar (a) || ~isscalar(b)) [retval, x, a, b] = common_size (x, a, b); if (retval > 0) - error ('betainv: x, a and b must be of common size or scalars'); + error ('betainv: x, a and b must be of common size or scalars'); end - end - - sz = size (x); - inv = zeros (sz); +end + +sz = size (x); +inv = zeros (sz); - k = find ((x < 0) | (x > 1) | ~(a > 0) | ~(b > 0) | isnan (x)); - if (any (k)) +k = find ((x < 0) | (x > 1) | ~(a > 0) | ~(b > 0) | isnan (x)); +if (any (k)) inv (k) = NaN; - end +end - k = find ((x == 1) & (a > 0) & (b > 0)); - if (any (k)) +k = find ((x == 1) & (a > 0) & (b > 0)); +if (any (k)) inv (k) = 1; - end +end - k = find ((x > 0) & (x < 1) & (a > 0) & (b > 0)); - if (any (k)) +k = find ((x > 0) & (x < 1) & (a > 0) & (b > 0)); +if (any (k)) if (~isscalar(a) || ~isscalar(b)) - a = a (k); - b = b (k); - y = a ./ (a + b); + a = a (k); + b = b (k); + y = a ./ (a + b); else - y = a / (a + b) * ones (size (k)); + y = a / (a + b) * ones (size (k)); end x = x (k); l = find (y < eps); if (any (l)) - y(l) = sqrt (eps) * ones (length (l), 1); + y(l) = sqrt (eps) * ones (length (l), 1); end l = find (y > 1 - eps); if (any (l)) - y(l) = 1 - sqrt (eps) * ones (length (l), 1); + y(l) = 1 - sqrt (eps) * ones (length (l), 1); end y_old = y; for i = 1 : 10000 - h = (betacdf (y_old, a, b) - x) ./ betapdf (y_old, a, b); - y_new = y_old - h; - ind = find (y_new <= eps); - if (any (ind)) - y_new (ind) = y_old (ind) / 10; - end - ind = find (y_new >= 1 - eps); - if (any (ind)) - y_new (ind) = 1 - (1 - y_old (ind)) / 10; - end - h = y_old - y_new; - if (max (abs (h)) < sqrt (eps)) - break; - end - y_old = y_new; + h = (betacdf (y_old, a, b) - x) ./ betapdf (y_old, a, b); + y_new = y_old - h; + ind = find (y_new <= eps); + if (any (ind)) + y_new (ind) = y_old (ind) / 10; + end + ind = find (y_new >= 1 - eps); + if (any (ind)) + y_new (ind) = 1 - (1 - y_old (ind)) / 10; + end + h = y_old - y_new; + if (max (abs (h)) < sqrt (eps)) + break; + end + y_old = y_new; end inv (k) = y_new; - end +end end diff --git a/matlab/missing/stats/betapdf.m b/matlab/missing/stats/betapdf.m index 12d51f2c20..b94834c7a6 100644 --- a/matlab/missing/stats/betapdf.m +++ b/matlab/missing/stats/betapdf.m @@ -27,34 +27,34 @@ function pdf = betapdf (x, a, b) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if (nargin ~= 3) +if (nargin ~= 3) error ('betapdf: you must give three arguments'); - end - - if (~isscalar (a) || ~isscalar(b)) +end + +if (~isscalar (a) || ~isscalar(b)) [retval, x, a, b] = common_size (x, a, b); if (retval > 0) - error ('betapdf: x, a and b must be of common size or scalar'); + error ('betapdf: x, a and b must be of common size or scalar'); end - end +end - sz = size (x); - pdf = zeros (sz); +sz = size (x); +pdf = zeros (sz); - k = find (~(a > 0) | ~(b > 0) | isnan (x)); - if (any (k)) +k = find (~(a > 0) | ~(b > 0) | isnan (x)); +if (any (k)) pdf (k) = NaN; - end +end - k = find ((x > 0) & (x < 1) & (a > 0) & (b > 0)); - if (any (k)) +k = find ((x > 0) & (x < 1) & (a > 0) & (b > 0)); +if (any (k)) if (isscalar(a) && isscalar(b)) - pdf(k) = exp ((a - 1) .* log (x(k)) ... - + (b - 1) .* log (1 - x(k))) ./ beta (a, b); + pdf(k) = exp ((a - 1) .* log (x(k)) ... + + (b - 1) .* log (1 - x(k))) ./ beta (a, b); else - pdf(k) = exp ((a(k) - 1) .* log (x(k)) ... - + (b(k) - 1) .* log (1 - x(k))) ./ beta (a(k), b(k)); + pdf(k) = exp ((a(k) - 1) .* log (x(k)) ... + + (b(k) - 1) .* log (1 - x(k))) ./ beta (a(k), b(k)); end - end +end end diff --git a/matlab/missing/stats/betarnd.m b/matlab/missing/stats/betarnd.m index e3a906524c..f27fca4413 100644 --- a/matlab/missing/stats/betarnd.m +++ b/matlab/missing/stats/betarnd.m @@ -31,7 +31,7 @@ function rnd = betarnd(a, b) % along with Dynare. If not, see <http://www.gnu.org/licenses/>. if (nargin ~= 2) - error('betarnd: you must give two arguments'); + error('betarnd: you must give two arguments'); end if (any(a<0)) || (any(b<0)) || (any(a==Inf)) || (any(b==Inf)) diff --git a/matlab/missing/stats/chi2inv.m b/matlab/missing/stats/chi2inv.m index 29744bd8fc..cf62307bc9 100644 --- a/matlab/missing/stats/chi2inv.m +++ b/matlab/missing/stats/chi2inv.m @@ -26,17 +26,17 @@ function inv = chi2inv (x, n) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if (nargin ~= 2) +if (nargin ~= 2) error ('chi2inv: you must give two arguments'); - end +end - if (~isscalar (n)) +if (~isscalar (n)) [retval, x, n] = common_size (x, n); if (retval > 0) - error ('chi2inv: x and n must be of common size or scalar'); + error ('chi2inv: x and n must be of common size or scalar'); end - end +end - inv = gaminv (x, n / 2, 2); +inv = gaminv (x, n / 2, 2); end diff --git a/matlab/missing/stats/common_size.m b/matlab/missing/stats/common_size.m index 516655d716..47c72266b4 100644 --- a/matlab/missing/stats/common_size.m +++ b/matlab/missing/stats/common_size.m @@ -36,38 +36,38 @@ function [errorcode, varargout] = common_size (varargin) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if (nargin < 2) +if (nargin < 2) error ('common_size: only makes sense if nargin >= 2'); - end +end - len = 2; - for i = 1 : nargin +len = 2; +for i = 1 : nargin sz = size (varargin{i}); if (length (sz) < len) - s(i,:) = [sz, ones(1,len - length(sz))]; + s(i,:) = [sz, ones(1,len - length(sz))]; else - if (length (sz) > len) - if (i > 1) - s = [s, ones(size(s,1), length(sz) - len)]; + if (length (sz) > len) + if (i > 1) + s = [s, ones(size(s,1), length(sz) - len)]; + end + len = length (sz); end - len = length (sz); - end - s(i,:) = sz; + s(i,:) = sz; end - end +end - m = max (s); - if (any (any ((s ~= 1)') & any ((s ~= ones (nargin, 1) * m)'))) +m = max (s); +if (any (any ((s ~= 1)') & any ((s ~= ones (nargin, 1) * m)'))) errorcode = 1; varargout = varargin; - else +else errorcode = 0; for i = 1 : nargin - varargout{i} = varargin{i}; - if (prod (s(i,:)) == 1) - varargout{i} = varargout{i} * ones (m); - end + varargout{i} = varargin{i}; + if (prod (s(i,:)) == 1) + varargout{i} = varargout{i} * ones (m); + end end - end +end end diff --git a/matlab/missing/stats/exprnd.m b/matlab/missing/stats/exprnd.m index 7f53538569..65855db6e3 100644 --- a/matlab/missing/stats/exprnd.m +++ b/matlab/missing/stats/exprnd.m @@ -33,10 +33,10 @@ function rnd = exprnd(a) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if any(a(:)<0) - disp('exprnd:: The parameter of the exponential distribution has to be positive!') - error; - end - [m,n] = size(a); - uniform_variates = rand(m,n); - rnd = -log(uniform_variates).*a; \ No newline at end of file +if any(a(:)<0) + disp('exprnd:: The parameter of the exponential distribution has to be positive!') + error; +end +[m,n] = size(a); +uniform_variates = rand(m,n); +rnd = -log(uniform_variates).*a; \ No newline at end of file diff --git a/matlab/missing/stats/gamcdf.m b/matlab/missing/stats/gamcdf.m index 8c81a288b7..3b009b5f80 100644 --- a/matlab/missing/stats/gamcdf.m +++ b/matlab/missing/stats/gamcdf.m @@ -27,32 +27,32 @@ function cdf = gamcdf (x, a, b) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if (nargin ~= 3) +if (nargin ~= 3) error ('gamcdf: you must give three arguments'); - end +end - if (~isscalar (a) || ~isscalar(b)) +if (~isscalar (a) || ~isscalar(b)) [retval, x, a, b] = common_size (x, a, b); if (retval > 0) - error ('gamcdf: x, a and b must be of common size or scalars'); + error ('gamcdf: x, a and b must be of common size or scalars'); end - end +end - sz = size (x); - cdf = zeros (sz); +sz = size (x); +cdf = zeros (sz); - k = find (~(a > 0) | ~(b > 0) | isnan (x)); - if (any (k)) +k = find (~(a > 0) | ~(b > 0) | isnan (x)); +if (any (k)) cdf (k) = NaN; - end +end - k = find ((x > 0) & (a > 0) & (b > 0)); - if (any (k)) +k = find ((x > 0) & (a > 0) & (b > 0)); +if (any (k)) if (isscalar (a) && isscalar(b)) - cdf (k) = gammainc (x(k) ./ b, a); + cdf (k) = gammainc (x(k) ./ b, a); else - cdf (k) = gammainc (x(k) ./ b(k), a(k)); + cdf (k) = gammainc (x(k) ./ b(k), a(k)); end - end +end end diff --git a/matlab/missing/stats/gaminv.m b/matlab/missing/stats/gaminv.m index c851972476..ee66a7852a 100644 --- a/matlab/missing/stats/gaminv.m +++ b/matlab/missing/stats/gaminv.m @@ -29,59 +29,59 @@ function inv = gaminv (x, a, b) if (nargin ~= 3) error ('gaminv: you must give three arguments'); - end +end - if (~isscalar (a) || ~isscalar(b)) +if (~isscalar (a) || ~isscalar(b)) [retval, x, a, b] = common_size (x, a, b); if (retval > 0) - error ('gaminv: x, a and b must be of common size or scalars'); + error ('gaminv: x, a and b must be of common size or scalars'); end - end +end - sz = size (x); - inv = zeros (sz); +sz = size (x); +inv = zeros (sz); - k = find ((x < 0) | (x > 1) | isnan (x) | ~(a > 0) | ~(b > 0)); - if (any (k)) +k = find ((x < 0) | (x > 1) | isnan (x) | ~(a > 0) | ~(b > 0)); +if (any (k)) inv (k) = NaN; - end +end - k = find ((x == 1) & (a > 0) & (b > 0)); - if (any (k)) +k = find ((x == 1) & (a > 0) & (b > 0)); +if (any (k)) inv (k) = Inf; - end +end - k = find ((x > 0) & (x < 1) & (a > 0) & (b > 0)); - if (any (k)) +k = find ((x > 0) & (x < 1) & (a > 0) & (b > 0)); +if (any (k)) if (~isscalar(a) || ~isscalar(b)) - a = a (k); - b = b (k); - y = a .* b; + a = a (k); + b = b (k); + y = a .* b; else - y = a * b * ones (size (k)); + y = a * b * ones (size (k)); end x = x (k); l = find (x < eps); if (any (l)) - y(l) = sqrt (eps) * ones (length (l), 1); + y(l) = sqrt (eps) * ones (length (l), 1); end y_old = y; for i = 1 : 100 - h = (gamcdf (y_old, a, b) - x) ./ gampdf (y_old, a, b); - y_new = y_old - h; - ind = find (y_new <= eps); - if (any (ind)) - y_new (ind) = y_old (ind) / 10; - h = y_old - y_new; - end - if (max (abs (h)) < sqrt (eps)) - break; - end - y_old = y_new; + h = (gamcdf (y_old, a, b) - x) ./ gampdf (y_old, a, b); + y_new = y_old - h; + ind = find (y_new <= eps); + if (any (ind)) + y_new (ind) = y_old (ind) / 10; + h = y_old - y_new; + end + if (max (abs (h)) < sqrt (eps)) + break; + end + y_old = y_new; end inv (k) = y_new; - end +end end diff --git a/matlab/missing/stats/gampdf.m b/matlab/missing/stats/gampdf.m index dfd457d7e6..74420653f9 100644 --- a/matlab/missing/stats/gampdf.m +++ b/matlab/missing/stats/gampdf.m @@ -27,45 +27,45 @@ function pdf = gampdf (x, a, b) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if (nargin ~= 3) +if (nargin ~= 3) error ('gampdf: you must give three arguments'); - end +end - if (~isscalar (a) || ~isscalar(b)) +if (~isscalar (a) || ~isscalar(b)) [retval, x, a, b] = common_size (x, a, b); if (retval > 0) - error ('gampdf: x, a and b must be of common size or scalars'); + error ('gampdf: x, a and b must be of common size or scalars'); end - end +end - sz = size(x); - pdf = zeros (sz); +sz = size(x); +pdf = zeros (sz); - k = find (~(a > 0) | ~(b > 0) | isnan (x)); - if (any (k)) +k = find (~(a > 0) | ~(b > 0) | isnan (x)); +if (any (k)) pdf (k) = NaN; - end +end - k = find ((x > 0) & (a > 0) & (a <= 1) & (b > 0)); - if (any (k)) +k = find ((x > 0) & (a > 0) & (a <= 1) & (b > 0)); +if (any (k)) if (isscalar(a) && isscalar(b)) - pdf(k) = (x(k) .^ (a - 1)) ... - .* exp(- x(k) ./ b) ./ gamma (a) ./ (b .^ a); + pdf(k) = (x(k) .^ (a - 1)) ... + .* exp(- x(k) ./ b) ./ gamma (a) ./ (b .^ a); else - pdf(k) = (x(k) .^ (a(k) - 1)) ... - .* exp(- x(k) ./ b(k)) ./ gamma (a(k)) ./ (b(k) .^ a(k)); + pdf(k) = (x(k) .^ (a(k) - 1)) ... + .* exp(- x(k) ./ b(k)) ./ gamma (a(k)) ./ (b(k) .^ a(k)); end - end +end - k = find ((x > 0) & (a > 1) & (b > 0)); - if (any (k)) +k = find ((x > 0) & (a > 1) & (b > 0)); +if (any (k)) if (isscalar(a) && isscalar(b)) - pdf(k) = exp (- a .* log (b) + (a-1) .* log (x(k)) ... - - x(k) ./ b - gammaln (a)); + pdf(k) = exp (- a .* log (b) + (a-1) .* log (x(k)) ... + - x(k) ./ b - gammaln (a)); else - pdf(k) = exp (- a(k) .* log (b(k)) + (a(k)-1) .* log (x(k)) ... - - x(k) ./ b(k) - gammaln (a(k))); + pdf(k) = exp (- a(k) .* log (b(k)) + (a(k)-1) .* log (x(k)) ... + - x(k) ./ b(k) - gammaln (a(k))); end - end +end end diff --git a/matlab/missing/stats/gamrnd.m b/matlab/missing/stats/gamrnd.m index 5260832bb7..e1139944cd 100644 --- a/matlab/missing/stats/gamrnd.m +++ b/matlab/missing/stats/gamrnd.m @@ -39,14 +39,14 @@ if nargin==2 if any(a<1) method = 'Devroye'; Devroye.small = 'Best'; % 'Weibull' , 'Johnk' , 'Berman' , 'GS' , 'Best' - % REMARK: The first algorithm (Weibull) is producing too much extreme values. + % REMARK: The first algorithm (Weibull) is producing too much extreme values. end if ~strcmpi(method,'BauwensLubranoRichard') Devroye.big = 'Best'; % 'Cheng' , 'Best' - % REMARK 1: The first algorithm (Cheng) is still producing obviously wrong simulations. - % REMARK 2: The second algorithm seems slightly slower than the algorithm advocated by Bauwens, - % Lubrano and Richard, but the comparison depends on the value of a (this should be - % investigated further). + % REMARK 1: The first algorithm (Cheng) is still producing obviously wrong simulations. + % REMARK 2: The second algorithm seems slightly slower than the algorithm advocated by Bauwens, + % Lubrano and Richard, but the comparison depends on the value of a (this should be + % investigated further). end end @@ -131,277 +131,276 @@ end - + function gamma_variates = weibull_rejection_algorithm(a,b) - nn = length(a); - mm = nn; - cc = 1./a ; - dd = a.^(a./(1-a)).*(1-a); - ZE = NaN(nn,2); - X = NaN(nn,1); - INDEX = 1:mm; - index = INDEX; - while mm - ZE(index,:) = exprnd(ones(mm,2)); - X(index) = ZE(index,1).^cc(index); - id = find( (ZE(:,1)+ZE(:,2) > dd + X) ); - if isempty(id) - mm = 0; - else - index = INDEX(id); - mm = length(index); - end +nn = length(a); +mm = nn; +cc = 1./a ; +dd = a.^(a./(1-a)).*(1-a); +ZE = NaN(nn,2); +X = NaN(nn,1); +INDEX = 1:mm; +index = INDEX; +while mm + ZE(index,:) = exprnd(ones(mm,2)); + X(index) = ZE(index,1).^cc(index); + id = find( (ZE(:,1)+ZE(:,2) > dd + X) ); + if isempty(id) + mm = 0; + else + index = INDEX(id); + mm = length(index); end - gamma_variates = X.*b; +end +gamma_variates = X.*b; + - function gamma_variates = johnk_algorithm(a,b) - nn = length(a); - mm = nn; - aa = 1./a ; - bb = 1./b ; - INDEX = 1:mm; - index = INDEX; - UV = NaN(nn,2); - X = NaN(nn,1); - Y = NaN(nn,1); - while mm - UV(index,:) = rand(mm,2); - X(index) = UV(index,1).^aa(index); - Y(index) = UV(index,2).^bb(index); - id = find(X+Y>1); - if isempty(id) - mm = 0; - else - index = INDEX(id); - mm = length(index); - end +nn = length(a); +mm = nn; +aa = 1./a ; +bb = 1./b ; +INDEX = 1:mm; +index = INDEX; +UV = NaN(nn,2); +X = NaN(nn,1); +Y = NaN(nn,1); +while mm + UV(index,:) = rand(mm,2); + X(index) = UV(index,1).^aa(index); + Y(index) = UV(index,2).^bb(index); + id = find(X+Y>1); + if isempty(id) + mm = 0; + else + index = INDEX(id); + mm = length(index); end - gamma_variates = exprnd(ones(nn,1)).*X./(X+Y); - +end +gamma_variates = exprnd(ones(nn,1)).*X./(X+Y); + function gamma_variates = berman_algorithm(a,b) - nn = length(a); - mm = nn; - aa = 1./a ; - cc = 1./(1-a) ; - INDEX = 1:mm; - index = INDEX; - UV = NaN(nn,2); - X = NaN(nn,1); - Y = NaN(nn,1); - while mm - UV(index,:) = rand(mm,2); - X(index) = UV(index,1).^aa(index); - Y(index) = UV(index,2).^cc(index); - id = find(X+Y>1); - if isempty(id) - mm = 0; - else - index = INDEX(id); - mm = length(index); - end +nn = length(a); +mm = nn; +aa = 1./a ; +cc = 1./(1-a) ; +INDEX = 1:mm; +index = INDEX; +UV = NaN(nn,2); +X = NaN(nn,1); +Y = NaN(nn,1); +while mm + UV(index,:) = rand(mm,2); + X(index) = UV(index,1).^aa(index); + Y(index) = UV(index,2).^cc(index); + id = find(X+Y>1); + if isempty(id) + mm = 0; + else + index = INDEX(id); + mm = length(index); end - Z = gamrnd(2*ones(nn,1),ones(nn,1)); - gamma_variates = Z.*X.*b ; - +end +Z = gamrnd(2*ones(nn,1),ones(nn,1)); +gamma_variates = Z.*X.*b ; + function gamma_variates = ahrens_dieter_algorithm(a,b) - nn = length(a); - mm = nn; - bb = (exp(1)+a)/exp(1); - cc = 1./a; - INDEX = 1:mm; - index = INDEX; - UW = NaN(nn,2); - V = NaN(nn,1); - X = NaN(nn,1); - while mm - UW(index,:) = rand(mm,2); - V(index) = UW(index,1).*bb(index); - state1 = find(V(index)<=1); - state2 = find(V(index)>1);%setdiff(index,index(state1)); - ID = []; - if ~isempty(state1) - X(index(state1)) = V(index(state1)).^cc(index(state1)); - test1 = UW(index(state1),2) <= exp(-X(index(state1))) ; - id1 = find(~test1); - ID = INDEX(index(state1(id1))); - end - if ~isempty(state2) - X(index(state2)) = -log(cc(index(state2)).*(bb(index(state2))-V(index(state2)))); - test2 = UW(index(state2),2) <= X(index(state2)).^(a(index(state2))-1); - id2 = find(~test2); - if isempty(ID) - ID = INDEX(index(state2(id2))); - else - ID = [ID,INDEX(index(state2(id2)))]; - end - end - mm = length(ID); - if mm - index = ID; +nn = length(a); +mm = nn; +bb = (exp(1)+a)/exp(1); +cc = 1./a; +INDEX = 1:mm; +index = INDEX; +UW = NaN(nn,2); +V = NaN(nn,1); +X = NaN(nn,1); +while mm + UW(index,:) = rand(mm,2); + V(index) = UW(index,1).*bb(index); + state1 = find(V(index)<=1); + state2 = find(V(index)>1);%setdiff(index,index(state1)); + ID = []; + if ~isempty(state1) + X(index(state1)) = V(index(state1)).^cc(index(state1)); + test1 = UW(index(state1),2) <= exp(-X(index(state1))) ; + id1 = find(~test1); + ID = INDEX(index(state1(id1))); + end + if ~isempty(state2) + X(index(state2)) = -log(cc(index(state2)).*(bb(index(state2))-V(index(state2)))); + test2 = UW(index(state2),2) <= X(index(state2)).^(a(index(state2))-1); + id2 = find(~test2); + if isempty(ID) + ID = INDEX(index(state2(id2))); + else + ID = [ID,INDEX(index(state2(id2)))]; end end - gamma_variates = X.*b ; - + mm = length(ID); + if mm + index = ID; + end +end +gamma_variates = X.*b ; + function gamma_variates = best_1983_algorithm(a,b) - nn = length(a); - mm = nn; - tt = .07 + .75*sqrt(1-a); - bb = 1 + exp(-tt).*a./tt; - cc = 1./a; - INDEX = 1:mm; - index = INDEX; - UW = NaN(nn,2); - V = NaN(nn,1); - X = NaN(nn,1); - Y = NaN(nn,1); - while mm - UW(index,:) = rand(mm,2); - V(index) = UW(index,1).*bb(index); - state1 = find(V(index)<=1); - state2 = find(V(index)>1);%setdiff(index,index(state1)); - ID = []; - if ~isempty(state1) - X(index(state1)) = tt(index(state1)).*V(index(state1)).^cc(index(state1)); - test11 = UW(index(state1),2) <= (2-X(index(state1)))./(2+X(index(state1))) ; - id11 = find(~test11); - if ~isempty(id11) - test12 = UW(index(state1(id11)),2) <= exp(-X(index(state1(id11)))) ; - id12 = find(~test12); - else - id12 = []; - end - ID = INDEX(index(state1(id11(id12)))); +nn = length(a); +mm = nn; +tt = .07 + .75*sqrt(1-a); +bb = 1 + exp(-tt).*a./tt; +cc = 1./a; +INDEX = 1:mm; +index = INDEX; +UW = NaN(nn,2); +V = NaN(nn,1); +X = NaN(nn,1); +Y = NaN(nn,1); +while mm + UW(index,:) = rand(mm,2); + V(index) = UW(index,1).*bb(index); + state1 = find(V(index)<=1); + state2 = find(V(index)>1);%setdiff(index,index(state1)); + ID = []; + if ~isempty(state1) + X(index(state1)) = tt(index(state1)).*V(index(state1)).^cc(index(state1)); + test11 = UW(index(state1),2) <= (2-X(index(state1)))./(2+X(index(state1))) ; + id11 = find(~test11); + if ~isempty(id11) + test12 = UW(index(state1(id11)),2) <= exp(-X(index(state1(id11)))) ; + id12 = find(~test12); + else + id12 = []; end - if ~isempty(state2) - X(index(state2)) = -log(cc(index(state2)).*tt(index(state2)).*(bb(index(state2))-V(index(state2)))) ; - Y(index(state2)) = X(index(state2))./tt(index(state2)) ; - test21 = UW(index(state2),2).*(a(index(state2)) + Y(index(state2)) - a(index(state2)).*Y(index(state2)) ) <= 1 ; - id21 = find(~test21); - if ~isempty(id21) - test22 = UW(index(state2(id21)),2) <= Y(index(state2(id21))).^(a(index(state2(id21)))-1) ; - id22 = find(~test22); - else - id22 = []; - end - if isempty(ID) - ID = INDEX(index(state2(id21(id22)))); - else - ID = [ID,INDEX(index(state2(id21(id22))))]; - end + ID = INDEX(index(state1(id11(id12)))); + end + if ~isempty(state2) + X(index(state2)) = -log(cc(index(state2)).*tt(index(state2)).*(bb(index(state2))-V(index(state2)))) ; + Y(index(state2)) = X(index(state2))./tt(index(state2)) ; + test21 = UW(index(state2),2).*(a(index(state2)) + Y(index(state2)) - a(index(state2)).*Y(index(state2)) ) <= 1 ; + id21 = find(~test21); + if ~isempty(id21) + test22 = UW(index(state2(id21)),2) <= Y(index(state2(id21))).^(a(index(state2(id21)))-1) ; + id22 = find(~test22); + else + id22 = []; end - mm = length(ID); - if mm - index = ID; + if isempty(ID) + ID = INDEX(index(state2(id21(id22)))); + else + ID = [ID,INDEX(index(state2(id21(id22))))]; end end - gamma_variates = X.*b ; - - + mm = length(ID); + if mm + index = ID; + end +end +gamma_variates = X.*b ; + + function gamma_variates = knuth_algorithm(a,b) - nn = length(a); - mm = nn; - bb = sqrt(2*a-1); - dd = 1./(a-1); - Y = NaN(nn,1); - X = NaN(nn,1); - INDEX = 1:mm; - index = INDEX; - while mm - Y(index) = tan(pi*rand(mm,1)); - X(index) = Y(index).*bb(index) + a(index) - 1 ; - idy1 = find(X(index)>=0); - idn1 = setdiff(index,index(idy1)); - if ~isempty(idy1) - test = log(rand(length(idy1),1)) <= ... - log(1+Y(index(idy1)).*Y(index(idy1))) + ... - (a(index(idy1))-1).*log(X(index(idy1)).*dd(index(idy1))) - ... - Y(index(idy1)).*bb(index(idy1)) ; - idy2 = find(test); - idn2 = setdiff(idy1,idy1(idy2)); - else - idy2 = []; - idn2 = []; - end - index = [ INDEX(idn1) , INDEX(index(idn2)) ] ; - mm = length(index); +nn = length(a); +mm = nn; +bb = sqrt(2*a-1); +dd = 1./(a-1); +Y = NaN(nn,1); +X = NaN(nn,1); +INDEX = 1:mm; +index = INDEX; +while mm + Y(index) = tan(pi*rand(mm,1)); + X(index) = Y(index).*bb(index) + a(index) - 1 ; + idy1 = find(X(index)>=0); + idn1 = setdiff(index,index(idy1)); + if ~isempty(idy1) + test = log(rand(length(idy1),1)) <= ... + log(1+Y(index(idy1)).*Y(index(idy1))) + ... + (a(index(idy1))-1).*log(X(index(idy1)).*dd(index(idy1))) - ... + Y(index(idy1)).*bb(index(idy1)) ; + idy2 = find(test); + idn2 = setdiff(idy1,idy1(idy2)); + else + idy2 = []; + idn2 = []; end - gamma_variates = X.*b; - + index = [ INDEX(idn1) , INDEX(index(idn2)) ] ; + mm = length(index); +end +gamma_variates = X.*b; + function gamma_variates = cheng_algorithm(a,b) - nn = length(a); - mm = nn; - bb = a-log(4); - cc = a+sqrt(2*a-1); - UV = NaN(nn,2); - Y = NaN(nn,1); - X = NaN(nn,1); - Z = NaN(nn,1); - R = NaN(nn,1); - index = 1:nn; - INDEX = index; - while mm - UV(index,:) = rand(mm,2); - Y(index) = a(index).*log(UV(index,2)./(1-UV(index,2))); - X(index) = a(index).*exp(UV(index,2)); - Z(index) = UV(index,1).*UV(index,2).*UV(index,2); - R(index) = bb(index) + cc(index).*Y(index)-X(index); - test1 = (R(index) >= 4.5*Z(index)-(1+log(4.5))); - jndex = index(find(test1)); - Jndex = setdiff(index,jndex); - if ~isempty(Jndex) - test2 = (R(Jndex) >= log(Z(Jndex))); - lndex = Jndex(find(test2)); - Lndex = setdiff(Jndex,lndex); - else - Lndex = []; - end - index = INDEX(Lndex); - mm = length(index); +nn = length(a); +mm = nn; +bb = a-log(4); +cc = a+sqrt(2*a-1); +UV = NaN(nn,2); +Y = NaN(nn,1); +X = NaN(nn,1); +Z = NaN(nn,1); +R = NaN(nn,1); +index = 1:nn; +INDEX = index; +while mm + UV(index,:) = rand(mm,2); + Y(index) = a(index).*log(UV(index,2)./(1-UV(index,2))); + X(index) = a(index).*exp(UV(index,2)); + Z(index) = UV(index,1).*UV(index,2).*UV(index,2); + R(index) = bb(index) + cc(index).*Y(index)-X(index); + test1 = (R(index) >= 4.5*Z(index)-(1+log(4.5))); + jndex = index(find(test1)); + Jndex = setdiff(index,jndex); + if ~isempty(Jndex) + test2 = (R(Jndex) >= log(Z(Jndex))); + lndex = Jndex(find(test2)); + Lndex = setdiff(Jndex,lndex); + else + Lndex = []; end - gamma_variates = X.*b; - - + index = INDEX(Lndex); + mm = length(index); +end +gamma_variates = X.*b; + + function gamma_variates = best_1978_algorithm(a,b) - nn = length(a); - mm = nn; - bb = a-1; - cc = 3*a-.75; - UV = NaN(nn,2); - Y = NaN(nn,1); - X = NaN(nn,1); - Z = NaN(nn,1); - W = NaN(nn,1); - index = 1:nn; - INDEX = index; - while mm - UV(index,:) = rand(mm,2); - W(index) = UV(index,1).*(1-UV(index,1)); - Y(index) = sqrt(cc(index)./W(index)).*(UV(index,1)-.5); - X(index) = bb(index)+Y(index); - jndex = index(find(X(index)>=0)); - Jndex = setdiff(index,jndex); - if ~isempty(jndex) - Z(jndex) = 64*W(jndex).*W(jndex).*W(jndex).*UV(jndex,2).*UV(jndex,2); - kndex = jndex(find(Z(jndex)<=1-2*Y(jndex).*Y(jndex)./X(jndex))); - Kndex = setdiff(jndex,kndex); - if ~isempty(Kndex) - lndex = Kndex(find(log(Z(Kndex))<=2*(bb(Kndex).*log(X(Kndex)./bb(Kndex))-Y(Kndex)))); - Lndex = setdiff(Kndex,lndex); - else - Lndex = []; - end - new_index = INDEX(Lndex); - %mm = length(index); +nn = length(a); +mm = nn; +bb = a-1; +cc = 3*a-.75; +UV = NaN(nn,2); +Y = NaN(nn,1); +X = NaN(nn,1); +Z = NaN(nn,1); +W = NaN(nn,1); +index = 1:nn; +INDEX = index; +while mm + UV(index,:) = rand(mm,2); + W(index) = UV(index,1).*(1-UV(index,1)); + Y(index) = sqrt(cc(index)./W(index)).*(UV(index,1)-.5); + X(index) = bb(index)+Y(index); + jndex = index(find(X(index)>=0)); + Jndex = setdiff(index,jndex); + if ~isempty(jndex) + Z(jndex) = 64*W(jndex).*W(jndex).*W(jndex).*UV(jndex,2).*UV(jndex,2); + kndex = jndex(find(Z(jndex)<=1-2*Y(jndex).*Y(jndex)./X(jndex))); + Kndex = setdiff(jndex,kndex); + if ~isempty(Kndex) + lndex = Kndex(find(log(Z(Kndex))<=2*(bb(Kndex).*log(X(Kndex)./bb(Kndex))-Y(Kndex)))); + Lndex = setdiff(Kndex,lndex); + else + Lndex = []; end - index = union(new_index,INDEX(Jndex)); - mm = length(index); + new_index = INDEX(Lndex); + %mm = length(index); end - gamma_variates = X.*b; - - - \ No newline at end of file + index = union(new_index,INDEX(Jndex)); + mm = length(index); +end +gamma_variates = X.*b; + + diff --git a/matlab/missing/stats/normcdf.m b/matlab/missing/stats/normcdf.m index 4178ba15a6..06c8e14b7e 100644 --- a/matlab/missing/stats/normcdf.m +++ b/matlab/missing/stats/normcdf.m @@ -28,43 +28,43 @@ function cdf = normcdf (x, m, s) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if (~ ((nargin == 1) || (nargin == 3))) +if (~ ((nargin == 1) || (nargin == 3))) error ('normcdf: you must give one or three arguments'); - end +end - if (nargin == 1) +if (nargin == 1) m = 0; s = 1; - end +end - if (~isscalar (m) || ~isscalar (s)) +if (~isscalar (m) || ~isscalar (s)) [retval, x, m, s] = common_size (x, m, s); if (retval > 0) - error ('normcdf: x, m and s must be of common size or scalar'); + error ('normcdf: x, m and s must be of common size or scalar'); end - end +end - sz = size (x); - cdf = zeros (sz); +sz = size (x); +cdf = zeros (sz); - if (isscalar (m) && isscalar(s)) +if (isscalar (m) && isscalar(s)) if (find (isinf (m) | isnan (m) | ~(s >= 0) | ~(s < Inf))) - cdf = NaN * ones (sz); + cdf = NaN * ones (sz); else - cdf = stdnormal_cdf ((x - m) ./ s); + cdf = stdnormal_cdf ((x - m) ./ s); end - else +else k = find (isinf (m) | isnan (m) | ~(s >= 0) | ~(s < Inf)); if (any (k)) - cdf(k) = NaN; + cdf(k) = NaN; end k = find (~isinf (m) & ~isnan (m) & (s >= 0) & (s < Inf)); if (any (k)) - cdf(k) = stdnormal_cdf ((x(k) - m(k)) ./ s(k)); + cdf(k) = stdnormal_cdf ((x(k) - m(k)) ./ s(k)); end - end +end - cdf((s == 0) & (x == m)) = 0.5; +cdf((s == 0) & (x == m)) = 0.5; end diff --git a/matlab/missing/stats/norminv.m b/matlab/missing/stats/norminv.m index d98edf0563..83aae4c89b 100644 --- a/matlab/missing/stats/norminv.m +++ b/matlab/missing/stats/norminv.m @@ -28,49 +28,49 @@ function inv = norminv (x, m, s) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if (nargin ~= 1 && nargin ~= 3) +if (nargin ~= 1 && nargin ~= 3) error ('norminv: you must give one or three arguments'); - end +end - if (nargin == 1) +if (nargin == 1) m = 0; s = 1; - end +end - if (~isscalar (m) || ~isscalar (s)) +if (~isscalar (m) || ~isscalar (s)) [retval, x, m, s] = common_size (x, m, s); if (retval > 0) - error ('norminv: x, m and s must be of common size or scalars'); + error ('norminv: x, m and s must be of common size or scalars'); end - end +end - sz = size (x); - inv = zeros (sz); +sz = size (x); +inv = zeros (sz); - if (isscalar (m) && isscalar (s)) +if (isscalar (m) && isscalar (s)) if (find (isinf (m) | isnan (m) | ~(s > 0) | ~(s < Inf))) - inv = NaN * ones (sz); + inv = NaN * ones (sz); else - inv = m + s .* stdnormal_inv (x); + inv = m + s .* stdnormal_inv (x); end - else +else k = find (isinf (m) | isnan (m) | ~(s > 0) | ~(s < Inf)); if (any (k)) - inv(k) = NaN; + inv(k) = NaN; end k = find (~isinf (m) & ~isnan (m) & (s > 0) & (s < Inf)); if (any (k)) - inv(k) = m(k) + s(k) .* stdnormal_inv (x(k)); + inv(k) = m(k) + s(k) .* stdnormal_inv (x(k)); end - end +end - k = find ((s == 0) & (x > 0) & (x < 1)); - if (any (k)) +k = find ((s == 0) & (x > 0) & (x < 1)); +if (any (k)) inv(k) = m(k); - end +end - inv((s == 0) & (x == 0)) = -Inf; - inv((s == 0) & (x == 1)) = Inf; +inv((s == 0) & (x == 0)) = -Inf; +inv((s == 0) & (x == 1)) = Inf; end diff --git a/matlab/missing/stats/normpdf.m b/matlab/missing/stats/normpdf.m index 3459b9403f..5b7e96045d 100644 --- a/matlab/missing/stats/normpdf.m +++ b/matlab/missing/stats/normpdf.m @@ -28,44 +28,44 @@ function pdf = normpdf (x, m, s) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if (nargin ~= 1 && nargin ~= 3) +if (nargin ~= 1 && nargin ~= 3) error('normpdf: you must give one or three arguments'); - end +end - if (nargin == 1) +if (nargin == 1) m = 0; s = 1; - end +end - if (~isscalar (m) || ~isscalar (s)) +if (~isscalar (m) || ~isscalar (s)) [retval, x, m, s] = common_size (x, m, s); if (retval > 0) - error ('normpdf: x, m and s must be of common size or scalars'); + error ('normpdf: x, m and s must be of common size or scalars'); end - end +end - sz = size (x); - pdf = zeros (sz); +sz = size (x); +pdf = zeros (sz); - if (isscalar (m) && isscalar (s)) +if (isscalar (m) && isscalar (s)) if (find (isinf (m) | isnan (m) | ~(s >= 0) | ~(s < Inf))) - pdf = NaN * ones (sz); + pdf = NaN * ones (sz); else - pdf = stdnormal_pdf ((x - m) ./ s) ./ s; + pdf = stdnormal_pdf ((x - m) ./ s) ./ s; end - else +else k = find (isinf (m) | isnan (m) | ~(s >= 0) | ~(s < Inf)); if (any (k)) - pdf(k) = NaN; + pdf(k) = NaN; end k = find (~isinf (m) & ~isnan (m) & (s >= 0) & (s < Inf)); if (any (k)) - pdf(k) = stdnormal_pdf ((x(k) - m(k)) ./ s(k)) ./ s(k); + pdf(k) = stdnormal_pdf ((x(k) - m(k)) ./ s(k)) ./ s(k); end - end +end - pdf((s == 0) & (x == m)) = Inf; - pdf((s == 0) & ((x < m) | (x > m))) = 0; +pdf((s == 0) & (x == m)) = Inf; +pdf((s == 0) & ((x < m) | (x > m))) = 0; end diff --git a/matlab/missing/stats/stdnormal_cdf.m b/matlab/missing/stats/stdnormal_cdf.m index a84f76eb61..38c955f14e 100644 --- a/matlab/missing/stats/stdnormal_cdf.m +++ b/matlab/missing/stats/stdnormal_cdf.m @@ -27,15 +27,15 @@ function cdf = stdnormal_cdf (x) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if (nargin ~= 1) +if (nargin ~= 1) error('stdnormal_cdf: you should provide one argument'); - end +end - sz = size (x); - if (numel(x) == 0) +sz = size (x); +if (numel(x) == 0) error ('stdnormal_cdf: x must not be empty'); - end +end - cdf = (ones (sz) + erf (x / sqrt (2))) / 2; +cdf = (ones (sz) + erf (x / sqrt (2))) / 2; end diff --git a/matlab/missing/stats/stdnormal_inv.m b/matlab/missing/stats/stdnormal_inv.m index 05bac4db00..008fd36125 100644 --- a/matlab/missing/stats/stdnormal_inv.m +++ b/matlab/missing/stats/stdnormal_inv.m @@ -27,11 +27,11 @@ function inv = stdnormal_inv (x) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if (nargin ~= 1) +if (nargin ~= 1) error('stdnormal_inv: you should provide one argument'); - end +end - inv = sqrt (2) * erfinv (2 * x - 1); +inv = sqrt (2) * erfinv (2 * x - 1); end diff --git a/matlab/missing/stats/stdnormal_pdf.m b/matlab/missing/stats/stdnormal_pdf.m index 4b7dce504e..3db92cd511 100644 --- a/matlab/missing/stats/stdnormal_pdf.m +++ b/matlab/missing/stats/stdnormal_pdf.m @@ -27,21 +27,21 @@ function pdf = stdnormal_pdf (x) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if (nargin ~= 1) +if (nargin ~= 1) error('stdnormal_pdf: you should provide one argument'); - end +end - sz = size(x); - pdf = zeros (sz); +sz = size(x); +pdf = zeros (sz); - k = find (isnan (x)); - if (any (k)) +k = find (isnan (x)); +if (any (k)) pdf(k) = NaN; - end +end - k = find (~isinf (x)); - if (any (k)) +k = find (~isinf (x)); +if (any (k)) pdf (k) = (2 * pi)^(- 1/2) * exp (- x(k) .^ 2 / 2); - end +end end diff --git a/matlab/missing_DiffuseKalmanSmoother1.m b/matlab/missing_DiffuseKalmanSmoother1.m index d86830f526..cb70be9565 100644 --- a/matlab/missing_DiffuseKalmanSmoother1.m +++ b/matlab/missing_DiffuseKalmanSmoother1.m @@ -1,207 +1,207 @@ -function [alphahat,etahat,atilde, aK] = DiffuseKalmanSmoother1(T,R,Q,Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf,data_index) - -% function [alphahat,etahat,a, aK] = DiffuseKalmanSmoother1(T,R,Q,Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf) -% Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix -% -% INPUTS -% T: mm*mm matrix -% R: mm*rr matrix -% Q: rr*rr matrix -% Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros -% Pstar1: mm*mm variance-covariance matrix with stationary variables -% Y: pp*1 vector -% trend -% pp: number of observed variables -% mm: number of state variables -% smpl: sample size -% mf: observed variables index in the state vector -% data_index [cell] 1*smpl cell of column vectors of indices. -% -% OUTPUTS -% alphahat: smoothed state variables (a_{t|T}) -% etahat: smoothed shocks -% atilde: matrix of updated variables (a_{t|t}) -% aK: 3D array of k step ahead filtered state variables (a_{t+k|t}) - -% SPECIAL REQUIREMENTS -% See "Filtering and Smoothing of State Vector for Diffuse State Space -% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series -% Analysis, vol. 24(1), pp. 85-98). - -% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. - -% modified by M. Ratto: -% new output argument aK (1-step to k-step predictions) -% new options_.nk: the max step ahed prediction in aK (default is 4) -% new crit1 value for rank of Pinf -% it is assured that P is symmetric - - -global options_ - -nk = options_.nk; -spinf = size(Pinf1); -spstar = size(Pstar1); -v = zeros(pp,smpl); -a = zeros(mm,smpl+1); -atilde = zeros(mm,smpl); -aK = zeros(nk,mm,smpl+1); -iF = zeros(pp,pp,smpl); -Fstar = zeros(pp,pp,smpl); -iFinf = zeros(pp,pp,smpl); -K = zeros(mm,pp,smpl); -L = zeros(mm,mm,smpl); -Linf = zeros(mm,mm,smpl); -Kstar = zeros(mm,pp,smpl); -P = zeros(mm,mm,smpl+1); -Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1; -Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1; -crit = options_.kalman_tol; -crit1 = 1.e-8; -steady = smpl; -rr = size(Q,1); -QQ = R*Q*transpose(R); -QRt = Q*transpose(R); -alphahat = zeros(mm,smpl); -etahat = zeros(rr,smpl); -r = zeros(mm,smpl+1); - -Z = zeros(pp,mm); -for i=1:pp; - Z(i,mf(i)) = 1; -end - -t = 0; -while rank(Pinf(:,:,t+1),crit1) & t<smpl - t = t+1; - di = data_index{t}; - if isempty(di) - atilde(:,t) = a(:,t); - Linf(:,:,t) = T; - Pstar(:,:,t+1) = T*Pstar(:,:,t)*T' + QQ; - Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'; - else - mf1 = mf(di); - v(di,t)= Y(di,t) - a(mf1,t) - trend(di,t); - if rcond(Pinf(mf1,mf1,t)) < crit - return - end - iFinf(di,di,t) = inv(Pinf(mf1,mf1,t)); - PZI = Pinf(:,mf1,t)*iFinf(di,di,t); - atilde(:,t) = a(:,t) + PZI*v(di,t); - Kinf(:,di,t) = T*PZI; - a(:,t+1) = T*atilde(:,t); - Linf(:,:,t) = T - Kinf(:,di,t)*Z(di,:); - Fstar(di,di,t) = Pstar(mf1,mf1,t); - Kstar(:,di,t) = (T*Pstar(:,mf1,t)-Kinf(:,di,t)*Fstar(di,di,t))*iFinf(di,di,t); - Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)-T*Pstar(:,mf1,t)*transpose(Kinf(:,di,t))-Kinf(:,di,t)*Pinf(mf1,mf1,t)*transpose(Kstar(:,di,t)) + QQ; - Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T)-T*Pinf(:,mf1,t)* ... - transpose(Kinf(:,di,t)); - end - aK(1,:,t+1) = a(:,t+1); - for jnk=2:nk, - aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); - end -end -d = t; -P(:,:,d+1) = Pstar(:,:,d+1); -iFinf = iFinf(:,:,1:d); -Linf = Linf(:,:,1:d); -Fstar = Fstar(:,:,1:d); -Kstar = Kstar(:,:,1:d); -Pstar = Pstar(:,:,1:d); -Pinf = Pinf(:,:,1:d); -notsteady = 1; -while notsteady & t<smpl - t = t+1; - P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); - di = data_index{t}; - if isempty(di) - atilde(:,t) = a(:,t); - L(:,:,t) = T; - P(:,:,t+1) = T*P(:,:,t)*T' + QQ; - else - mf1 = mf(di); - v(di,t) = Y(di,t) - a(mf1,t) - trend(di,t); - if rcond(P(mf1,mf1,t)) < crit - return - end - iF(di,di,t) = inv(P(mf1,mf1,t)); - PZI = P(:,mf1,t)*iF(di,di,t); - atilde(:,t) = a(:,t) + PZI*v(di,t); - K(:,di,t) = T*PZI; - L(:,:,t) = T-K(:,di,t)*Z(di,:); - a(:,t+1) = T*atilde(:,t); - end - aK(1,:,t+1) = a(:,t+1); - for jnk=2:nk, - aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); - end - P(:,:,t+1) = T*P(:,:,t)*transpose(T)-T*P(:,mf,t)*transpose(K(:,:,t)) + QQ; -% notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); -end -% $$$ if t<smpl -% $$$ PZI_s = PZI; -% $$$ K_s = K(:,:,t); -% $$$ iF_s = iF(:,:,t); -% $$$ P_s = P(:,:,t+1); -% $$$ t_steady = t+1; -% $$$ P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1])); -% $$$ iF = cat(3,iF(:,:,1:t),repmat(inv(P_s(mf,mf)),[1 1 smpl-t_steady+1])); -% $$$ L = cat(3,L(:,:,1:t),repmat(T-K_s*Z,[1 1 smpl-t_steady+1])); -% $$$ K = cat(3,K(:,:,1:t),repmat(T*P_s(:,mf)*iF_s,[1 1 smpl-t_steady+1])); -% $$$ end -% $$$ while t<smpl -% $$$ t=t+1; -% $$$ v(:,t) = Y(:,t) - a(mf,t) - trend(:,t); -% $$$ atilde(:,t) = a(:,t) + PZI*v(:,t); -% $$$ a(:,t+1) = T*a(:,t) + K_s*v(:,t); -% $$$ aK(1,:,t+1) = a(:,t+1); -% $$$ for jnk=2:nk, -% $$$ aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); -% $$$ end -% $$$ end -t = smpl+1; -while t>d+1 - t = t-1; - di = data_index{t}; - if isempty(di) - r(:,t) = L(:,:,t)'*r(:,t+1); - else - r(:,t) = Z(di,:)'*iF(di,di,t)*v(di,t) + L(:,:,t)'*r(:,t+1); - end - alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t); - etahat(:,t) = QRt*r(:,t); -end -if d - r0 = zeros(mm,d+1); - r0(:,d+1) = r(:,d+1); - r1 = zeros(mm,d+1); - for t = d:-1:1 - r0(:,t) = Linf(:,:,t)'*r0(:,t+1); - di = data_index{t}; - if isempty(di) - r1(:,t) = Linf(:,:,t)'*r1(:,t+1); - else - r1(:,t) = Z(di,:)'*(iFinf(di,di,t)*v(di,t)-Kstar(:,di,t)'*r0(:,t+1)) ... - + Linf(:,:,t)'*r1(:,t+1); - end - alphahat(:,t) = a(:,t) + Pstar(:,:,t)*r0(:,t) + Pinf(:,:,t)*r1(:,t); - etahat(:,t) = QRt*r0(:,t); - end -end +function [alphahat,etahat,atilde, aK] = missing_DiffuseKalmanSmoother1(T,R,Q,Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf,data_index) + +% function [alphahat,etahat,a, aK] = DiffuseKalmanSmoother1(T,R,Q,Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf) +% Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix +% +% INPUTS +% T: mm*mm matrix +% R: mm*rr matrix +% Q: rr*rr matrix +% Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros +% Pstar1: mm*mm variance-covariance matrix with stationary variables +% Y: pp*1 vector +% trend +% pp: number of observed variables +% mm: number of state variables +% smpl: sample size +% mf: observed variables index in the state vector +% data_index [cell] 1*smpl cell of column vectors of indices. +% +% OUTPUTS +% alphahat: smoothed state variables (a_{t|T}) +% etahat: smoothed shocks +% atilde: matrix of updated variables (a_{t|t}) +% aK: 3D array of k step ahead filtered state variables (a_{t+k|t}) + +% SPECIAL REQUIREMENTS +% See "Filtering and Smoothing of State Vector for Diffuse State Space +% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series +% Analysis, vol. 24(1), pp. 85-98). + +% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. + +% modified by M. Ratto: +% new output argument aK (1-step to k-step predictions) +% new options_.nk: the max step ahed prediction in aK (default is 4) +% new crit1 value for rank of Pinf +% it is assured that P is symmetric + + +global options_ + +nk = options_.nk; +spinf = size(Pinf1); +spstar = size(Pstar1); +v = zeros(pp,smpl); +a = zeros(mm,smpl+1); +atilde = zeros(mm,smpl); +aK = zeros(nk,mm,smpl+1); +iF = zeros(pp,pp,smpl); +Fstar = zeros(pp,pp,smpl); +iFinf = zeros(pp,pp,smpl); +K = zeros(mm,pp,smpl); +L = zeros(mm,mm,smpl); +Linf = zeros(mm,mm,smpl); +Kstar = zeros(mm,pp,smpl); +P = zeros(mm,mm,smpl+1); +Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1; +Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1; +crit = options_.kalman_tol; +crit1 = 1.e-8; +steady = smpl; +rr = size(Q,1); +QQ = R*Q*transpose(R); +QRt = Q*transpose(R); +alphahat = zeros(mm,smpl); +etahat = zeros(rr,smpl); +r = zeros(mm,smpl+1); + +Z = zeros(pp,mm); +for i=1:pp; + Z(i,mf(i)) = 1; +end + +t = 0; +while rank(Pinf(:,:,t+1),crit1) & t<smpl + t = t+1; + di = data_index{t}; + if isempty(di) + atilde(:,t) = a(:,t); + Linf(:,:,t) = T; + Pstar(:,:,t+1) = T*Pstar(:,:,t)*T' + QQ; + Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'; + else + mf1 = mf(di); + v(di,t)= Y(di,t) - a(mf1,t) - trend(di,t); + if rcond(Pinf(mf1,mf1,t)) < crit + return + end + iFinf(di,di,t) = inv(Pinf(mf1,mf1,t)); + PZI = Pinf(:,mf1,t)*iFinf(di,di,t); + atilde(:,t) = a(:,t) + PZI*v(di,t); + Kinf(:,di,t) = T*PZI; + a(:,t+1) = T*atilde(:,t); + Linf(:,:,t) = T - Kinf(:,di,t)*Z(di,:); + Fstar(di,di,t) = Pstar(mf1,mf1,t); + Kstar(:,di,t) = (T*Pstar(:,mf1,t)-Kinf(:,di,t)*Fstar(di,di,t))*iFinf(di,di,t); + Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)-T*Pstar(:,mf1,t)*transpose(Kinf(:,di,t))-Kinf(:,di,t)*Pinf(mf1,mf1,t)*transpose(Kstar(:,di,t)) + QQ; + Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T)-T*Pinf(:,mf1,t)* ... + transpose(Kinf(:,di,t)); + end + aK(1,:,t+1) = a(:,t+1); + for jnk=2:nk, + aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); + end +end +d = t; +P(:,:,d+1) = Pstar(:,:,d+1); +iFinf = iFinf(:,:,1:d); +Linf = Linf(:,:,1:d); +Fstar = Fstar(:,:,1:d); +Kstar = Kstar(:,:,1:d); +Pstar = Pstar(:,:,1:d); +Pinf = Pinf(:,:,1:d); +notsteady = 1; +while notsteady & t<smpl + t = t+1; + P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); + di = data_index{t}; + if isempty(di) + atilde(:,t) = a(:,t); + L(:,:,t) = T; + P(:,:,t+1) = T*P(:,:,t)*T' + QQ; + else + mf1 = mf(di); + v(di,t) = Y(di,t) - a(mf1,t) - trend(di,t); + if rcond(P(mf1,mf1,t)) < crit + return + end + iF(di,di,t) = inv(P(mf1,mf1,t)); + PZI = P(:,mf1,t)*iF(di,di,t); + atilde(:,t) = a(:,t) + PZI*v(di,t); + K(:,di,t) = T*PZI; + L(:,:,t) = T-K(:,di,t)*Z(di,:); + a(:,t+1) = T*atilde(:,t); + end + aK(1,:,t+1) = a(:,t+1); + for jnk=2:nk, + aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); + end + P(:,:,t+1) = T*P(:,:,t)*transpose(T)-T*P(:,mf,t)*transpose(K(:,:,t)) + QQ; + % notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); +end +% $$$ if t<smpl +% $$$ PZI_s = PZI; +% $$$ K_s = K(:,:,t); +% $$$ iF_s = iF(:,:,t); +% $$$ P_s = P(:,:,t+1); +% $$$ t_steady = t+1; +% $$$ P = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1])); +% $$$ iF = cat(3,iF(:,:,1:t),repmat(inv(P_s(mf,mf)),[1 1 smpl-t_steady+1])); +% $$$ L = cat(3,L(:,:,1:t),repmat(T-K_s*Z,[1 1 smpl-t_steady+1])); +% $$$ K = cat(3,K(:,:,1:t),repmat(T*P_s(:,mf)*iF_s,[1 1 smpl-t_steady+1])); +% $$$ end +% $$$ while t<smpl +% $$$ t=t+1; +% $$$ v(:,t) = Y(:,t) - a(mf,t) - trend(:,t); +% $$$ atilde(:,t) = a(:,t) + PZI*v(:,t); +% $$$ a(:,t+1) = T*a(:,t) + K_s*v(:,t); +% $$$ aK(1,:,t+1) = a(:,t+1); +% $$$ for jnk=2:nk, +% $$$ aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); +% $$$ end +% $$$ end +t = smpl+1; +while t>d+1 + t = t-1; + di = data_index{t}; + if isempty(di) + r(:,t) = L(:,:,t)'*r(:,t+1); + else + r(:,t) = Z(di,:)'*iF(di,di,t)*v(di,t) + L(:,:,t)'*r(:,t+1); + end + alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t); + etahat(:,t) = QRt*r(:,t); +end +if d + r0 = zeros(mm,d+1); + r0(:,d+1) = r(:,d+1); + r1 = zeros(mm,d+1); + for t = d:-1:1 + r0(:,t) = Linf(:,:,t)'*r0(:,t+1); + di = data_index{t}; + if isempty(di) + r1(:,t) = Linf(:,:,t)'*r1(:,t+1); + else + r1(:,t) = Z(di,:)'*(iFinf(di,di,t)*v(di,t)-Kstar(:,di,t)'*r0(:,t+1)) ... + + Linf(:,:,t)'*r1(:,t+1); + end + alphahat(:,t) = a(:,t) + Pstar(:,:,t)*r0(:,t) + Pinf(:,:,t)*r1(:,t); + etahat(:,t) = QRt*r0(:,t); + end +end diff --git a/matlab/missing_DiffuseKalmanSmoother1_Z.m b/matlab/missing_DiffuseKalmanSmoother1_Z.m index 60edcd8f06..e06fba958d 100644 --- a/matlab/missing_DiffuseKalmanSmoother1_Z.m +++ b/matlab/missing_DiffuseKalmanSmoother1_Z.m @@ -1,238 +1,238 @@ -function [alphahat,etahat,atilde,P,aK,PK,d,decomp] = DiffuseKalmanSmoother1_Z(T,Z,R,Q,Pinf1,Pstar1,Y,pp,mm,smpl,data_index) - -% function [alphahat,etahat,a, aK] = DiffuseKalmanSmoother1(T,Z,R,Q,Pinf1,Pstar1,Y,pp,mm,smpl) -% Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix -% -% INPUTS -% T: mm*mm matrix -% Z: pp*mm matrix -% R: mm*rr matrix -% Q: rr*rr matrix -% Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros -% Pstar1: mm*mm variance-covariance matrix with stationary variables -% Y: pp*1 vector -% pp: number of observed variables -% mm: number of state variables -% smpl: sample size -% data_index [cell] 1*smpl cell of column vectors of indices. -% -% OUTPUTS -% alphahat: smoothed variables (a_{t|T}) -% etahat: smoothed shocks -% atilde: matrix of updated variables (a_{t|t}) -% aK: 3D array of k step ahead filtered state variables (a_{t+k|t) -% (meaningless for periods 1:d) -% P: 3D array of one-step ahead forecast error variance -% matrices -% PK: 4D array of k-step ahead forecast error variance -% matrices (meaningless for periods 1:d) -% d: number of periods where filter remains in diffuse part -% (should be equal to the order of integration of the model) -% decomp: decomposition of the effect of shocks on filtered values -% -% SPECIAL REQUIREMENTS -% See "Filtering and Smoothing of State Vector for Diffuse State Space -% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series -% Analysis, vol. 24(1), pp. 85-98). - -% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. - -% modified by M. Ratto: -% new output argument aK (1-step to k-step predictions) -% new options_.nk: the max step ahed prediction in aK (default is 4) -% new crit1 value for rank of Pinf -% it is assured that P is symmetric - - -global options_ - -d = 0; -decomp = []; -nk = options_.nk; -spinf = size(Pinf1); -spstar = size(Pstar1); -v = zeros(pp,smpl); -a = zeros(mm,smpl+1); -atilde = zeros(mm,smpl); -aK = zeros(nk,mm,smpl+nk); -PK = zeros(nk,mm,mm,smpl+nk); -iF = zeros(pp,pp,smpl); -Fstar = zeros(pp,pp,smpl); -iFinf = zeros(pp,pp,smpl); -K = zeros(mm,pp,smpl); -L = zeros(mm,mm,smpl); -Linf = zeros(mm,mm,smpl); -Kstar = zeros(mm,pp,smpl); -P = zeros(mm,mm,smpl+1); -Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1; -Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1; -crit = options_.kalman_tol; -crit1 = 1.e-8; -steady = smpl; -rr = size(Q,1); -QQ = R*Q*transpose(R); -QRt = Q*transpose(R); -alphahat = zeros(mm,smpl); -etahat = zeros(rr,smpl); -r = zeros(mm,smpl+1); - -t = 0; -while rank(Pinf(:,:,t+1),crit1) & t<smpl - t = t+1; - di = data_index{t}; - if isempty(di) - atilde(:,t) = a(:,t); - Linf(:,:,t) = T; - Pstar(:,:,t+1) = T*Pstar(:,:,t)*T' + QQ; - Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'; - else - ZZ = Z(di,:); - v(di,t)= Y(di,t) - ZZ*a(:,t); - F = ZZ*Pinf(:,:,t)*ZZ'; - if rcond(F) < crit - return - end - iFinf(di,di,t) = inv(F); - PZI = Pinf(:,:,t)*ZZ'*iFinf(di,di,t); - atilde(:,t) = a(:,t) + PZI*v(di,t); - Kinf(:,di,t) = T*PZI; - Linf(:,:,t) = T - Kinf(:,di,t)*ZZ; - Fstar(di,di,t) = ZZ*Pstar(:,:,t)*ZZ'; - Kstar(:,di,t) = (T*Pstar(:,:,t)*ZZ'-Kinf(:,di,t)*Fstar(di,di,t))*iFinf(di,di,t); - Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'-T*Pstar(:,:,t)*ZZ'*Kinf(:,di,t)'-Kinf(:,di,t)*F*Kstar(:,di,t)' + QQ; - Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'-T*Pinf(:,:,t)*ZZ'*Kinf(:,di,t)'; - end - a(:,t+1) = T*atilde(:,t); - aK(1,:,t+1) = a(:,t+1); - % isn't a meaningless as long as we are in the diffuse part? MJ - for jnk=2:nk, - aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); - end -end -d = t; -P(:,:,d+1) = Pstar(:,:,d+1); -iFinf = iFinf(:,:,1:d); -Linf = Linf(:,:,1:d); -Fstar = Fstar(:,:,1:d); -Kstar = Kstar(:,:,1:d); -Pstar = Pstar(:,:,1:d); -Pinf = Pinf(:,:,1:d); -notsteady = 1; -while notsteady & t<smpl - t = t+1; - P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); - di = data_index{t}; - if isempty(di) - atilde(:,t) = a(:,t); - L(:,:,t) = T; - P(:,:,t+1) = T*P(:,:,t)*T' + QQ; - else - ZZ = Z(di,:); - v(di,t) = Y(di,t) - ZZ*a(:,t); - F = ZZ*P(:,:,t)*ZZ'; - if rcond(F) < crit - return - end - iF(di,di,t) = inv(F); - PZI = P(:,:,t)*ZZ'*iF(di,di,t); - atilde(:,t) = a(:,t) + PZI*v(di,t); - K(:,di,t) = T*PZI; - L(:,:,t) = T-K(:,di,t)*ZZ; - P(:,:,t+1) = T*P(:,:,t)*T'-T*P(:,:,t)*ZZ'*K(:,di,t)' + QQ; - end - a(:,t+1) = T*atilde(:,t); - Pf = P(:,:,t); - for jnk=1:nk, - Pf = T*Pf*T' + QQ; - aK(jnk,:,t+jnk) = T^jnk*atilde(:,t); - PK(jnk,:,:,t+jnk) = Pf; - end -% notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); -end -% $$$ if t<smpl -% $$$ PZI_s = PZI; -% $$$ K_s = K(:,:,t); -% $$$ iF_s = iF(:,:,t); -% $$$ P_s = P(:,:,t+1); -% $$$ P = cat(3,P(:,:,1:t),repmat(P_s,[1 1 smpl-t])); -% $$$ iF = cat(3,iF(:,:,1:t),repmat(iF_s,[1 1 smpl-t])); -% $$$ L = cat(3,L(:,:,1:t),repmat(T-K_s*Z,[1 1 smpl-t])); -% $$$ K = cat(3,K(:,:,1:t),repmat(T*P_s*Z'*iF_s,[1 1 smpl-t])); -% $$$ end -% $$$ while t<smpl -% $$$ t=t+1; -% $$$ v(:,t) = Y(:,t) - Z*a(:,t); -% $$$ atilde(:,t) = a(:,t) + PZI*v(:,t); -% $$$ a(:,t+1) = T*atilde(:,t); -% $$$ Pf = P(:,:,t); -% $$$ for jnk=1:nk, -% $$$ Pf = T*Pf*T' + QQ; -% $$$ aK(jnk,:,t+jnk) = T^jnk*atilde(:,t); -% $$$ PK(jnk,:,:,t+jnk) = Pf; -% $$$ end -% $$$ end -t = smpl+1; -while t>d+1 - t = t-1; - di = data_index{t}; - if isempty(di) - r(:,t) = L(:,:,t)'*r(:,t+1); - else - ZZ = Z(di,:); - r(:,t) = ZZ'*iF(di,di,t)*v(di,t) + L(:,:,t)'*r(:,t+1); - end - alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t); - etahat(:,t) = QRt*r(:,t); -end -if d - r0 = zeros(mm,d+1); - r0(:,d+1) = r(:,d+1); - r1 = zeros(mm,d+1); - for t = d:-1:1 - r0(:,t) = Linf(:,:,t)'*r0(:,t+1); - di = data_index{t}; - if isempty(di) - r1(:,t) = Linf(:,:,t)'*r1(:,t+1); - else - r1(:,t) = Z(di,:)'*(iFinf(di,di,t)*v(di,t)-Kstar(:,di,t)'*r0(:,t+1)) ... - + Linf(:,:,t)'*r1(:,t+1); - end - alphahat(:,t) = a(:,t) + Pstar(:,:,t)*r0(:,t) + Pinf(:,:,t)*r1(:,t); - etahat(:,t) = QRt*r0(:,t); - end -end - -if nargout > 7 - decomp = zeros(nk,mm,rr,smpl+nk); - ZRQinv = inv(Z*QQ*Z'); - for t = max(d,1):smpl - ri_d = Z'*iF(:,:,t)*v(:,t); - - % calculate eta_tm1t - eta_tm1t = QRt*ri_d; - % calculate decomposition - Ttok = eye(mm,mm); - for h = 1:nk - for j=1:rr - eta=zeros(rr,1); - eta(j) = eta_tm1t(j); - decomp(h,:,j,t+h) = T^(h-1)*P(:,:,t)*Z'*ZRQinv*Z*R*eta; - end - end - end -end +function [alphahat,etahat,atilde,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmoother1_Z(T,Z,R,Q,Pinf1,Pstar1,Y,pp,mm,smpl,data_index) + +% function [alphahat,etahat,a, aK] = DiffuseKalmanSmoother1(T,Z,R,Q,Pinf1,Pstar1,Y,pp,mm,smpl) +% Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix +% +% INPUTS +% T: mm*mm matrix +% Z: pp*mm matrix +% R: mm*rr matrix +% Q: rr*rr matrix +% Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros +% Pstar1: mm*mm variance-covariance matrix with stationary variables +% Y: pp*1 vector +% pp: number of observed variables +% mm: number of state variables +% smpl: sample size +% data_index [cell] 1*smpl cell of column vectors of indices. +% +% OUTPUTS +% alphahat: smoothed variables (a_{t|T}) +% etahat: smoothed shocks +% atilde: matrix of updated variables (a_{t|t}) +% aK: 3D array of k step ahead filtered state variables (a_{t+k|t) +% (meaningless for periods 1:d) +% P: 3D array of one-step ahead forecast error variance +% matrices +% PK: 4D array of k-step ahead forecast error variance +% matrices (meaningless for periods 1:d) +% d: number of periods where filter remains in diffuse part +% (should be equal to the order of integration of the model) +% decomp: decomposition of the effect of shocks on filtered values +% +% SPECIAL REQUIREMENTS +% See "Filtering and Smoothing of State Vector for Diffuse State Space +% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series +% Analysis, vol. 24(1), pp. 85-98). + +% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. + +% modified by M. Ratto: +% new output argument aK (1-step to k-step predictions) +% new options_.nk: the max step ahed prediction in aK (default is 4) +% new crit1 value for rank of Pinf +% it is assured that P is symmetric + + +global options_ + +d = 0; +decomp = []; +nk = options_.nk; +spinf = size(Pinf1); +spstar = size(Pstar1); +v = zeros(pp,smpl); +a = zeros(mm,smpl+1); +atilde = zeros(mm,smpl); +aK = zeros(nk,mm,smpl+nk); +PK = zeros(nk,mm,mm,smpl+nk); +iF = zeros(pp,pp,smpl); +Fstar = zeros(pp,pp,smpl); +iFinf = zeros(pp,pp,smpl); +K = zeros(mm,pp,smpl); +L = zeros(mm,mm,smpl); +Linf = zeros(mm,mm,smpl); +Kstar = zeros(mm,pp,smpl); +P = zeros(mm,mm,smpl+1); +Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1; +Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1; +crit = options_.kalman_tol; +crit1 = 1.e-8; +steady = smpl; +rr = size(Q,1); +QQ = R*Q*transpose(R); +QRt = Q*transpose(R); +alphahat = zeros(mm,smpl); +etahat = zeros(rr,smpl); +r = zeros(mm,smpl+1); + +t = 0; +while rank(Pinf(:,:,t+1),crit1) & t<smpl + t = t+1; + di = data_index{t}; + if isempty(di) + atilde(:,t) = a(:,t); + Linf(:,:,t) = T; + Pstar(:,:,t+1) = T*Pstar(:,:,t)*T' + QQ; + Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'; + else + ZZ = Z(di,:); + v(di,t)= Y(di,t) - ZZ*a(:,t); + F = ZZ*Pinf(:,:,t)*ZZ'; + if rcond(F) < crit + return + end + iFinf(di,di,t) = inv(F); + PZI = Pinf(:,:,t)*ZZ'*iFinf(di,di,t); + atilde(:,t) = a(:,t) + PZI*v(di,t); + Kinf(:,di,t) = T*PZI; + Linf(:,:,t) = T - Kinf(:,di,t)*ZZ; + Fstar(di,di,t) = ZZ*Pstar(:,:,t)*ZZ'; + Kstar(:,di,t) = (T*Pstar(:,:,t)*ZZ'-Kinf(:,di,t)*Fstar(di,di,t))*iFinf(di,di,t); + Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'-T*Pstar(:,:,t)*ZZ'*Kinf(:,di,t)'-Kinf(:,di,t)*F*Kstar(:,di,t)' + QQ; + Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'-T*Pinf(:,:,t)*ZZ'*Kinf(:,di,t)'; + end + a(:,t+1) = T*atilde(:,t); + aK(1,:,t+1) = a(:,t+1); + % isn't a meaningless as long as we are in the diffuse part? MJ + for jnk=2:nk, + aK(jnk,:,t+jnk) = T^(jnk-1)*a(:,t+1); + end +end +d = t; +P(:,:,d+1) = Pstar(:,:,d+1); +iFinf = iFinf(:,:,1:d); +Linf = Linf(:,:,1:d); +Fstar = Fstar(:,:,1:d); +Kstar = Kstar(:,:,1:d); +Pstar = Pstar(:,:,1:d); +Pinf = Pinf(:,:,1:d); +notsteady = 1; +while notsteady & t<smpl + t = t+1; + P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); + di = data_index{t}; + if isempty(di) + atilde(:,t) = a(:,t); + L(:,:,t) = T; + P(:,:,t+1) = T*P(:,:,t)*T' + QQ; + else + ZZ = Z(di,:); + v(di,t) = Y(di,t) - ZZ*a(:,t); + F = ZZ*P(:,:,t)*ZZ'; + if rcond(F) < crit + return + end + iF(di,di,t) = inv(F); + PZI = P(:,:,t)*ZZ'*iF(di,di,t); + atilde(:,t) = a(:,t) + PZI*v(di,t); + K(:,di,t) = T*PZI; + L(:,:,t) = T-K(:,di,t)*ZZ; + P(:,:,t+1) = T*P(:,:,t)*T'-T*P(:,:,t)*ZZ'*K(:,di,t)' + QQ; + end + a(:,t+1) = T*atilde(:,t); + Pf = P(:,:,t); + for jnk=1:nk, + Pf = T*Pf*T' + QQ; + aK(jnk,:,t+jnk) = T^jnk*atilde(:,t); + PK(jnk,:,:,t+jnk) = Pf; + end + % notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); +end +% $$$ if t<smpl +% $$$ PZI_s = PZI; +% $$$ K_s = K(:,:,t); +% $$$ iF_s = iF(:,:,t); +% $$$ P_s = P(:,:,t+1); +% $$$ P = cat(3,P(:,:,1:t),repmat(P_s,[1 1 smpl-t])); +% $$$ iF = cat(3,iF(:,:,1:t),repmat(iF_s,[1 1 smpl-t])); +% $$$ L = cat(3,L(:,:,1:t),repmat(T-K_s*Z,[1 1 smpl-t])); +% $$$ K = cat(3,K(:,:,1:t),repmat(T*P_s*Z'*iF_s,[1 1 smpl-t])); +% $$$ end +% $$$ while t<smpl +% $$$ t=t+1; +% $$$ v(:,t) = Y(:,t) - Z*a(:,t); +% $$$ atilde(:,t) = a(:,t) + PZI*v(:,t); +% $$$ a(:,t+1) = T*atilde(:,t); +% $$$ Pf = P(:,:,t); +% $$$ for jnk=1:nk, +% $$$ Pf = T*Pf*T' + QQ; +% $$$ aK(jnk,:,t+jnk) = T^jnk*atilde(:,t); +% $$$ PK(jnk,:,:,t+jnk) = Pf; +% $$$ end +% $$$ end +t = smpl+1; +while t>d+1 + t = t-1; + di = data_index{t}; + if isempty(di) + r(:,t) = L(:,:,t)'*r(:,t+1); + else + ZZ = Z(di,:); + r(:,t) = ZZ'*iF(di,di,t)*v(di,t) + L(:,:,t)'*r(:,t+1); + end + alphahat(:,t) = a(:,t) + P(:,:,t)*r(:,t); + etahat(:,t) = QRt*r(:,t); +end +if d + r0 = zeros(mm,d+1); + r0(:,d+1) = r(:,d+1); + r1 = zeros(mm,d+1); + for t = d:-1:1 + r0(:,t) = Linf(:,:,t)'*r0(:,t+1); + di = data_index{t}; + if isempty(di) + r1(:,t) = Linf(:,:,t)'*r1(:,t+1); + else + r1(:,t) = Z(di,:)'*(iFinf(di,di,t)*v(di,t)-Kstar(:,di,t)'*r0(:,t+1)) ... + + Linf(:,:,t)'*r1(:,t+1); + end + alphahat(:,t) = a(:,t) + Pstar(:,:,t)*r0(:,t) + Pinf(:,:,t)*r1(:,t); + etahat(:,t) = QRt*r0(:,t); + end +end + +if nargout > 7 + decomp = zeros(nk,mm,rr,smpl+nk); + ZRQinv = inv(Z*QQ*Z'); + for t = max(d,1):smpl + ri_d = Z'*iF(:,:,t)*v(:,t); + + % calculate eta_tm1t + eta_tm1t = QRt*ri_d; + % calculate decomposition + Ttok = eye(mm,mm); + for h = 1:nk + for j=1:rr + eta=zeros(rr,1); + eta(j) = eta_tm1t(j); + decomp(h,:,j,t+h) = T^(h-1)*P(:,:,t)*Z'*ZRQinv*Z*R*eta; + end + end + end +end diff --git a/matlab/missing_DiffuseKalmanSmoother3.m b/matlab/missing_DiffuseKalmanSmoother3.m index 9929f24def..26f766bb01 100644 --- a/matlab/missing_DiffuseKalmanSmoother3.m +++ b/matlab/missing_DiffuseKalmanSmoother3.m @@ -71,9 +71,9 @@ aK = zeros(nk,mm,smpl+nk); PK = zeros(nk,mm,mm,smpl+nk); if isempty(options_.diffuse_d), - smpl_diff = 1; + smpl_diff = 1; else - smpl_diff=rank(Pinf1); + smpl_diff=rank(Pinf1); end Fstar = zeros(pp,smpl_diff); @@ -102,82 +102,82 @@ r = zeros(mm,smpl+1); Z = zeros(pp,mm); for i=1:pp; - Z(i,mf(i)) = 1; + Z(i,mf(i)) = 1; end t = 0; icc=0; newRank = rank(Pinf(:,:,1),crit1); while newRank & t < smpl - t = t+1; - a(:,t) = a1(:,t); - Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); - Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1)); - Pstar1(:,:,t) = Pstar(:,:,t); - Pinf1(:,:,t) = Pinf(:,:,t); - di = data_index{t}'; - for i=di - v(i,t) = Y(i,t)-a(mf(i),t)-trend(i,t); - Fstar(i,t) = Pstar(mf(i),mf(i),t); - Finf(i,t) = Pinf(mf(i),mf(i),t); - Kstar(:,i,t) = Pstar(:,mf(i),t); - if Finf(i,t) > crit & newRank, % original MJ: if Finf(i,t) > crit - icc=icc+1; - Kinf(:,i,t) = Pinf(:,mf(i),t); - Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t); - L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Z(i,:)/Finf(i,t); - a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t); - Pstar(:,:,t) = Pstar(:,:,t) + ... - Kinf(:,i,t)*transpose(Kinf(:,i,t))*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ... - (Kstar(:,i,t)*transpose(Kinf(:,i,t)) +... - Kinf(:,i,t)*transpose(Kstar(:,i,t)))/Finf(i,t); - Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*transpose(Kinf(:,i,t))/Finf(i,t); - Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); - Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1)); - % new terminiation criteria by M. Ratto - P0=Pinf(:,:,t); - % newRank = any(diag(P0(mf,mf))>crit); - % if newRank==0, id = i; end, - if ~isempty(options_.diffuse_d), - newRank = (icc<options_.diffuse_d); - %if newRank & any(diag(P0(mf,mf))>crit)==0; - if newRank & (any(diag(P0(mf,mf))>crit)==0 & rank(P0,crit1)==0); - disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF') - options_.diffuse_d = icc; - newRank=0; + t = t+1; + a(:,t) = a1(:,t); + Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); + Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1)); + Pstar1(:,:,t) = Pstar(:,:,t); + Pinf1(:,:,t) = Pinf(:,:,t); + di = data_index{t}'; + for i=di + v(i,t) = Y(i,t)-a(mf(i),t)-trend(i,t); + Fstar(i,t) = Pstar(mf(i),mf(i),t); + Finf(i,t) = Pinf(mf(i),mf(i),t); + Kstar(:,i,t) = Pstar(:,mf(i),t); + if Finf(i,t) > crit & newRank, % original MJ: if Finf(i,t) > crit + icc=icc+1; + Kinf(:,i,t) = Pinf(:,mf(i),t); + Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t); + L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Z(i,:)/Finf(i,t); + a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t); + Pstar(:,:,t) = Pstar(:,:,t) + ... + Kinf(:,i,t)*transpose(Kinf(:,i,t))*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ... + (Kstar(:,i,t)*transpose(Kinf(:,i,t)) +... + Kinf(:,i,t)*transpose(Kstar(:,i,t)))/Finf(i,t); + Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*transpose(Kinf(:,i,t))/Finf(i,t); + Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); + Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1)); + % new terminiation criteria by M. Ratto + P0=Pinf(:,:,t); + % newRank = any(diag(P0(mf,mf))>crit); + % if newRank==0, id = i; end, + if ~isempty(options_.diffuse_d), + newRank = (icc<options_.diffuse_d); + %if newRank & any(diag(P0(mf,mf))>crit)==0; + if newRank & (any(diag(P0(mf,mf))>crit)==0 & rank(P0,crit1)==0); + disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF') + options_.diffuse_d = icc; + newRank=0; + end + else + %newRank = any(diag(P0(mf,mf))>crit); + newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1)); + if newRank==0, + options_.diffuse_d = icc; + end + end, + % if newRank==0, + % options_.diffuse_d=i; %this is buggy + % end + % end new terminiation criteria by M. Ratto + elseif Fstar(i,t) > crit + %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition + %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that + %% rank(Pinf)=0. [st�phane,11-03-2004]. + Li(:,:,i,t) = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t); % we need to store Li for DKF smoother + a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t); + Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*transpose(Kstar(:,i,t))/Fstar(i,t); + Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); end - else - %newRank = any(diag(P0(mf,mf))>crit); - newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1)); - if newRank==0, - options_.diffuse_d = icc; - end - end, - % if newRank==0, - % options_.diffuse_d=i; %this is buggy - % end - % end new terminiation criteria by M. Ratto - elseif Fstar(i,t) > crit - %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition - %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that - %% rank(Pinf)=0. [st�phane,11-03-2004]. - Li(:,:,i,t) = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t); % we need to store Li for DKF smoother - a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t); - Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*transpose(Kstar(:,i,t))/Fstar(i,t); - Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1)); end - end - a1(:,t+1) = T*a(:,t); - for jnk=1:nk, - aK(jnk,:,t+jnk) = T^jnk*a(:,t); - end - Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)+ QQ; - Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T); - P0=Pinf(:,:,t+1); - if newRank, - %newRank = any(diag(P0(mf,mf))>crit); - newRank = rank(P0,crit1); - end + a1(:,t+1) = T*a(:,t); + for jnk=1:nk, + aK(jnk,:,t+jnk) = T^jnk*a(:,t); + end + Pstar(:,:,t+1) = T*Pstar(:,:,t)*transpose(T)+ QQ; + Pinf(:,:,t+1) = T*Pinf(:,:,t)*transpose(T); + P0=Pinf(:,:,t+1); + if newRank, + %newRank = any(diag(P0(mf,mf))>crit); + newRank = rank(P0,crit1); + end end @@ -194,31 +194,31 @@ Pstar1 = Pstar1(:,:,1:d); Pinf1 = Pinf1(:,:,1:d); notsteady = 1; while notsteady & t<smpl - t = t+1; - a(:,t) = a1(:,t); - P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); - P1(:,:,t) = P(:,:,t); - di = data_index{t}'; - for i=di - v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t); - Fi(i,t) = P(mf(i),mf(i),t); - Ki(:,i,t) = P(:,mf(i),t); - if Fi(i,t) > crit - Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t); - a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t); - P(:,:,t) = P(:,:,t) - Ki(:,i,t)*transpose(Ki(:,i,t))/Fi(i,t); - P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); + t = t+1; + a(:,t) = a1(:,t); + P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); + P1(:,:,t) = P(:,:,t); + di = data_index{t}'; + for i=di + v(i,t) = Y(i,t) - a(mf(i),t) - trend(i,t); + Fi(i,t) = P(mf(i),mf(i),t); + Ki(:,i,t) = P(:,mf(i),t); + if Fi(i,t) > crit + Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t); + a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t); + P(:,:,t) = P(:,:,t) - Ki(:,i,t)*transpose(Ki(:,i,t))/Fi(i,t); + P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); + end end - end - a1(:,t+1) = T*a(:,t); - Pf = P(:,:,t); - for jnk=1:nk, - Pf = T*Pf*T' + QQ; - aK(jnk,:,t+jnk) = T^jnk*a1(:,t); - PK(jnk,:,:,t+jnk) = Pf; - end - P(:,:,t+1) = T*P(:,:,t)*transpose(T) + QQ; -% notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); + a1(:,t+1) = T*a(:,t); + Pf = P(:,:,t); + for jnk=1:nk, + Pf = T*Pf*T' + QQ; + aK(jnk,:,t+jnk) = T^jnk*a1(:,t); + PK(jnk,:,:,t+jnk) = Pf; + end + P(:,:,t+1) = T*P(:,:,t)*transpose(T) + QQ; + % notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); end % $$$ P_s=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1)); % $$$ Fi_s = Fi(:,t); @@ -249,43 +249,43 @@ end ri=zeros(mm,1); t = smpl+1; while t>d+1 - t = t-1; - di = flipud(data_index{t})'; - for i = di - if Fi(i,t) > crit - ri = Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri; + t = t-1; + di = flipud(data_index{t})'; + for i = di + if Fi(i,t) > crit + ri = Z(i,:)'/Fi(i,t)*v(i,t)+Li(:,:,i,t)'*ri; + end end - end - r(:,t) = ri; - alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t); - etahat(:,t) = QRt*r(:,t); - ri = T'*ri; + r(:,t) = ri; + alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t); + etahat(:,t) = QRt*r(:,t); + ri = T'*ri; end if d - r0 = zeros(mm,d); - r0(:,d) = ri; - r1 = zeros(mm,d); - for t = d:-1:1 - di = flipud(data_index{t})'; - for i = di - if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d), - % use of options_.diffuse_d to be sure of DKF termination - %r1(:,t) = transpose(Z)*v(:,t)/Finf(i,t) + ... BUG HERE in transpose(Z) - r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ... - L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t); - r0(:,t) = Linf(:,:,i,t)'*r0(:,t); - elseif Fstar(i,t) > crit % step needed whe Finf == 0 - r0(:,t) = Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t); - end - end - alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t); - r(:,t) = r0(:,t); - etahat(:,t) = QRt*r(:,t); - if t > 1 - r0(:,t-1) = T'*r0(:,t); - r1(:,t-1) = T'*r1(:,t); - end - end + r0 = zeros(mm,d); + r0(:,d) = ri; + r1 = zeros(mm,d); + for t = d:-1:1 + di = flipud(data_index{t})'; + for i = di + if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d), + % use of options_.diffuse_d to be sure of DKF termination + %r1(:,t) = transpose(Z)*v(:,t)/Finf(i,t) + ... BUG HERE in transpose(Z) + r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ... + L0(:,:,i,t)'*r0(:,t) + Linf(:,:,i,t)'*r1(:,t); + r0(:,t) = Linf(:,:,i,t)'*r0(:,t); + elseif Fstar(i,t) > crit % step needed whe Finf == 0 + r0(:,t) = Z(i,:)'/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t); + end + end + alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t); + r(:,t) = r0(:,t); + etahat(:,t) = QRt*r(:,t); + if t > 1 + r0(:,t-1) = T'*r0(:,t); + r1(:,t-1) = T'*r1(:,t); + end + end end if nargout > 7 diff --git a/matlab/missing_DiffuseKalmanSmoother3_Z.m b/matlab/missing_DiffuseKalmanSmoother3_Z.m index b4b75823d2..88cde2ff18 100644 --- a/matlab/missing_DiffuseKalmanSmoother3_Z.m +++ b/matlab/missing_DiffuseKalmanSmoother3_Z.m @@ -77,9 +77,9 @@ a1 = zeros(mm,smpl+1); aK = zeros(nk,mm,smpl+nk); if isempty(options_.diffuse_d), - smpl_diff = 1; + smpl_diff = 1; else - smpl_diff=rank(Pinf1); + smpl_diff=rank(Pinf1); end Fstar = zeros(pp,smpl_diff); @@ -112,68 +112,68 @@ t = 0; icc=0; newRank = rank(Pinf(:,:,1),crit1); while newRank & t < smpl - t = t+1; - a(:,t) = a1(:,t); - Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)'; - Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)'; - Pstar1(:,:,t) = Pstar(:,:,t); - Pinf1(:,:,t) = Pinf(:,:,t); - di = data_index{t}'; - for i=di - Zi = Z(i,:); - v(i,t) = Y(i,t)-Zi*a(:,t); - Fstar(i,t) = Zi*Pstar(:,:,t)*Zi'; - Finf(i,t) = Zi*Pinf(:,:,t)*Zi'; - Kstar(:,i,t) = Pstar(:,:,t)*Zi'; - if Finf(i,t) > crit & newRank - icc=icc+1; - Kinf(:,i,t) = Pinf(:,:,t)*Zi'; -% Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t); -% L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Zi/Finf(i,t); - a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t); - Pstar(:,:,t) = Pstar(:,:,t) + ... - Kinf(:,i,t)*Kinf(:,i,t)'*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ... - (Kstar(:,i,t)*Kinf(:,i,t)' +... - Kinf(:,i,t)*Kstar(:,i,t)')/Finf(i,t); - Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*Kinf(:,i,t)'/Finf(i,t); - Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)'; - Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)'; - % new terminiation criteria by M. Ratto - P0=Pinf(:,:,t); - if ~isempty(options_.diffuse_d), - newRank = (icc<options_.diffuse_d); - if newRank & (any(diag(Z*P0*Z')>crit)==0 & rank(P0,crit1)==0); - disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF') - options_.diffuse_d = icc; - newRank=0; + t = t+1; + a(:,t) = a1(:,t); + Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)'; + Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)'; + Pstar1(:,:,t) = Pstar(:,:,t); + Pinf1(:,:,t) = Pinf(:,:,t); + di = data_index{t}'; + for i=di + Zi = Z(i,:); + v(i,t) = Y(i,t)-Zi*a(:,t); + Fstar(i,t) = Zi*Pstar(:,:,t)*Zi'; + Finf(i,t) = Zi*Pinf(:,:,t)*Zi'; + Kstar(:,i,t) = Pstar(:,:,t)*Zi'; + if Finf(i,t) > crit & newRank + icc=icc+1; + Kinf(:,i,t) = Pinf(:,:,t)*Zi'; + % Linf(:,:,i,t) = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t); + % L0(:,:,i,t) = (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Zi/Finf(i,t); + a(:,t) = a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t); + Pstar(:,:,t) = Pstar(:,:,t) + ... + Kinf(:,i,t)*Kinf(:,i,t)'*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ... + (Kstar(:,i,t)*Kinf(:,i,t)' +... + Kinf(:,i,t)*Kstar(:,i,t)')/Finf(i,t); + Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*Kinf(:,i,t)'/Finf(i,t); + Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)'; + Pinf(:,:,t)=tril(Pinf(:,:,t))+tril(Pinf(:,:,t),-1)'; + % new terminiation criteria by M. Ratto + P0=Pinf(:,:,t); + if ~isempty(options_.diffuse_d), + newRank = (icc<options_.diffuse_d); + if newRank & (any(diag(Z*P0*Z')>crit)==0 & rank(P0,crit1)==0); + disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF') + options_.diffuse_d = icc; + newRank=0; + end + else + newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1)); + if newRank==0, + options_.diffuse_d = icc; + end + end, + % end new terminiation criteria by M. Ratto + elseif Fstar(i,t) > crit + %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition + %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that + %% rank(Pinf)=0. [st�phane,11-03-2004]. + %Li(:,:,i,t) = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t); % we need to store Li for DKF smoother + a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t); + Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*Kstar(:,i,t)'/Fstar(i,t); + Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)'; end - else - newRank = (any(diag(Z*P0*Z')>crit) | rank(P0,crit1)); - if newRank==0, - options_.diffuse_d = icc; - end - end, - % end new terminiation criteria by M. Ratto - elseif Fstar(i,t) > crit - %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition - %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that - %% rank(Pinf)=0. [st�phane,11-03-2004]. - %Li(:,:,i,t) = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t); % we need to store Li for DKF smoother - a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t); - Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*Kstar(:,i,t)'/Fstar(i,t); - Pstar(:,:,t)=tril(Pstar(:,:,t))+tril(Pstar(:,:,t),-1)'; end - end - a1(:,t+1) = T*a(:,t); - for jnk=1:nk, - aK(jnk,:,t+jnk) = T^jnk*a(:,t); - end - Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'+ QQ; - Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'; - P0=Pinf(:,:,t+1); - if newRank, - newRank = rank(P0,crit1); - end + a1(:,t+1) = T*a(:,t); + for jnk=1:nk, + aK(jnk,:,t+jnk) = T^jnk*a(:,t); + end + Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'+ QQ; + Pinf(:,:,t+1) = T*Pinf(:,:,t)*T'; + P0=Pinf(:,:,t+1); + if newRank, + newRank = rank(P0,crit1); + end end @@ -190,32 +190,32 @@ Pstar1 = Pstar1(:,:,1:d); Pinf1 = Pinf1(:,:,1:d); notsteady = 1; while notsteady & t<smpl - t = t+1; - a(:,t) = a1(:,t); - P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)'; - P1(:,:,t) = P(:,:,t); - di = data_index{t}'; - for i=di - Zi = Z(i,:); - v(i,t) = Y(i,t) - Zi*a(:,t); - Fi(i,t) = Zi*P(:,:,t)*Zi'; - Ki(:,i,t) = P(:,:,t)*Zi'; - if Fi(i,t) > crit - %Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t); - a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t); - P(:,:,t) = P(:,:,t) - Ki(:,i,t)*Ki(:,i,t)'/Fi(i,t); - P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)'; + t = t+1; + a(:,t) = a1(:,t); + P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)'; + P1(:,:,t) = P(:,:,t); + di = data_index{t}'; + for i=di + Zi = Z(i,:); + v(i,t) = Y(i,t) - Zi*a(:,t); + Fi(i,t) = Zi*P(:,:,t)*Zi'; + Ki(:,i,t) = P(:,:,t)*Zi'; + if Fi(i,t) > crit + %Li(:,:,i,t) = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t); + a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t); + P(:,:,t) = P(:,:,t) - Ki(:,i,t)*Ki(:,i,t)'/Fi(i,t); + P(:,:,t)=tril(P(:,:,t))+tril(P(:,:,t),-1)'; + end end - end - a1(:,t+1) = T*a(:,t); - Pf = P(:,:,t); - for jnk=1:nk, - Pf = T*Pf*T' + QQ; - aK(jnk,:,t+jnk) = T^jnk*a(:,t); - PK(jnk,:,:,t+jnk) = Pf; - end - P(:,:,t+1) = T*P(:,:,t)*T' + QQ; -% notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); + a1(:,t+1) = T*a(:,t); + Pf = P(:,:,t); + for jnk=1:nk, + Pf = T*Pf*T' + QQ; + aK(jnk,:,t+jnk) = T^jnk*a(:,t); + PK(jnk,:,:,t+jnk) = Pf; + end + P(:,:,t+1) = T*P(:,:,t)*T' + QQ; + % notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit); end % $$$ P_s=tril(P(:,:,t))+tril(P(:,:,t),-1)'; % $$$ P1_s=tril(P1(:,:,t))+tril(P1(:,:,t),-1)'; @@ -251,43 +251,43 @@ end ri=zeros(mm,1); t = smpl+1; while t > d+1 - t = t-1; - di = flipud(data_index{t})'; - for i = di - if Fi(i,t) > crit - ri = Z(i,:)'/Fi(i,t)*v(i,t)+ri-Ki(:,i,t)'*ri/Fi(i,t)*Z(i,:)'; + t = t-1; + di = flipud(data_index{t})'; + for i = di + if Fi(i,t) > crit + ri = Z(i,:)'/Fi(i,t)*v(i,t)+ri-Ki(:,i,t)'*ri/Fi(i,t)*Z(i,:)'; + end end - end - r(:,t) = ri; - alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t); - etahat(:,t) = QRt*r(:,t); - ri = T'*ri; + r(:,t) = ri; + alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t); + etahat(:,t) = QRt*r(:,t); + ri = T'*ri; end if d - r0 = zeros(mm,d); - r0(:,d) = ri; - r1 = zeros(mm,d); - for t = d:-1:1 - di = flipud(data_index{t})'; - for i = di - % if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d), % use of options_.diffuse_d to be sure of DKF termination - if Finf(i,t) > crit - r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ... - (Kinf(:,i,t)'*Fstar(i,t)/Finf(i,t)-Kstar(:,i,t)')*r0(:,t)/Finf(i,t)*Z(i,:)' + ... - r1(:,t)-Kinf(:,i,t)'*r1(:,t)/Finf(i,t)*Z(i,:)'; - r0(:,t) = r0(:,t)-Kinf(:,i,t)'*r0(:,t)/Finf(i,t)*Z(i,:)'; - elseif Fstar(i,t) > crit % step needed whe Finf == 0 - r0(:,t) = Z(i,:)'/Fstar(i,t)*v(i,t)+r0(:,t)-(Kstar(:,i,t)'*r0(:,t))/Fstar(i,t)*Z(i,:)'; - end - end - alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t); - r(:,t) = r0(:,t); - etahat(:,t) = QRt*r(:,t); - if t > 1 - r0(:,t-1) = T'*r0(:,t); - r1(:,t-1) = T'*r1(:,t); - end - end + r0 = zeros(mm,d); + r0(:,d) = ri; + r1 = zeros(mm,d); + for t = d:-1:1 + di = flipud(data_index{t})'; + for i = di + % if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d), % use of options_.diffuse_d to be sure of DKF termination + if Finf(i,t) > crit + r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ... + (Kinf(:,i,t)'*Fstar(i,t)/Finf(i,t)-Kstar(:,i,t)')*r0(:,t)/Finf(i,t)*Z(i,:)' + ... + r1(:,t)-Kinf(:,i,t)'*r1(:,t)/Finf(i,t)*Z(i,:)'; + r0(:,t) = r0(:,t)-Kinf(:,i,t)'*r0(:,t)/Finf(i,t)*Z(i,:)'; + elseif Fstar(i,t) > crit % step needed whe Finf == 0 + r0(:,t) = Z(i,:)'/Fstar(i,t)*v(i,t)+r0(:,t)-(Kstar(:,i,t)'*r0(:,t))/Fstar(i,t)*Z(i,:)'; + end + end + alphahat(:,t) = a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t); + r(:,t) = r0(:,t); + etahat(:,t) = QRt*r(:,t); + if t > 1 + r0(:,t-1) = T'*r0(:,t); + r1(:,t-1) = T'*r1(:,t); + end + end end disp('smoother done'); diff --git a/matlab/mode_check.m b/matlab/mode_check.m index a53f0aa991..a4695ef3c0 100644 --- a/matlab/mode_check.m +++ b/matlab/mode_check.m @@ -79,16 +79,16 @@ for plt = 1:nbplt, l2 = min(ub(kk),1.5*x(kk)); z = [l1:(l2-l1)/20:l2]; if options_.mode_check_nolik==0, - y = zeros(length(z),2); - dy = priordens(xx,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4); + y = zeros(length(z),2); + dy = priordens(xx,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4); end for i=1:length(z) xx(kk) = z(i); if isempty(strmatch('dsge_prior_weight',M_.param_names)) try - [fval,cost_flag] = DsgeLikelihood(xx,gend,data,data_index,number_of_observations,no_more_missing_observations); + [fval,cost_flag] = DsgeLikelihood(xx,gend,data,data_index,number_of_observations,no_more_missing_observations); catch - cost_flag = 0; + cost_flag = 0; end if cost_flag y(i,1) = fval; diff --git a/matlab/model_diagnostics.m b/matlab/model_diagnostics.m index 76908e1c92..c3432d9e79 100644 --- a/matlab/model_diagnostics.m +++ b/matlab/model_diagnostics.m @@ -32,137 +32,137 @@ function model_diagnostics(M_,options_,oo_) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - global jacob - - endo_nbr = M_.endo_nbr; - endo_names = M_.endo_names; - lead_lag_incidence = M_.lead_lag_incidence; - maximum_lag = M_.maximum_lag; - maximum_lead = M_.maximum_lead; - - % - % missing variables at the current period - % - k = find(lead_lag_incidence(maximum_lag+1,:)==0); - if ~isempty(k) - disp(['The following endogenous variables aren''t present at ' ... - 'the current period in the model:']) - for i=1:length(k) - disp(endo_names(k(i),:)) - end - end - - % - % check steady state - % - info = 0; - it_ = M_.maximum_lag + 1 ; +global jacob - if M_.exo_nbr == 0 - oo_.exo_steady_state = [] ; - end +endo_nbr = M_.endo_nbr; +endo_names = M_.endo_names; +lead_lag_incidence = M_.lead_lag_incidence; +maximum_lag = M_.maximum_lag; +maximum_lead = M_.maximum_lead; - % check if ys is steady state - tempex = oo_.exo_simul; - oo_.exo_simul = repmat(oo_.exo_steady_state',M_.maximum_lag+M_.maximum_lead+1,1); - if M_.exo_det_nbr > 0 - tempexdet = oo_.exo_det_simul; - oo_.exo_det_simul = repmat(oo_.exo_det_steady_state',M_.maximum_lag+M_.maximum_lead+1,1); +% +% missing variables at the current period +% +k = find(lead_lag_incidence(maximum_lag+1,:)==0); +if ~isempty(k) + disp(['The following endogenous variables aren''t present at ' ... + 'the current period in the model:']) + for i=1:length(k) + disp(endo_names(k(i),:)) end - dr.ys = oo_.steady_state; - check1 = 0; - % testing for steadystate file - fh = str2func([M_.fname '_static']); - if options_.steadystate_flag - [ys,check1] = feval([M_.fname '_steadystate'],dr.ys,... - [oo_.exo_steady_state; oo_.exo_det_steady_state]); - if size(ys,1) < M_.endo_nbr - if length(M_.aux_vars) > 0 - ys = add_auxiliary_variables_to_steadystate(ys,M_.aux_vars,... - M_.fname,... - oo_.exo_steady_state,... - oo_.exo_det_steady_state); - else - error([M_.fname '_steadystate.m doesn''t match the model']); - end +end + +% +% check steady state +% +info = 0; + +it_ = M_.maximum_lag + 1 ; + +if M_.exo_nbr == 0 + oo_.exo_steady_state = [] ; +end + +% check if ys is steady state +tempex = oo_.exo_simul; +oo_.exo_simul = repmat(oo_.exo_steady_state',M_.maximum_lag+M_.maximum_lead+1,1); +if M_.exo_det_nbr > 0 + tempexdet = oo_.exo_det_simul; + oo_.exo_det_simul = repmat(oo_.exo_det_steady_state',M_.maximum_lag+M_.maximum_lead+1,1); +end +dr.ys = oo_.steady_state; +check1 = 0; +% testing for steadystate file +fh = str2func([M_.fname '_static']); +if options_.steadystate_flag + [ys,check1] = feval([M_.fname '_steadystate'],dr.ys,... + [oo_.exo_steady_state; oo_.exo_det_steady_state]); + if size(ys,1) < M_.endo_nbr + if length(M_.aux_vars) > 0 + ys = add_auxiliary_variables_to_steadystate(ys,M_.aux_vars,... + M_.fname,... + oo_.exo_steady_state,... + oo_.exo_det_steady_state); + else + error([M_.fname '_steadystate.m doesn''t match the model']); end - dr.ys = ys; - else - % testing if ys isn't a steady state or if we aren't computing Ramsey policy - if options_.ramsey_policy == 0 - if options_.linear == 0 - % nonlinear models - if max(abs(feval(fh,dr.ys,[oo_.exo_steady_state; ... - oo_.exo_det_steady_state], M_.params))) > options_.dynatol - [dr.ys,check1] = dynare_solve(fh,dr.ys,1,... - [oo_.exo_steady_state; ... - oo_.exo_det_steady_state], M_.params); - end - else - % linear models - [fvec,jacob] = feval(fh,dr.ys,[oo_.exo_steady_state;... + end + dr.ys = ys; +else + % testing if ys isn't a steady state or if we aren't computing Ramsey policy + if options_.ramsey_policy == 0 + if options_.linear == 0 + % nonlinear models + if max(abs(feval(fh,dr.ys,[oo_.exo_steady_state; ... + oo_.exo_det_steady_state], M_.params))) > options_.dynatol + [dr.ys,check1] = dynare_solve(fh,dr.ys,1,... + [oo_.exo_steady_state; ... oo_.exo_det_steady_state], M_.params); - if max(abs(fvec)) > 1e-12 - dr.ys = dr.ys-jacob\fvec; - end + end + else + % linear models + [fvec,jacob] = feval(fh,dr.ys,[oo_.exo_steady_state;... + oo_.exo_det_steady_state], M_.params); + if max(abs(fvec)) > 1e-12 + dr.ys = dr.ys-jacob\fvec; end end end - % testing for problem - if check1 - disp('model diagnostic can''t obtain the steady state') - return - end +end +% testing for problem +if check1 + disp('model diagnostic can''t obtain the steady state') + return +end - if ~isreal(dr.ys) - disp(['model diagnostic obtains a steady state with complex ' ... - 'numbers']) - return - end +if ~isreal(dr.ys) + disp(['model diagnostic obtains a steady state with complex ' ... + 'numbers']) + return +end - % - % singular Jacobian of static model - % - - [res,jacob]=feval(fh,dr.ys,[dr.ys; oo_.exo_det_steady_state], ... - M_.params); - rank_jacob = rank(jacob); - if rank_jacob < endo_nbr - disp(['model_diagnostic: the Jacobian of the static model is ' ... - 'singular']) - disp(['there is ' num2str(endo_nbr-rank_jacob) ... - ' colinear relationships between the variables and the equations']) - ncol = null(jacob); - n_rel = size(ncol,2); - for i = 1:n_rel - if n_rel > 1 - disp(['Relation ' int2str(i)]) - end - disp('Colinear variables:') - for j=1:10 - k = find(abs(ncol(:,i)) > 10^-j); - if max(abs(jacob(:,k)*ncol(k,i))) < 1e-6 - break - end - end - disp(endo_names(k,:)) +% +% singular Jacobian of static model +% + +[res,jacob]=feval(fh,dr.ys,[dr.ys; oo_.exo_det_steady_state], ... + M_.params); +rank_jacob = rank(jacob); +if rank_jacob < endo_nbr + disp(['model_diagnostic: the Jacobian of the static model is ' ... + 'singular']) + disp(['there is ' num2str(endo_nbr-rank_jacob) ... + ' colinear relationships between the variables and the equations']) + ncol = null(jacob); + n_rel = size(ncol,2); + for i = 1:n_rel + if n_rel > 1 + disp(['Relation ' int2str(i)]) end - neq = null(jacob'); - n_rel = size(neq,2); - for i = 1:n_rel - if n_rel > 1 - disp(['Relation ' int2str(i)]) + disp('Colinear variables:') + for j=1:10 + k = find(abs(ncol(:,i)) > 10^-j); + if max(abs(jacob(:,k)*ncol(k,i))) < 1e-6 + break end - disp('Colinear equations') - for j=1:10 - k = find(abs(neq(:,i)) > 10^-j); - if max(abs(jacob(k,:)'*neq(k,i))) < 1e-6 - break - end + end + disp(endo_names(k,:)) + end + neq = null(jacob'); + n_rel = size(neq,2); + for i = 1:n_rel + if n_rel > 1 + disp(['Relation ' int2str(i)]) + end + disp('Colinear equations') + for j=1:10 + k = find(abs(neq(:,i)) > 10^-j); + if max(abs(jacob(k,:)'*neq(k,i))) < 1e-6 + break end - disp(k') end + disp(k') end - +end + diff --git a/matlab/model_info.m b/matlab/model_info.m index 38af19f050..9d96feb57d 100644 --- a/matlab/model_info.m +++ b/matlab/model_info.m @@ -1,109 +1,109 @@ -function model_info; -%function model_info; - -% Copyright (C) 2008-2009 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 <http://www.gnu.org/licenses/>. - - global M_; - fprintf(' Informations about %s\n',M_.fname); - fprintf(strcat(' ===================',char(ones(1,length(M_.fname))*'='),'\n\n')); - if(isfield(M_,'block_structure')) - nb_blocks=length(M_.block_structure.block); - fprintf('The model has %d equations and is decomposed in %d blocks as follow:\n',M_.endo_nbr,nb_blocks); - fprintf('===============================================================================================================\n'); - fprintf('| %10s | %10s | %30s | %14s | %31s |\n','Block no','Size','Block Type',' Equation','Dependent variable'); - fprintf('|============|============|================================|================|=================================|\n'); - for i=1:nb_blocks - size_block=length(M_.block_structure.block(i).equation); - if(i>1) - fprintf('|------------|------------|--------------------------------|----------------|---------------------------------|\n'); - end; - for j=1:size_block - if(j==1) - fprintf('| %3d (%4d) | %10d | %30s | %14d | %-6d %24s |\n',i,M_.block_structure.block(i).num,size_block,Sym_type(M_.block_structure.block(i).Simulation_Type),M_.block_structure.block(i).equation(j),M_.block_structure.block(i).variable(j),M_.endo_names(M_.block_structure.block(i).variable(j),:)); - else - fprintf('| %10s | %10s | %30s | %14d | %-6d %24s |\n','','','',M_.block_structure.block(i).equation(j),M_.block_structure.block(i).variable(j),M_.endo_names(M_.block_structure.block(i).variable(j),:)); - end; - end; - end; - fprintf('===============================================================================================================\n'); - fprintf('\n'); - for k=1:M_.maximum_endo_lag+M_.maximum_endo_lead+1 - if(k==M_.maximum_endo_lag+1) - fprintf('%-30s %s','the variable','is used in equations ontemporaneously'); - elseif(k<M_.maximum_endo_lag+1) - fprintf('%-30s %s %d','the variable','is used in equations with lag ',M_.maximum_endo_lag+1-k); - else - fprintf('%-30s %s %d','the variable','is used in equations with lead ',k-(M_.maximum_endo_lag+1)); - end; - if(size(M_.block_structure.incidence(k).sparse_IM,1)>0) - IM=sortrows(M_.block_structure.incidence(k).sparse_IM,2); - else - IM=[]; - end; - size_IM=size(IM,1); - last=0; - for i=1:size_IM - if(last~=IM(i,2)) - fprintf('\n%-30s',M_.endo_names(IM(i,2),:)); - end; - fprintf(' %5d',IM(i,1)); - last=IM(i,2); - end; - fprintf('\n\n'); - end; - else - fprintf('There is no block decomposition of the model.\nUse ''block'' model''s option.\n'); - end; - - -function ret=Sym_type(type); - UNKNOWN=0; - EVALUATE_FORWARD=1; - EVALUATE_BACKWARD=2; - SOLVE_FORWARD_SIMPLE=3; - SOLVE_BACKWARD_SIMPLE=4; - SOLVE_TWO_BOUNDARIES_SIMPLE=5; - SOLVE_FORWARD_COMPLETE=6; - SOLVE_BACKWARD_COMPLETE=7; - SOLVE_TWO_BOUNDARIES_COMPLETE=8; - EVALUATE_FORWARD_R=9; - EVALUATE_BACKWARD_R=10; - switch (type) - case (UNKNOWN), - ret='UNKNOWN '; - case {EVALUATE_FORWARD,EVALUATE_FORWARD_R}, - ret='EVALUATE FORWARD '; - case {EVALUATE_BACKWARD,EVALUATE_BACKWARD_R}, - ret='EVALUATE BACKWARD '; - case SOLVE_FORWARD_SIMPLE, - ret='SOLVE FORWARD SIMPLE '; - case SOLVE_BACKWARD_SIMPLE, - ret='SOLVE BACKWARD SIMPLE '; - case SOLVE_TWO_BOUNDARIES_SIMPLE, - ret='SOLVE TWO BOUNDARIES SIMPLE '; - case SOLVE_FORWARD_COMPLETE, - ret='SOLVE FORWARD COMPLETE '; - case SOLVE_BACKWARD_COMPLETE, - ret='SOLVE BACKWARD COMPLETE '; - case SOLVE_TWO_BOUNDARIES_COMPLETE, - ret='SOLVE TWO BOUNDARIES COMPLETE'; - end; - - - - +function model_info; +%function model_info; + +% Copyright (C) 2008-2009 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 <http://www.gnu.org/licenses/>. + +global M_; +fprintf(' Informations about %s\n',M_.fname); +fprintf(strcat(' ===================',char(ones(1,length(M_.fname))*'='),'\n\n')); +if(isfield(M_,'block_structure')) + nb_blocks=length(M_.block_structure.block); + fprintf('The model has %d equations and is decomposed in %d blocks as follow:\n',M_.endo_nbr,nb_blocks); + fprintf('===============================================================================================================\n'); + fprintf('| %10s | %10s | %30s | %14s | %31s |\n','Block no','Size','Block Type',' Equation','Dependent variable'); + fprintf('|============|============|================================|================|=================================|\n'); + for i=1:nb_blocks + size_block=length(M_.block_structure.block(i).equation); + if(i>1) + fprintf('|------------|------------|--------------------------------|----------------|---------------------------------|\n'); + end; + for j=1:size_block + if(j==1) + fprintf('| %3d (%4d) | %10d | %30s | %14d | %-6d %24s |\n',i,M_.block_structure.block(i).num,size_block,Sym_type(M_.block_structure.block(i).Simulation_Type),M_.block_structure.block(i).equation(j),M_.block_structure.block(i).variable(j),M_.endo_names(M_.block_structure.block(i).variable(j),:)); + else + fprintf('| %10s | %10s | %30s | %14d | %-6d %24s |\n','','','',M_.block_structure.block(i).equation(j),M_.block_structure.block(i).variable(j),M_.endo_names(M_.block_structure.block(i).variable(j),:)); + end; + end; + end; + fprintf('===============================================================================================================\n'); + fprintf('\n'); + for k=1:M_.maximum_endo_lag+M_.maximum_endo_lead+1 + if(k==M_.maximum_endo_lag+1) + fprintf('%-30s %s','the variable','is used in equations ontemporaneously'); + elseif(k<M_.maximum_endo_lag+1) + fprintf('%-30s %s %d','the variable','is used in equations with lag ',M_.maximum_endo_lag+1-k); + else + fprintf('%-30s %s %d','the variable','is used in equations with lead ',k-(M_.maximum_endo_lag+1)); + end; + if(size(M_.block_structure.incidence(k).sparse_IM,1)>0) + IM=sortrows(M_.block_structure.incidence(k).sparse_IM,2); + else + IM=[]; + end; + size_IM=size(IM,1); + last=0; + for i=1:size_IM + if(last~=IM(i,2)) + fprintf('\n%-30s',M_.endo_names(IM(i,2),:)); + end; + fprintf(' %5d',IM(i,1)); + last=IM(i,2); + end; + fprintf('\n\n'); + end; +else + fprintf('There is no block decomposition of the model.\nUse ''block'' model''s option.\n'); +end; + + +function ret=Sym_type(type); +UNKNOWN=0; +EVALUATE_FORWARD=1; +EVALUATE_BACKWARD=2; +SOLVE_FORWARD_SIMPLE=3; +SOLVE_BACKWARD_SIMPLE=4; +SOLVE_TWO_BOUNDARIES_SIMPLE=5; +SOLVE_FORWARD_COMPLETE=6; +SOLVE_BACKWARD_COMPLETE=7; +SOLVE_TWO_BOUNDARIES_COMPLETE=8; +EVALUATE_FORWARD_R=9; +EVALUATE_BACKWARD_R=10; +switch (type) + case (UNKNOWN), + ret='UNKNOWN '; + case {EVALUATE_FORWARD,EVALUATE_FORWARD_R}, + ret='EVALUATE FORWARD '; + case {EVALUATE_BACKWARD,EVALUATE_BACKWARD_R}, + ret='EVALUATE BACKWARD '; + case SOLVE_FORWARD_SIMPLE, + ret='SOLVE FORWARD SIMPLE '; + case SOLVE_BACKWARD_SIMPLE, + ret='SOLVE BACKWARD SIMPLE '; + case SOLVE_TWO_BOUNDARIES_SIMPLE, + ret='SOLVE TWO BOUNDARIES SIMPLE '; + case SOLVE_FORWARD_COMPLETE, + ret='SOLVE FORWARD COMPLETE '; + case SOLVE_BACKWARD_COMPLETE, + ret='SOLVE BACKWARD COMPLETE '; + case SOLVE_TWO_BOUNDARIES_COMPLETE, + ret='SOLVE TWO BOUNDARIES COMPLETE'; +end; + + + + diff --git a/matlab/mr_gstep.m b/matlab/mr_gstep.m index 6a0e7f9277..06e6965ae4 100644 --- a/matlab/mr_gstep.m +++ b/matlab/mr_gstep.m @@ -1,152 +1,152 @@ -function [f0, x, ig] = mr_gstep(func0,x,htol0,varargin) -% function [f0, x] = mr_gstep(func0,x,htol0,varargin) -% -% Gibbs type step in optimisation - -% Copyright (C) 2006 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 <http://www.gnu.org/licenses/>. - -global bayestopt_ options_ -persistent h1 - -gstep_ = options_.gstep; -if nargin<3, - htol = 1.e-6; -else - htol = htol0; -end -func = str2func(func0); -f0=feval(func,x,varargin{:}); -n=size(x,1); -h2=bayestopt_.ub-bayestopt_.lb; - -if isempty(h1), - h1=max(abs(x),sqrt(gstep_)*ones(n,1))*eps^(1/4); -end - -xh1=x; -f1=zeros(size(f0,1),n); -f_1=f1; -%for i=1:n, -i=0; -ig=zeros(n,1); -while i<n, - i=i+1; - h10=h1(i); - hcheck=0; - dx=[]; - xh1(i)=x(i)+h1(i); - fx = feval(func,xh1,varargin{:}); - it=1; - dx=(fx-f0); - ic=0; -% if abs(dx)>(2*htol), -% c=mr_nlincon(xh1,varargin{:}); -% while c -% h1(i)=h1(i)*0.9; -% xh1(i)=x(i)+h1(i); -% c=mr_nlincon(xh1,varargin{:}); -% ic=1; -% end -% if ic, -% fx = feval(func,xh1,varargin{:}); -% dx=(fx-f0); -% end -% end - - icount = 0; - h0=h1(i); - while (abs(dx(it))<0.5*htol | abs(dx(it))>(2*htol)) & icount<10 & ic==0, - %while abs(dx(it))<0.5*htol & icount< 10 & ic==0, - icount=icount+1; - if abs(dx(it)) ~= 0, - if abs(dx(it))<0.5*htol - h1(i)=min(0.3*abs(x(i)), 0.9*htol/abs(dx(it))*h1(i)); - xh1(i)=x(i)+h1(i); -% c=mr_nlincon(xh1,varargin{:}); -% while c -% h1(i)=h1(i)*0.9; -% xh1(i)=x(i)+h1(i); -% c=mr_nlincon(xh1,varargin{:}); -% ic=1; -% end - end - if abs(dx(it))>(2*htol), - h1(i)= htol/abs(dx(it))*h1(i); - xh1(i)=x(i)+h1(i); - end - try - fx = feval(func,xh1,varargin{:}); - catch - fx=1.e8; - end - it=it+1; - dx(it)=(fx-f0); - h0(it)=h1(i); - if h1(i)<1.e-12*min(1,h2(i)), - ic=1; - hcheck=1; - end - else - h1(i)=1; - ic=1; - end - end - f1(:,i)=fx; - xh1(i)=x(i)-h1(i); -% c=mr_nlincon(xh1,varargin{:}); -% ic=0; -% while c -% h1(i)=h1(i)*0.9; -% xh1(i)=x(i)-h1(i); -% c=mr_nlincon(xh1,varargin{:}); -% ic = 1; -% end - fx = feval(func,xh1,varargin{:}); - f_1(:,i)=fx; -% if ic, -% xh1(i)=x(i)+h1(i); -% f1(:,i)=feval(func,xh1,varargin{:}); -% end - if hcheck & htol<1, - htol=min(1,max(min(abs(dx))*2,htol*10)); - h1(i)=h10; - xh1(i)=x(i); - i=i-1; - else - gg=zeros(size(x)); - hh=gg; - gg(i)=(f1(i)'-f_1(i)')./(2.*h1(i)); - if abs(f1(i)+f_1(i)-2*f0)>1.e-12, - hh(i) = abs(1/( (f1(i)+f_1(i)-2*f0)./(h1(i)*h1(i)) )); - else - hh(i) = 1; - end - - if gg(i)*(hh(i)*gg(i))/2 > htol, - [f0 x fc retcode] = csminit(func0,x,f0,gg,0,diag(hh),varargin{:}); - ig(i)=1; - end - xh1=x; - end - save gstep -end - -save gstep - - - +function [f0, x, ig] = mr_gstep(func0,x,htol0,varargin) +% function [f0, x] = mr_gstep(func0,x,htol0,varargin) +% +% Gibbs type step in optimisation + +% Copyright (C) 2006 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 <http://www.gnu.org/licenses/>. + +global bayestopt_ options_ +persistent h1 + +gstep_ = options_.gstep; +if nargin<3, + htol = 1.e-6; +else + htol = htol0; +end +func = str2func(func0); +f0=feval(func,x,varargin{:}); +n=size(x,1); +h2=bayestopt_.ub-bayestopt_.lb; + +if isempty(h1), + h1=max(abs(x),sqrt(gstep_)*ones(n,1))*eps^(1/4); +end + +xh1=x; +f1=zeros(size(f0,1),n); +f_1=f1; +%for i=1:n, +i=0; +ig=zeros(n,1); +while i<n, + i=i+1; + h10=h1(i); + hcheck=0; + dx=[]; + xh1(i)=x(i)+h1(i); + fx = feval(func,xh1,varargin{:}); + it=1; + dx=(fx-f0); + ic=0; + % if abs(dx)>(2*htol), + % c=mr_nlincon(xh1,varargin{:}); + % while c + % h1(i)=h1(i)*0.9; + % xh1(i)=x(i)+h1(i); + % c=mr_nlincon(xh1,varargin{:}); + % ic=1; + % end + % if ic, + % fx = feval(func,xh1,varargin{:}); + % dx=(fx-f0); + % end + % end + + icount = 0; + h0=h1(i); + while (abs(dx(it))<0.5*htol | abs(dx(it))>(2*htol)) & icount<10 & ic==0, + %while abs(dx(it))<0.5*htol & icount< 10 & ic==0, + icount=icount+1; + if abs(dx(it)) ~= 0, + if abs(dx(it))<0.5*htol + h1(i)=min(0.3*abs(x(i)), 0.9*htol/abs(dx(it))*h1(i)); + xh1(i)=x(i)+h1(i); + % c=mr_nlincon(xh1,varargin{:}); + % while c + % h1(i)=h1(i)*0.9; + % xh1(i)=x(i)+h1(i); + % c=mr_nlincon(xh1,varargin{:}); + % ic=1; + % end + end + if abs(dx(it))>(2*htol), + h1(i)= htol/abs(dx(it))*h1(i); + xh1(i)=x(i)+h1(i); + end + try + fx = feval(func,xh1,varargin{:}); + catch + fx=1.e8; + end + it=it+1; + dx(it)=(fx-f0); + h0(it)=h1(i); + if h1(i)<1.e-12*min(1,h2(i)), + ic=1; + hcheck=1; + end + else + h1(i)=1; + ic=1; + end + end + f1(:,i)=fx; + xh1(i)=x(i)-h1(i); + % c=mr_nlincon(xh1,varargin{:}); + % ic=0; + % while c + % h1(i)=h1(i)*0.9; + % xh1(i)=x(i)-h1(i); + % c=mr_nlincon(xh1,varargin{:}); + % ic = 1; + % end + fx = feval(func,xh1,varargin{:}); + f_1(:,i)=fx; + % if ic, + % xh1(i)=x(i)+h1(i); + % f1(:,i)=feval(func,xh1,varargin{:}); + % end + if hcheck & htol<1, + htol=min(1,max(min(abs(dx))*2,htol*10)); + h1(i)=h10; + xh1(i)=x(i); + i=i-1; + else + gg=zeros(size(x)); + hh=gg; + gg(i)=(f1(i)'-f_1(i)')./(2.*h1(i)); + if abs(f1(i)+f_1(i)-2*f0)>1.e-12, + hh(i) = abs(1/( (f1(i)+f_1(i)-2*f0)./(h1(i)*h1(i)) )); + else + hh(i) = 1; + end + + if gg(i)*(hh(i)*gg(i))/2 > htol, + [f0 x fc retcode] = csminit(func0,x,f0,gg,0,diag(hh),varargin{:}); + ig(i)=1; + end + xh1=x; + end + save gstep +end + +save gstep + + + diff --git a/matlab/mr_hessian.m b/matlab/mr_hessian.m index be2496bf0a..18e9f6fd8c 100644 --- a/matlab/mr_hessian.m +++ b/matlab/mr_hessian.m @@ -1,328 +1,328 @@ -function [hessian_mat, gg, htol1, ihh, hh_mat0] = mr_hessian(func,x,hflag,htol0,varargin) -% [hessian_mat, gg, htol1, ihh, hh_mat0] = mr_hessian(func,x,hflag,htol0,varargin) -% -% numerical gradient and Hessian, with 'automatic' check of numerical -% error -% -% adapted from Michel Juillard original rutine hessian.m -% -% func = name of the function: func must give two outputs: -% - the log-likelihood AND the single contributions at times t=1,...,T -% of the log-likelihood to compute outer product gradient -% x = parameter values -% hflag = 0, Hessian computed with outer product gradient, one point -% increments for partial derivatives in gradients -% hflag = 1, 'mixed' Hessian: diagonal elements computed with numerical second order derivatives -% with correlation structure as from outer product gradient; -% two point evaluation of derivatives for partial derivatives -% in gradients -% hflag = 2, full numerical Hessian, computes second order partial derivatives -% uses Abramowitz and Stegun (1965) formulas 25.3.24 and 25.3.27 -% p. 884. -% htol0 = 'precision' of increment of function values for numerical -% derivatives -% -% varargin: other parameters of func - -% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. - -global options_ bayestopt_ -persistent h1 htol - -gstep_=options_.gstep; -if isempty(htol), htol = 1.e-4; end -func = str2func(func); -[f0, ff0]=feval(func,x,varargin{:}); -n=size(x,1); -h2=bayestopt_.ub-bayestopt_.lb; -hmax=bayestopt_.ub-x; -hmax=min(hmax,x-bayestopt_.lb); -%h1=max(abs(x),gstep_*ones(n,1))*eps^(1/3); -%h1=max(abs(x),sqrt(gstep_)*ones(n,1))*eps^(1/6); -if isempty(h1), - h1=max(abs(x),sqrt(gstep_)*ones(n,1))*eps^(1/4); -end - -h1 = min(h1,0.5.*hmax); - -if htol0<htol, - htol=htol0; -end -xh1=x; -f1=zeros(size(f0,1),n); -f_1=f1; -ff1=zeros(size(ff0)); -ff_1=ff1; - -%for i=1:n, -i=0; -while i<n, - i=i+1; - h10=h1(i); - hcheck=0; - dx=[]; - xh1(i)=x(i)+h1(i); - try - [fx, ffx]=feval(func,xh1,varargin{:}); - catch - fx=1.e8; - end - it=1; - dx=(fx-f0); - ic=0; -% if abs(dx)>(2*htol), -% c=mr_nlincon(xh1,varargin{:}); -% while c -% h1(i)=h1(i)*0.9; -% xh1(i)=x(i)+h1(i); -% c=mr_nlincon(xh1,varargin{:}); -% ic=1; -% end -% if ic, -% [fx, ffx]=feval(func,xh1,varargin{:}); -% dx=(fx-f0); -% end -% end - - icount = 0; - h0=h1(i); - while (abs(dx(it))<0.5*htol | abs(dx(it))>(2*htol)) & icount<10 & ic==0, - %while abs(dx(it))<0.5*htol & icount< 10 & ic==0, - icount=icount+1; - %if abs(dx(it)) ~= 0, - if abs(dx(it))<0.5*htol - if abs(dx(it)) ~= 0, - h1(i)=min(max(1.e-10,0.3*abs(x(i))), 0.9*htol/abs(dx(it))*h1(i)); - else - h1(i)=2.1*h1(i); - end - h1(i) = min(h1(i),0.5*hmax(i)); - xh1(i)=x(i)+h1(i); -% c=mr_nlincon(xh1,varargin{:}); -% while c -% h1(i)=h1(i)*0.9; -% xh1(i)=x(i)+h1(i); -% c=mr_nlincon(xh1,varargin{:}); -% ic=1; -% end - try - [fx, ffx]=feval(func,xh1,varargin{:}); - catch - fx=1.e8; - end - end - if abs(dx(it))>(2*htol), - h1(i)= htol/abs(dx(it))*h1(i); - xh1(i)=x(i)+h1(i); - try - [fx, ffx]=feval(func,xh1,varargin{:}); - catch - fx=1.e8; - end - while (fx-f0)==0, - h1(i)= h1(i)*2; - xh1(i)=x(i)+h1(i); - [fx, ffx]=feval(func,xh1,varargin{:}); - ic=1; - end - end - it=it+1; - dx(it)=(fx-f0); - h0(it)=h1(i); - if h1(i)<1.e-12*min(1,h2(i)) & h1(i)<0.5*hmax(i), - ic=1; - hcheck=1; - end - %else - % h1(i)=1; - % ic=1; - %end - end - % if (it>2 & dx(1)<10^(log10(htol)/2)) , - % [dum, is]=sort(h0); - % if find(diff(sign(diff(dx(is))))); - % hcheck=1; - % end - % elseif (it>3 & dx(1)>10^(log10(htol)/2)) , - % [dum, is]=sort(h0); - % if find(diff(sign(diff(dx(is(1:end-1)))))); - % hcheck=1; - % end - % end - f1(:,i)=fx; - if any(isnan(ffx)), - ff1=ones(size(ff0)).*fx/length(ff0); - else - ff1=ffx; - end - if hflag, % two point based derivatives - xh1(i)=x(i)-h1(i); -% c=mr_nlincon(xh1,varargin{:}); -% ic=0; -% while c -% h1(i)=h1(i)*0.9; -% xh1(i)=x(i)-h1(i); -% c=mr_nlincon(xh1,varargin{:}); -% ic = 1; -% end - [fx, ffx]=feval(func,xh1,varargin{:}); - f_1(:,i)=fx; - if any(isnan(ffx)), - ff_1=ones(size(ff0)).*fx/length(ff0); - else - ff_1=ffx; - end -% if ic, -% xh1(i)=x(i)+h1(i); -% [f1(:,i), ff1]=feval(func,xh1,varargin{:}); -% end - ggh(:,i)=(ff1-ff_1)./(2.*h1(i)); - else - ggh(:,i)=(ff1-ff0)./h1(i); - end - xh1(i)=x(i); - if hcheck & htol<1, - htol=min(1,max(min(abs(dx))*2,htol*10)); - h1(i)=h10; - i=0; - end - save hess -end - -h_1=h1; -xh1=x; -xh_1=xh1; - -if hflag, - gg=(f1'-f_1')./(2.*h1); -else - gg=(f1'-f0)./h1; -end - -if hflag==2, - gg=(f1'-f_1')./(2.*h1); - hessian_mat = zeros(size(f0,1),n*n); - for i=1:n - if i > 1 - k=[i:n:n*(i-1)]; - hessian_mat(:,(i-1)*n+1:(i-1)*n+i-1)=hessian_mat(:,k); - end - hessian_mat(:,(i-1)*n+i)=(f1(:,i)+f_1(:,i)-2*f0)./(h1(i)*h_1(i)); - temp=f1+f_1-f0*ones(1,n); - for j=i+1:n - xh1(i)=x(i)+h1(i); - xh1(j)=x(j)+h_1(j); - xh_1(i)=x(i)-h1(i); - xh_1(j)=x(j)-h_1(j); - %hessian_mat(:,(i-1)*n+j)=-(-feval(func,xh1,varargin{:})-feval(func,xh_1,varargin{:})+temp(:,i)+temp(:,j))./(2*h1(i)*h_1(j)); - %temp1 = feval(func,xh1,varargin{:}); -% c=mr_nlincon(xh1,varargin{:}); -% lam=1; -% while c, -% lam=lam*0.9; -% xh1(i)=x(i)+h1(i)*lam; -% xh1(j)=x(j)+h_1(j)*lam; -% %disp( ['hessian warning cross ', num2str(c) ]), -% c=mr_nlincon(xh1,varargin{:}); -% end -% temp1 = f0+(feval(func,xh1,varargin{:})-f0)/lam; - temp1 = feval(func,xh1,varargin{:}); - -% c=mr_nlincon(xh_1,varargin{:}); -% while c, -% lam=lam*0.9; -% xh_1(i)=x(i)-h1(i)*lam; -% xh_1(j)=x(j)-h_1(j)*lam; -% %disp( ['hessian warning cross ', num2str(c) ]), -% c=mr_nlincon(xh_1,varargin{:}); -% end -% temp2 = f0+(feval(func,xh_1,varargin{:})-f0)/lam; - temp2 = feval(func,xh_1,varargin{:}); - - hessian_mat(:,(i-1)*n+j)=-(-temp1 -temp2+temp(:,i)+temp(:,j))./(2*h1(i)*h_1(j)); - xh1(i)=x(i); - xh1(j)=x(j); - xh_1(i)=x(i); - xh_1(j)=x(j); - j=j+1; - save hess - end - i=i+1; - end - -elseif hflag==1, - hessian_mat = zeros(size(f0,1),n*n); - for i=1:n, - dum = (f1(:,i)+f_1(:,i)-2*f0)./(h1(i)*h_1(i)); - if dum>eps, - hessian_mat(:,(i-1)*n+i)=dum; - else - hessian_mat(:,(i-1)*n+i)=max(eps, gg(i)^2); - end - end - %hessian_mat2=hh_mat(:)'; -end - -gga=ggh.*kron(ones(size(ff1)),2.*h1'); % re-scaled gradient -hh_mat=gga'*gga; % rescaled outer product hessian -hh_mat0=ggh'*ggh; % outer product hessian -A=diag(2.*h1); % rescaling matrix -igg=inv(hh_mat); % inverted rescaled outer product hessian -ihh=A'*igg*A; % inverted outer product hessian -if hflag>0 & min(eig(reshape(hessian_mat,n,n)))>0, - hh0 = A*reshape(hessian_mat,n,n)*A'; %rescaled second order derivatives - hh = reshape(hessian_mat,n,n); %rescaled second order derivatives - sd0=sqrt(diag(hh0)); %rescaled 'standard errors' using second order derivatives - sd=sqrt(diag(hh_mat)); %rescaled 'standard errors' using outer product - hh_mat=hh_mat./(sd*sd').*(sd0*sd0'); %rescaled inverse outer product with 'true' std's - igg=inv(hh_mat); % rescaled outer product hessian with 'true' std's - ihh=A'*igg*A; % inverted outer product hessian - hh_mat0=inv(A)'*hh_mat*inv(A); % outer product hessian with 'true' std's - sd=sqrt(diag(ihh)); %standard errors - sdh=sqrt(1./diag(hh)); %diagonal standard errors - for j=1:length(sd), - sd0(j,1)=min(bayestopt_.p2(j), sd(j)); %prior std - sd0(j,1)=10^(0.5*(log10(sd0(j,1))+log10(sdh(j,1)))); - %sd0(j,1)=0.5*(sd0(j,1)+sdh(j,1)); - end - ihh=ihh./(sd*sd').*(sd0*sd0'); %inverse outer product with modified std's - igg=inv(A)'*ihh*inv(A); % inverted rescaled outer product hessian with modified std's - hh_mat=inv(igg); % outer product rescaled hessian with modified std's - hh_mat0=inv(A)'*hh_mat*inv(A); % outer product hessian with modified std's -% sd0=sqrt(1./diag(hh0)); %rescaled 'standard errors' using second order derivatives -% sd=sqrt(diag(igg)); %rescaled 'standard errors' using outer product -% igg=igg./(sd*sd').*(sd0*sd0'); %rescaled inverse outer product with 'true' std's -% hh_mat=inv(igg); % rescaled outer product hessian with 'true' std's -% ihh=A'*igg*A; % inverted outer product hessian -% hh_mat0=inv(A)'*hh_mat*inv(A); % outer product hessian with 'true' std's -end -if hflag<2, - hessian_mat=hh_mat0(:); -end - -if any(isnan(hessian_mat)), - hh_mat0=eye(length(hh_mat0)); - ihh=hh_mat0; - hessian_mat=hh_mat0(:); -end -hh1=h1; -htol1=htol; -save hess -% 11/25/03 SA Created from Hessian_sparse (removed sparse) - - +function [hessian_mat, gg, htol1, ihh, hh_mat0] = mr_hessian(func,x,hflag,htol0,varargin) +% [hessian_mat, gg, htol1, ihh, hh_mat0] = mr_hessian(func,x,hflag,htol0,varargin) +% +% numerical gradient and Hessian, with 'automatic' check of numerical +% error +% +% adapted from Michel Juillard original rutine hessian.m +% +% func = name of the function: func must give two outputs: +% - the log-likelihood AND the single contributions at times t=1,...,T +% of the log-likelihood to compute outer product gradient +% x = parameter values +% hflag = 0, Hessian computed with outer product gradient, one point +% increments for partial derivatives in gradients +% hflag = 1, 'mixed' Hessian: diagonal elements computed with numerical second order derivatives +% with correlation structure as from outer product gradient; +% two point evaluation of derivatives for partial derivatives +% in gradients +% hflag = 2, full numerical Hessian, computes second order partial derivatives +% uses Abramowitz and Stegun (1965) formulas 25.3.24 and 25.3.27 +% p. 884. +% htol0 = 'precision' of increment of function values for numerical +% derivatives +% +% varargin: other parameters of func + +% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. + +global options_ bayestopt_ +persistent h1 htol + +gstep_=options_.gstep; +if isempty(htol), htol = 1.e-4; end +func = str2func(func); +[f0, ff0]=feval(func,x,varargin{:}); +n=size(x,1); +h2=bayestopt_.ub-bayestopt_.lb; +hmax=bayestopt_.ub-x; +hmax=min(hmax,x-bayestopt_.lb); +%h1=max(abs(x),gstep_*ones(n,1))*eps^(1/3); +%h1=max(abs(x),sqrt(gstep_)*ones(n,1))*eps^(1/6); +if isempty(h1), + h1=max(abs(x),sqrt(gstep_)*ones(n,1))*eps^(1/4); +end + +h1 = min(h1,0.5.*hmax); + +if htol0<htol, + htol=htol0; +end +xh1=x; +f1=zeros(size(f0,1),n); +f_1=f1; +ff1=zeros(size(ff0)); +ff_1=ff1; + +%for i=1:n, +i=0; +while i<n, + i=i+1; + h10=h1(i); + hcheck=0; + dx=[]; + xh1(i)=x(i)+h1(i); + try + [fx, ffx]=feval(func,xh1,varargin{:}); + catch + fx=1.e8; + end + it=1; + dx=(fx-f0); + ic=0; + % if abs(dx)>(2*htol), + % c=mr_nlincon(xh1,varargin{:}); + % while c + % h1(i)=h1(i)*0.9; + % xh1(i)=x(i)+h1(i); + % c=mr_nlincon(xh1,varargin{:}); + % ic=1; + % end + % if ic, + % [fx, ffx]=feval(func,xh1,varargin{:}); + % dx=(fx-f0); + % end + % end + + icount = 0; + h0=h1(i); + while (abs(dx(it))<0.5*htol | abs(dx(it))>(2*htol)) & icount<10 & ic==0, + %while abs(dx(it))<0.5*htol & icount< 10 & ic==0, + icount=icount+1; + %if abs(dx(it)) ~= 0, + if abs(dx(it))<0.5*htol + if abs(dx(it)) ~= 0, + h1(i)=min(max(1.e-10,0.3*abs(x(i))), 0.9*htol/abs(dx(it))*h1(i)); + else + h1(i)=2.1*h1(i); + end + h1(i) = min(h1(i),0.5*hmax(i)); + xh1(i)=x(i)+h1(i); + % c=mr_nlincon(xh1,varargin{:}); + % while c + % h1(i)=h1(i)*0.9; + % xh1(i)=x(i)+h1(i); + % c=mr_nlincon(xh1,varargin{:}); + % ic=1; + % end + try + [fx, ffx]=feval(func,xh1,varargin{:}); + catch + fx=1.e8; + end + end + if abs(dx(it))>(2*htol), + h1(i)= htol/abs(dx(it))*h1(i); + xh1(i)=x(i)+h1(i); + try + [fx, ffx]=feval(func,xh1,varargin{:}); + catch + fx=1.e8; + end + while (fx-f0)==0, + h1(i)= h1(i)*2; + xh1(i)=x(i)+h1(i); + [fx, ffx]=feval(func,xh1,varargin{:}); + ic=1; + end + end + it=it+1; + dx(it)=(fx-f0); + h0(it)=h1(i); + if h1(i)<1.e-12*min(1,h2(i)) & h1(i)<0.5*hmax(i), + ic=1; + hcheck=1; + end + %else + % h1(i)=1; + % ic=1; + %end + end + % if (it>2 & dx(1)<10^(log10(htol)/2)) , + % [dum, is]=sort(h0); + % if find(diff(sign(diff(dx(is))))); + % hcheck=1; + % end + % elseif (it>3 & dx(1)>10^(log10(htol)/2)) , + % [dum, is]=sort(h0); + % if find(diff(sign(diff(dx(is(1:end-1)))))); + % hcheck=1; + % end + % end + f1(:,i)=fx; + if any(isnan(ffx)), + ff1=ones(size(ff0)).*fx/length(ff0); + else + ff1=ffx; + end + if hflag, % two point based derivatives + xh1(i)=x(i)-h1(i); + % c=mr_nlincon(xh1,varargin{:}); + % ic=0; + % while c + % h1(i)=h1(i)*0.9; + % xh1(i)=x(i)-h1(i); + % c=mr_nlincon(xh1,varargin{:}); + % ic = 1; + % end + [fx, ffx]=feval(func,xh1,varargin{:}); + f_1(:,i)=fx; + if any(isnan(ffx)), + ff_1=ones(size(ff0)).*fx/length(ff0); + else + ff_1=ffx; + end + % if ic, + % xh1(i)=x(i)+h1(i); + % [f1(:,i), ff1]=feval(func,xh1,varargin{:}); + % end + ggh(:,i)=(ff1-ff_1)./(2.*h1(i)); + else + ggh(:,i)=(ff1-ff0)./h1(i); + end + xh1(i)=x(i); + if hcheck & htol<1, + htol=min(1,max(min(abs(dx))*2,htol*10)); + h1(i)=h10; + i=0; + end + save hess +end + +h_1=h1; +xh1=x; +xh_1=xh1; + +if hflag, + gg=(f1'-f_1')./(2.*h1); +else + gg=(f1'-f0)./h1; +end + +if hflag==2, + gg=(f1'-f_1')./(2.*h1); + hessian_mat = zeros(size(f0,1),n*n); + for i=1:n + if i > 1 + k=[i:n:n*(i-1)]; + hessian_mat(:,(i-1)*n+1:(i-1)*n+i-1)=hessian_mat(:,k); + end + hessian_mat(:,(i-1)*n+i)=(f1(:,i)+f_1(:,i)-2*f0)./(h1(i)*h_1(i)); + temp=f1+f_1-f0*ones(1,n); + for j=i+1:n + xh1(i)=x(i)+h1(i); + xh1(j)=x(j)+h_1(j); + xh_1(i)=x(i)-h1(i); + xh_1(j)=x(j)-h_1(j); + %hessian_mat(:,(i-1)*n+j)=-(-feval(func,xh1,varargin{:})-feval(func,xh_1,varargin{:})+temp(:,i)+temp(:,j))./(2*h1(i)*h_1(j)); + %temp1 = feval(func,xh1,varargin{:}); + % c=mr_nlincon(xh1,varargin{:}); + % lam=1; + % while c, + % lam=lam*0.9; + % xh1(i)=x(i)+h1(i)*lam; + % xh1(j)=x(j)+h_1(j)*lam; + % %disp( ['hessian warning cross ', num2str(c) ]), + % c=mr_nlincon(xh1,varargin{:}); + % end + % temp1 = f0+(feval(func,xh1,varargin{:})-f0)/lam; + temp1 = feval(func,xh1,varargin{:}); + + % c=mr_nlincon(xh_1,varargin{:}); + % while c, + % lam=lam*0.9; + % xh_1(i)=x(i)-h1(i)*lam; + % xh_1(j)=x(j)-h_1(j)*lam; + % %disp( ['hessian warning cross ', num2str(c) ]), + % c=mr_nlincon(xh_1,varargin{:}); + % end + % temp2 = f0+(feval(func,xh_1,varargin{:})-f0)/lam; + temp2 = feval(func,xh_1,varargin{:}); + + hessian_mat(:,(i-1)*n+j)=-(-temp1 -temp2+temp(:,i)+temp(:,j))./(2*h1(i)*h_1(j)); + xh1(i)=x(i); + xh1(j)=x(j); + xh_1(i)=x(i); + xh_1(j)=x(j); + j=j+1; + save hess + end + i=i+1; + end + +elseif hflag==1, + hessian_mat = zeros(size(f0,1),n*n); + for i=1:n, + dum = (f1(:,i)+f_1(:,i)-2*f0)./(h1(i)*h_1(i)); + if dum>eps, + hessian_mat(:,(i-1)*n+i)=dum; + else + hessian_mat(:,(i-1)*n+i)=max(eps, gg(i)^2); + end + end + %hessian_mat2=hh_mat(:)'; +end + +gga=ggh.*kron(ones(size(ff1)),2.*h1'); % re-scaled gradient +hh_mat=gga'*gga; % rescaled outer product hessian +hh_mat0=ggh'*ggh; % outer product hessian +A=diag(2.*h1); % rescaling matrix +igg=inv(hh_mat); % inverted rescaled outer product hessian +ihh=A'*igg*A; % inverted outer product hessian +if hflag>0 & min(eig(reshape(hessian_mat,n,n)))>0, + hh0 = A*reshape(hessian_mat,n,n)*A'; %rescaled second order derivatives + hh = reshape(hessian_mat,n,n); %rescaled second order derivatives + sd0=sqrt(diag(hh0)); %rescaled 'standard errors' using second order derivatives + sd=sqrt(diag(hh_mat)); %rescaled 'standard errors' using outer product + hh_mat=hh_mat./(sd*sd').*(sd0*sd0'); %rescaled inverse outer product with 'true' std's + igg=inv(hh_mat); % rescaled outer product hessian with 'true' std's + ihh=A'*igg*A; % inverted outer product hessian + hh_mat0=inv(A)'*hh_mat*inv(A); % outer product hessian with 'true' std's + sd=sqrt(diag(ihh)); %standard errors + sdh=sqrt(1./diag(hh)); %diagonal standard errors + for j=1:length(sd), + sd0(j,1)=min(bayestopt_.p2(j), sd(j)); %prior std + sd0(j,1)=10^(0.5*(log10(sd0(j,1))+log10(sdh(j,1)))); + %sd0(j,1)=0.5*(sd0(j,1)+sdh(j,1)); + end + ihh=ihh./(sd*sd').*(sd0*sd0'); %inverse outer product with modified std's + igg=inv(A)'*ihh*inv(A); % inverted rescaled outer product hessian with modified std's + hh_mat=inv(igg); % outer product rescaled hessian with modified std's + hh_mat0=inv(A)'*hh_mat*inv(A); % outer product hessian with modified std's + % sd0=sqrt(1./diag(hh0)); %rescaled 'standard errors' using second order derivatives + % sd=sqrt(diag(igg)); %rescaled 'standard errors' using outer product + % igg=igg./(sd*sd').*(sd0*sd0'); %rescaled inverse outer product with 'true' std's + % hh_mat=inv(igg); % rescaled outer product hessian with 'true' std's + % ihh=A'*igg*A; % inverted outer product hessian + % hh_mat0=inv(A)'*hh_mat*inv(A); % outer product hessian with 'true' std's +end +if hflag<2, + hessian_mat=hh_mat0(:); +end + +if any(isnan(hessian_mat)), + hh_mat0=eye(length(hh_mat0)); + ihh=hh_mat0; + hessian_mat=hh_mat0(:); +end +hh1=h1; +htol1=htol; +save hess +% 11/25/03 SA Created from Hessian_sparse (removed sparse) + + diff --git a/matlab/mult_elimination.m b/matlab/mult_elimination.m index 6c5a9a0230..4ece70e4ac 100644 --- a/matlab/mult_elimination.m +++ b/matlab/mult_elimination.m @@ -1,121 +1,120 @@ -function dr=mult_elimination(varlist,M_, options_, oo_) -% function mult_elimination() -% replaces Lagrange multipliers in Ramsey policy by lagged value of state -% and shock variables -% -% INPUT -% none -% -% OUTPUT -% dr: a structure with the new decision rule -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2003-2008 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 <http://www.gnu.org/licenses/>. - - dr = oo_.dr; - - nstatic = dr.nstatic; - npred = dr.npred; - order_var = dr.order_var; - nstates = M_.endo_names(order_var(nstatic+(1:npred)),:); - - il = strmatch('mult_',nstates); - nil = setdiff(1:dr.npred,il); - m_nbr = length(il); - nm_nbr = length(nil); - - AA1 = dr.ghx(:,nil); - AA2 = dr.ghx(:,il); - A1 = dr.ghx(nstatic+(1:npred),nil); - A2 = dr.ghx(nstatic+(1:npred),il); - B = dr.ghu(nstatic+(1:npred),:); - A11 = A1(nil,:); - A21 = A1(il,:); - A12 = A2(nil,:); - A22 = A2(il,:); - - [Q1,R1,E1] = qr(A2); - n1 = sum(abs(diag(R1)) > 1e-8); - - Q1_12 = Q1(1:nm_nbr,n1+1:end); - Q1_22 = Q1(nm_nbr+1:end,n1+1:end); - [Q2,R2,E2] = qr(Q1_22'); - n2 = sum(abs(diag(R2)) > 1e-8); - - R2_1 = inv(R2(1:n2,1:n2)); - - M1(order_var,:) = AA1 - AA2*E2*[R2_1*Q2(:,1:n2)'*Q1_12'; zeros(m_nbr-n2,nm_nbr)]; - M2(order_var,:) = AA2*E2*[R2_1*Q2(:,1:n2)'*[Q1_12' Q1_22']*A1; zeros(m_nbr-n2,length(nil))]; - M3(order_var,:) = dr.ghu; - M4(order_var,:) = AA2*E2*[R2_1*Q2(:,1:n2)'*[Q1_12' Q1_22']*B; zeros(m_nbr-n2,size(B,2))]; - - endo_nbr = M_.orig_model.endo_nbr; - exo_nbr = M_.exo_nbr; - - lead_lag_incidence = M_.lead_lag_incidence(:,1:endo_nbr+exo_nbr); - lead_lag_incidence1 = lead_lag_incidence(1,:) > 0; - maximum_lag = M_.maximum_lag; - for i=1:maximum_lag-1 - lead_lag_incidence1 = [lead_lag_incidence1; lead_lag_incidence(i,:)| ... - lead_lag_incidence(i+1,:)]; - end - lead_lag_incidence1 = [lead_lag_incidence1; ... - lead_lag_incidence(M_.maximum_lag,:) > 0]; - k = find(lead_lag_incidence1'); - lead_lag_incidence1 = zeros(size(lead_lag_incidence1')); - lead_lag_incidence1(k) = 1:length(k); - lead_lag_incidence1 = lead_lag_incidence1'; - - kstate = zeros(0,2); - for i=maximum_lag:-1:1 - k = find(lead_lag_incidence(i,:)); - kstate = [kstate; [k' repmat(i+1,length(k),1)]]; - end - - dr.M1 = M1; - dr.M2 = M2; - dr.M3 = M3; - dr.M4 = M4; - - nvar = length(varlist); - nspred = dr.nspred; - nspred = 6; - if nvar > 0 - res_table = zeros(2*(nspred+M_.exo_nbr),nvar); - headers = 'Variables'; - for i=1:length(varlist) - k = strmatch(varlist{i},M_.endo_names(dr.order_var,:),'exact'); - headers = strvcat(headers,varlist{i}); - - res_table(1:nspred,i) = M1(k,:)'; - res_table(nspred+(1:nspred),i) = M2(k,:)'; - res_table(2*nspred+(1:M_.exo_nbr),i) = M3(k,:)'; - res_table(2*nspred+M_.exo_nbr+(1:M_.exo_nbr),i) = M4(k,:)'; - end - - my_title='ELIMINATION OF THE MULTIPLIERS'; - lab1 = M_.endo_names(dr.order_var(dr.nstatic+[ 1 2 5:8]),:); - labels = strvcat(lab1,lab1,M_.exo_names,M_.exo_names); - lh = size(labels,2)+2; - dyntable(my_title,headers,labels,res_table,lh,10,6); - disp(' ') - end - - \ No newline at end of file +function dr=mult_elimination(varlist,M_, options_, oo_) +% function mult_elimination() +% replaces Lagrange multipliers in Ramsey policy by lagged value of state +% and shock variables +% +% INPUT +% none +% +% OUTPUT +% dr: a structure with the new decision rule +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2003-2008 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 <http://www.gnu.org/licenses/>. + +dr = oo_.dr; + +nstatic = dr.nstatic; +npred = dr.npred; +order_var = dr.order_var; +nstates = M_.endo_names(order_var(nstatic+(1:npred)),:); + +il = strmatch('mult_',nstates); +nil = setdiff(1:dr.npred,il); +m_nbr = length(il); +nm_nbr = length(nil); + +AA1 = dr.ghx(:,nil); +AA2 = dr.ghx(:,il); +A1 = dr.ghx(nstatic+(1:npred),nil); +A2 = dr.ghx(nstatic+(1:npred),il); +B = dr.ghu(nstatic+(1:npred),:); +A11 = A1(nil,:); +A21 = A1(il,:); +A12 = A2(nil,:); +A22 = A2(il,:); + +[Q1,R1,E1] = qr(A2); +n1 = sum(abs(diag(R1)) > 1e-8); + +Q1_12 = Q1(1:nm_nbr,n1+1:end); +Q1_22 = Q1(nm_nbr+1:end,n1+1:end); +[Q2,R2,E2] = qr(Q1_22'); +n2 = sum(abs(diag(R2)) > 1e-8); + +R2_1 = inv(R2(1:n2,1:n2)); + +M1(order_var,:) = AA1 - AA2*E2*[R2_1*Q2(:,1:n2)'*Q1_12'; zeros(m_nbr-n2,nm_nbr)]; +M2(order_var,:) = AA2*E2*[R2_1*Q2(:,1:n2)'*[Q1_12' Q1_22']*A1; zeros(m_nbr-n2,length(nil))]; +M3(order_var,:) = dr.ghu; +M4(order_var,:) = AA2*E2*[R2_1*Q2(:,1:n2)'*[Q1_12' Q1_22']*B; zeros(m_nbr-n2,size(B,2))]; + +endo_nbr = M_.orig_model.endo_nbr; +exo_nbr = M_.exo_nbr; + +lead_lag_incidence = M_.lead_lag_incidence(:,1:endo_nbr+exo_nbr); +lead_lag_incidence1 = lead_lag_incidence(1,:) > 0; +maximum_lag = M_.maximum_lag; +for i=1:maximum_lag-1 + lead_lag_incidence1 = [lead_lag_incidence1; lead_lag_incidence(i,:)| ... + lead_lag_incidence(i+1,:)]; +end +lead_lag_incidence1 = [lead_lag_incidence1; ... + lead_lag_incidence(M_.maximum_lag,:) > 0]; +k = find(lead_lag_incidence1'); +lead_lag_incidence1 = zeros(size(lead_lag_incidence1')); +lead_lag_incidence1(k) = 1:length(k); +lead_lag_incidence1 = lead_lag_incidence1'; + +kstate = zeros(0,2); +for i=maximum_lag:-1:1 + k = find(lead_lag_incidence(i,:)); + kstate = [kstate; [k' repmat(i+1,length(k),1)]]; +end + +dr.M1 = M1; +dr.M2 = M2; +dr.M3 = M3; +dr.M4 = M4; + +nvar = length(varlist); +nspred = dr.nspred; +nspred = 6; +if nvar > 0 + res_table = zeros(2*(nspred+M_.exo_nbr),nvar); + headers = 'Variables'; + for i=1:length(varlist) + k = strmatch(varlist{i},M_.endo_names(dr.order_var,:),'exact'); + headers = strvcat(headers,varlist{i}); + + res_table(1:nspred,i) = M1(k,:)'; + res_table(nspred+(1:nspred),i) = M2(k,:)'; + res_table(2*nspred+(1:M_.exo_nbr),i) = M3(k,:)'; + res_table(2*nspred+M_.exo_nbr+(1:M_.exo_nbr),i) = M4(k,:)'; + end + + my_title='ELIMINATION OF THE MULTIPLIERS'; + lab1 = M_.endo_names(dr.order_var(dr.nstatic+[ 1 2 5:8]),:); + labels = strvcat(lab1,lab1,M_.exo_names,M_.exo_names); + lh = size(labels,2)+2; + dyntable(my_title,headers,labels,res_table,lh,10,6); + disp(' ') +end + diff --git a/matlab/my_subplot.m b/matlab/my_subplot.m index 2f1e3c5495..2049485f16 100644 --- a/matlab/my_subplot.m +++ b/matlab/my_subplot.m @@ -34,23 +34,23 @@ function my_subplot(i,imax,irow,icol,fig_title) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - nfig_max = irow*icol; - if imax < nfig_max +nfig_max = irow*icol; +if imax < nfig_max icol = ceil(sqrt(imax)); irow=icol; if (icol-1)*(icol-2) >= imax - irow = icol-2; - icol = icol-1; + irow = icol-2; + icol = icol-1; elseif (icol)*(icol-2) >= imax - irow = icol-2; + irow = icol-2; elseif icol*(icol-1) >= imax - irow = icol-1; + irow = icol-1; end - end +end - i1 = mod(i-1,nfig_max); - if i1 == 0 +i1 = mod(i-1,nfig_max); +if i1 == 0 figure('Name',fig_title); - end - - subplot(irow,icol,i1+1); \ No newline at end of file +end + +subplot(irow,icol,i1+1); \ No newline at end of file diff --git a/matlab/mydelete.m b/matlab/mydelete.m index 333b959cd6..13ef6ee9d6 100644 --- a/matlab/mydelete.m +++ b/matlab/mydelete.m @@ -1,33 +1,33 @@ -function mydelete(fname,pname) -% Specialized version of delete() function - -% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. - -if nargin ==0, - disp('mydelete(fname)') - return -end - -if nargin ==1, - pname=''; -end - -file_to_delete = dir([pname,fname]); -for j=1:length(file_to_delete), - delete([pname,file_to_delete(j).name]); -end +function mydelete(fname,pname) +% Specialized version of delete() function + +% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. + +if nargin ==0, + disp('mydelete(fname)') + return +end + +if nargin ==1, + pname=''; +end + +file_to_delete = dir([pname,fname]); +for j=1:length(file_to_delete), + delete([pname,file_to_delete(j).name]); +end diff --git a/matlab/name2index.m b/matlab/name2index.m index 2eeda95d2c..bf1d736bbf 100644 --- a/matlab/name2index.m +++ b/matlab/name2index.m @@ -33,85 +33,85 @@ function i = name2index(options_, M_, estim_params_, type, name1, name2 ) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - nvx = estim_params_.nvx; - nvn = estim_params_.nvn; - ncx = estim_params_.ncx; - ncn = estim_params_.ncn; - npa = estim_params_.np ; - nnn = nvx+nvn+ncx+ncn+npa; - - i = []; - - if strcmpi(type,'DeepParameter') - i = nvx + nvn + ncx + ncn + ... - strmatch(name1,M_.param_names(estim_params_.param_vals(:,1),:),'exact'); - if nargin>5 - disp('The last input argument is useless!') - end +nvx = estim_params_.nvx; +nvn = estim_params_.nvn; +ncx = estim_params_.ncx; +ncn = estim_params_.ncn; +npa = estim_params_.np ; +nnn = nvx+nvn+ncx+ncn+npa; + +i = []; + +if strcmpi(type,'DeepParameter') + i = nvx + nvn + ncx + ncn + ... + strmatch(name1,M_.param_names(estim_params_.param_vals(:,1),:),'exact'); + if nargin>5 + disp('The last input argument is useless!') + end + if isempty(i) + disp([name1 ' is not an estimated deep parameter!']) + end + return +end + +if strcmpi(type,'StructuralShock') + if nargin<6% Covariance matrix diagonal term. + i = strmatch(name1,M_.exo_names(estim_params_.var_exo(:,1),:),'exact'); if isempty(i) - disp([name1 ' is not an estimated deep parameter!']) + disp(['The standard deviation of ' name1 ' is not an estimated parameter!']) + return end - return - end - - if strcmpi(type,'StructuralShock') - if nargin<6% Covariance matrix diagonal term. - i = strmatch(name1,M_.exo_names(estim_params_.var_exo(:,1),:),'exact'); + else% Covariance matrix off-diagonal term + offset = nvx+nvn; + try + list_of_structural_shocks = [ M_.exo_names(estim_params_.corrx(:,1),:) , M_.exo_names(estim_params_.corrx(:,2),:) ]; + k1 = strmatch(name1,list_of_structural_shocks(:,1),'exact'); + k2 = strmatch(name2,list_of_structural_shocks(:,2),'exact'); + i = offset+intersect(k1,k2); if isempty(i) - disp(['The standard deviation of ' name1 ' is not an estimated parameter!']) - return - end - else% Covariance matrix off-diagonal term - offset = nvx+nvn; - try - list_of_structural_shocks = [ M_.exo_names(estim_params_.corrx(:,1),:) , M_.exo_names(estim_params_.corrx(:,2),:) ]; - k1 = strmatch(name1,list_of_structural_shocks(:,1),'exact'); - k2 = strmatch(name2,list_of_structural_shocks(:,2),'exact'); + k1 = strmatch(name1,list_of_structural_shocks(:,2),'exact'); + k2 = strmatch(name2,list_of_structural_shocks(:,1),'exact'); i = offset+intersect(k1,k2); + end + if isempty(i) if isempty(i) - k1 = strmatch(name1,list_of_structural_shocks(:,2),'exact'); - k2 = strmatch(name2,list_of_structural_shocks(:,1),'exact'); - i = offset+intersect(k1,k2); - end - if isempty(i) - if isempty(i) - disp(['The correlation between' name1 ' and ' name2 ' is not an estimated parameter!']) - return - end + disp(['The correlation between' name1 ' and ' name2 ' is not an estimated parameter!']) + return end - catch - disp(['Off diagonal terms of the covariance matrix are not estimated (state equation)']) end + catch + disp(['Off diagonal terms of the covariance matrix are not estimated (state equation)']) end end - - if strcmpi(type,'MeasurementError') - if nargin<6% Covariance matrix diagonal term - i = nvx + strmatch(name1,M_.endo_names(estim_params_.var_endo(:,1),:),'exact'); +end + +if strcmpi(type,'MeasurementError') + if nargin<6% Covariance matrix diagonal term + i = nvx + strmatch(name1,M_.endo_names(estim_params_.var_endo(:,1),:),'exact'); + if isempty(i) + disp(['The standard deviation of the measurement error on ' name1 ' is not an estimated parameter!']) + return + end + else% Covariance matrix off-diagonal term + offset = nvx+nvn+ncx; + try + list_of_measurement_errors = [ M_.endo_names(estim_params_.corrn(:,1),:) , M_.endo_names(estim_params_.corrn(:,2),:) ]; + k1 = strmatch(name1,list_of_measurement_errors(:,1),'exact'); + k2 = strmatch(name2,list_of_measurement_errors(:,2),'exact'); + i = offset+intersect(k1,k2); if isempty(i) - disp(['The standard deviation of the measurement error on ' name1 ' is not an estimated parameter!']) - return - end - else% Covariance matrix off-diagonal term - offset = nvx+nvn+ncx; - try - list_of_measurement_errors = [ M_.endo_names(estim_params_.corrn(:,1),:) , M_.endo_names(estim_params_.corrn(:,2),:) ]; - k1 = strmatch(name1,list_of_measurement_errors(:,1),'exact'); - k2 = strmatch(name2,list_of_measurement_errors(:,2),'exact'); + k1 = strmatch(name1,list_of_measurement_errors(:,2),'exact'); + k2 = strmatch(name2,list_of_measurement_errors(:,1),'exact'); i = offset+intersect(k1,k2); + end + if isempty(i) if isempty(i) - k1 = strmatch(name1,list_of_measurement_errors(:,2),'exact'); - k2 = strmatch(name2,list_of_measurement_errors(:,1),'exact'); - i = offset+intersect(k1,k2); - end - if isempty(i) - if isempty(i) - disp(['The correlation between the measurement errors on ' name1 ' and ' name2 ' is not an estimated parameter!']) - return - end + disp(['The correlation between the measurement errors on ' name1 ' and ' name2 ' is not an estimated parameter!']) + return end - catch - disp('Off diagonal terms of the covariance matrix are not estimated (measurement equation)') end + catch + disp('Off diagonal terms of the covariance matrix are not estimated (measurement equation)') end - end \ No newline at end of file + end +end \ No newline at end of file diff --git a/matlab/newrat.m b/matlab/newrat.m index 7e59922434..3a256e279d 100644 --- a/matlab/newrat.m +++ b/matlab/newrat.m @@ -1,275 +1,275 @@ -function [xparam1, hh, gg, fval, igg] = newrat(func0, x, hh, gg, igg, ftol0, nit, flagg, varargin) -% [xparam1, hh, gg, fval, igg] = newrat(func0, x, hh, gg, igg, ftol0, nit, flagg, varargin) -% -% Optimiser with outer product gradient and with sequences of univariate steps -% uses Chris Sims subroutine for line search -% -% func0 = name of the function -% there must be a version of the function called [func0,'_hh.m'], that also -% gives as second OUTPUT the single contributions at times t=1,...,T -% of the log-likelihood to compute outer product gradient -% -% x = starting guess -% hh = initial Hessian [OPTIONAL] -% gg = initial gradient [OPTIONAL] -% igg = initial inverse Hessian [OPTIONAL] -% ftol0 = ending criterion for function change -% nit = maximum number of iterations -% -% In each iteration, Hessian is computed with outer product gradient. -% for final Hessian (to start Metropolis): -% flagg = 0, final Hessian computed with outer product gradient -% flagg = 1, final 'mixed' Hessian: diagonal elements computed with numerical second order derivatives -% with correlation structure as from outer product gradient, -% flagg = 2, full numerical Hessian -% -% varargin = list of parameters for func0 - -% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. - - global bayestopt_ -icount=0; -nx=length(x); -xparam1=x; -%ftol0=1.e-6; -htol_base = max(1.e-5, ftol0); -flagit=0; % mode of computation of hessian in each iteration -ftol=ftol0; -gtol=1.e-3; -htol=htol_base; -htol0=htol_base; -gibbstol=length(bayestopt_.pshape)/50; %25; - -func_hh = [func0,'_hh']; -func = str2func(func0); -fval0=feval(func,x,varargin{:}); -fval=fval0; -if isempty(hh) - [dum, gg, htol0, igg, hhg]=mr_hessian(func_hh,x,flagit,htol,varargin{:}); - hh0 = reshape(dum,nx,nx); - hh=hhg; - if min(eig(hh0))<0, - hh0=hhg; %generalized_cholesky(hh0); - elseif flagit==2, - hh=hh0; - igg=inv(hh); - end - if htol0>htol, - htol=htol0; - %ftol=htol0; - end -else - hh0=hh; - hhg=hh; - igg=inv(hh); -end -disp(['Gradient norm ',num2str(norm(gg))]) -ee=eig(hh); -disp(['Minimum Hessian eigenvalue ',num2str(min(ee))]) -disp(['Maximum Hessian eigenvalue ',num2str(max(ee))]) -g=gg; -check=0; -if max(eig(hh))<0, disp('Negative definite Hessian! Local maximum!'), pause, end, -save m1 x hh g hhg igg fval0 - -igrad=1; -igibbs=1; -inx=eye(nx); -jit=0; -nig=[]; -ig=ones(nx,1); -ggx=zeros(nx,1); -while norm(gg)>gtol & check==0 & jit<nit, - jit=jit+1; - tic - icount=icount+1; - bayestopt_.penalty = fval0(icount); - disp([' ']) - disp(['Iteration ',num2str(icount)]) - [fval x0 fc retcode] = csminit(func0,xparam1,fval0(icount),gg,0,igg,varargin{:}); - if igrad, - [fval1 x01 fc retcode1] = csminit(func0,x0,fval,gg,0,inx,varargin{:}); - if (fval-fval1)>1, %(fval0(icount)-fval), - disp('Gradient step!!') - else - igrad=0; - end - fval=fval1; - x0=x01; - end - if (fval0(icount)-fval)<1.e-2*(gg'*(igg*gg))/2 & igibbs, - if length(find(ig))<nx, - ggx=ggx*0; - ggx(find(ig))=gg(find(ig)); - hhx = reshape(dum,nx,nx); - iggx=eye(length(gg)); - iggx(find(ig),find(ig)) = inv( hhx(find(ig),find(ig)) ); - [fvala x0 fc retcode] = csminit(func0,x0,fval,ggx,0,iggx,varargin{:}); - end - [fvala, x0, ig] = mr_gstep(func0,x0,htol,varargin{:}); - nig=[nig ig]; - if (fval-fvala)<gibbstol*(fval0(icount)-fval), - igibbs=0; - disp('Last sequence of univariate step, gain too small!!') - else - disp('Sequence of univariate steps!!') - end - fval=fvala; - end - if (fval0(icount)-fval)<ftol & flagit==0, - disp('Try diagonal Hessian') - ihh=diag(1./(diag(hhg))); - [fval2 x0 fc retcode2] = csminit(func2str(func),x0,fval,gg,0,ihh,varargin{:}); - if (fval-fval2)>=ftol , - %hh=diag(diag(hh)); - disp('Diagonal Hessian successful') - end - fval=fval2; - end - if (fval0(icount)-fval)<ftol & flagit==0, - disp('Try gradient direction') - ihh0=inx.*1.e-4; - [fval3 x0 fc retcode3] = csminit(func2str(func),x0,fval,gg,0,ihh0,varargin{:}); - if (fval-fval3)>=ftol , - %hh=hh0; - %ihh=ihh0; - disp('Gradient direction successful') - end - fval=fval3; - end - xparam1=x0; - x(:,icount+1)=xparam1; - fval0(icount+1)=fval; - %if (fval0(icount)-fval)<ftol*ftol & flagg==1;, - if (fval0(icount)-fval)<ftol, - disp('No further improvement is possible!') - check=1; - if flagit==2, - hh=hh0; - elseif flagg>0, - [dum, gg, htol0, igg, hhg]=mr_hessian(func_hh,xparam1,flagg,ftol0,varargin{:}); - if flagg==2, - hh = reshape(dum,nx,nx); - ee=eig(hh); - if min(ee)<0 - hh=hhg; - end - else - hh=hhg; - end - end - disp(['Actual dxnorm ',num2str(norm(x(:,end)-x(:,end-1)))]) - disp(['FVAL ',num2str(fval)]) - disp(['Improvement ',num2str(fval0(icount)-fval)]) - disp(['Ftol ',num2str(ftol)]) - disp(['Htol ',num2str(htol0)]) - disp(['Gradient norm ',num2str(norm(gg))]) - ee=eig(hh); - disp(['Minimum Hessian eigenvalue ',num2str(min(ee))]) - disp(['Maximum Hessian eigenvalue ',num2str(max(ee))]) - g(:,icount+1)=gg; - else - - df = fval0(icount)-fval; - disp(['Actual dxnorm ',num2str(norm(x(:,end)-x(:,end-1)))]) - disp(['FVAL ',num2str(fval)]) - disp(['Improvement ',num2str(df)]) - disp(['Ftol ',num2str(ftol)]) - disp(['Htol ',num2str(htol0)]) - - if df<htol0, - htol=max(htol_base,df/10); - end - - if norm(x(:,icount)-xparam1)>1.e-12, - try - save m1 x fval0 nig -append - catch - save m1 x fval0 nig - end - [dum, gg, htol0, igg, hhg]=mr_hessian(func_hh,xparam1,flagit,htol,varargin{:}); - if htol0>htol, %ftol, - %ftol=htol0; - htol=htol0; - disp(' ') - disp('Numerical noise in the likelihood') - disp('Tolerance has to be relaxed') - disp(' ') -% elseif htol0<ftol, -% ftol=max(htol0, ftol0); - end - hh0 = reshape(dum,nx,nx); - hh=hhg; - if flagit==2, - if min(eig(hh0))<=0, - hh0=hhg; %generalized_cholesky(hh0); - else - hh=hh0; - igg=inv(hh); - end - end - end - disp(['Gradient norm ',num2str(norm(gg))]) - ee=eig(hh); - disp(['Minimum Hessian eigenvalue ',num2str(min(ee))]) - disp(['Maximum Hessian eigenvalue ',num2str(max(ee))]) - if max(eig(hh))<0, disp('Negative definite Hessian! Local maximum!'), pause, end, - t=toc; - disp(['Elapsed time for iteration ',num2str(t),' s.']) - - g(:,icount+1)=gg; - save m1 x hh g hhg igg fval0 nig - end -end - -save m1 x hh g hhg igg fval0 nig -if ftol>ftol0, - disp(' ') - disp('Numerical noise in the likelihood') - disp('Tolerance had to be relaxed') - disp(' ') -end - -if jit==nit, - disp(' ') - disp('Maximum number of iterations reached') - disp(' ') -end - -if norm(gg)<=gtol, - disp(['Estimation ended:']) - disp(['Gradient norm < ', num2str(gtol)]) -end -if check==1, - disp(['Estimation successful.']) -end - -return - -% -function f00 = lsearch(lam,func,x,dx,varargin) - - -x0=x-dx*lam; -f00=feval(func,x0,varargin{:}); - - - - - - +function [xparam1, hh, gg, fval, igg] = newrat(func0, x, hh, gg, igg, ftol0, nit, flagg, varargin) +% [xparam1, hh, gg, fval, igg] = newrat(func0, x, hh, gg, igg, ftol0, nit, flagg, varargin) +% +% Optimiser with outer product gradient and with sequences of univariate steps +% uses Chris Sims subroutine for line search +% +% func0 = name of the function +% there must be a version of the function called [func0,'_hh.m'], that also +% gives as second OUTPUT the single contributions at times t=1,...,T +% of the log-likelihood to compute outer product gradient +% +% x = starting guess +% hh = initial Hessian [OPTIONAL] +% gg = initial gradient [OPTIONAL] +% igg = initial inverse Hessian [OPTIONAL] +% ftol0 = ending criterion for function change +% nit = maximum number of iterations +% +% In each iteration, Hessian is computed with outer product gradient. +% for final Hessian (to start Metropolis): +% flagg = 0, final Hessian computed with outer product gradient +% flagg = 1, final 'mixed' Hessian: diagonal elements computed with numerical second order derivatives +% with correlation structure as from outer product gradient, +% flagg = 2, full numerical Hessian +% +% varargin = list of parameters for func0 + +% Copyright (C) 2004-2008 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 <http://www.gnu.org/licenses/>. + +global bayestopt_ +icount=0; +nx=length(x); +xparam1=x; +%ftol0=1.e-6; +htol_base = max(1.e-5, ftol0); +flagit=0; % mode of computation of hessian in each iteration +ftol=ftol0; +gtol=1.e-3; +htol=htol_base; +htol0=htol_base; +gibbstol=length(bayestopt_.pshape)/50; %25; + +func_hh = [func0,'_hh']; +func = str2func(func0); +fval0=feval(func,x,varargin{:}); +fval=fval0; +if isempty(hh) + [dum, gg, htol0, igg, hhg]=mr_hessian(func_hh,x,flagit,htol,varargin{:}); + hh0 = reshape(dum,nx,nx); + hh=hhg; + if min(eig(hh0))<0, + hh0=hhg; %generalized_cholesky(hh0); + elseif flagit==2, + hh=hh0; + igg=inv(hh); + end + if htol0>htol, + htol=htol0; + %ftol=htol0; + end +else + hh0=hh; + hhg=hh; + igg=inv(hh); +end +disp(['Gradient norm ',num2str(norm(gg))]) +ee=eig(hh); +disp(['Minimum Hessian eigenvalue ',num2str(min(ee))]) +disp(['Maximum Hessian eigenvalue ',num2str(max(ee))]) +g=gg; +check=0; +if max(eig(hh))<0, disp('Negative definite Hessian! Local maximum!'), pause, end, +save m1 x hh g hhg igg fval0 + +igrad=1; +igibbs=1; +inx=eye(nx); +jit=0; +nig=[]; +ig=ones(nx,1); +ggx=zeros(nx,1); +while norm(gg)>gtol & check==0 & jit<nit, + jit=jit+1; + tic + icount=icount+1; + bayestopt_.penalty = fval0(icount); + disp([' ']) + disp(['Iteration ',num2str(icount)]) + [fval x0 fc retcode] = csminit(func0,xparam1,fval0(icount),gg,0,igg,varargin{:}); + if igrad, + [fval1 x01 fc retcode1] = csminit(func0,x0,fval,gg,0,inx,varargin{:}); + if (fval-fval1)>1, %(fval0(icount)-fval), + disp('Gradient step!!') + else + igrad=0; + end + fval=fval1; + x0=x01; + end + if (fval0(icount)-fval)<1.e-2*(gg'*(igg*gg))/2 & igibbs, + if length(find(ig))<nx, + ggx=ggx*0; + ggx(find(ig))=gg(find(ig)); + hhx = reshape(dum,nx,nx); + iggx=eye(length(gg)); + iggx(find(ig),find(ig)) = inv( hhx(find(ig),find(ig)) ); + [fvala x0 fc retcode] = csminit(func0,x0,fval,ggx,0,iggx,varargin{:}); + end + [fvala, x0, ig] = mr_gstep(func0,x0,htol,varargin{:}); + nig=[nig ig]; + if (fval-fvala)<gibbstol*(fval0(icount)-fval), + igibbs=0; + disp('Last sequence of univariate step, gain too small!!') + else + disp('Sequence of univariate steps!!') + end + fval=fvala; + end + if (fval0(icount)-fval)<ftol & flagit==0, + disp('Try diagonal Hessian') + ihh=diag(1./(diag(hhg))); + [fval2 x0 fc retcode2] = csminit(func2str(func),x0,fval,gg,0,ihh,varargin{:}); + if (fval-fval2)>=ftol , + %hh=diag(diag(hh)); + disp('Diagonal Hessian successful') + end + fval=fval2; + end + if (fval0(icount)-fval)<ftol & flagit==0, + disp('Try gradient direction') + ihh0=inx.*1.e-4; + [fval3 x0 fc retcode3] = csminit(func2str(func),x0,fval,gg,0,ihh0,varargin{:}); + if (fval-fval3)>=ftol , + %hh=hh0; + %ihh=ihh0; + disp('Gradient direction successful') + end + fval=fval3; + end + xparam1=x0; + x(:,icount+1)=xparam1; + fval0(icount+1)=fval; + %if (fval0(icount)-fval)<ftol*ftol & flagg==1;, + if (fval0(icount)-fval)<ftol, + disp('No further improvement is possible!') + check=1; + if flagit==2, + hh=hh0; + elseif flagg>0, + [dum, gg, htol0, igg, hhg]=mr_hessian(func_hh,xparam1,flagg,ftol0,varargin{:}); + if flagg==2, + hh = reshape(dum,nx,nx); + ee=eig(hh); + if min(ee)<0 + hh=hhg; + end + else + hh=hhg; + end + end + disp(['Actual dxnorm ',num2str(norm(x(:,end)-x(:,end-1)))]) + disp(['FVAL ',num2str(fval)]) + disp(['Improvement ',num2str(fval0(icount)-fval)]) + disp(['Ftol ',num2str(ftol)]) + disp(['Htol ',num2str(htol0)]) + disp(['Gradient norm ',num2str(norm(gg))]) + ee=eig(hh); + disp(['Minimum Hessian eigenvalue ',num2str(min(ee))]) + disp(['Maximum Hessian eigenvalue ',num2str(max(ee))]) + g(:,icount+1)=gg; + else + + df = fval0(icount)-fval; + disp(['Actual dxnorm ',num2str(norm(x(:,end)-x(:,end-1)))]) + disp(['FVAL ',num2str(fval)]) + disp(['Improvement ',num2str(df)]) + disp(['Ftol ',num2str(ftol)]) + disp(['Htol ',num2str(htol0)]) + + if df<htol0, + htol=max(htol_base,df/10); + end + + if norm(x(:,icount)-xparam1)>1.e-12, + try + save m1 x fval0 nig -append + catch + save m1 x fval0 nig + end + [dum, gg, htol0, igg, hhg]=mr_hessian(func_hh,xparam1,flagit,htol,varargin{:}); + if htol0>htol, %ftol, + %ftol=htol0; + htol=htol0; + disp(' ') + disp('Numerical noise in the likelihood') + disp('Tolerance has to be relaxed') + disp(' ') + % elseif htol0<ftol, + % ftol=max(htol0, ftol0); + end + hh0 = reshape(dum,nx,nx); + hh=hhg; + if flagit==2, + if min(eig(hh0))<=0, + hh0=hhg; %generalized_cholesky(hh0); + else + hh=hh0; + igg=inv(hh); + end + end + end + disp(['Gradient norm ',num2str(norm(gg))]) + ee=eig(hh); + disp(['Minimum Hessian eigenvalue ',num2str(min(ee))]) + disp(['Maximum Hessian eigenvalue ',num2str(max(ee))]) + if max(eig(hh))<0, disp('Negative definite Hessian! Local maximum!'), pause, end, + t=toc; + disp(['Elapsed time for iteration ',num2str(t),' s.']) + + g(:,icount+1)=gg; + save m1 x hh g hhg igg fval0 nig + end +end + +save m1 x hh g hhg igg fval0 nig +if ftol>ftol0, + disp(' ') + disp('Numerical noise in the likelihood') + disp('Tolerance had to be relaxed') + disp(' ') +end + +if jit==nit, + disp(' ') + disp('Maximum number of iterations reached') + disp(' ') +end + +if norm(gg)<=gtol, + disp(['Estimation ended:']) + disp(['Gradient norm < ', num2str(gtol)]) +end +if check==1, + disp(['Estimation successful.']) +end + +return + +% +function f00 = lsearch(lam,func,x,dx,varargin) + + +x0=x-dx*lam; +f00=feval(func,x0,varargin{:}); + + + + + + diff --git a/matlab/numgrad.m b/matlab/numgrad.m index b3c4f494ad..4c41ffa3c0 100644 --- a/matlab/numgrad.m +++ b/matlab/numgrad.m @@ -46,41 +46,41 @@ badg=0; goog=1;% stepan 07/07/2008 scale=1; % stepan 07/07/2008 for i=1:n - % i,tveci=tvec(:,i)% ,plus=x+scale*tvec(:,i) % Jinill Kim on 9/6/95 - if size(x,1)>size(x,2) - tvecv=tvec(i,:); - else - tvecv=tvec(:,i); - end - [fh,cost_flag] = feval(fcn, x+scale*transpose(tvecv), varargin{:});% stepan 07/07/2008 - if cost_flag% stepan 07/07/2008 - g0 = (fh - f0) / (scale*delta); - else - [fh,cost_flag] = feval(fcn, x-scale*transpose(tvecv), varargin{:}); - if cost_flag - g0 = (f0-fh) / (scale*delta); - else - goog=0; - end - end - % disp(' fcn in the i=1:n loop of numgrad.m ------------------')% Jinill 9/6/95 - % disp(' and i is') % Jinill - % i % Jinill - % fprintf('Gradient w.r.t. %3d: %10g\n',i,g0) %see below Jinill 9/6/95 -% -------------------------- special code to essentially quit here - % absg0=abs(g0) % Jinill on 9/6/95 - if goog && abs(g0)< 1e15 % stepan 07/07/2008 - g(i)=g0; - % disp('good gradient') % Jinill Kim - else - disp('bad gradient ------------------------') % Jinill Kim - % fprintf('Gradient w.r.t. %3d: %10g\n',i,g0) %see above - g(i)=0; - badg=1; - % return - % can return here to save time if the gradient will never be - % used when badg returns as true. - end + % i,tveci=tvec(:,i)% ,plus=x+scale*tvec(:,i) % Jinill Kim on 9/6/95 + if size(x,1)>size(x,2) + tvecv=tvec(i,:); + else + tvecv=tvec(:,i); + end + [fh,cost_flag] = feval(fcn, x+scale*transpose(tvecv), varargin{:});% stepan 07/07/2008 + if cost_flag% stepan 07/07/2008 + g0 = (fh - f0) / (scale*delta); + else + [fh,cost_flag] = feval(fcn, x-scale*transpose(tvecv), varargin{:}); + if cost_flag + g0 = (f0-fh) / (scale*delta); + else + goog=0; + end + end + % disp(' fcn in the i=1:n loop of numgrad.m ------------------')% Jinill 9/6/95 + % disp(' and i is') % Jinill + % i % Jinill + % fprintf('Gradient w.r.t. %3d: %10g\n',i,g0) %see below Jinill 9/6/95 + % -------------------------- special code to essentially quit here + % absg0=abs(g0) % Jinill on 9/6/95 + if goog && abs(g0)< 1e15 % stepan 07/07/2008 + g(i)=g0; + % disp('good gradient') % Jinill Kim + else + disp('bad gradient ------------------------') % Jinill Kim + % fprintf('Gradient w.r.t. %3d: %10g\n',i,g0) %see above + g(i)=0; + badg=1; + % return + % can return here to save time if the gradient will never be + % used when badg returns as true. + end end %------------------------------------------------------------- % if g0 > 0 diff --git a/matlab/numgrad3.m b/matlab/numgrad3.m index 19f0ce9419..598266bc5e 100644 --- a/matlab/numgrad3.m +++ b/matlab/numgrad3.m @@ -43,29 +43,29 @@ badg=0; goog=1; scale=1; for i=1:n - if size(x,1)>size(x,2) - tvecv=tvec(i,:); - else - tvecv=tvec(:,i); - end - [f1,cost_flag1] = feval(fcn, x+scale*transpose(tvecv), varargin{:}); - [f2,cost_flag2] = feval(fcn, x-scale*transpose(tvecv), varargin{:}); - if cost_flag1 && cost_flag2 - g0 = (f1 - f2) / (2*scale*delta); - else - if cost_flag1 - g0 = (f1-f0) / (scale*delta); - elseif cost_flag2 - g0 = (f0-f2) / (scale*delta); - else - goog=0; - end - end - if goog && abs(g0)< 1e15 - g(i)=g0; - else - disp('bad gradient ------------------------') - g(i)=0; - badg=1; - end + if size(x,1)>size(x,2) + tvecv=tvec(i,:); + else + tvecv=tvec(:,i); + end + [f1,cost_flag1] = feval(fcn, x+scale*transpose(tvecv), varargin{:}); + [f2,cost_flag2] = feval(fcn, x-scale*transpose(tvecv), varargin{:}); + if cost_flag1 && cost_flag2 + g0 = (f1 - f2) / (2*scale*delta); + else + if cost_flag1 + g0 = (f1-f0) / (scale*delta); + elseif cost_flag2 + g0 = (f0-f2) / (scale*delta); + else + goog=0; + end + end + if goog && abs(g0)< 1e15 + g(i)=g0; + else + disp('bad gradient ------------------------') + g(i)=0; + badg=1; + end end \ No newline at end of file diff --git a/matlab/numgrad5.m b/matlab/numgrad5.m index 0afe3f5bf8..9ea398b2e3 100644 --- a/matlab/numgrad5.m +++ b/matlab/numgrad5.m @@ -48,41 +48,41 @@ goog=1; scale=1; for i=1:n - if size(x,1)>size(x,2) - tvecv=tvec(i,:); - else - tvecv=tvec(:,i); - end - [f1,cost_flag1] = feval(fcn, x+scale*transpose(tvecv), varargin{:}); - [f2,cost_flag2] = feval(fcn, x-scale*transpose(tvecv), varargin{:}); - if cost_flag1==0 || cost_flag2==0 - cost_flag3 = 0; - cost_flag4 = 0; - disp('numgrad:: I cannot use the five points formula!!') - else - [f3,cost_flag3] = feval(fcn, x+2*scale*transpose(tvecv), varargin{:}); - [f4,cost_flag4] = feval(fcn, x-2*scale*transpose(tvecv), varargin{:}); - end - if cost_flag1 && cost_flag2 && cost_flag3 && cost_flag4% Five Points formula - g0 = (8*(f1 - f2)+ f4-f3) / (12*scale*delta); - elseif cost_flag3==0 || cost_flag4==0 - if cost_flag1 && cost_flag2% Three points formula - g0 = (f1-f2)/(2*scale*delta); - else - if cost_flag1% Two points formula - g0 = (f1-f0) / (scale*delta); - elseif cost_flag2% Two points formula - g0 = (f0-f2) / (scale*delta); - else% Bad gradient! - goog=0; - end - end - end - if goog && abs(g0)< 1e15 - g(i)=g0; - else - disp('bad gradient ------------------------') - g(i)=0; - badg=1; - end + if size(x,1)>size(x,2) + tvecv=tvec(i,:); + else + tvecv=tvec(:,i); + end + [f1,cost_flag1] = feval(fcn, x+scale*transpose(tvecv), varargin{:}); + [f2,cost_flag2] = feval(fcn, x-scale*transpose(tvecv), varargin{:}); + if cost_flag1==0 || cost_flag2==0 + cost_flag3 = 0; + cost_flag4 = 0; + disp('numgrad:: I cannot use the five points formula!!') + else + [f3,cost_flag3] = feval(fcn, x+2*scale*transpose(tvecv), varargin{:}); + [f4,cost_flag4] = feval(fcn, x-2*scale*transpose(tvecv), varargin{:}); + end + if cost_flag1 && cost_flag2 && cost_flag3 && cost_flag4% Five Points formula + g0 = (8*(f1 - f2)+ f4-f3) / (12*scale*delta); + elseif cost_flag3==0 || cost_flag4==0 + if cost_flag1 && cost_flag2% Three points formula + g0 = (f1-f2)/(2*scale*delta); + else + if cost_flag1% Two points formula + g0 = (f1-f0) / (scale*delta); + elseif cost_flag2% Two points formula + g0 = (f0-f2) / (scale*delta); + else% Bad gradient! + goog=0; + end + end + end + if goog && abs(g0)< 1e15 + g(i)=g0; + else + disp('bad gradient ------------------------') + g(i)=0; + badg=1; + end end \ No newline at end of file diff --git a/matlab/octave_ver_less_than.m b/matlab/octave_ver_less_than.m index f42fba1af5..e036faba0c 100644 --- a/matlab/octave_ver_less_than.m +++ b/matlab/octave_ver_less_than.m @@ -32,14 +32,14 @@ function r = octave_ver_less_than(verstr) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - cur_verstr = version(); - - r = get_ver_numeric(cur_verstr) < get_ver_numeric(verstr); +cur_verstr = version(); + +r = get_ver_numeric(cur_verstr) < get_ver_numeric(verstr); function x = get_ver_numeric(verstr) - nums = sscanf(verstr, '%d.%d.%d')'; - if length(nums) < 3 +nums = sscanf(verstr, '%d.%d.%d')'; +if length(nums) < 3 nums(3) = 0; - end - x = nums * [1; 0.01; 0.0001 ]; +end +x = nums * [1; 0.01; 0.0001 ]; diff --git a/matlab/osr.m b/matlab/osr.m index 275763fc50..a5b3af9778 100644 --- a/matlab/osr.m +++ b/matlab/osr.m @@ -17,33 +17,33 @@ function osr(var_list,params,i_var,W) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ options_ oo_ +global M_ options_ oo_ - options_.order = 1; - options_ = set_default_option(options_,'linear',0); - options_ = set_default_option(options_,'ar',5); - options_ = set_default_option(options_,'irf',40); - options_ = set_default_option(options_,'drop',100); - options_ = set_default_option(options_,'replic',1); - options_ = set_default_option(options_,'nomoments',0); - options_ = set_default_option(options_,'nocorr',0); - options_ = set_default_option(options_,'simul_seed',[]); - options_ = set_default_option(options_,'hp_filter',0); - options_ = set_default_option(options_,'hp_ngrid',512); - options_ = set_default_option(options_,'simul',0); - options_ = set_default_option(options_,'periods',1); - - make_ex_; +options_.order = 1; +options_ = set_default_option(options_,'linear',0); +options_ = set_default_option(options_,'ar',5); +options_ = set_default_option(options_,'irf',40); +options_ = set_default_option(options_,'drop',100); +options_ = set_default_option(options_,'replic',1); +options_ = set_default_option(options_,'nomoments',0); +options_ = set_default_option(options_,'nocorr',0); +options_ = set_default_option(options_,'simul_seed',[]); +options_ = set_default_option(options_,'hp_filter',0); +options_ = set_default_option(options_,'hp_ngrid',512); +options_ = set_default_option(options_,'simul',0); +options_ = set_default_option(options_,'periods',1); - np = size(params,1); - i_params = zeros(np,1); - for i=1:np +make_ex_; + +np = size(params,1); +i_params = zeros(np,1); +for i=1:np i_params(i) = strmatch(deblank(params(i,:)),M_.param_names,'exact'); - end - - disp(' ') - disp('OPTIMAL SIMPLE RULE') - disp(' ') - osr1(i_params,i_var,W); +end + +disp(' ') +disp('OPTIMAL SIMPLE RULE') +disp(' ') +osr1(i_params,i_var,W); - stoch_simul(var_list); \ No newline at end of file +stoch_simul(var_list); \ No newline at end of file diff --git a/matlab/osr1.m b/matlab/osr1.m index 17dda24a3b..6f964e48fb 100644 --- a/matlab/osr1.m +++ b/matlab/osr1.m @@ -17,65 +17,65 @@ function osr1(i_params,i_var,weights) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ oo_ options_ it_ +global M_ oo_ options_ it_ - klen = M_.maximum_lag + M_.maximum_lead + 1; - iyv = M_.lead_lag_incidence'; - iyv = iyv(:); - iyr0 = find(iyv) ; - it_ = M_.maximum_lag + 1 ; +klen = M_.maximum_lag + M_.maximum_lead + 1; +iyv = M_.lead_lag_incidence'; +iyv = iyv(:); +iyr0 = find(iyv) ; +it_ = M_.maximum_lag + 1 ; - if M_.exo_nbr == 0 +if M_.exo_nbr == 0 oo_.exo_steady_state = [] ; - end +end - if ~ M_.lead_lag_incidence(M_.maximum_lag+1,:) > 0 +if ~ M_.lead_lag_incidence(M_.maximum_lag+1,:) > 0 error ('OSR: Error in model specification: some variables don"t appear as current') ; - end +end - if M_.maximum_lead == 0 +if M_.maximum_lead == 0 error ('Backward or static model: no point in using OLR') ; - end - - exe =zeros(M_.exo_nbr,1); - - dr = set_state_space(oo_.dr,M_); - - % check if ys is steady state - if exist([M_.fname '_steadystate']) - [ys,check1] = feval([M_.fname '_steadystate'],oo_.steady_state,... - [oo_.exo_steady_state; oo_.exo_det_steady_state]); - if size(ys,1) < M_.endo_nbr - if length(M_.aux_vars) > 0 - ys = add_auxiliary_variables_to_steadystate(ys,M_.aux_vars,... - M_.fname,... - oo_.exo_steady_state,... - oo_.exo_det_steady_state); - else - error([M_.fname '_steadystate.m doesn''t match the model']); - end - end - dr.ys = ys; - else - % testing if ys isn't a steady state or if we aren't computing Ramsey policy - fh = str2func([M_.fname '_static']); - if max(abs(feval(fh,oo_.steady_state,[oo_.exo_steady_state; oo_.exo_det_steady_state], M_.params))) ... - > options_.dynatol & options_.ramsey_policy == 0 - if options_.linear == 0 - % nonlinear models - [dr.ys,check1] = dynare_solve(fh,dr.ys,options_.jacobian_flag,... - [oo_.exo_steady_state; ... - oo_.exo_det_steady_state], M_.params); - else - % linear models - [fvec,jacob] = feval(fh,oo_.steady_state,[oo_.exo_steady_state;... - oo_.exo_det_steady_state], M_.params); - dr.ys = oo_.steady_state-jacob\fvec; - end - end - end - oo_.dr = dr; +end + +exe =zeros(M_.exo_nbr,1); + +dr = set_state_space(oo_.dr,M_); + +% check if ys is steady state +if exist([M_.fname '_steadystate']) + [ys,check1] = feval([M_.fname '_steadystate'],oo_.steady_state,... + [oo_.exo_steady_state; oo_.exo_det_steady_state]); + if size(ys,1) < M_.endo_nbr + if length(M_.aux_vars) > 0 + ys = add_auxiliary_variables_to_steadystate(ys,M_.aux_vars,... + M_.fname,... + oo_.exo_steady_state,... + oo_.exo_det_steady_state); + else + error([M_.fname '_steadystate.m doesn''t match the model']); + end + end + dr.ys = ys; +else + % testing if ys isn't a steady state or if we aren't computing Ramsey policy + fh = str2func([M_.fname '_static']); + if max(abs(feval(fh,oo_.steady_state,[oo_.exo_steady_state; oo_.exo_det_steady_state], M_.params))) ... + > options_.dynatol & options_.ramsey_policy == 0 + if options_.linear == 0 + % nonlinear models + [dr.ys,check1] = dynare_solve(fh,dr.ys,options_.jacobian_flag,... + [oo_.exo_steady_state; ... + oo_.exo_det_steady_state], M_.params); + else + % linear models + [fvec,jacob] = feval(fh,oo_.steady_state,[oo_.exo_steady_state;... + oo_.exo_det_steady_state], M_.params); + dr.ys = oo_.steady_state-jacob\fvec; + end + end +end +oo_.dr = dr; % $$$ if max(abs(feval(fh, oo_.steady_state, exe, M_.params))) > options_.dynatol % $$$ [oo_.dr.ys, check] = dynare_solve([M_.fname '_static'], oo_.steady_state, 1, exe, M_.params); % $$$ if check @@ -85,34 +85,34 @@ function osr1(i_params,i_var,weights) % $$$ oo_.dr.ys = oo_.steady_state; % $$$ end - - np = size(i_params,1); - t0 = M_.params(i_params); - inv_order_var = oo_.dr.inv_order_var; - H0 = 1e-4*eye(np); - crit = 1e-7; - nit = 1000; - verbose = 2; +np = size(i_params,1); +t0 = M_.params(i_params); +inv_order_var = oo_.dr.inv_order_var; - [f,p]=csminwel('osr_obj',t0,H0,[],crit,nit,options_.gradient_method,i_params,... - inv_order_var(i_var),weights(i_var,i_var)); +H0 = 1e-4*eye(np); +crit = 1e-7; +nit = 1000; +verbose = 2; - % options = optimset('fminunc'); +[f,p]=csminwel('osr_obj',t0,H0,[],crit,nit,options_.gradient_method,i_params,... + inv_order_var(i_var),weights(i_var,i_var)); + +% options = optimset('fminunc'); % options = optimset('display','iter'); % [p,f]=fminunc(@osr_obj,t0,options,i_params,... % inv_order_var(i_var),weights(i_var,i_var)); - - disp('') - disp('OPTIMAL VALUE OF THE PARAMETERS:') - disp('') - for i=1:np + +disp('') +disp('OPTIMAL VALUE OF THE PARAMETERS:') +disp('') +for i=1:np disp(sprintf('%16s %16.6g\n',M_.param_names(i_params(i),:),p(i))) - end - disp(sprintf('Objective function : %16.6g\n',f)); - disp(' ') - oo_.dr=resol(oo_.steady_state,0); +end +disp(sprintf('Objective function : %16.6g\n',f)); +disp(' ') +oo_.dr=resol(oo_.steady_state,0); - % 05/10/03 MJ modified to work with osr.m and give full report \ No newline at end of file +% 05/10/03 MJ modified to work with osr.m and give full report \ No newline at end of file diff --git a/matlab/osr_obj.m b/matlab/osr_obj.m index d5d8148da8..d109b070a7 100644 --- a/matlab/osr_obj.m +++ b/matlab/osr_obj.m @@ -18,42 +18,42 @@ function [loss,vx,info]=osr_obj(x,i_params,i_var,weights); % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ oo_ optimal_Q_ it_ +global M_ oo_ optimal_Q_ it_ % global ys_ Sigma_e_ endo_nbr exo_nbr optimal_Q_ it_ ykmin_ options_ - - vx = []; - % set parameters of the policiy rule - M_.params(i_params) = x; - - % don't change below until the part where the loss function is computed - it_ = M_.maximum_lag+1; - [dr,info] = resol(oo_.steady_state,0); - - switch info(1) - case 1 + +vx = []; +% set parameters of the policiy rule +M_.params(i_params) = x; + +% don't change below until the part where the loss function is computed +it_ = M_.maximum_lag+1; +[dr,info] = resol(oo_.steady_state,0); + +switch info(1) + case 1 loss = 1e8; return - case 2 + case 2 loss = 1e8*min(1e3,info(2)); return - case 3 + case 3 loss = 1e8*min(1e3,info(2)); return - case 4 + case 4 loss = 1e8*min(1e3,info(2)); return - case 5 + case 5 loss = 1e8; return - case 20 + case 20 loss = 1e8*min(1e3,info(2)); return - otherwise - end - - vx = get_variance_of_endogenous_variables(dr,i_var); - loss = weights(:)'*vx(:); - + otherwise +end + +vx = get_variance_of_endogenous_variables(dr,i_var); +loss = weights(:)'*vx(:); + diff --git a/matlab/perfect_foresight_simulation.m b/matlab/perfect_foresight_simulation.m index 047c91b59b..b00ec2c99c 100644 --- a/matlab/perfect_foresight_simulation.m +++ b/matlab/perfect_foresight_simulation.m @@ -1,172 +1,172 @@ function [info,endo_simul] = perfect_foresight_simulation(endo_simul,exo_simul,compute_linear_solution,steady_state) - % Performs deterministic simulations with lead or lag on one period - % - % INPUTS - % endo_simul [double] n*T matrix, where n is the number of endogenous variables. - % exo_simul [double] q*T matrix, where q is the number of shocks. - % compute_linear_solution [integer] scalar equal to zero or one. - % - % OUTPUTS - % none - % - % ALGORITHM - % Laffargue, Boucekkine, Juillard (LBJ) - % see Juillard (1996) Dynare: A program for the resolution and - % simulation of dynamic models with forward variables through the use - % of a relaxation algorithm. CEPREMAP. Couverture Orange. 9602. - % - % SPECIAL REQUIREMENTS - % None. - - % Copyright (C) 1996-2009 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 <http://www.gnu.org/licenses/>. - - global M_ options_ it_ - - persistent flag_init - persistent lead_lag_incidence dynamic_model ny nyp nyf nrs nrc iyf iyp isp is isf isf1 iz icf - persistent ghx - - if isempty(flag_init) - lead_lag_incidence = M_.lead_lag_incidence; - dynamic_model = [M_.fname '_dynamic']; - ny = size(endo_simul,1); - nyp = nnz(lead_lag_incidence(1,:));% number of lagged variables. - nyf = nnz(lead_lag_incidence(3,:));% number of leaded variables. - nrs = ny+nyp+nyf+1; - nrc = nyf+1; - iyf = find(lead_lag_incidence(3,:)>0);% indices for leaded variables. - iyp = find(lead_lag_incidence(1,:)>0);% indices for lagged variables. - isp = 1:nyp; - is = (nyp+1):(nyp+ny); % Indices for contemporaneaous variables. - isf = iyf+nyp; - isf1 = (nyp+ny+1):(nyf+nyp+ny+1); - iz = 1:(ny+nyp+nyf); - icf = 1:size(iyf,2); - flag_init = 1; - end - - if nargin<3 - compute_linear_solution = 0; - if nargin<4 - error('The steady state (fourth input argument) is missing!'); - end - end - - if compute_linear_solution - [dr,info]=resol(steady_state,0); - ghx = dr.ghx(end-dr.nfwrd+1:end,:); - end - - periods = options_.periods; - - stop = 0 ; - it_init = M_.maximum_lag+1; - - info.convergence = 1; - info.time = 0; - info.error = 0; - info.iterations.time = zeros(options_.maxit_,1); - info.iterations.error = info.iterations.time; - - last_line = options_.maxit_; - error_growth = 0; - - h1 = clock; - for iter = 1:options_.maxit_ - h2 = clock; - if options_.terminal_condition - c = zeros(ny*(periods+1),nrc); - else - c = zeros(ny*periods,nrc); - end - it_ = it_init; - z = [ endo_simul(iyp,it_-1) ; endo_simul(:,it_) ; endo_simul(iyf,it_+1) ]; - [d1,jacobian] = feval(dynamic_model,z,exo_simul, M_.params, it_); - jacobian = [jacobian(:,iz) , -d1]; - ic = 1:ny; - icp = iyp; - c(ic,:) = jacobian(:,is)\jacobian(:,isf1) ; - for it_ = it_init+(1:periods-1) - z = [ endo_simul(iyp,it_-1) ; endo_simul(:,it_) ; endo_simul(iyf,it_+1)]; - [d1,jacobian] = feval(dynamic_model,z,exo_simul, M_.params, it_); - jacobian = [jacobian(:,iz) , -d1]; - jacobian(:,[isf nrs]) = jacobian(:,[isf nrs])-jacobian(:,isp)*c(icp,:); - ic = ic + ny; - icp = icp + ny; - c(ic,:) = jacobian(:,is)\jacobian(:,isf1); - end - if options_.terminal_condition - if options_.terminal_condition==1% Terminal condition is Y_{T} = Y_{T+1} - s = eye(ny); - s(:,isf) = s(:,isf)+c(ic,1:nyf); - ic = ic + ny; - c(ic,nrc) = s\c(ic,nrc); - else% Terminal condition is Y_{T}-Y^{\star} = TransitionMatrix*(Y_{T+1}-Y^{\star}) - z = [ endo_simul(iyp,it_-1) ; endo_simul(:,it_) ; endo_simul(iyf,it_+1) ] ; - [d1,jacobian] = feval(dynamic_model,z,exo_simul, M_.params, it_); - jacobian = [jacobian(:,iz) -d1]; - jacobian(:,[isf nrs]) = jacobian(:,[isf nrs])-jacobian(:,isp)*c(icp,:) ; - ic = ic + ny; - icp = icp + ny; - s = jacobian(:,is); - s(:,iyp-nyp) = s(:,iyp-nyp)+jacobian(:,isf)*ghx; - c (ic,:) = s\jacobian(:,isf1); - end - c = bksup0(c,ny,nrc,iyf,icf,periods); - c = reshape(c,ny,periods+1); - endo_simul(:,it_init+(0:periods)) = endo_simul(:,it_init+(0:periods))+options_.slowc*c; - else% Terminal condition is Y_{T}=Y^{\star} - c = bksup0(c,ny,nrc,iyf,icf,periods); - c = reshape(c,ny,periods); - endo_simul(:,it_init+(0:periods-1)) = endo_simul(:,it_init+(0:periods-1))+options_.slowc*c; - end - err = max(max(abs(c))); - info.iterations.time(iter) = etime(clock,h2); - info.iterations.error(iter) = err; - % if iter>1 - % error_growth = error_growth + (info.iterations.error(iter)>info.iterations.error(iter-1)); - % end - % if isnan(err) || error_growth>3 - % last_line = iter; - % break - % end - if err < options_.dynatol - stop = 1; - info.time = etime(clock,h1); - info.error = err; - info.iterations.time = info.iterations.time(1:iter); - info.iterations.error = info.iterations.error(1:iter); - break - end - end - - if options_.terminal_condition==2 - distance_to_steady_state = abs(((endo_simul(:,end-1)-endo_simul(:,end))./endo_simul(:,end)))*100; - disp('Distance to steady state at the end is (in percentage):') - distance_to_steady_state - end - - if ~stop - info.time = etime(clock,h1); - info.error = err; - info.convergence = 0; - info.iterations.time = info.iterations.time(1:last_line); - info.iterations.error = info.iterations.error(1:last_line); - info.iterations.error - endo_simul = [ ]; - end \ No newline at end of file +% Performs deterministic simulations with lead or lag on one period +% +% INPUTS +% endo_simul [double] n*T matrix, where n is the number of endogenous variables. +% exo_simul [double] q*T matrix, where q is the number of shocks. +% compute_linear_solution [integer] scalar equal to zero or one. +% +% OUTPUTS +% none +% +% ALGORITHM +% Laffargue, Boucekkine, Juillard (LBJ) +% see Juillard (1996) Dynare: A program for the resolution and +% simulation of dynamic models with forward variables through the use +% of a relaxation algorithm. CEPREMAP. Couverture Orange. 9602. +% +% SPECIAL REQUIREMENTS +% None. + +% Copyright (C) 1996-2009 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 <http://www.gnu.org/licenses/>. + +global M_ options_ it_ + +persistent flag_init +persistent lead_lag_incidence dynamic_model ny nyp nyf nrs nrc iyf iyp isp is isf isf1 iz icf +persistent ghx + +if isempty(flag_init) + lead_lag_incidence = M_.lead_lag_incidence; + dynamic_model = [M_.fname '_dynamic']; + ny = size(endo_simul,1); + nyp = nnz(lead_lag_incidence(1,:));% number of lagged variables. + nyf = nnz(lead_lag_incidence(3,:));% number of leaded variables. + nrs = ny+nyp+nyf+1; + nrc = nyf+1; + iyf = find(lead_lag_incidence(3,:)>0);% indices for leaded variables. + iyp = find(lead_lag_incidence(1,:)>0);% indices for lagged variables. + isp = 1:nyp; + is = (nyp+1):(nyp+ny); % Indices for contemporaneaous variables. + isf = iyf+nyp; + isf1 = (nyp+ny+1):(nyf+nyp+ny+1); + iz = 1:(ny+nyp+nyf); + icf = 1:size(iyf,2); + flag_init = 1; +end + +if nargin<3 + compute_linear_solution = 0; + if nargin<4 + error('The steady state (fourth input argument) is missing!'); + end +end + +if compute_linear_solution + [dr,info]=resol(steady_state,0); + ghx = dr.ghx(end-dr.nfwrd+1:end,:); +end + +periods = options_.periods; + +stop = 0 ; +it_init = M_.maximum_lag+1; + +info.convergence = 1; +info.time = 0; +info.error = 0; +info.iterations.time = zeros(options_.maxit_,1); +info.iterations.error = info.iterations.time; + +last_line = options_.maxit_; +error_growth = 0; + +h1 = clock; +for iter = 1:options_.maxit_ + h2 = clock; + if options_.terminal_condition + c = zeros(ny*(periods+1),nrc); + else + c = zeros(ny*periods,nrc); + end + it_ = it_init; + z = [ endo_simul(iyp,it_-1) ; endo_simul(:,it_) ; endo_simul(iyf,it_+1) ]; + [d1,jacobian] = feval(dynamic_model,z,exo_simul, M_.params, it_); + jacobian = [jacobian(:,iz) , -d1]; + ic = 1:ny; + icp = iyp; + c(ic,:) = jacobian(:,is)\jacobian(:,isf1) ; + for it_ = it_init+(1:periods-1) + z = [ endo_simul(iyp,it_-1) ; endo_simul(:,it_) ; endo_simul(iyf,it_+1)]; + [d1,jacobian] = feval(dynamic_model,z,exo_simul, M_.params, it_); + jacobian = [jacobian(:,iz) , -d1]; + jacobian(:,[isf nrs]) = jacobian(:,[isf nrs])-jacobian(:,isp)*c(icp,:); + ic = ic + ny; + icp = icp + ny; + c(ic,:) = jacobian(:,is)\jacobian(:,isf1); + end + if options_.terminal_condition + if options_.terminal_condition==1% Terminal condition is Y_{T} = Y_{T+1} + s = eye(ny); + s(:,isf) = s(:,isf)+c(ic,1:nyf); + ic = ic + ny; + c(ic,nrc) = s\c(ic,nrc); + else% Terminal condition is Y_{T}-Y^{\star} = TransitionMatrix*(Y_{T+1}-Y^{\star}) + z = [ endo_simul(iyp,it_-1) ; endo_simul(:,it_) ; endo_simul(iyf,it_+1) ] ; + [d1,jacobian] = feval(dynamic_model,z,exo_simul, M_.params, it_); + jacobian = [jacobian(:,iz) -d1]; + jacobian(:,[isf nrs]) = jacobian(:,[isf nrs])-jacobian(:,isp)*c(icp,:) ; + ic = ic + ny; + icp = icp + ny; + s = jacobian(:,is); + s(:,iyp-nyp) = s(:,iyp-nyp)+jacobian(:,isf)*ghx; + c (ic,:) = s\jacobian(:,isf1); + end + c = bksup0(c,ny,nrc,iyf,icf,periods); + c = reshape(c,ny,periods+1); + endo_simul(:,it_init+(0:periods)) = endo_simul(:,it_init+(0:periods))+options_.slowc*c; + else% Terminal condition is Y_{T}=Y^{\star} + c = bksup0(c,ny,nrc,iyf,icf,periods); + c = reshape(c,ny,periods); + endo_simul(:,it_init+(0:periods-1)) = endo_simul(:,it_init+(0:periods-1))+options_.slowc*c; + end + err = max(max(abs(c))); + info.iterations.time(iter) = etime(clock,h2); + info.iterations.error(iter) = err; + % if iter>1 + % error_growth = error_growth + (info.iterations.error(iter)>info.iterations.error(iter-1)); + % end + % if isnan(err) || error_growth>3 + % last_line = iter; + % break + % end + if err < options_.dynatol + stop = 1; + info.time = etime(clock,h1); + info.error = err; + info.iterations.time = info.iterations.time(1:iter); + info.iterations.error = info.iterations.error(1:iter); + break + end +end + +if options_.terminal_condition==2 + distance_to_steady_state = abs(((endo_simul(:,end-1)-endo_simul(:,end))./endo_simul(:,end)))*100; + disp('Distance to steady state at the end is (in percentage):') + distance_to_steady_state +end + +if ~stop + info.time = etime(clock,h1); + info.error = err; + info.convergence = 0; + info.iterations.time = info.iterations.time(1:last_line); + info.iterations.error = info.iterations.error(1:last_line); + info.iterations.error + endo_simul = [ ]; +end \ No newline at end of file diff --git a/matlab/plot_icforecast.m b/matlab/plot_icforecast.m index 88a1145b90..8d35fab0ec 100644 --- a/matlab/plot_icforecast.m +++ b/matlab/plot_icforecast.m @@ -42,18 +42,18 @@ for i=1:size(Variables,1) end function build_figure(name,cci1,cci2,mm1,mm2) - figure('Name',['Conditional forecast: ' name '.']); - H = length(mm1); - h1 = area(1:H,cci1(2,1:H)); - set(h1,'BaseValue',min([min(cci1(1,:)),min(cci2(1,:))])) - set(h1,'FaceColor',[.9 .9 .9]) - hold on - h2 = area(1:H,cci1(1,1:H)); - set(h2,'BaseValue',min([min(cci1(1,:)),min(cci2(1,:))])) - set(h2,'FaceColor',[1 1 1]) - plot(1:H,mm1,'-k','linewidth',3) - plot(1:H,mm2,'--k','linewidth',3) - plot(1:H,cci2(1,:),'--k','linewidth',1) - plot(1:H,cci2(2,:),'--k','linewidth',1) - axis tight - hold off \ No newline at end of file +figure('Name',['Conditional forecast: ' name '.']); +H = length(mm1); +h1 = area(1:H,cci1(2,1:H)); +set(h1,'BaseValue',min([min(cci1(1,:)),min(cci2(1,:))])) +set(h1,'FaceColor',[.9 .9 .9]) +hold on +h2 = area(1:H,cci1(1,1:H)); +set(h2,'BaseValue',min([min(cci1(1,:)),min(cci2(1,:))])) +set(h2,'FaceColor',[1 1 1]) +plot(1:H,mm1,'-k','linewidth',3) +plot(1:H,mm2,'--k','linewidth',3) +plot(1:H,cci2(1,:),'--k','linewidth',1) +plot(1:H,cci2(2,:),'--k','linewidth',1) +axis tight +hold off \ No newline at end of file diff --git a/matlab/plot_priors.m b/matlab/plot_priors.m index 1a10e2ddda..94e9b221e6 100644 --- a/matlab/plot_priors.m +++ b/matlab/plot_priors.m @@ -37,10 +37,10 @@ npar = length(bayestopt_.p1); [nbplt,nr,nc,lr,lc,nstar] = pltorg(npar); if TeX - fidTeX = fopen([M_.fname '_Priors.TeX'],'w'); - fprintf(fidTeX,'%% TeX eps-loader file generated by plot_priors.m (Dynare).\n'); - fprintf(fidTeX,['%% ' datestr(now,0) '\n']); - fprintf(fidTeX,' \n'); + fidTeX = fopen([M_.fname '_Priors.TeX'],'w'); + fprintf(fidTeX,'%% TeX eps-loader file generated by plot_priors.m (Dynare).\n'); + fprintf(fidTeX,['%% ' datestr(now,0) '\n']); + fprintf(fidTeX,' \n'); end if nbplt == 1 h1 = figure('Name',figurename); @@ -64,14 +64,14 @@ if nbplt == 1 end eval(['print -depsc2 ' M_.fname '_Priors' int2str(1) '.eps']); if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' M_.fname '_Priors' int2str(1)]); - saveas(h1,[M_.fname '_Priors' int2str(1) '.fig']); + eval(['print -dpdf ' M_.fname '_Priors' int2str(1)]); + saveas(h1,[M_.fname '_Priors' int2str(1) '.fig']); end if options_.nograph, close(h1), end if TeX fprintf(fidTeX,'\\begin{figure}[H]\n'); for jj = 1:npar - fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); + fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); end fprintf(fidTeX,'\\centering\n'); fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_Priors%s}\n',M_.fname,int2str(1)); @@ -81,7 +81,7 @@ if nbplt == 1 fprintf(fidTeX,' \n'); fprintf(fidTeX,'%% End of TeX file.\n'); fclose(fidTeX); - end + end else for plt = 1:nbplt-1 hplt = figure('Name',figurename); @@ -107,11 +107,11 @@ else end % index=1:nstar eval(['print -depsc2 ' M_.fname '_Priors' int2str(plt) '.eps']); if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' M_.fname '_Priors' int2str(plt)]); - saveas(hplt,[M_.fname '_Priors' int2str(plt) '.fig']); + eval(['print -dpdf ' M_.fname '_Priors' int2str(plt)]); + saveas(hplt,[M_.fname '_Priors' int2str(plt) '.fig']); end if options_.nograph, close(hplt), end - if TeX + if TeX fprintf(fidTeX,'\\begin{figure}[H]\n'); for jj = 1:nstar fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); @@ -150,11 +150,11 @@ else end % index=1:npar-(nbplt-1)*nstar eval(['print -depsc2 ' M_.fname '_Priors' int2str(nbplt) '.eps']); if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' M_.fname '_Priors' int2str(nbplt)]); - saveas(hplt,[M_.fname '_Priors' int2str(nbplt) '.fig']); + eval(['print -dpdf ' M_.fname '_Priors' int2str(nbplt)]); + saveas(hplt,[M_.fname '_Priors' int2str(nbplt) '.fig']); end if options_.nograph, close(hplt), end - if TeX + if TeX fprintf(fidTeX,'\\begin{figure}[H]\n'); for jj = 1:npar-(nbplt-1)*nstar fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); diff --git a/matlab/pm3.m b/matlab/pm3.m index ca093f8299..134d426b73 100644 --- a/matlab/pm3.m +++ b/matlab/pm3.m @@ -17,57 +17,57 @@ function pm3(n1,n2,ifil,B,tit1,tit2,tit3,tit_tex,names1,names2,name3,DirectoryNa % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global options_ M_ oo_ +global options_ M_ oo_ - nn = 3; - MaxNumberOfPlotsPerFigure = nn^2; % must be square - varlist = names2; - if isempty(varlist) +nn = 3; +MaxNumberOfPlotsPerFigure = nn^2; % must be square +varlist = names2; +if isempty(varlist) varlist = names1; SelecVariables = (1:M_.endo_nbr)'; nvar = M_.endo_nbr; - else +else nvar = size(varlist,1); SelecVariables = []; for i=1:nvar - if ~isempty(strmatch(varlist(i,:),names1,'exact')) - SelecVariables = [SelecVariables;strmatch(varlist(i,:),names1,'exact')]; - end + if ~isempty(strmatch(varlist(i,:),names1,'exact')) + SelecVariables = [SelecVariables;strmatch(varlist(i,:),names1,'exact')]; + end end - end - if options_.TeX - % needs to be fixed +end +if options_.TeX + % needs to be fixed varlist_TeX = []; for i=1:nvar - varlist_TeX = strvcat(varlist_TeX,M_.endo_names_tex(SelecVariables(i),:)); + varlist_TeX = strvcat(varlist_TeX,M_.endo_names_tex(SelecVariables(i),:)); end - end - Mean = zeros(n2,nvar); - Median = zeros(n2,nvar); - Std = zeros(n2,nvar); - Distrib = zeros(9,n2,nvar); - HPD = zeros(2,n2,nvar); - fprintf(['MH: ' tit1 '\n']); - stock1 = zeros(n1,n2,B); - k = 0; - for file = 1:ifil +end +Mean = zeros(n2,nvar); +Median = zeros(n2,nvar); +Std = zeros(n2,nvar); +Distrib = zeros(9,n2,nvar); +HPD = zeros(2,n2,nvar); +fprintf(['MH: ' tit1 '\n']); +stock1 = zeros(n1,n2,B); +k = 0; +for file = 1:ifil load([DirectoryName '/' M_.fname var_type int2str(file)]); if size(size(stock),2) == 4 stock = squeeze(stock(1,:,1:n2,:)); end k = k(end)+(1:size(stock,3)); stock1(:,:,k) = stock; - end - clear stock - tmp =zeros(B,1); - for i = 1:nvar +end +clear stock +tmp =zeros(B,1); +for i = 1:nvar for j = 1:n2 - [Mean(j,i),Median(j,i),Var(j,i),HPD(:,j,i),Distrib(:,j,i)] = ... - posterior_moments(squeeze(stock1(SelecVariables(i),j,:)),0,options_.mh_conf_sig); + [Mean(j,i),Median(j,i),Var(j,i),HPD(:,j,i),Distrib(:,j,i)] = ... + posterior_moments(squeeze(stock1(SelecVariables(i),j,:)),0,options_.mh_conf_sig); end - end - clear stock1 - for i = 1:nvar +end +clear stock1 +for i = 1:nvar name = deblank(names1(SelecVariables(i),:)); eval(['oo_.' name3 '.Mean.' name ' = Mean(:,i);']); eval(['oo_.' name3 '.Median.' name ' = Median(:,i);']); @@ -75,79 +75,79 @@ function pm3(n1,n2,ifil,B,tit1,tit2,tit3,tit_tex,names1,names2,name3,DirectoryNa eval(['oo_.' name3 '.Distribution.' name ' = Distrib(:,:,i);']); eval(['oo_.' name3 '.HPDinf.' name ' = HPD(1,:,i);']); eval(['oo_.' name3 '.HPDsup.' name ' = HPD(2,:,i);']); - end - %% - %% Finally I build the plots. - %% - if options_.TeX +end +%% +%% Finally I build the plots. +%% +if options_.TeX fidTeX = fopen([M_.dname '/Output/' M_.fname '_' name3 '.TeX'],'w'); fprintf(fidTeX,'%% TeX eps-loader file generated by Dynare.\n'); fprintf(fidTeX,['%% ' datestr(now,0) '\n']); fprintf(fidTeX,' \n'); - end - %% - figunumber = 0; - subplotnum = 0; - hh = figure('Name',[tit1 ' ' int2str(figunumber+1)]); - for i=1:nvar +end +%% +figunumber = 0; +subplotnum = 0; +hh = figure('Name',[tit1 ' ' int2str(figunumber+1)]); +for i=1:nvar NAMES = []; if options_.TeX - TEXNAMES = []; + TEXNAMES = []; end if max(abs(Mean(:,i))) > 10^(-6) - subplotnum = subplotnum+1; - set(0,'CurrentFigure',hh) - subplot(nn,nn,subplotnum); - plot([1 n2],[0 0],'-r','linewidth',0.5); - hold on - for k = 1:9 - plot(1:n2,squeeze(Distrib(k,:,i)),'-g','linewidth',0.5) - end - plot(1:n2,Mean(:,i),'-k','linewidth',1) - xlim([1 n2]); - hold off - name = deblank(varlist(i,:)); - NAMES = strvcat(NAMES,name); - if options_.TeX - texname = deblank(varlist_TeX(i,:)); - TEXNAMES = strvcat(TEXNAMES,['$' texname '$']); - end - title(name,'Interpreter','none') + subplotnum = subplotnum+1; + set(0,'CurrentFigure',hh) + subplot(nn,nn,subplotnum); + plot([1 n2],[0 0],'-r','linewidth',0.5); + hold on + for k = 1:9 + plot(1:n2,squeeze(Distrib(k,:,i)),'-g','linewidth',0.5) + end + plot(1:n2,Mean(:,i),'-k','linewidth',1) + xlim([1 n2]); + hold off + name = deblank(varlist(i,:)); + NAMES = strvcat(NAMES,name); + if options_.TeX + texname = deblank(varlist_TeX(i,:)); + TEXNAMES = strvcat(TEXNAMES,['$' texname '$']); + end + title(name,'Interpreter','none') end if subplotnum == MaxNumberOfPlotsPerFigure | i == nvar - eval(['print -depsc2 ' M_.dname '/Output/' M_.fname '_' name3 '_' deblank(tit3(i,:)) '.eps' ]); - if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' M_.dname '/Output/' M_.fname '_' name3 '_' deblank(tit3(i,:))]); - saveas(hh,[M_.dname '/Output/' M_.fname '_' name3 '_' deblank(tit3(i,:)) '.fig']); - end - if options_.nograph, close(hh), end - if options_.TeX - fprintf(fidTeX,'\\begin{figure}[H]\n'); - for jj = 1:size(TEXNAMES,1) - fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{%s}\n'],deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:))); - end - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,['\\includegraphics[scale=0.5]{%s_' name3 '_%s}\n'],M_.fname,deblank(tit3(i,:))); - if options_.relative_irf - fprintf(fidTeX,['\\caption{' caption '.}']); - else - fprintf(fidTeX,['\\caption{' caption '.}']); - end - fprintf(fidTeX,'\\label{Fig:%s:%s}\n',name3,deblank(tit3(i,:))); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,' \n'); - end - subplotnum = 0; - figunumber = figunumber+1; - if (i ~= nvar) - hh = figure('Name',[name3 ' ' int2str(figunumber+1)]); - end + eval(['print -depsc2 ' M_.dname '/Output/' M_.fname '_' name3 '_' deblank(tit3(i,:)) '.eps' ]); + if ~exist('OCTAVE_VERSION') + eval(['print -dpdf ' M_.dname '/Output/' M_.fname '_' name3 '_' deblank(tit3(i,:))]); + saveas(hh,[M_.dname '/Output/' M_.fname '_' name3 '_' deblank(tit3(i,:)) '.fig']); + end + if options_.nograph, close(hh), end + if options_.TeX + fprintf(fidTeX,'\\begin{figure}[H]\n'); + for jj = 1:size(TEXNAMES,1) + fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{%s}\n'],deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:))); + end + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,['\\includegraphics[scale=0.5]{%s_' name3 '_%s}\n'],M_.fname,deblank(tit3(i,:))); + if options_.relative_irf + fprintf(fidTeX,['\\caption{' caption '.}']); + else + fprintf(fidTeX,['\\caption{' caption '.}']); + end + fprintf(fidTeX,'\\label{Fig:%s:%s}\n',name3,deblank(tit3(i,:))); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,' \n'); + end + subplotnum = 0; + figunumber = figunumber+1; + if (i ~= nvar) + hh = figure('Name',[name3 ' ' int2str(figunumber+1)]); + end end - end - %% - if options_.TeX +end +%% +if options_.TeX fprintf(fidTeX,'%% End of TeX file.\n'); fclose(fidTeX); - end - fprintf(['MH: ' tit1 ', done!\n']); +end +fprintf(['MH: ' tit1 ', done!\n']); diff --git a/matlab/posterior_analysis.m b/matlab/posterior_analysis.m index d943edec67..37e43ba1f2 100644 --- a/matlab/posterior_analysis.m +++ b/matlab/posterior_analysis.m @@ -15,68 +15,68 @@ function oo_ = posterior_analysis(type,arg1,arg2,arg3,options_,M_,oo_) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - info = check_posterior_analysis_data(type,M_); - SampleSize = options_.PosteriorSampleSize; - switch info - case 0 - disp('check_posterior_analysis_data:: Can''t find any mcmc file!') - error('Check the options of the estimation command...') - case {1,2} - MaxMegaBytes = options_.MaximumNumberOfMegaBytes; - drsize = size_of_the_reduced_form_model(oo_.dr); - if drsize*SampleSize>MaxMegaBytes - drsize=0; - end - SampleAddress = selec_posterior_draws(SampleSize,drsize); - oo_ = job(type,SampleSize,arg1,arg2,arg3,options_,M_,oo_); - case {4,5} - oo_ = job(type,SampleSize,arg1,arg2,arg3,options_,M_,oo_); - case 6 - [ivar,vartan] = set_stationary_variables_list(options_,M_); - nvar = length(ivar); - oo_ = job(type,SampleSize,arg1,arg2,arg3,options_,M_,oo_,nvar,vartan); - otherwise - error(['posterior_analysis:: Check_posterior_analysis_data gave a meaningless output!']) + +info = check_posterior_analysis_data(type,M_); +SampleSize = options_.PosteriorSampleSize; +switch info + case 0 + disp('check_posterior_analysis_data:: Can''t find any mcmc file!') + error('Check the options of the estimation command...') + case {1,2} + MaxMegaBytes = options_.MaximumNumberOfMegaBytes; + drsize = size_of_the_reduced_form_model(oo_.dr); + if drsize*SampleSize>MaxMegaBytes + drsize=0; end - - - + SampleAddress = selec_posterior_draws(SampleSize,drsize); + oo_ = job(type,SampleSize,arg1,arg2,arg3,options_,M_,oo_); + case {4,5} + oo_ = job(type,SampleSize,arg1,arg2,arg3,options_,M_,oo_); + case 6 + [ivar,vartan] = set_stationary_variables_list(options_,M_); + nvar = length(ivar); + oo_ = job(type,SampleSize,arg1,arg2,arg3,options_,M_,oo_,nvar,vartan); + otherwise + error(['posterior_analysis:: Check_posterior_analysis_data gave a meaningless output!']) +end + + + function oo_ = job(type,SampleSize,arg1,arg2,arg3,options_,M_,oo_,nvar,vartan) - narg1 = 8; - narg2 = 10; - if ~(nargin==narg1 || nargin==narg2) - error('posterior_analysis:: Call to function job is buggy!') +narg1 = 8; +narg2 = 10; +if ~(nargin==narg1 || nargin==narg2) + error('posterior_analysis:: Call to function job is buggy!') +end +switch type + case 'variance' + if nargin==narg1 + [nvar,vartan,NumberOfFiles] = ... + dsge_simulated_theoretical_covariance(SampleSize,M_,options_,oo_,'posterior'); end - switch type - case 'variance' - if nargin==narg1 - [nvar,vartan,NumberOfFiles] = ... - dsge_simulated_theoretical_covariance(SampleSize,M_,options_,oo_,'posterior'); - end - oo_ = covariance_mc_analysis(SampleSize,'posterior',M_.dname,M_.fname,... - vartan,nvar,arg1,arg2,options_.mh_conf_sig,oo_); - case 'decomposition' - if nargin==narg1 - [nvar,vartan,NumberOfFiles] = ... - dsge_simulated_theoretical_variance_decomposition(SampleSize,M_,options_,oo_,'posterior'); - end - oo_ = variance_decomposition_mc_analysis(SampleSize,'posterior',M_.dname,M_.fname,... - M_.exo_names,arg2,vartan,arg1,options_.mh_conf_sig,oo_); - case 'correlation' - if nargin==narg1 - [nvar,vartan,NumberOfFiles] = ... - dsge_simulated_theoretical_correlation(SampleSize,arg3,M_,options_,oo_,'posterior'); - end - oo_ = correlation_mc_analysis(SampleSize,'posterior',M_.dname,M_.fname,... - vartan,nvar,arg1,arg2,arg3,options_.mh_conf_sig,oo_,M_,options_); - case 'conditional decomposition' - if nargin==narg1 - [nvar,vartan,NumberOfFiles] = ... - dsge_simulated_theoretical_conditional_variance_decomposition(SampleSize,arg3,M_,options_,oo_,'posterior'); - end - oo_ = conditional_variance_decomposition_mc_analysis(SampleSize,'posterior',M_.dname,M_.fname,... - arg3,M_.exo_names,arg2,vartan,arg1,options_.mh_conf_sig,oo_); - otherwise - disp('Not yet implemented') - end \ No newline at end of file + oo_ = covariance_mc_analysis(SampleSize,'posterior',M_.dname,M_.fname,... + vartan,nvar,arg1,arg2,options_.mh_conf_sig,oo_); + case 'decomposition' + if nargin==narg1 + [nvar,vartan,NumberOfFiles] = ... + dsge_simulated_theoretical_variance_decomposition(SampleSize,M_,options_,oo_,'posterior'); + end + oo_ = variance_decomposition_mc_analysis(SampleSize,'posterior',M_.dname,M_.fname,... + M_.exo_names,arg2,vartan,arg1,options_.mh_conf_sig,oo_); + case 'correlation' + if nargin==narg1 + [nvar,vartan,NumberOfFiles] = ... + dsge_simulated_theoretical_correlation(SampleSize,arg3,M_,options_,oo_,'posterior'); + end + oo_ = correlation_mc_analysis(SampleSize,'posterior',M_.dname,M_.fname,... + vartan,nvar,arg1,arg2,arg3,options_.mh_conf_sig,oo_,M_,options_); + case 'conditional decomposition' + if nargin==narg1 + [nvar,vartan,NumberOfFiles] = ... + dsge_simulated_theoretical_conditional_variance_decomposition(SampleSize,arg3,M_,options_,oo_,'posterior'); + end + oo_ = conditional_variance_decomposition_mc_analysis(SampleSize,'posterior',M_.dname,M_.fname,... + arg3,M_.exo_names,arg2,vartan,arg1,options_.mh_conf_sig,oo_); + otherwise + disp('Not yet implemented') +end \ No newline at end of file diff --git a/matlab/posterior_moments.m b/matlab/posterior_moments.m index 767ded9652..c45cb3ed03 100644 --- a/matlab/posterior_moments.m +++ b/matlab/posterior_moments.m @@ -51,21 +51,21 @@ hpd_draws = round((1-mh_conf_sig)*number_of_draws); kk = zeros(hpd_draws,1); jj = number_of_draws-hpd_draws; for ii = 1:hpd_draws - kk(ii) = xx(jj)-xx(ii); - jj = jj + 1; + kk(ii) = xx(jj)-xx(ii); + jj = jj + 1; end [kmin,idx] = min(kk); hpd_interval = [xx(idx) xx(idx)+kmin]; post_deciles = xx([round(0.1*number_of_draws) ... - round(0.2*number_of_draws) ... - round(0.3*number_of_draws) ... - round(0.4*number_of_draws) ... - round(0.5*number_of_draws) ... - round(0.6*number_of_draws) ... - round(0.7*number_of_draws) ... - round(0.8*number_of_draws) ... - round(0.9*number_of_draws)]); + round(0.2*number_of_draws) ... + round(0.3*number_of_draws) ... + round(0.4*number_of_draws) ... + round(0.5*number_of_draws) ... + round(0.6*number_of_draws) ... + round(0.7*number_of_draws) ... + round(0.8*number_of_draws) ... + round(0.9*number_of_draws)]); density = []; if info @@ -74,5 +74,5 @@ if info kernel_function = 'gaussian'; % Gaussian kernel for Fast Fourrier Transform approximaton. optimal_bandwidth = mh_optimal_bandwidth(xx,number_of_draws,bandwidth,kernel_function); [density(:,1),density(:,2)] = kernel_density_estimate(xx,number_of_grid_points,... - number_of_draws,optimal_bandwidth,kernel_function); + number_of_draws,optimal_bandwidth,kernel_function); end \ No newline at end of file diff --git a/matlab/print_info.m b/matlab/print_info.m index be56f7e4c8..c997d97d5f 100644 --- a/matlab/print_info.m +++ b/matlab/print_info.m @@ -1,62 +1,62 @@ -function print_info(info,noprint) -% Prints error messages -% -% INPUTS -% info [double] vector returned by resol.m -% noprint [integer] equal to 0 if the error message has to be printed. -% OUTPUTS -% none -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2005-2009 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 <http://www.gnu.org/licenses/>. - - if ~noprint - switch info(1) - case 1 - error(['The model doesn''t determine the current variables' ... - ' uniquely']) - case 2 - error(['MJDGGES returns the following error code: ' ... - int2str(info(2))]) - case 3 - error(['Blanchard Kahn conditions are not satisfied: no stable' ... - ' equilibrium']) - case 4 - error(['Blanchard Kahn conditions are not satisfied:' ... - ' indeterminacy']) - case 5 - error(['Blanchard Kahn conditions are not satisfied:' ... - ' indeterminacy due to rank failure']) - case 6 - error('The jacobian matrix evaluated at the steady state is complex') - case 19 - error('The steadystate file did not compute the steady state (inconsistent deep parameters).') - case 20 - error(['Impossible to find the steady state. Either the model' ... - ' doesn''t have a unique steady state of the guess values' ... - ' are too far from the solution']) - case 21 - error('The steady state is complex.') - case 30 - error('Variance can''t be computed') - otherwise - error('This case shouldn''t happen. Contact the authors of Dynare') - end - end \ No newline at end of file +function print_info(info,noprint) +% Prints error messages +% +% INPUTS +% info [double] vector returned by resol.m +% noprint [integer] equal to 0 if the error message has to be printed. +% OUTPUTS +% none +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2005-2009 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 <http://www.gnu.org/licenses/>. + +if ~noprint + switch info(1) + case 1 + error(['The model doesn''t determine the current variables' ... + ' uniquely']) + case 2 + error(['MJDGGES returns the following error code: ' ... + int2str(info(2))]) + case 3 + error(['Blanchard Kahn conditions are not satisfied: no stable' ... + ' equilibrium']) + case 4 + error(['Blanchard Kahn conditions are not satisfied:' ... + ' indeterminacy']) + case 5 + error(['Blanchard Kahn conditions are not satisfied:' ... + ' indeterminacy due to rank failure']) + case 6 + error('The jacobian matrix evaluated at the steady state is complex') + case 19 + error('The steadystate file did not compute the steady state (inconsistent deep parameters).') + case 20 + error(['Impossible to find the steady state. Either the model' ... + ' doesn''t have a unique steady state of the guess values' ... + ' are too far from the solution']) + case 21 + error('The steady state is complex.') + case 30 + error('Variance can''t be computed') + otherwise + error('This case shouldn''t happen. Contact the authors of Dynare') + end +end \ No newline at end of file diff --git a/matlab/prior_analysis.m b/matlab/prior_analysis.m index 0f6408917f..63e4a678d7 100644 --- a/matlab/prior_analysis.m +++ b/matlab/prior_analysis.m @@ -15,69 +15,69 @@ function oo_ = prior_analysis(type,arg1,arg2,arg3,options_,M_,oo_) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - info = check_prior_analysis_data(type,M_); - SampleSize = options_.prior_mc; - switch info - case {0,1,2} - MaxMegaBytes = options_.MaximumNumberOfMegaBytes; - drsize = size_of_the_reduced_form_model(oo_.dr); - if drsize*SampleSize>MaxMegaBytes - drsave=0; - else - drsave=1; - end - load([M_.dname '/prior/definition.mat']); - prior_sampler(drsave,M_,bayestopt_,options_,oo_); - clear('bayestopt_'); - oo_ = job(type,SampleSize,arg1,arg2,arg3,options_,M_,oo_); - case {4,5} - oo_ = job(type,SampleSize,arg1,arg2,arg3,options_,M_,oo_); - case 6 - [ivar,vartan] = set_stationary_variables_list(options_,M_); - nvar = length(ivar); - oo_ = job(type,SampleSize,arg1,arg2,arg3,options_,M_,oo_,nvar,vartan); - otherwise - error(['prior_analysis:: Check_prior_analysis_data gave a meaningless output!']) + +info = check_prior_analysis_data(type,M_); +SampleSize = options_.prior_mc; +switch info + case {0,1,2} + MaxMegaBytes = options_.MaximumNumberOfMegaBytes; + drsize = size_of_the_reduced_form_model(oo_.dr); + if drsize*SampleSize>MaxMegaBytes + drsave=0; + else + drsave=1; end - - - + load([M_.dname '/prior/definition.mat']); + prior_sampler(drsave,M_,bayestopt_,options_,oo_); + clear('bayestopt_'); + oo_ = job(type,SampleSize,arg1,arg2,arg3,options_,M_,oo_); + case {4,5} + oo_ = job(type,SampleSize,arg1,arg2,arg3,options_,M_,oo_); + case 6 + [ivar,vartan] = set_stationary_variables_list(options_,M_); + nvar = length(ivar); + oo_ = job(type,SampleSize,arg1,arg2,arg3,options_,M_,oo_,nvar,vartan); + otherwise + error(['prior_analysis:: Check_prior_analysis_data gave a meaningless output!']) +end + + + function oo_ = job(type,SampleSize,arg1,arg2,arg3,options_,M_,oo_,nvar,vartan) - narg1 = 8; - narg2 = 10; - if ~(nargin==narg1 || nargin==narg2) - error('prior_analysis:: Call to function job is buggy!') +narg1 = 8; +narg2 = 10; +if ~(nargin==narg1 || nargin==narg2) + error('prior_analysis:: Call to function job is buggy!') +end +switch type + case 'variance' + if nargin==narg1 + [nvar,vartan,NumberOfFiles] = ... + dsge_simulated_theoretical_covariance(SampleSize,M_,options_,oo_,'prior'); end - switch type - case 'variance' - if nargin==narg1 - [nvar,vartan,NumberOfFiles] = ... - dsge_simulated_theoretical_covariance(SampleSize,M_,options_,oo_,'prior'); - end - oo_ = covariance_mc_analysis(SampleSize,'prior',M_.dname,M_.fname,... - vartan,nvar,arg1,arg2,options_.mh_conf_sig,oo_); - case 'decomposition' - if nargin==narg1 - [nvar,vartan,NumberOfFiles] = ... - dsge_simulated_theoretical_variance_decomposition(SampleSize,M_,options_,oo_,'prior'); - end - oo_ = variance_decomposition_mc_analysis(SampleSize,'prior',M_.dname,M_.fname,... - M_.exo_names,arg2,vartan,arg1,options_.mh_conf_sig,oo_); - case 'correlation' - if nargin==narg1 - [nvar,vartan,NumberOfFiles] = ... - dsge_simulated_theoretical_correlation(SampleSize,arg3,M_,options_,oo_,'prior'); - end - oo_ = correlation_mc_analysis(SampleSize,'prior',M_.dname,M_.fname,... - vartan,nvar,arg1,arg2,arg3,options_.mh_conf_sig,oo_,M_,options_); - case 'conditional decomposition' - if nargin==narg1 - [nvar,vartan,NumberOfFiles] = ... - dsge_simulated_theoretical_conditional_variance_decomposition(SampleSize,arg3,M_,options_,oo_,'prior'); - end - oo_ = conditional_variance_decomposition_mc_analysis(SampleSize,'prior',M_.dname,M_.fname,... - arg3,M_.exo_names,arg2,vartan,arg1,options_.mh_conf_sig,oo_); - otherwise - disp('Not yet implemented') - end \ No newline at end of file + oo_ = covariance_mc_analysis(SampleSize,'prior',M_.dname,M_.fname,... + vartan,nvar,arg1,arg2,options_.mh_conf_sig,oo_); + case 'decomposition' + if nargin==narg1 + [nvar,vartan,NumberOfFiles] = ... + dsge_simulated_theoretical_variance_decomposition(SampleSize,M_,options_,oo_,'prior'); + end + oo_ = variance_decomposition_mc_analysis(SampleSize,'prior',M_.dname,M_.fname,... + M_.exo_names,arg2,vartan,arg1,options_.mh_conf_sig,oo_); + case 'correlation' + if nargin==narg1 + [nvar,vartan,NumberOfFiles] = ... + dsge_simulated_theoretical_correlation(SampleSize,arg3,M_,options_,oo_,'prior'); + end + oo_ = correlation_mc_analysis(SampleSize,'prior',M_.dname,M_.fname,... + vartan,nvar,arg1,arg2,arg3,options_.mh_conf_sig,oo_,M_,options_); + case 'conditional decomposition' + if nargin==narg1 + [nvar,vartan,NumberOfFiles] = ... + dsge_simulated_theoretical_conditional_variance_decomposition(SampleSize,arg3,M_,options_,oo_,'prior'); + end + oo_ = conditional_variance_decomposition_mc_analysis(SampleSize,'prior',M_.dname,M_.fname,... + arg3,M_.exo_names,arg2,vartan,arg1,options_.mh_conf_sig,oo_); + otherwise + disp('Not yet implemented') +end \ No newline at end of file diff --git a/matlab/prior_bounds.m b/matlab/prior_bounds.m index 0e150a046f..0043ef762c 100644 --- a/matlab/prior_bounds.m +++ b/matlab/prior_bounds.m @@ -40,58 +40,58 @@ prior_trunc = options_.prior_trunc; bounds = zeros(length(p6),2); for i=1:length(p6) - switch pshape(i) - case 1 - if prior_trunc == 0 - bounds(i,1) = p3(i); - bounds(i,2) = p4(i); - else - bounds(i,1) = betainv(prior_trunc,p6(i),p7(i))*(p4(i)-p3(i))+p3(i); - bounds(i,2) = betainv(1-prior_trunc,p6(i),p7(i))* ... - (p4(i)-p3(i))+p3(i); - end - case 2 - if prior_trunc == 0 - bounds(i,1) = p3(i); - bounds(i,2) = Inf; - else - bounds(i,1) = gaminv(prior_trunc,p6(i),p7(i))+p3(i); - bounds(i,2) = gaminv(1-prior_trunc,p6(i),p7(i))+p3(i); - end - case 3 - if prior_trunc == 0 - bounds(i,1) = -Inf; - bounds(i,2) = Inf; - else - bounds(i,1) = norminv(prior_trunc,p6(i),p7(i)); - bounds(i,2) = norminv(1-prior_trunc,p6(i),p7(i)); - end - case 4 - if prior_trunc == 0 - bounds(i,1) = p3(i); - bounds(i,2) = Inf; - else - bounds(i,1) = 1/sqrt(gaminv(1-prior_trunc, p7(i)/2, 2/p6(i)))+p3(i); - bounds(i,2) = 1/sqrt(gaminv(prior_trunc, p7(i)/2, ... - 2/p6(i)))+p3(i); - end - case 5 - if prior_trunc == 0 - bounds(i,1) = p6(i); - bounds(i,2) = p7(i); - else - bounds(i,1) = p6(i)+(p7(i)-p6(i))*prior_trunc; - bounds(i,2) = p7(i)-(p7(i)-p6(i))*prior_trunc; - end - case 6 - if prior_trunc == 0 - bounds(i,1) = p3(i); - bounds(i,2) = Inf; - else - bounds(i,1) = 1/gaminv(1-prior_trunc, p7(i)/2, 2/p6(i))+p3(i); - bounds(i,2) = 1/gaminv(prior_trunc, p7(i)/2, 2/p6(i))+ p3(i); - end - otherwise - error(sprintf('prior_bounds: unknown distribution shape (index %d, type %d)', i, pshape(i))); - end + switch pshape(i) + case 1 + if prior_trunc == 0 + bounds(i,1) = p3(i); + bounds(i,2) = p4(i); + else + bounds(i,1) = betainv(prior_trunc,p6(i),p7(i))*(p4(i)-p3(i))+p3(i); + bounds(i,2) = betainv(1-prior_trunc,p6(i),p7(i))* ... + (p4(i)-p3(i))+p3(i); + end + case 2 + if prior_trunc == 0 + bounds(i,1) = p3(i); + bounds(i,2) = Inf; + else + bounds(i,1) = gaminv(prior_trunc,p6(i),p7(i))+p3(i); + bounds(i,2) = gaminv(1-prior_trunc,p6(i),p7(i))+p3(i); + end + case 3 + if prior_trunc == 0 + bounds(i,1) = -Inf; + bounds(i,2) = Inf; + else + bounds(i,1) = norminv(prior_trunc,p6(i),p7(i)); + bounds(i,2) = norminv(1-prior_trunc,p6(i),p7(i)); + end + case 4 + if prior_trunc == 0 + bounds(i,1) = p3(i); + bounds(i,2) = Inf; + else + bounds(i,1) = 1/sqrt(gaminv(1-prior_trunc, p7(i)/2, 2/p6(i)))+p3(i); + bounds(i,2) = 1/sqrt(gaminv(prior_trunc, p7(i)/2, ... + 2/p6(i)))+p3(i); + end + case 5 + if prior_trunc == 0 + bounds(i,1) = p6(i); + bounds(i,2) = p7(i); + else + bounds(i,1) = p6(i)+(p7(i)-p6(i))*prior_trunc; + bounds(i,2) = p7(i)-(p7(i)-p6(i))*prior_trunc; + end + case 6 + if prior_trunc == 0 + bounds(i,1) = p3(i); + bounds(i,2) = Inf; + else + bounds(i,1) = 1/gaminv(1-prior_trunc, p7(i)/2, 2/p6(i))+p3(i); + bounds(i,2) = 1/gaminv(prior_trunc, p7(i)/2, 2/p6(i))+ p3(i); + end + otherwise + error(sprintf('prior_bounds: unknown distribution shape (index %d, type %d)', i, pshape(i))); + end end \ No newline at end of file diff --git a/matlab/prior_draw.m b/matlab/prior_draw.m index 791aef8f48..3ce8c02a86 100644 --- a/matlab/prior_draw.m +++ b/matlab/prior_draw.m @@ -88,8 +88,8 @@ if gaussian_draws pdraw(gaussian_index) = randn(length(gaussian_index),1).*p7(gaussian_index) + p6(gaussian_index); out_of_bound = find( (pdraw(gaussian_index)'>ub(gaussian_index)) | (pdraw(gaussian_index)'<lb(gaussian_index))); while ~isempty(out_of_bound), - pdraw(gaussian_index(out_of_bound)) = randn(length(gaussian_index(out_of_bound)),1).*p7(gaussian_index(out_of_bound)) + p6(gaussian_index(out_of_bound)); - out_of_bound = find( (pdraw(gaussian_index)'>ub(gaussian_index)) | (pdraw(gaussian_index)'<lb(gaussian_index))); + pdraw(gaussian_index(out_of_bound)) = randn(length(gaussian_index(out_of_bound)),1).*p7(gaussian_index(out_of_bound)) + p6(gaussian_index(out_of_bound)); + out_of_bound = find( (pdraw(gaussian_index)'>ub(gaussian_index)) | (pdraw(gaussian_index)'<lb(gaussian_index))); end end @@ -97,8 +97,8 @@ if gamma_draws pdraw(gamma_index) = gamrnd(p6(gamma_index),p7(gamma_index))+p3(gamma_index); out_of_bound = find( (pdraw(gamma_index)'>ub(gamma_index)) | (pdraw(gamma_index)'<lb(gamma_index))); while ~isempty(out_of_bound), - pdraw(gamma_index(out_of_bound)) = gamrnd(p6(gamma_index(out_of_bound)),p7(gamma_index(out_of_bound)))+p3(gamma_index(out_of_bound)); - out_of_bound = find( (pdraw(gamma_index)'>ub(gamma_index)) | (pdraw(gamma_index)'<lb(gamma_index))); + pdraw(gamma_index(out_of_bound)) = gamrnd(p6(gamma_index(out_of_bound)),p7(gamma_index(out_of_bound)))+p3(gamma_index(out_of_bound)); + out_of_bound = find( (pdraw(gamma_index)'>ub(gamma_index)) | (pdraw(gamma_index)'<lb(gamma_index))); end end @@ -106,8 +106,8 @@ if beta_draws pdraw(beta_index) = (p4(beta_index)-p3(beta_index)).*betarnd(p6(beta_index),p7(beta_index))+p3(beta_index); out_of_bound = find( (pdraw(beta_index)'>ub(beta_index)) | (pdraw(beta_index)'<lb(beta_index))); while ~isempty(out_of_bound), - pdraw(beta_index(out_of_bound)) = (p4(beta_index(out_of_bound))-p3(beta_index(out_of_bound))).*betarnd(p6(beta_index(out_of_bound)),p7(beta_index(out_of_bound)))+p3(beta_index(out_of_bound)); - out_of_bound = find( (pdraw(beta_index)'>ub(beta_index)) | (pdraw(beta_index)'<lb(beta_index))); + pdraw(beta_index(out_of_bound)) = (p4(beta_index(out_of_bound))-p3(beta_index(out_of_bound))).*betarnd(p6(beta_index(out_of_bound)),p7(beta_index(out_of_bound)))+p3(beta_index(out_of_bound)); + out_of_bound = find( (pdraw(beta_index)'>ub(beta_index)) | (pdraw(beta_index)'<lb(beta_index))); end end @@ -116,9 +116,9 @@ if inverse_gamma_1_draws sqrt(1./gamrnd(p7(inverse_gamma_1_index)/2,2./p6(inverse_gamma_1_index)))+p3(inverse_gamma_1_index); out_of_bound = find( (pdraw(inverse_gamma_1_index)'>ub(inverse_gamma_1_index)) | (pdraw(inverse_gamma_1_index)'<lb(inverse_gamma_1_index))); while ~isempty(out_of_bound), - pdraw(inverse_gamma_1_index(out_of_bound)) = ... - sqrt(1./gamrnd(p7(inverse_gamma_1_index(out_of_bound))/2,2./p6(inverse_gamma_1_index(out_of_bound))))+p3(inverse_gamma_1_index(out_of_bound)); - out_of_bound = find( (pdraw(inverse_gamma_1_index)'>ub(inverse_gamma_1_index)) | (pdraw(inverse_gamma_1_index)'<lb(inverse_gamma_1_index))); + pdraw(inverse_gamma_1_index(out_of_bound)) = ... + sqrt(1./gamrnd(p7(inverse_gamma_1_index(out_of_bound))/2,2./p6(inverse_gamma_1_index(out_of_bound))))+p3(inverse_gamma_1_index(out_of_bound)); + out_of_bound = find( (pdraw(inverse_gamma_1_index)'>ub(inverse_gamma_1_index)) | (pdraw(inverse_gamma_1_index)'<lb(inverse_gamma_1_index))); end end @@ -127,8 +127,8 @@ if inverse_gamma_2_draws 1./gamrnd(p7(inverse_gamma_2_index)/2,2./p6(inverse_gamma_2_index))+p3(inverse_gamma_2_index); out_of_bound = find( (pdraw(inverse_gamma_2_index)'>ub(inverse_gamma_2_index)) | (pdraw(inverse_gamma_2_index)'<lb(inverse_gamma_2_index))); while ~isempty(out_of_bound), - pdraw(inverse_gamma_2_index(out_of_bound)) = ... - sqrt(1./gamrnd(p7(inverse_gamma_2_index(out_of_bound))/2,2./p6(inverse_gamma_2_index(out_of_bound))))+p3(inverse_gamma_2_index(out_of_bound)); - out_of_bound = find( (pdraw(inverse_gamma_2_index)'>ub(inverse_gamma_2_index)) | (pdraw(inverse_gamma_2_index)'<lb(inverse_gamma_2_index))); -end + pdraw(inverse_gamma_2_index(out_of_bound)) = ... + sqrt(1./gamrnd(p7(inverse_gamma_2_index(out_of_bound))/2,2./p6(inverse_gamma_2_index(out_of_bound))))+p3(inverse_gamma_2_index(out_of_bound)); + out_of_bound = find( (pdraw(inverse_gamma_2_index)'>ub(inverse_gamma_2_index)) | (pdraw(inverse_gamma_2_index)'<lb(inverse_gamma_2_index))); + end end diff --git a/matlab/prior_posterior_statistics.m b/matlab/prior_posterior_statistics.m index 71367a7ae6..a2986cdfea 100644 --- a/matlab/prior_posterior_statistics.m +++ b/matlab/prior_posterior_statistics.m @@ -1,318 +1,318 @@ -function prior_posterior_statistics(type,Y,gend,data_index,missing_value) -% function PosteriorFilterSmootherAndForecast(Y,gend, type) -% Computes posterior filter smoother and forecasts -% -% INPUTS -% type: posterior -% prior -% gsa -% Y: data -% gend: number of observations -% data_index [cell] 1*smpl cell of column vectors of indices. -% missing_value 1 if missing values, 0 otherwise -% -% OUTPUTS -% none -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2005-2009 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 <http://www.gnu.org/licenses/>. - -global options_ estim_params_ oo_ M_ bayestopt_ - -nvx = estim_params_.nvx; -nvn = estim_params_.nvn; -ncx = estim_params_.ncx; -ncn = estim_params_.ncn; -np = estim_params_.np ; -npar = nvx+nvn+ncx+ncn+np; -offset = npar-np; -naK = length(options_.filter_step_ahead); -%% -MaxNumberOfBytes=options_.MaxNumberOfBytes; -endo_nbr=M_.endo_nbr; -exo_nbr=M_.exo_nbr; -nvobs = size(options_.varobs,1); -iendo = 1:endo_nbr; -horizon = options_.forecast; -% moments_varendo = options_.moments_varendo; -filtered_vars = options_.filtered_vars; -if horizon - i_last_obs = gend+(1-M_.maximum_endo_lag:0); -end -maxlag = M_.maximum_endo_lag; -%% -DirectoryName = CheckPath('metropolis'); -load([ DirectoryName '/' M_.fname '_mh_history']) -FirstMhFile = record.KeepedDraws.FirstMhFile; -FirstLine = record.KeepedDraws.FirstLine; -TotalNumberOfMhFiles = sum(record.MhDraws(:,2)); LastMhFile = TotalNumberOfMhFiles; -TotalNumberOfMhDraws = sum(record.MhDraws(:,1)); -NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws); -clear record; -if ~isempty(options_.subdraws) - B = options_.subdraws; - if B > NumberOfDraws - B = NumberOfDraws; - end -else - B = min(1200, round(0.25*NumberOfDraws)); -end - -%% -MAX_nruns = min(B,ceil(MaxNumberOfBytes/(npar+2)/8)); -MAX_nsmoo = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*gend)/8)); -MAX_ninno = min(B,ceil(MaxNumberOfBytes/(exo_nbr*gend)/8)); -MAX_nerro = min(B,ceil(MaxNumberOfBytes/(size(options_.varobs,1)*gend)/8)); -if naK - MAX_naK = min(B,ceil(MaxNumberOfBytes/(size(options_.varobs,1)* ... - length(options_.filter_step_ahead)*gend)/8)); -end -if horizon - MAX_nforc1 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/8)); - MAX_nforc2 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/ ... - 8)); - IdObs = bayestopt_.mfys; - -end -MAX_momentsno = min(B,ceil(MaxNumberOfBytes/(get_moments_size(options_)*8))); -%% -varlist = options_.varlist; -if isempty(varlist) - varlist = M_.endo_names(1:M_.orig_endo_nbr, :); -end - nvar = size(varlist,1); - SelecVariables = []; - for i=1:nvar - if ~isempty(strmatch(varlist(i,:),M_.endo_names,'exact')) - SelecVariables = [SelecVariables;strmatch(varlist(i,:),M_.endo_names,'exact')]; - end - end - -irun = ones(7,1); -ifil = zeros(7,1); - -if exist('OCTAVE_VERSION') - diary off; -else - h = waitbar(0,'Taking subdraws...'); -end - -stock_param = zeros(MAX_nruns, npar); -stock_logpo = zeros(MAX_nruns,1); -stock_ys = zeros(MAX_nruns,endo_nbr); -run_smoother = 0; -if options_.smoother - stock_smooth = zeros(endo_nbr,gend,MAX_nsmoo); - stock_innov = zeros(exo_nbr,gend,B); - stock_error = zeros(nvobs,gend,MAX_nerro); - stock_update = zeros(endo_nbr,gend,MAX_nsmoo); - run_smoother = 1; -end - -if options_.filter_step_ahead - stock_filter_step_ahead = zeros(naK,endo_nbr,gend+ ... - options_.filter_step_ahead(end),MAX_naK); - run_smoother = 1; -end -if options_.forecast - stock_forcst_mean = zeros(endo_nbr,horizon+maxlag,MAX_nforc1); - stock_forcst_point = zeros(endo_nbr,horizon+maxlag,MAX_nforc2); - run_smoother = 1; -end -%if moments_varendo -% stock_moments = cell(MAX_momentsno,1); -%end -for b=1:B - [deep, logpo] = GetOneDraw(type); - set_all_parameters(deep); - dr = resol(oo_.steady_state,0); - - %if moments_varendo - % stock_moments{irun(8)} = compute_model_moments(dr,M_,options_); - %end - - if run_smoother - [alphahat,etahat,epsilonhat,alphatilde,SteadyState,trend_coeff,aK] = ... - DsgeSmoother(deep,gend,Y,data_index,missing_value); - if options_.loglinear - stock_smooth(dr.order_var,:,irun(1)) = alphahat(1:endo_nbr,:)+ ... - repmat(log(dr.ys(dr.order_var)),1,gend); - stock_update(dr.order_var,:,irun(1)) = alphatilde(1:endo_nbr,:)+ ... - repmat(log(dr.ys(dr.order_var)),1,gend); - else - stock_smooth(dr.order_var,:,irun(1)) = alphahat(1:endo_nbr,:)+ ... - repmat(dr.ys(dr.order_var),1,gend); - stock_update(dr.order_var,:,irun(1)) = alphatilde(1:endo_nbr,:)+ ... - repmat(dr.ys(dr.order_var),1,gend); - end - stock_innov(:,:,irun(2)) = etahat; - if nvn - stock_error(:,:,irun(3)) = epsilonhat; - end - if naK - stock_filter_step_ahead(:,dr.order_var,:,irun(4)) = aK(options_.filter_step_ahead,1:endo_nbr,:); - end - - if horizon - yyyy = alphahat(iendo,i_last_obs); - yf = forcst2a(yyyy,dr,zeros(horizon,exo_nbr)); - if options_.prefilter == 1 - yf(:,IdObs) = yf(:,IdObs)+repmat(bayestopt_.mean_varobs', ... - horizon+maxlag,1); - end - yf(:,IdObs) = yf(:,IdObs)+(gend+[1-maxlag:horizon]')*trend_coeff'; - if options_.loglinear == 1 - yf = yf+repmat(log(SteadyState'),horizon+maxlag,1); - else - yf = yf+repmat(SteadyState',horizon+maxlag,1); - end - yf1 = forcst2(yyyy,horizon,dr,1); - if options_.prefilter == 1 - yf1(:,IdObs,:) = yf1(:,IdObs,:)+ ... - repmat(bayestopt_.mean_varobs',[horizon+maxlag,1,1]); - end - yf1(:,IdObs,:) = yf1(:,IdObs,:)+repmat((gend+[1-maxlag:horizon]')* ... - trend_coeff',[1,1,1]); - if options_.loglinear == 1 - yf1 = yf1 + repmat(log(SteadyState'),[horizon+maxlag,1,1]); - else - yf1 = yf1 + repmat(SteadyState',[horizon+maxlag,1,1]); - end - - stock_forcst_mean(:,:,irun(6)) = yf'; - stock_forcst_point(:,:,irun(7)) = yf1'; - end - - end - stock_param(irun(5),:) = deep; - stock_logpo(irun(5),1) = logpo; - stock_ys(irun(5),:) = SteadyState'; - - irun = irun + ones(7,1); - - if irun(1) > MAX_nsmoo || b == B - stock = stock_smooth(:,:,1:irun(1)-1); - ifil(1) = ifil(1) + 1; - save([DirectoryName '/' M_.fname '_smooth' int2str(ifil(1)) '.mat'],'stock'); - stock = stock_update(:,:,1:irun(1)-1); - save([DirectoryName '/' M_.fname '_update' int2str(ifil(1)) '.mat'],'stock'); - irun(1) = 1; - end - - if irun(2) > MAX_ninno || b == B - stock = stock_innov(:,:,1:irun(2)-1); - ifil(2) = ifil(2) + 1; - save([DirectoryName '/' M_.fname '_inno' int2str(ifil(2)) '.mat'],'stock'); - irun(2) = 1; - end - - if nvn && (irun(3) > MAX_nerro || b == B) - stock = stock_error(:,:,1:irun(3)-1); - ifil(3) = ifil(3) + 1; - save([DirectoryName '/' M_.fname '_error' int2str(ifil(3)) '.mat'],'stock'); - irun(3) = 1; - end - - if naK && (irun(4) > MAX_naK || b == B) - stock = stock_filter_step_ahead(:,:,:,1:irun(4)-1); - ifil(4) = ifil(4) + 1; - save([DirectoryName '/' M_.fname '_filter_step_ahead' int2str(ifil(4)) '.mat'],'stock'); - irun(4) = 1; - end - - if irun(5) > MAX_nruns || b == B - stock = stock_param(1:irun(5)-1,:); - ifil(5) = ifil(5) + 1; - save([DirectoryName '/' M_.fname '_param' int2str(ifil(5)) '.mat'],'stock','stock_logpo','stock_ys'); - irun(5) = 1; - end - - if horizon && (irun(6) > MAX_nforc1 || b == B) - stock = stock_forcst_mean(:,:,1:irun(6)-1); - ifil(6) = ifil(6) + 1; - save([DirectoryName '/' M_.fname '_forc_mean' int2str(ifil(6)) '.mat'],'stock'); - irun(6) = 1; - end - - if horizon && (irun(7) > MAX_nforc2 || b == B) - stock = stock_forcst_point(:,:,1:irun(7)-1); - ifil(7) = ifil(7) + 1; - save([DirectoryName '/' M_.fname '_forc_point' int2str(ifil(7)) '.mat'],'stock'); - irun(7) = 1; - end - - % if moments_varendo && (irun(8) > MAX_momentsno || b == B) - % stock = stock_moments(1:irun(8)-1); - % ifil(8) = ifil(8) + 1; - % save([DirectoryName '/' M_.fname '_moments' int2str(ifil(8)) '.mat'],'stock'); - % irun(8) = 1; - % end - - if exist('OCTAVE_VERSION') - printf('Taking subdraws: %3.f%% done\r', b/B); - else - waitbar(b/B,h); - end -end - -if exist('OCTAVE_VERSION') - printf('\n'); - diary on; -else - close(h) -end - -stock_gend=gend; -stock_data=Y; -save([DirectoryName '/' M_.fname '_data.mat'],'stock_gend','stock_data'); - -if options_.smoother - pm3(endo_nbr,gend,ifil(1),B,'Smoothed variables',... - '',varlist,'tit_tex',M_.endo_names,... - varlist,'SmoothedVariables',[M_.dname '/metropolis'],'_smooth'); - pm3(exo_nbr,gend,ifil(2),B,'Smoothed shocks',... - '',M_.exo_names,'tit_tex',M_.exo_names,... - M_.exo_names,'SmoothedShocks',[M_.dname '/metropolis'],'_inno'); - if nvn - % needs to be fixed -% pm3(endo_nbr,gend,ifil(3),B,'Smoothed measurement errors',... -% M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,... -% 'names2','smooth_errors',[M_.fname '/metropolis'],'_error') - end -end - -if options_.filtered_vars - pm3(endo_nbr,gend,ifil(1),B,'Updated Variables',... - '',varlist,'tit_tex',M_.endo_names,... - varlist,'UpdatedVariables',[M_.dname '/metropolis'], ... - '_update'); - pm3(endo_nbr,gend+1,ifil(4),B,'One step ahead forecast',... - '',varlist,'tit_tex',M_.endo_names,... - varlist,'FilteredVariables',[M_.dname '/metropolis'],'_filter_step_ahead'); -end - -if options_.forecast - pm3(endo_nbr,horizon+maxlag,ifil(6),B,'Forecasted variables (mean)',... - '',varlist,'tit_tex',M_.endo_names,... - varlist,'MeanForecast',[M_.dname '/metropolis'],'_forc_mean'); - pm3(endo_nbr,horizon+maxlag,ifil(6),B,'Forecasted variables (point)',... - '',varlist,'tit_tex',M_.endo_names,... - varlist,'PointForecast',[M_.dname '/metropolis'],'_forc_point'); +function prior_posterior_statistics(type,Y,gend,data_index,missing_value) +% function PosteriorFilterSmootherAndForecast(Y,gend, type) +% Computes posterior filter smoother and forecasts +% +% INPUTS +% type: posterior +% prior +% gsa +% Y: data +% gend: number of observations +% data_index [cell] 1*smpl cell of column vectors of indices. +% missing_value 1 if missing values, 0 otherwise +% +% OUTPUTS +% none +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2005-2009 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 <http://www.gnu.org/licenses/>. + +global options_ estim_params_ oo_ M_ bayestopt_ + +nvx = estim_params_.nvx; +nvn = estim_params_.nvn; +ncx = estim_params_.ncx; +ncn = estim_params_.ncn; +np = estim_params_.np ; +npar = nvx+nvn+ncx+ncn+np; +offset = npar-np; +naK = length(options_.filter_step_ahead); +%% +MaxNumberOfBytes=options_.MaxNumberOfBytes; +endo_nbr=M_.endo_nbr; +exo_nbr=M_.exo_nbr; +nvobs = size(options_.varobs,1); +iendo = 1:endo_nbr; +horizon = options_.forecast; +% moments_varendo = options_.moments_varendo; +filtered_vars = options_.filtered_vars; +if horizon + i_last_obs = gend+(1-M_.maximum_endo_lag:0); +end +maxlag = M_.maximum_endo_lag; +%% +DirectoryName = CheckPath('metropolis'); +load([ DirectoryName '/' M_.fname '_mh_history']) +FirstMhFile = record.KeepedDraws.FirstMhFile; +FirstLine = record.KeepedDraws.FirstLine; +TotalNumberOfMhFiles = sum(record.MhDraws(:,2)); LastMhFile = TotalNumberOfMhFiles; +TotalNumberOfMhDraws = sum(record.MhDraws(:,1)); +NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws); +clear record; +if ~isempty(options_.subdraws) + B = options_.subdraws; + if B > NumberOfDraws + B = NumberOfDraws; + end +else + B = min(1200, round(0.25*NumberOfDraws)); +end + +%% +MAX_nruns = min(B,ceil(MaxNumberOfBytes/(npar+2)/8)); +MAX_nsmoo = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*gend)/8)); +MAX_ninno = min(B,ceil(MaxNumberOfBytes/(exo_nbr*gend)/8)); +MAX_nerro = min(B,ceil(MaxNumberOfBytes/(size(options_.varobs,1)*gend)/8)); +if naK + MAX_naK = min(B,ceil(MaxNumberOfBytes/(size(options_.varobs,1)* ... + length(options_.filter_step_ahead)*gend)/8)); +end +if horizon + MAX_nforc1 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/8)); + MAX_nforc2 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/ ... + 8)); + IdObs = bayestopt_.mfys; + +end +MAX_momentsno = min(B,ceil(MaxNumberOfBytes/(get_moments_size(options_)*8))); +%% +varlist = options_.varlist; +if isempty(varlist) + varlist = M_.endo_names(1:M_.orig_endo_nbr, :); +end +nvar = size(varlist,1); +SelecVariables = []; +for i=1:nvar + if ~isempty(strmatch(varlist(i,:),M_.endo_names,'exact')) + SelecVariables = [SelecVariables;strmatch(varlist(i,:),M_.endo_names,'exact')]; + end +end + +irun = ones(7,1); +ifil = zeros(7,1); + +if exist('OCTAVE_VERSION') + diary off; +else + h = waitbar(0,'Taking subdraws...'); +end + +stock_param = zeros(MAX_nruns, npar); +stock_logpo = zeros(MAX_nruns,1); +stock_ys = zeros(MAX_nruns,endo_nbr); +run_smoother = 0; +if options_.smoother + stock_smooth = zeros(endo_nbr,gend,MAX_nsmoo); + stock_innov = zeros(exo_nbr,gend,B); + stock_error = zeros(nvobs,gend,MAX_nerro); + stock_update = zeros(endo_nbr,gend,MAX_nsmoo); + run_smoother = 1; +end + +if options_.filter_step_ahead + stock_filter_step_ahead = zeros(naK,endo_nbr,gend+ ... + options_.filter_step_ahead(end),MAX_naK); + run_smoother = 1; +end +if options_.forecast + stock_forcst_mean = zeros(endo_nbr,horizon+maxlag,MAX_nforc1); + stock_forcst_point = zeros(endo_nbr,horizon+maxlag,MAX_nforc2); + run_smoother = 1; +end +%if moments_varendo +% stock_moments = cell(MAX_momentsno,1); +%end +for b=1:B + [deep, logpo] = GetOneDraw(type); + set_all_parameters(deep); + dr = resol(oo_.steady_state,0); + + %if moments_varendo + % stock_moments{irun(8)} = compute_model_moments(dr,M_,options_); + %end + + if run_smoother + [alphahat,etahat,epsilonhat,alphatilde,SteadyState,trend_coeff,aK] = ... + DsgeSmoother(deep,gend,Y,data_index,missing_value); + if options_.loglinear + stock_smooth(dr.order_var,:,irun(1)) = alphahat(1:endo_nbr,:)+ ... + repmat(log(dr.ys(dr.order_var)),1,gend); + stock_update(dr.order_var,:,irun(1)) = alphatilde(1:endo_nbr,:)+ ... + repmat(log(dr.ys(dr.order_var)),1,gend); + else + stock_smooth(dr.order_var,:,irun(1)) = alphahat(1:endo_nbr,:)+ ... + repmat(dr.ys(dr.order_var),1,gend); + stock_update(dr.order_var,:,irun(1)) = alphatilde(1:endo_nbr,:)+ ... + repmat(dr.ys(dr.order_var),1,gend); + end + stock_innov(:,:,irun(2)) = etahat; + if nvn + stock_error(:,:,irun(3)) = epsilonhat; + end + if naK + stock_filter_step_ahead(:,dr.order_var,:,irun(4)) = aK(options_.filter_step_ahead,1:endo_nbr,:); + end + + if horizon + yyyy = alphahat(iendo,i_last_obs); + yf = forcst2a(yyyy,dr,zeros(horizon,exo_nbr)); + if options_.prefilter == 1 + yf(:,IdObs) = yf(:,IdObs)+repmat(bayestopt_.mean_varobs', ... + horizon+maxlag,1); + end + yf(:,IdObs) = yf(:,IdObs)+(gend+[1-maxlag:horizon]')*trend_coeff'; + if options_.loglinear == 1 + yf = yf+repmat(log(SteadyState'),horizon+maxlag,1); + else + yf = yf+repmat(SteadyState',horizon+maxlag,1); + end + yf1 = forcst2(yyyy,horizon,dr,1); + if options_.prefilter == 1 + yf1(:,IdObs,:) = yf1(:,IdObs,:)+ ... + repmat(bayestopt_.mean_varobs',[horizon+maxlag,1,1]); + end + yf1(:,IdObs,:) = yf1(:,IdObs,:)+repmat((gend+[1-maxlag:horizon]')* ... + trend_coeff',[1,1,1]); + if options_.loglinear == 1 + yf1 = yf1 + repmat(log(SteadyState'),[horizon+maxlag,1,1]); + else + yf1 = yf1 + repmat(SteadyState',[horizon+maxlag,1,1]); + end + + stock_forcst_mean(:,:,irun(6)) = yf'; + stock_forcst_point(:,:,irun(7)) = yf1'; + end + + end + stock_param(irun(5),:) = deep; + stock_logpo(irun(5),1) = logpo; + stock_ys(irun(5),:) = SteadyState'; + + irun = irun + ones(7,1); + + if irun(1) > MAX_nsmoo || b == B + stock = stock_smooth(:,:,1:irun(1)-1); + ifil(1) = ifil(1) + 1; + save([DirectoryName '/' M_.fname '_smooth' int2str(ifil(1)) '.mat'],'stock'); + stock = stock_update(:,:,1:irun(1)-1); + save([DirectoryName '/' M_.fname '_update' int2str(ifil(1)) '.mat'],'stock'); + irun(1) = 1; + end + + if irun(2) > MAX_ninno || b == B + stock = stock_innov(:,:,1:irun(2)-1); + ifil(2) = ifil(2) + 1; + save([DirectoryName '/' M_.fname '_inno' int2str(ifil(2)) '.mat'],'stock'); + irun(2) = 1; + end + + if nvn && (irun(3) > MAX_nerro || b == B) + stock = stock_error(:,:,1:irun(3)-1); + ifil(3) = ifil(3) + 1; + save([DirectoryName '/' M_.fname '_error' int2str(ifil(3)) '.mat'],'stock'); + irun(3) = 1; + end + + if naK && (irun(4) > MAX_naK || b == B) + stock = stock_filter_step_ahead(:,:,:,1:irun(4)-1); + ifil(4) = ifil(4) + 1; + save([DirectoryName '/' M_.fname '_filter_step_ahead' int2str(ifil(4)) '.mat'],'stock'); + irun(4) = 1; + end + + if irun(5) > MAX_nruns || b == B + stock = stock_param(1:irun(5)-1,:); + ifil(5) = ifil(5) + 1; + save([DirectoryName '/' M_.fname '_param' int2str(ifil(5)) '.mat'],'stock','stock_logpo','stock_ys'); + irun(5) = 1; + end + + if horizon && (irun(6) > MAX_nforc1 || b == B) + stock = stock_forcst_mean(:,:,1:irun(6)-1); + ifil(6) = ifil(6) + 1; + save([DirectoryName '/' M_.fname '_forc_mean' int2str(ifil(6)) '.mat'],'stock'); + irun(6) = 1; + end + + if horizon && (irun(7) > MAX_nforc2 || b == B) + stock = stock_forcst_point(:,:,1:irun(7)-1); + ifil(7) = ifil(7) + 1; + save([DirectoryName '/' M_.fname '_forc_point' int2str(ifil(7)) '.mat'],'stock'); + irun(7) = 1; + end + + % if moments_varendo && (irun(8) > MAX_momentsno || b == B) + % stock = stock_moments(1:irun(8)-1); + % ifil(8) = ifil(8) + 1; + % save([DirectoryName '/' M_.fname '_moments' int2str(ifil(8)) '.mat'],'stock'); + % irun(8) = 1; + % end + + if exist('OCTAVE_VERSION') + printf('Taking subdraws: %3.f%% done\r', b/B); + else + waitbar(b/B,h); + end +end + +if exist('OCTAVE_VERSION') + printf('\n'); + diary on; +else + close(h) +end + +stock_gend=gend; +stock_data=Y; +save([DirectoryName '/' M_.fname '_data.mat'],'stock_gend','stock_data'); + +if options_.smoother + pm3(endo_nbr,gend,ifil(1),B,'Smoothed variables',... + '',varlist,'tit_tex',M_.endo_names,... + varlist,'SmoothedVariables',[M_.dname '/metropolis'],'_smooth'); + pm3(exo_nbr,gend,ifil(2),B,'Smoothed shocks',... + '',M_.exo_names,'tit_tex',M_.exo_names,... + M_.exo_names,'SmoothedShocks',[M_.dname '/metropolis'],'_inno'); + if nvn + % needs to be fixed + % pm3(endo_nbr,gend,ifil(3),B,'Smoothed measurement errors',... + % M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,... + % 'names2','smooth_errors',[M_.fname '/metropolis'],'_error') + end +end + +if options_.filtered_vars + pm3(endo_nbr,gend,ifil(1),B,'Updated Variables',... + '',varlist,'tit_tex',M_.endo_names,... + varlist,'UpdatedVariables',[M_.dname '/metropolis'], ... + '_update'); + pm3(endo_nbr,gend+1,ifil(4),B,'One step ahead forecast',... + '',varlist,'tit_tex',M_.endo_names,... + varlist,'FilteredVariables',[M_.dname '/metropolis'],'_filter_step_ahead'); +end + +if options_.forecast + pm3(endo_nbr,horizon+maxlag,ifil(6),B,'Forecasted variables (mean)',... + '',varlist,'tit_tex',M_.endo_names,... + varlist,'MeanForecast',[M_.dname '/metropolis'],'_forc_mean'); + pm3(endo_nbr,horizon+maxlag,ifil(6),B,'Forecasted variables (point)',... + '',varlist,'tit_tex',M_.endo_names,... + varlist,'PointForecast',[M_.dname '/metropolis'],'_forc_point'); end \ No newline at end of file diff --git a/matlab/prior_sampler.m b/matlab/prior_sampler.m index 407eaefc74..4d8465abe7 100644 --- a/matlab/prior_sampler.m +++ b/matlab/prior_sampler.m @@ -29,125 +29,125 @@ function results = prior_sampler(drsave,M_,bayestopt_,options_,oo_) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - % Initialization. - prior_draw(1,bayestopt_); - PriorDirectoryName = CheckPath('prior/draws'); - work = ~drsave; - iteration = 0; - loop_indx = 0; - file_indx = []; - count_bk_indeterminacy = 0; - count_bk_unstability = 0; - count_bk_singularity = 0; - count_static_var_def = 0; - count_no_steadystate = 0; - count_steadystate_file_exit = 0; - count_dll_problem = 0; - count_complex_jacobian = 0; - count_complex_steadystate = 0; - count_unknown_problem = 0; - NumberOfSimulations = options_.prior_mc; - NumberOfParameters = length(bayestopt_.p1); - NumberOfEndogenousVariables = size(M_.endo_names,1); - NumberOfElementsPerFile = ceil(options_.MaxNumberOfBytes/NumberOfParameters/NumberOfEndogenousVariables/8) ; - - if NumberOfSimulations <= NumberOfElementsPerFile - TableOfInformations = [ 1 , NumberOfSimulations , 1] ; - else - NumberOfFiles = ceil(NumberOfSimulations/NumberOfElementsPerFile) ; - NumberOfElementsInTheLastFile = NumberOfSimulations - NumberOfElementsPerFile*(NumberOfFiles-1) ; - TableOfInformations = NaN(NumberOfFiles,3) ; - TableOfInformations(:,1) = transpose(1:NumberOfFiles) ; - TableOfInformations(1:NumberOfFiles-1,2) = NumberOfElementsPerFile*ones(NumberOfFiles-1,1) ; - TableOfInformations(NumberOfFiles,2) = NumberOfElementsInTheLastFile ; - TableOfInformations(1,3) = 1; - TableOfInformations(2:end,3) = cumsum(TableOfInformations(1:end-1,2))+1; - end - pdraws = cell(TableOfInformations(1,2),drsave+1) ; - sampled_prior_expectation = zeros(NumberOfParameters,1); - sampled_prior_covariance = zeros(NumberOfParameters,NumberOfParameters); - - file_line_number = 0; - file_indx_number = 0; - - % Simulations. - while iteration < NumberOfSimulations - loop_indx = loop_indx+1; - params = prior_draw(); - set_all_parameters(params); - [dr,INFO] = resol(oo_.steady_state,work); - switch INFO(1) - case 0 - file_line_number = file_line_number + 1 ; - iteration = iteration + 1; - pdraws(file_line_number,1) = {params}; - if drsave - pdraws(file_line_number,2) = {dr}; - end - [sampled_prior_expectation,sampled_prior_covariance] = ... - recursive_prior_moments(sampled_prior_expectation,sampled_prior_covariance,params,iteration); - case 1 - count_static_undefined = count_static_undefined + 1; - case 2 - count_dll_problem = count_dll_problem + 1; - case 3 - count_bk_unstability = count_bk_unstability + 1 ; - case 4 - count_bk_indeterminacy = count_bk_indeterminacy + 1 ; - case 5 - count_bk_singularity = count_bk_singularity + 1 ; - case 20 - count_no_steadystate = count_no_steadystate + 1 ; - case 19 - count_steadystate_file_exit = count_steadystate_file_exit + 1 ; - case 6 - count_complex_jacobian = count_complex_jacobian + 1 ; - case 21 - count_complex_steadystate = count_complex_steadystate + 1 ; - otherwise - count_unknown_problem = count_unknown_problem + 1 ; +% Initialization. +prior_draw(1,bayestopt_); +PriorDirectoryName = CheckPath('prior/draws'); +work = ~drsave; +iteration = 0; +loop_indx = 0; +file_indx = []; +count_bk_indeterminacy = 0; +count_bk_unstability = 0; +count_bk_singularity = 0; +count_static_var_def = 0; +count_no_steadystate = 0; +count_steadystate_file_exit = 0; +count_dll_problem = 0; +count_complex_jacobian = 0; +count_complex_steadystate = 0; +count_unknown_problem = 0; +NumberOfSimulations = options_.prior_mc; +NumberOfParameters = length(bayestopt_.p1); +NumberOfEndogenousVariables = size(M_.endo_names,1); +NumberOfElementsPerFile = ceil(options_.MaxNumberOfBytes/NumberOfParameters/NumberOfEndogenousVariables/8) ; + +if NumberOfSimulations <= NumberOfElementsPerFile + TableOfInformations = [ 1 , NumberOfSimulations , 1] ; +else + NumberOfFiles = ceil(NumberOfSimulations/NumberOfElementsPerFile) ; + NumberOfElementsInTheLastFile = NumberOfSimulations - NumberOfElementsPerFile*(NumberOfFiles-1) ; + TableOfInformations = NaN(NumberOfFiles,3) ; + TableOfInformations(:,1) = transpose(1:NumberOfFiles) ; + TableOfInformations(1:NumberOfFiles-1,2) = NumberOfElementsPerFile*ones(NumberOfFiles-1,1) ; + TableOfInformations(NumberOfFiles,2) = NumberOfElementsInTheLastFile ; + TableOfInformations(1,3) = 1; + TableOfInformations(2:end,3) = cumsum(TableOfInformations(1:end-1,2))+1; +end + +pdraws = cell(TableOfInformations(1,2),drsave+1) ; +sampled_prior_expectation = zeros(NumberOfParameters,1); +sampled_prior_covariance = zeros(NumberOfParameters,NumberOfParameters); + +file_line_number = 0; +file_indx_number = 0; + +% Simulations. +while iteration < NumberOfSimulations + loop_indx = loop_indx+1; + params = prior_draw(); + set_all_parameters(params); + [dr,INFO] = resol(oo_.steady_state,work); + switch INFO(1) + case 0 + file_line_number = file_line_number + 1 ; + iteration = iteration + 1; + pdraws(file_line_number,1) = {params}; + if drsave + pdraws(file_line_number,2) = {dr}; end - if ( file_line_number==TableOfInformations(file_indx_number+1,2) ) - file_indx_number = file_indx_number + 1; - save([ PriorDirectoryName '/prior_draws' int2str(file_indx_number) '.mat' ],'pdraws'); - if file_indx_number<NumberOfFiles - pdraws = cell(TableOfInformations(file_indx_number+1,2),drsave+1); - end - file_line_number = 0; + [sampled_prior_expectation,sampled_prior_covariance] = ... + recursive_prior_moments(sampled_prior_expectation,sampled_prior_covariance,params,iteration); + case 1 + count_static_undefined = count_static_undefined + 1; + case 2 + count_dll_problem = count_dll_problem + 1; + case 3 + count_bk_unstability = count_bk_unstability + 1 ; + case 4 + count_bk_indeterminacy = count_bk_indeterminacy + 1 ; + case 5 + count_bk_singularity = count_bk_singularity + 1 ; + case 20 + count_no_steadystate = count_no_steadystate + 1 ; + case 19 + count_steadystate_file_exit = count_steadystate_file_exit + 1 ; + case 6 + count_complex_jacobian = count_complex_jacobian + 1 ; + case 21 + count_complex_steadystate = count_complex_steadystate + 1 ; + otherwise + count_unknown_problem = count_unknown_problem + 1 ; + end + if ( file_line_number==TableOfInformations(file_indx_number+1,2) ) + file_indx_number = file_indx_number + 1; + save([ PriorDirectoryName '/prior_draws' int2str(file_indx_number) '.mat' ],'pdraws'); + if file_indx_number<NumberOfFiles + pdraws = cell(TableOfInformations(file_indx_number+1,2),drsave+1); end + file_line_number = 0; end - - % Get informations about BK conditions and other things... - results.bk.indeterminacy_share = count_bk_indeterminacy/loop_indx; - results.bk.unstability_share = count_bk_unstability/loop_indx; - results.bk.singularity_share = count_bk_singularity/loop_indx; - results.dll.problem_share = count_dll_problem/loop_indx; - results.ss.problem_share = count_no_steadystate/loop_indx; - results.ss.complex_share = count_complex_steadystate/loop_indx; - results.ass.problem_share = count_steadystate_file_exit/loop_indx; - results.jacobian.problem_share = count_complex_jacobian/loop_indx; - results.garbage_share = ... - results.bk.indeterminacy_share + ... - results.bk.unstability_share + ... - results.bk.singularity_share + ... - results.dll.problem_share + ... - results.ss.problem_share + ... - results.ass.problem_share + ... - results.jacobian.problem_share + ... - count_unknown_problem/loop_indx ; - results.prior.mean = sampled_prior_expectation; - results.prior.variance = sampled_prior_covariance; - results.prior.mass = 1-results.garbage_share; +end + +% Get informations about BK conditions and other things... +results.bk.indeterminacy_share = count_bk_indeterminacy/loop_indx; +results.bk.unstability_share = count_bk_unstability/loop_indx; +results.bk.singularity_share = count_bk_singularity/loop_indx; +results.dll.problem_share = count_dll_problem/loop_indx; +results.ss.problem_share = count_no_steadystate/loop_indx; +results.ss.complex_share = count_complex_steadystate/loop_indx; +results.ass.problem_share = count_steadystate_file_exit/loop_indx; +results.jacobian.problem_share = count_complex_jacobian/loop_indx; +results.garbage_share = ... + results.bk.indeterminacy_share + ... + results.bk.unstability_share + ... + results.bk.singularity_share + ... + results.dll.problem_share + ... + results.ss.problem_share + ... + results.ass.problem_share + ... + results.jacobian.problem_share + ... + count_unknown_problem/loop_indx ; +results.prior.mean = sampled_prior_expectation; +results.prior.variance = sampled_prior_covariance; +results.prior.mass = 1-results.garbage_share; function [mu,sigma] = recursive_prior_moments(m0,s0,newobs,iter) % Recursive estimation of order one and two moments (expectation and % covariance matrix). newobs should be a row vector. I do not use the % function recursive_moments here, because this function is to be used when % newobs is a 2D array. - m1 = m0 + (newobs'-m0)/iter; - qq = m1*m1'; - s1 = s0 + ( (newobs'*newobs-qq-s0) + (iter-1)*(m0*m0'-qq') )/iter; - mu = m1; - sigma = s1; \ No newline at end of file +m1 = m0 + (newobs'-m0)/iter; +qq = m1*m1'; +s1 = s0 + ( (newobs'*newobs-qq-s0) + (iter-1)*(m0*m0'-qq') )/iter; +mu = m1; +sigma = s1; \ No newline at end of file diff --git a/matlab/prior_statistics.m b/matlab/prior_statistics.m index 1dfb11c200..d2f9fda62f 100644 --- a/matlab/prior_statistics.m +++ b/matlab/prior_statistics.m @@ -30,7 +30,7 @@ function pstat = prior_statistics(info,M_,bayestopt_,options_) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if ~info(0) - results = prior_sampler(1,M_,bayestopt_,options_); - results.prior.mass - end \ No newline at end of file +if ~info(0) + results = prior_sampler(1,M_,bayestopt_,options_); + results.prior.mass +end \ No newline at end of file diff --git a/matlab/qr2.m b/matlab/qr2.m index 714da06c43..24f83da600 100644 --- a/matlab/qr2.m +++ b/matlab/qr2.m @@ -1,42 +1,42 @@ -function [Q,R] = qr2(X) -% This routine performs a qr decomposition of matrix X such that the -% diagonal scalars of the upper-triangular matrix R are positive. If X -% is a full (column) rank matrix, then R is also the cholesky -% factorization of X'X. This property is needed for the Del Negro -% & Schorfheides's identification scheme. -% -% INPUTS -% See matlab's documentation for QR decomposition. -% -% OUTPUTS -% See matlab's documentation for QR decomposition. -% -% ALGORITHM -% None. -% -% SPECIAL REQUIREMENTS -% None. - -% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. - -[Q,R] = qr(X); -indx = find(diag(R)<0); -if ~isempty(indx) - Q(:,indx) = -Q(:,indx); - R(indx,:) = -R(indx,:); +function [Q,R] = qr2(X) +% This routine performs a qr decomposition of matrix X such that the +% diagonal scalars of the upper-triangular matrix R are positive. If X +% is a full (column) rank matrix, then R is also the cholesky +% factorization of X'X. This property is needed for the Del Negro +% & Schorfheides's identification scheme. +% +% INPUTS +% See matlab's documentation for QR decomposition. +% +% OUTPUTS +% See matlab's documentation for QR decomposition. +% +% ALGORITHM +% None. +% +% SPECIAL REQUIREMENTS +% None. + +% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. + +[Q,R] = qr(X); +indx = find(diag(R)<0); +if ~isempty(indx) + Q(:,indx) = -Q(:,indx); + R(indx,:) = -R(indx,:); end \ No newline at end of file diff --git a/matlab/qz/mjdgges.m b/matlab/qz/mjdgges.m index 73576f7567..3004091de0 100644 --- a/matlab/qz/mjdgges.m +++ b/matlab/qz/mjdgges.m @@ -37,7 +37,7 @@ function [ss,tt,w,sdim,eigval,info] = mjdgges(e,d,qz_criterium) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - + % Chek number of inputs and outputs. if nargin>3 | nargin<2 error('Three or two input arguments required!') diff --git a/matlab/qz/qzdiv.m b/matlab/qz/qzdiv.m index eebe52a46b..2ab7fb2a74 100644 --- a/matlab/qz/qzdiv.m +++ b/matlab/qz/qzdiv.m @@ -31,20 +31,20 @@ root = abs([diag(A) diag(B)]); root(:,1) = root(:,1)-(root(:,1)<1.e-13).*(root(:,1)+root(:,2)); root(:,2) = root(:,2)./root(:,1); for i = n:-1:1 - m=0; - for j=i:-1:1 - if (root(j,2) > stake | root(j,2) < -.1) - m=j; - break - end - end - if (m==0) - return - end - for k=m:1:i-1 - [A B Q Z] = qzswitch(k,A,B,Q,Z); - tmp = root(k,2); - root(k,2) = root(k+1,2); - root(k+1,2) = tmp; - end + m=0; + for j=i:-1:1 + if (root(j,2) > stake | root(j,2) < -.1) + m=j; + break + end + end + if (m==0) + return + end + for k=m:1:i-1 + [A B Q Z] = qzswitch(k,A,B,Q,Z); + tmp = root(k,2); + root(k,2) = root(k+1,2); + root(k+1,2) = tmp; + end end diff --git a/matlab/qz/qzswitch.m b/matlab/qz/qzswitch.m index f16d604cfe..ab2dd6a236 100644 --- a/matlab/qz/qzswitch.m +++ b/matlab/qz/qzswitch.m @@ -34,44 +34,44 @@ realsmall=sqrt(eps)*10; %realsmall=1e-3; a = A(i,i); d = B(i,i); b = A(i,i+1); e = B(i,i+1); c = A(i+1,i+1); f = B(i+1,i+1); - % A(i:i+1,i:i+1)=[a b; 0 c]; - % B(i:i+1,i:i+1)=[d e; 0 f]; +% A(i:i+1,i:i+1)=[a b; 0 c]; +% B(i:i+1,i:i+1)=[d e; 0 f]; if (abs(c)<realsmall & abs(f)<realsmall) - if abs(a)<realsmall - % l.r. coincident 0's with u.l. of A=0; do nothing - return - else - % l.r. coincident zeros; put 0 in u.l. of a - wz=[b; -a]; - wz=wz/sqrt(wz'*wz); - wz=[wz [wz(2)';-wz(1)'] ]; - xy=eye(2); - end + if abs(a)<realsmall + % l.r. coincident 0's with u.l. of A=0; do nothing + return + else + % l.r. coincident zeros; put 0 in u.l. of a + wz=[b; -a]; + wz=wz/sqrt(wz'*wz); + wz=[wz [wz(2)';-wz(1)'] ]; + xy=eye(2); + end elseif (abs(a)<realsmall & abs(d)<realsmall) - if abs(c)<realsmall - % u.l. coincident zeros with l.r. of A=0; do nothing - return - else - % u.l. coincident zeros; put 0 in l.r. of A - wz=eye(2); - xy=[c -b]; - xy=xy/sqrt(xy*xy'); - xy=[[xy(2)' -xy(1)'];xy]; - end + if abs(c)<realsmall + % u.l. coincident zeros with l.r. of A=0; do nothing + return + else + % u.l. coincident zeros; put 0 in l.r. of A + wz=eye(2); + xy=[c -b]; + xy=xy/sqrt(xy*xy'); + xy=[[xy(2)' -xy(1)'];xy]; + end else - % usual case - wz = [c*e-f*b, (c*d-f*a)']; - xy = [(b*d-e*a)', (c*d-f*a)']; - n = sqrt(wz*wz'); - m = sqrt(xy*xy'); - if m<eps*100 - % all elements of A and B proportional - return - end - wz = n\wz; - xy = m\xy; - wz = [wz; -wz(2)', wz(1)']; - xy = [xy;-xy(2)', xy(1)']; + % usual case + wz = [c*e-f*b, (c*d-f*a)']; + xy = [(b*d-e*a)', (c*d-f*a)']; + n = sqrt(wz*wz'); + m = sqrt(xy*xy'); + if m<eps*100 + % all elements of A and B proportional + return + end + wz = n\wz; + xy = m\xy; + wz = [wz; -wz(2)', wz(1)']; + xy = [xy;-xy(2)', xy(1)']; end A(i:i+1,:) = xy*A(i:i+1,:); B(i:i+1,:) = xy*B(i:i+1,:); diff --git a/matlab/ramsey_policy.m b/matlab/ramsey_policy.m index 8b3d2533d6..1887a15497 100644 --- a/matlab/ramsey_policy.m +++ b/matlab/ramsey_policy.m @@ -1,93 +1,93 @@ -function info = ramsey_policy(var_list) - -% Copyright (C) 2007-2008 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 <http://www.gnu.org/licenses/>. - - global options_ oo_ M_ - - oldoptions = options_; - options_.ramsey_policy = 1; - options_.order = 1; - info = stoch_simul(var_list); - - return - if info - return - end - - options_.ramsey_policy = 2; - info = stoch_simul(var_list); - dr = oo_.dr; - - orig_model = M_.orig_model; - endo_nbr1 = orig_model.endo_nbr; - exo_nbr1 = M_.exo_nbr; - - npred = dr.npred; - nspred = dr.nspred; - inv_order_var1 = dr.inv_order_var(1:endo_nbr1); - nstatic = dr.nstatic; - - ghx = dr.ghx; - ghx1 = ghx(inv_order_var1,:); - [ghx2,ghu2] = transition_matrix(dr); - ghu = dr.ghu; - ghu1 = ghu(inv_order_var1,:); - ghxx = dr.ghxx; - ghxx1 = ghxx(inv_order_var1,:); - ghxx2 = [ghxx(nstatic+(1:npred),:); zeros(nspred-npred,size(ghxx,2))]; - ghxu = dr.ghxu; - ghxu1 = ghxu(inv_order_var1,:); - ghxu2 = [ghxu(nstatic+(1:npred),:); zeros(nspred-npred,size(ghxu,2))]; - ghuu = dr.ghuu; - ghuu1 = ghuu(inv_order_var1,:); - ghuu2 = [ghuu(nstatic+(1:npred),:); zeros(nspred-npred,size(ghuu,2))]; - ghs2 = dr.ghs2; - ghs21 = ghs2(inv_order_var1,:); - ghs22 = [ghs2(nstatic+(1:npred),:); zeros(nspred-npred,size(ghs2,2))]; - - fname = [M_.fname '_objective_static']; - [ubar,uj,uh] = feval(fname,dr.ys(1:endo_nbr1),zeros(exo_nbr1,1), M_.params); - - bet = options_.planner_discount; - wbar = ubar/(1-bet); - % wx = ux*gx + bet*wx*hx - % wx*(I-bet*hx) = ux*gx - wx = uj*ghx1/(eye(nspred)-bet*ghx2); - % wu = ux*gu + bet*wx*hu - wu = uj*ghu1 + bet*wx*ghu2; - % wxx = uxx*kron(gx,gx)+ux*ghxx + bet(wxx*kron(hx,hx) + - % wx*hxx) - wxx = (uh*kron(ghx1,ghx1) + uj*ghxx1 + bet*wx*ghxx2)/(eye(nspred^2)-bet*kron(ghx2,ghx2)); - wxu = uh*kron(ghx1,ghu1) + uj*ghxu1 + bet*(wx*ghxu2+wxx*kron(ghx2,ghu2)); - wuu = uh*kron(ghu1,ghu1) + uj*ghuu1 + bet*(wx*ghuu2+wxx*kron(ghu2,ghu2)); - % ws2 = ux*ghs2 + bet*(ws2+wx*hs2+wuu*Sigma_u) - ws2 = (uj*ghs21 + bet*(wx*ghs22+wuu*M_.Sigma_e(:)))/(1-bet); - oo_.welfare.wbar = wbar; - oo_.welfare.wx = wx; - oo_.welfare.wu = wu; - oo_.welfare.wxx = wxx; - oo_.welfare.wxu = wxu; - oo_.welfare.wuu = wuu; - oo_.welfare.ws2 = ws2; - - disp(' ') - disp(' ') - disp(['Welfare at the deterministic steady state is ' num2str(wbar+0.5* ... - ws2)]); - - options_ = oldoptions; \ No newline at end of file +function info = ramsey_policy(var_list) + +% Copyright (C) 2007-2008 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 <http://www.gnu.org/licenses/>. + +global options_ oo_ M_ + +oldoptions = options_; +options_.ramsey_policy = 1; +options_.order = 1; +info = stoch_simul(var_list); + +return +if info + return +end + +options_.ramsey_policy = 2; +info = stoch_simul(var_list); +dr = oo_.dr; + +orig_model = M_.orig_model; +endo_nbr1 = orig_model.endo_nbr; +exo_nbr1 = M_.exo_nbr; + +npred = dr.npred; +nspred = dr.nspred; +inv_order_var1 = dr.inv_order_var(1:endo_nbr1); +nstatic = dr.nstatic; + +ghx = dr.ghx; +ghx1 = ghx(inv_order_var1,:); +[ghx2,ghu2] = transition_matrix(dr); +ghu = dr.ghu; +ghu1 = ghu(inv_order_var1,:); +ghxx = dr.ghxx; +ghxx1 = ghxx(inv_order_var1,:); +ghxx2 = [ghxx(nstatic+(1:npred),:); zeros(nspred-npred,size(ghxx,2))]; +ghxu = dr.ghxu; +ghxu1 = ghxu(inv_order_var1,:); +ghxu2 = [ghxu(nstatic+(1:npred),:); zeros(nspred-npred,size(ghxu,2))]; +ghuu = dr.ghuu; +ghuu1 = ghuu(inv_order_var1,:); +ghuu2 = [ghuu(nstatic+(1:npred),:); zeros(nspred-npred,size(ghuu,2))]; +ghs2 = dr.ghs2; +ghs21 = ghs2(inv_order_var1,:); +ghs22 = [ghs2(nstatic+(1:npred),:); zeros(nspred-npred,size(ghs2,2))]; + +fname = [M_.fname '_objective_static']; +[ubar,uj,uh] = feval(fname,dr.ys(1:endo_nbr1),zeros(exo_nbr1,1), M_.params); + +bet = options_.planner_discount; +wbar = ubar/(1-bet); +% wx = ux*gx + bet*wx*hx +% wx*(I-bet*hx) = ux*gx +wx = uj*ghx1/(eye(nspred)-bet*ghx2); +% wu = ux*gu + bet*wx*hu +wu = uj*ghu1 + bet*wx*ghu2; +% wxx = uxx*kron(gx,gx)+ux*ghxx + bet(wxx*kron(hx,hx) + +% wx*hxx) +wxx = (uh*kron(ghx1,ghx1) + uj*ghxx1 + bet*wx*ghxx2)/(eye(nspred^2)-bet*kron(ghx2,ghx2)); +wxu = uh*kron(ghx1,ghu1) + uj*ghxu1 + bet*(wx*ghxu2+wxx*kron(ghx2,ghu2)); +wuu = uh*kron(ghu1,ghu1) + uj*ghuu1 + bet*(wx*ghuu2+wxx*kron(ghu2,ghu2)); +% ws2 = ux*ghs2 + bet*(ws2+wx*hs2+wuu*Sigma_u) +ws2 = (uj*ghs21 + bet*(wx*ghs22+wuu*M_.Sigma_e(:)))/(1-bet); +oo_.welfare.wbar = wbar; +oo_.welfare.wx = wx; +oo_.welfare.wu = wu; +oo_.welfare.wxx = wxx; +oo_.welfare.wxu = wxu; +oo_.welfare.wuu = wuu; +oo_.welfare.ws2 = ws2; + +disp(' ') +disp(' ') +disp(['Welfare at the deterministic steady state is ' num2str(wbar+0.5* ... + ws2)]); + +options_ = oldoptions; \ No newline at end of file diff --git a/matlab/random_walk_metropolis_hastings.m b/matlab/random_walk_metropolis_hastings.m index c45db06823..ba38e9bd80 100644 --- a/matlab/random_walk_metropolis_hastings.m +++ b/matlab/random_walk_metropolis_hastings.m @@ -49,19 +49,19 @@ load([MhDirectoryName '/' ModelName '_mh_history.mat'],'record'); localVars = struct('TargetFun', TargetFun, ... - 'ProposalFun', ProposalFun, ... - 'xparam1', xparam1, ... - 'vv', vv, ... - 'mh_bounds', mh_bounds, ... - 'ix2', ix2, ... - 'ilogpo2', ilogpo2, ... - 'ModelName', ModelName, ... - 'fline', fline, ... - 'npar', npar, ... - 'nruns', nruns, ... - 'NewFile', NewFile, ... - 'MAX_nruns', MAX_nruns, ... - 'd', d); + 'ProposalFun', ProposalFun, ... + 'xparam1', xparam1, ... + 'vv', vv, ... + 'mh_bounds', mh_bounds, ... + 'ix2', ix2, ... + 'ilogpo2', ilogpo2, ... + 'ModelName', ModelName, ... + 'fline', fline, ... + 'npar', npar, ... + 'nruns', nruns, ... + 'NewFile', NewFile, ... + 'MAX_nruns', MAX_nruns, ... + 'd', d); localVars.InitSizeArray=InitSizeArray; localVars.record=record; localVars.varargin=varargin; @@ -76,10 +76,10 @@ if isnumeric(options_.parallel),% | isunix, % for the moment exclude unix platfo else % global variables for parallel routines globalVars = struct('M_',M_, ... - 'options_', options_, ... - 'bayestopt_', bayestopt_, ... - 'estim_params_', estim_params_, ... - 'oo_', oo_); + 'options_', options_, ... + 'bayestopt_', bayestopt_, ... + 'estim_params_', estim_params_, ... + 'oo_', oo_); % which files have to be copied to run remotely NamFileInput(1,:) = {'',[ModelName '_static.m']}; @@ -90,17 +90,17 @@ else if (options_.load_mh_file~=0) & any(fline>1) , NamFileInput(length(NamFileInput)+1,:)={[M_.dname '/metropolis/'],[ModelName '_mh' int2str(NewFile(1)) '_blck*.mat']}; end - + % from where to get back results -% NamFileOutput(1,:) = {[M_.dname,'/metropolis/'],'*.*'}; + % NamFileOutput(1,:) = {[M_.dname,'/metropolis/'],'*.*'}; [fout, nBlockPerCPU, totCPU] = masterParallel(options_.parallel, fblck, nblck,NamFileInput,'random_walk_metropolis_hastings_core', localVars, globalVars); for j=1:totCPU, - offset = sum(nBlockPerCPU(1:j-1))+fblck-1; - record.LastLogLiK(offset+1:sum(nBlockPerCPU(1:j)))=fout(j).record.LastLogLiK(offset+1:sum(nBlockPerCPU(1:j))); - record.LastParameters(offset+1:sum(nBlockPerCPU(1:j)),:)=fout(j).record.LastParameters(offset+1:sum(nBlockPerCPU(1:j)),:); - record.AcceptationRates(offset+1:sum(nBlockPerCPU(1:j)))=fout(j).record.AcceptationRates(offset+1:sum(nBlockPerCPU(1:j))); - record.Seeds(offset+1:sum(nBlockPerCPU(1:j)))=fout(j).record.Seeds(offset+1:sum(nBlockPerCPU(1:j))); + offset = sum(nBlockPerCPU(1:j-1))+fblck-1; + record.LastLogLiK(offset+1:sum(nBlockPerCPU(1:j)))=fout(j).record.LastLogLiK(offset+1:sum(nBlockPerCPU(1:j))); + record.LastParameters(offset+1:sum(nBlockPerCPU(1:j)),:)=fout(j).record.LastParameters(offset+1:sum(nBlockPerCPU(1:j)),:); + record.AcceptationRates(offset+1:sum(nBlockPerCPU(1:j)))=fout(j).record.AcceptationRates(offset+1:sum(nBlockPerCPU(1:j))); + record.Seeds(offset+1:sum(nBlockPerCPU(1:j)))=fout(j).record.Seeds(offset+1:sum(nBlockPerCPU(1:j))); end end @@ -108,7 +108,7 @@ end irun = fout(1).irun; NewFile = fout(1).NewFile; - + % ComptationalTime=toc, % record.Seeds.Normal = randn('state'); diff --git a/matlab/random_walk_metropolis_hastings_core.m b/matlab/random_walk_metropolis_hastings_core.m index ed840133ed..c35a07c9e4 100644 --- a/matlab/random_walk_metropolis_hastings_core.m +++ b/matlab/random_walk_metropolis_hastings_core.m @@ -1,185 +1,185 @@ -function myoutput = random_walk_metropolis_hastings_core(myinputs,fblck,nblck,whoiam, ThisMatlab) - -% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. - -if nargin<4, - whoiam=0; -end - - -global bayestopt_ estim_params_ options_ M_ oo_ - -struct2local(myinputs); - - -MhDirectoryName = CheckPath('metropolis'); - -options_.lik_algo = 1; -OpenOldFile = ones(nblck,1); -if strcmpi(ProposalFun,'rand_multivariate_normal') - n = npar; -elseif strcmpi(ProposalFun,'rand_multivariate_student') - n = options_.student_degrees_of_freedom; -end -% load([MhDirectoryName '/' ModelName '_mh_history.mat'],'record'); -%%%% -%%%% NOW i run the (nblck-fblck+1) metropolis-hastings chains -%%%% -jscale = diag(bayestopt_.jscale); - -jloop=0; - -for b = fblck:nblck, - jloop=jloop+1; - randn('state',record.Seeds(b).Normal); - rand('state',record.Seeds(b).Unifor); - if (options_.load_mh_file~=0) & (fline(b)>1) & OpenOldFile(b) - load(['./' MhDirectoryName '/' ModelName '_mh' int2str(NewFile(b)) ... - '_blck' int2str(b) '.mat']) - x2 = [x2;zeros(InitSizeArray(b)-fline(b)+1,npar)]; - logpo2 = [logpo2;zeros(InitSizeArray(b)-fline(b)+1,1)]; - OpenOldFile(b) = 0; - else - x2 = zeros(InitSizeArray(b),npar); - logpo2 = zeros(InitSizeArray(b),1); - end - if exist('OCTAVE_VERSION') - diary off; - elseif whoiam -% keyboard; - waitbarString = ['Please wait... Metropolis-Hastings (' int2str(b) '/' int2str(options_.mh_nblck) ')...']; -% waitbarTitle=['Metropolis-Hastings ',options_.parallel(ThisMatlab).PcName]; - if options_.parallel(ThisMatlab).Local, - waitbarTitle=['Local ']; - else - waitbarTitle=[options_.parallel(ThisMatlab).PcName]; - end - fMessageStatus(0,whoiam,waitbarString, waitbarTitle, options_.parallel(ThisMatlab), MasterName, DyMo); - else, - hh = waitbar(0,['Please wait... Metropolis-Hastings (' int2str(b) '/' int2str(options_.mh_nblck) ')...']); - set(hh,'Name','Metropolis-Hastings'); - - end - isux = 0; - jsux = 0; - irun = fline(b); - j = 1; - while j <= nruns(b) - par = feval(ProposalFun, ix2(b,:), d * jscale, n); - if all( par(:) > mh_bounds(:,1) ) & all( par(:) < mh_bounds(:,2) ) - try - logpost = - feval(TargetFun, par(:),varargin{:}); - catch - logpost = -inf; - end - else - logpost = -inf; - end - if (logpost > -inf) & (log(rand) < logpost-ilogpo2(b)) - x2(irun,:) = par; - ix2(b,:) = par; - logpo2(irun) = logpost; - ilogpo2(b) = logpost; - isux = isux + 1; - jsux = jsux + 1; - else - x2(irun,:) = ix2(b,:); - logpo2(irun) = ilogpo2(b); - end - prtfrc = j/nruns(b); - if exist('OCTAVE_VERSION') - if mod(j, 10) == 0, - printf('MH: Computing Metropolis-Hastings (chain %d/%d): %3.f%% done, acception rate: %3.f%%\r', b, nblck, 100 * prtfrc, 100 * isux / j); - end - if mod(j,50)==0 & whoiam, -% keyboard; - waitbarString = [ '(' int2str(b) '/' int2str(options_.mh_nblck) '), ' sprintf('accept. %3.f%%%%', 100 * isux/j)]; - fMessageStatus(prtfrc,whoiam,waitbarString, '', options_.parallel(ThisMatlab), MasterName, DyMo) - end - else - if mod(j, 3)==0 & ~whoiam - waitbar(prtfrc,hh,[ '(' int2str(b) '/' int2str(options_.mh_nblck) ') ' sprintf('%f done, acceptation rate %f',prtfrc,isux/j)]); - elseif mod(j,50)==0 & whoiam, -% keyboard; - waitbarString = [ '(' int2str(b) '/' int2str(options_.mh_nblck) ') ' sprintf('%f done, acceptation rate %f',prtfrc,isux/j)]; - fMessageStatus(prtfrc,whoiam,waitbarString, waitbarTitle, options_.parallel(ThisMatlab), MasterName, DyMo) - end - end - - if (irun == InitSizeArray(b)) | (j == nruns(b)) % Now I save the simulations - save([MhDirectoryName '/' ModelName '_mh' int2str(NewFile(b)) '_blck' int2str(b) '.mat'],'x2','logpo2'); - fidlog = fopen([MhDirectoryName '/metropolis.log'],'a'); - fprintf(fidlog,['\n']); - fprintf(fidlog,['%% Mh' int2str(NewFile(b)) 'Blck' int2str(b) ' (' datestr(now,0) ')\n']); - fprintf(fidlog,' \n'); - fprintf(fidlog,[' Number of simulations.: ' int2str(length(logpo2)) '\n']); - fprintf(fidlog,[' Acceptation rate......: ' num2str(jsux/length(logpo2)) '\n']); - fprintf(fidlog,[' Posterior mean........:\n']); - for i=1:length(x2(1,:)) - fprintf(fidlog,[' params:' int2str(i) ': ' num2str(mean(x2(:,i))) '\n']); - end - fprintf(fidlog,[' log2po:' num2str(mean(logpo2)) '\n']); - fprintf(fidlog,[' Minimum value.........:\n']);; - for i=1:length(x2(1,:)) - fprintf(fidlog,[' params:' int2str(i) ': ' num2str(min(x2(:,i))) '\n']); - end - fprintf(fidlog,[' log2po:' num2str(min(logpo2)) '\n']); - fprintf(fidlog,[' Maximum value.........:\n']); - for i=1:length(x2(1,:)) - fprintf(fidlog,[' params:' int2str(i) ': ' num2str(max(x2(:,i))) '\n']); - end - fprintf(fidlog,[' log2po:' num2str(max(logpo2)) '\n']); - fprintf(fidlog,' \n'); - fclose(fidlog); - jsux = 0; - if j == nruns(b) % I record the last draw... - record.LastParameters(b,:) = x2(end,:); - record.LastLogLiK(b) = logpo2(end); - end - % size of next file in chain b - InitSizeArray(b) = min(nruns(b)-j,MAX_nruns); - % initialization of next file if necessary - if InitSizeArray(b) - x2 = zeros(InitSizeArray(b),npar); - logpo2 = zeros(InitSizeArray(b),1); - NewFile(b) = NewFile(b) + 1; - irun = 0; - end - end - j=j+1; - irun = irun + 1; - end% End of the simulations for one mh-block. - record.AcceptationRates(b) = isux/j; - if exist('OCTAVE_VERSION') - printf('\n'); - diary on; - elseif ~whoiam - close(hh); - end - record.Seeds(b).Normal = randn('state'); - record.Seeds(b).Unifor = rand('state'); - OutputFileName(jloop,:) = {[MhDirectoryName,filesep], [ModelName '_mh*_blck' int2str(b) '.mat']}; -end% End of the loop over the mh-blocks. - - -myoutput.record = record; -myoutput.irun = irun; -myoutput.NewFile = NewFile; -myoutput.OutputFileName = OutputFileName; - - +function myoutput = random_walk_metropolis_hastings_core(myinputs,fblck,nblck,whoiam, ThisMatlab) + +% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. + +if nargin<4, + whoiam=0; +end + + +global bayestopt_ estim_params_ options_ M_ oo_ + +struct2local(myinputs); + + +MhDirectoryName = CheckPath('metropolis'); + +options_.lik_algo = 1; +OpenOldFile = ones(nblck,1); +if strcmpi(ProposalFun,'rand_multivariate_normal') + n = npar; +elseif strcmpi(ProposalFun,'rand_multivariate_student') + n = options_.student_degrees_of_freedom; +end +% load([MhDirectoryName '/' ModelName '_mh_history.mat'],'record'); +%%%% +%%%% NOW i run the (nblck-fblck+1) metropolis-hastings chains +%%%% +jscale = diag(bayestopt_.jscale); + +jloop=0; + +for b = fblck:nblck, + jloop=jloop+1; + randn('state',record.Seeds(b).Normal); + rand('state',record.Seeds(b).Unifor); + if (options_.load_mh_file~=0) & (fline(b)>1) & OpenOldFile(b) + load(['./' MhDirectoryName '/' ModelName '_mh' int2str(NewFile(b)) ... + '_blck' int2str(b) '.mat']) + x2 = [x2;zeros(InitSizeArray(b)-fline(b)+1,npar)]; + logpo2 = [logpo2;zeros(InitSizeArray(b)-fline(b)+1,1)]; + OpenOldFile(b) = 0; + else + x2 = zeros(InitSizeArray(b),npar); + logpo2 = zeros(InitSizeArray(b),1); + end + if exist('OCTAVE_VERSION') + diary off; + elseif whoiam + % keyboard; + waitbarString = ['Please wait... Metropolis-Hastings (' int2str(b) '/' int2str(options_.mh_nblck) ')...']; + % waitbarTitle=['Metropolis-Hastings ',options_.parallel(ThisMatlab).PcName]; + if options_.parallel(ThisMatlab).Local, + waitbarTitle=['Local ']; + else + waitbarTitle=[options_.parallel(ThisMatlab).PcName]; + end + fMessageStatus(0,whoiam,waitbarString, waitbarTitle, options_.parallel(ThisMatlab), MasterName, DyMo); + else, + hh = waitbar(0,['Please wait... Metropolis-Hastings (' int2str(b) '/' int2str(options_.mh_nblck) ')...']); + set(hh,'Name','Metropolis-Hastings'); + + end + isux = 0; + jsux = 0; + irun = fline(b); + j = 1; + while j <= nruns(b) + par = feval(ProposalFun, ix2(b,:), d * jscale, n); + if all( par(:) > mh_bounds(:,1) ) & all( par(:) < mh_bounds(:,2) ) + try + logpost = - feval(TargetFun, par(:),varargin{:}); + catch + logpost = -inf; + end + else + logpost = -inf; + end + if (logpost > -inf) & (log(rand) < logpost-ilogpo2(b)) + x2(irun,:) = par; + ix2(b,:) = par; + logpo2(irun) = logpost; + ilogpo2(b) = logpost; + isux = isux + 1; + jsux = jsux + 1; + else + x2(irun,:) = ix2(b,:); + logpo2(irun) = ilogpo2(b); + end + prtfrc = j/nruns(b); + if exist('OCTAVE_VERSION') + if mod(j, 10) == 0, + printf('MH: Computing Metropolis-Hastings (chain %d/%d): %3.f%% done, acception rate: %3.f%%\r', b, nblck, 100 * prtfrc, 100 * isux / j); + end + if mod(j,50)==0 & whoiam, + % keyboard; + waitbarString = [ '(' int2str(b) '/' int2str(options_.mh_nblck) '), ' sprintf('accept. %3.f%%%%', 100 * isux/j)]; + fMessageStatus(prtfrc,whoiam,waitbarString, '', options_.parallel(ThisMatlab), MasterName, DyMo) + end + else + if mod(j, 3)==0 & ~whoiam + waitbar(prtfrc,hh,[ '(' int2str(b) '/' int2str(options_.mh_nblck) ') ' sprintf('%f done, acceptation rate %f',prtfrc,isux/j)]); + elseif mod(j,50)==0 & whoiam, + % keyboard; + waitbarString = [ '(' int2str(b) '/' int2str(options_.mh_nblck) ') ' sprintf('%f done, acceptation rate %f',prtfrc,isux/j)]; + fMessageStatus(prtfrc,whoiam,waitbarString, waitbarTitle, options_.parallel(ThisMatlab), MasterName, DyMo) + end + end + + if (irun == InitSizeArray(b)) | (j == nruns(b)) % Now I save the simulations + save([MhDirectoryName '/' ModelName '_mh' int2str(NewFile(b)) '_blck' int2str(b) '.mat'],'x2','logpo2'); + fidlog = fopen([MhDirectoryName '/metropolis.log'],'a'); + fprintf(fidlog,['\n']); + fprintf(fidlog,['%% Mh' int2str(NewFile(b)) 'Blck' int2str(b) ' (' datestr(now,0) ')\n']); + fprintf(fidlog,' \n'); + fprintf(fidlog,[' Number of simulations.: ' int2str(length(logpo2)) '\n']); + fprintf(fidlog,[' Acceptation rate......: ' num2str(jsux/length(logpo2)) '\n']); + fprintf(fidlog,[' Posterior mean........:\n']); + for i=1:length(x2(1,:)) + fprintf(fidlog,[' params:' int2str(i) ': ' num2str(mean(x2(:,i))) '\n']); + end + fprintf(fidlog,[' log2po:' num2str(mean(logpo2)) '\n']); + fprintf(fidlog,[' Minimum value.........:\n']);; + for i=1:length(x2(1,:)) + fprintf(fidlog,[' params:' int2str(i) ': ' num2str(min(x2(:,i))) '\n']); + end + fprintf(fidlog,[' log2po:' num2str(min(logpo2)) '\n']); + fprintf(fidlog,[' Maximum value.........:\n']); + for i=1:length(x2(1,:)) + fprintf(fidlog,[' params:' int2str(i) ': ' num2str(max(x2(:,i))) '\n']); + end + fprintf(fidlog,[' log2po:' num2str(max(logpo2)) '\n']); + fprintf(fidlog,' \n'); + fclose(fidlog); + jsux = 0; + if j == nruns(b) % I record the last draw... + record.LastParameters(b,:) = x2(end,:); + record.LastLogLiK(b) = logpo2(end); + end + % size of next file in chain b + InitSizeArray(b) = min(nruns(b)-j,MAX_nruns); + % initialization of next file if necessary + if InitSizeArray(b) + x2 = zeros(InitSizeArray(b),npar); + logpo2 = zeros(InitSizeArray(b),1); + NewFile(b) = NewFile(b) + 1; + irun = 0; + end + end + j=j+1; + irun = irun + 1; + end% End of the simulations for one mh-block. + record.AcceptationRates(b) = isux/j; + if exist('OCTAVE_VERSION') + printf('\n'); + diary on; + elseif ~whoiam + close(hh); + end + record.Seeds(b).Normal = randn('state'); + record.Seeds(b).Unifor = rand('state'); + OutputFileName(jloop,:) = {[MhDirectoryName,filesep], [ModelName '_mh*_blck' int2str(b) '.mat']}; +end% End of the loop over the mh-blocks. + + +myoutput.record = record; +myoutput.irun = irun; +myoutput.NewFile = NewFile; +myoutput.OutputFileName = OutputFileName; + + diff --git a/matlab/read_data_.m b/matlab/read_data_.m index 137df4c964..3f81486d09 100644 --- a/matlab/read_data_.m +++ b/matlab/read_data_.m @@ -1,64 +1,64 @@ -function read_data_ -% function read_data_ -% reads endogenous and exogenous variables from a text file -% Used by datafile option in simulate -% -% INPUT -% none -% -% OUTPUT -% none -% -% SPECIAL REQUIREMENT -% none - -% Copyright (C) 2007-2008 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 <http://www.gnu.org/licenses/>. - - global options_ M_ oo_; - dname= options_.datafile; - fid = fopen([dname '_endo.dat'],'r'); - names_line = fgetl(fid); - allVariables = ''; - positions = ones(0); - while (any(names_line)) - [chopped,names_line] = strtok(names_line); - allVariables = strvcat(allVariables, chopped); - positions = [positions ; strmatch(chopped,M_.endo_names,'exact')]; - end - Values=fscanf(fid,'%f',inf); - Values=reshape(Values,M_.endo_nbr,size(Values,1)/M_.endo_nbr); - oo_.endo_simul=Values(positions,:); - fclose(fid); - - fid = fopen([dname '_exo.dat'],'r'); - names_line = fgetl(fid); - allVariables = ''; - positions = ones(0); - while (any(names_line)) - [chopped,names_line] = strtok(names_line); - allVariables = strvcat(allVariables, chopped); - positions = [positions ; strmatch(chopped,M_.exo_names,'exact')]; - end - Values=fscanf(fid,'%f',inf); - Values=reshape(Values,M_.exo_nbr,size(Values,1)/M_.exo_nbr); - oo_.exo_simul=(Values(positions,:))'; - fclose(fid); - %disp([allVariables M_.endo_names]); - %disp(positions); - +function read_data_ +% function read_data_ +% reads endogenous and exogenous variables from a text file +% Used by datafile option in simulate +% +% INPUT +% none +% +% OUTPUT +% none +% +% SPECIAL REQUIREMENT +% none + +% Copyright (C) 2007-2008 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 <http://www.gnu.org/licenses/>. + +global options_ M_ oo_; +dname= options_.datafile; +fid = fopen([dname '_endo.dat'],'r'); +names_line = fgetl(fid); +allVariables = ''; +positions = ones(0); +while (any(names_line)) + [chopped,names_line] = strtok(names_line); + allVariables = strvcat(allVariables, chopped); + positions = [positions ; strmatch(chopped,M_.endo_names,'exact')]; +end +Values=fscanf(fid,'%f',inf); +Values=reshape(Values,M_.endo_nbr,size(Values,1)/M_.endo_nbr); +oo_.endo_simul=Values(positions,:); +fclose(fid); + +fid = fopen([dname '_exo.dat'],'r'); +names_line = fgetl(fid); +allVariables = ''; +positions = ones(0); +while (any(names_line)) + [chopped,names_line] = strtok(names_line); + allVariables = strvcat(allVariables, chopped); + positions = [positions ; strmatch(chopped,M_.exo_names,'exact')]; +end +Values=fscanf(fid,'%f',inf); +Values=reshape(Values,M_.exo_nbr,size(Values,1)/M_.exo_nbr); +oo_.exo_simul=(Values(positions,:))'; +fclose(fid); +%disp([allVariables M_.endo_names]); +%disp(positions); + end \ No newline at end of file diff --git a/matlab/read_variables.m b/matlab/read_variables.m index 5bef3fefa2..8f27a861e8 100644 --- a/matlab/read_variables.m +++ b/matlab/read_variables.m @@ -1,88 +1,88 @@ -function dyn_data_01=read_variables(file_name_01,var_names_01,dyn_data_01,xls_sheet,xls_range) - -% function dyn_data_01=read_variables(file_name_01,var_names_01,dyn_data_01,xls_sheet,xls_range) -% Read data -% -% INPUTS -% file_name_01: file name -% var_names_01: variables name -% dyn_data_01: -% xls_sheet: Excel sheet name -% xls_range: Excel range specification -% -% OUTPUTS -% dyn_data_01: -% -% SPECIAL REQUIREMENTS -% all local variables have complicated names in order to avoid name -% conflicts with possible user variable names - -% Copyright (C) 2005-2009 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 <http://www.gnu.org/licenses/>. - - - old_pwd = pwd; - [path_name_02,file_name_02,ext_name_02] = fileparts(file_name_01); - if ~isempty(path_name_02) - file_name_01 = [file_name_02, ext_name_02]; - cd(path_name_02) - end - - dyn_size_01 = size(dyn_data_01,1); - var_size_01 = size(var_names_01,1); - if exist(file_name_01) - file_name_02 = [file_name_01 '.m']; - dyn_instr_01 = file_name_01; - eval(dyn_instr_01); - for dyn_i_01=1:var_size_01 - dyn_tmp_01 = eval(var_names_01(dyn_i_01,:)); - if length(dyn_tmp_01) > dyn_size_01 & dyn_size_01 > 0 - cd(old_pwd) - error('data size is too large') - end - dyn_data_01(:,dyn_i_01) = dyn_tmp_01; - end - elseif exist([file_name_01 '.mat']) - file_name_02 = [file_name_01 '.mat']; - s = load(file_name_01); - for dyn_i_01=1:var_size_01 - dyn_tmp_01 = s.(deblank(var_names_01(dyn_i_01,:))); - if length(dyn_tmp_01) > dyn_size_01 & dyn_size_01 > 0 - cd(old_pwd) - error('data size is too large') - end - dyn_data_01(:,dyn_i_01) = dyn_tmp_01; - end - elseif exist([file_name_01 '.xls']) - file_name_02 = [file_name_01 '.xls']; - [num,txt,raw] = xlsread(file_name_01,xls_sheet,xls_range); - for dyn_i_01=1:var_size_01 - iv = strmatch(var_names_01(dyn_i_01,:),raw(1,:),'exact'); - dyn_tmp_01 = [raw{2:end,iv}]'; - if length(dyn_tmp_01) > dyn_size_01 & dyn_size_01 > 0 - cd(old_pwd) - error('data size is too large') - end - dyn_data_01(:,dyn_i_01) = dyn_tmp_01; - end - else - cd(old_pwd) - error(['Can''t find datafile: ' file_name_01 ]); - end - cd(old_pwd) - disp(sprintf('Loading %d observations from %s\n',... - size(dyn_data_01,1),file_name_02)) +function dyn_data_01=read_variables(file_name_01,var_names_01,dyn_data_01,xls_sheet,xls_range) + +% function dyn_data_01=read_variables(file_name_01,var_names_01,dyn_data_01,xls_sheet,xls_range) +% Read data +% +% INPUTS +% file_name_01: file name +% var_names_01: variables name +% dyn_data_01: +% xls_sheet: Excel sheet name +% xls_range: Excel range specification +% +% OUTPUTS +% dyn_data_01: +% +% SPECIAL REQUIREMENTS +% all local variables have complicated names in order to avoid name +% conflicts with possible user variable names + +% Copyright (C) 2005-2009 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 <http://www.gnu.org/licenses/>. + + +old_pwd = pwd; +[path_name_02,file_name_02,ext_name_02] = fileparts(file_name_01); +if ~isempty(path_name_02) + file_name_01 = [file_name_02, ext_name_02]; + cd(path_name_02) +end + +dyn_size_01 = size(dyn_data_01,1); +var_size_01 = size(var_names_01,1); +if exist(file_name_01) + file_name_02 = [file_name_01 '.m']; + dyn_instr_01 = file_name_01; + eval(dyn_instr_01); + for dyn_i_01=1:var_size_01 + dyn_tmp_01 = eval(var_names_01(dyn_i_01,:)); + if length(dyn_tmp_01) > dyn_size_01 & dyn_size_01 > 0 + cd(old_pwd) + error('data size is too large') + end + dyn_data_01(:,dyn_i_01) = dyn_tmp_01; + end +elseif exist([file_name_01 '.mat']) + file_name_02 = [file_name_01 '.mat']; + s = load(file_name_01); + for dyn_i_01=1:var_size_01 + dyn_tmp_01 = s.(deblank(var_names_01(dyn_i_01,:))); + if length(dyn_tmp_01) > dyn_size_01 & dyn_size_01 > 0 + cd(old_pwd) + error('data size is too large') + end + dyn_data_01(:,dyn_i_01) = dyn_tmp_01; + end +elseif exist([file_name_01 '.xls']) + file_name_02 = [file_name_01 '.xls']; + [num,txt,raw] = xlsread(file_name_01,xls_sheet,xls_range); + for dyn_i_01=1:var_size_01 + iv = strmatch(var_names_01(dyn_i_01,:),raw(1,:),'exact'); + dyn_tmp_01 = [raw{2:end,iv}]'; + if length(dyn_tmp_01) > dyn_size_01 & dyn_size_01 > 0 + cd(old_pwd) + error('data size is too large') + end + dyn_data_01(:,dyn_i_01) = dyn_tmp_01; + end +else + cd(old_pwd) + error(['Can''t find datafile: ' file_name_01 ]); +end +cd(old_pwd) +disp(sprintf('Loading %d observations from %s\n',... + size(dyn_data_01,1),file_name_02)) diff --git a/matlab/recursive_moments.m b/matlab/recursive_moments.m index 5e9a134f28..1d39cc4167 100644 --- a/matlab/recursive_moments.m +++ b/matlab/recursive_moments.m @@ -1,52 +1,52 @@ -function [mu,sigma,offset] = recursive_moments(m0,s0,data,offset) -% Recursive estimation of order one and two moments (expectation and -% covariance matrix). -% -% INPUTS -% o m0 [double] (n*1) vector, the prior expectation. -% o s0 [double] (n*n) matrix, the prior covariance matrix. -% o data [double] (T*n) matrix. -% o offset [integer] scalar, number of observation previously -% used to compute m0 and s0. -% OUTPUTS -% o mu [double] (n*1) vector, the posterior expectation. -% o sigma [double] (n*n) matrix, the posterior covariance matrix. -% o offset [integer] = offset + T. -% -% ALGORITHM -% None. -% -% SPECIAL REQUIREMENTS -% None. - -% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. - -[T,n] = size(data); - -for t = 1:T - tt = t+offset; - m1 = m0 + (data(t,:)'-m0)/tt; - qq = m1*m1'; - s1 = s0 + ( (data(t,:)'*data(t,:)-qq-s0) + (tt-1)*(m0*m0'-qq') )/tt; - m0 = m1; - s0 = s1; -end - -mu = m1; -sigma = s1; +function [mu,sigma,offset] = recursive_moments(m0,s0,data,offset) +% Recursive estimation of order one and two moments (expectation and +% covariance matrix). +% +% INPUTS +% o m0 [double] (n*1) vector, the prior expectation. +% o s0 [double] (n*n) matrix, the prior covariance matrix. +% o data [double] (T*n) matrix. +% o offset [integer] scalar, number of observation previously +% used to compute m0 and s0. +% OUTPUTS +% o mu [double] (n*1) vector, the posterior expectation. +% o sigma [double] (n*n) matrix, the posterior covariance matrix. +% o offset [integer] = offset + T. +% +% ALGORITHM +% None. +% +% SPECIAL REQUIREMENTS +% None. + +% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. + +[T,n] = size(data); + +for t = 1:T + tt = t+offset; + m1 = m0 + (data(t,:)'-m0)/tt; + qq = m1*m1'; + s1 = s0 + ( (data(t,:)'*data(t,:)-qq-s0) + (tt-1)*(m0*m0'-qq') )/tt; + m0 = m1; + s0 = s1; +end + +mu = m1; +sigma = s1; offset = offset+T; \ No newline at end of file diff --git a/matlab/resid.m b/matlab/resid.m index 9c3c592b2e..37d2a8a017 100644 --- a/matlab/resid.m +++ b/matlab/resid.m @@ -29,12 +29,12 @@ function z = resid(junk) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ options_ oo_ +global M_ options_ oo_ - steady_state_old = oo_.steady_state; +steady_state_old = oo_.steady_state; - % If using a steady state file, initialize oo_.steady_state with that file - if options_.steadystate_flag +% If using a steady state file, initialize oo_.steady_state with that file +if options_.steadystate_flag [ys,check] = feval([M_.fname '_steadystate'], ... oo_.steady_state, ... [oo_.exo_steady_state; ... @@ -51,37 +51,37 @@ function z = resid(junk) end end oo_.steady_state = ys; - end +end - % Compute the residuals - if options_.block && ~options_.bytecode - error('RESID: incompatibility with "block" without "bytecode" option') - elseif options_.block && options_.bytecode - [z,check] = bytecode('evaluate','static'); - else - z = feval([M_.fname '_static'],... - oo_.steady_state,... - [oo_.exo_steady_state; ... - oo_.exo_det_steady_state], M_.params); - end - - % Display the non-zero residuals if no return value - if nargout == 0 - for i = 1:4 - disp(' ') - end - - for i=1:length(z) - if abs(z(i)) < options_.dynatol/100 - tmp = 0; - else - tmp = z(i); - end - disp(['Residual for equation number ' int2str(i) ' is equal to ' num2str(tmp)]) - end - for i = 1:2 - disp(' ') - end - end - - oo_.steady_state = steady_state_old; +% Compute the residuals +if options_.block && ~options_.bytecode + error('RESID: incompatibility with "block" without "bytecode" option') +elseif options_.block && options_.bytecode + [z,check] = bytecode('evaluate','static'); +else + z = feval([M_.fname '_static'],... + oo_.steady_state,... + [oo_.exo_steady_state; ... + oo_.exo_det_steady_state], M_.params); +end + +% Display the non-zero residuals if no return value +if nargout == 0 + for i = 1:4 + disp(' ') + end + + for i=1:length(z) + if abs(z(i)) < options_.dynatol/100 + tmp = 0; + else + tmp = z(i); + end + disp(['Residual for equation number ' int2str(i) ' is equal to ' num2str(tmp)]) + end + for i = 1:2 + disp(' ') + end +end + +oo_.steady_state = steady_state_old; diff --git a/matlab/resol.m b/matlab/resol.m index 2bf6a57a96..758f422847 100644 --- a/matlab/resol.m +++ b/matlab/resol.m @@ -53,56 +53,56 @@ info = 0; it_ = M_.maximum_lag + 1 ; if M_.exo_nbr == 0 - oo_.exo_steady_state = [] ; + oo_.exo_steady_state = [] ; end % check if ys is steady state tempex = oo_.exo_simul; oo_.exo_simul = repmat(oo_.exo_steady_state',M_.maximum_lag+M_.maximum_lead+1,1); if M_.exo_det_nbr > 0 - tempexdet = oo_.exo_det_simul; - oo_.exo_det_simul = repmat(oo_.exo_det_steady_state',M_.maximum_lag+M_.maximum_lead+1,1); + tempexdet = oo_.exo_det_simul; + oo_.exo_det_simul = repmat(oo_.exo_det_steady_state',M_.maximum_lag+M_.maximum_lead+1,1); end dr.ys = ys; check1 = 0; % testing for steadystate file fh = str2func([M_.fname '_static']); if options_.steadystate_flag - [dr.ys,check1] = feval([M_.fname '_steadystate'],dr.ys,... - [oo_.exo_steady_state; ... - oo_.exo_det_steady_state]); - if size(dr.ys,1) < M_.endo_nbr - if length(M_.aux_vars) > 0 - dr.ys = add_auxiliary_variables_to_steadystate(dr.ys,M_.aux_vars,... - M_.fname,... - oo_.exo_steady_state,... - oo_.exo_det_steady_state,... - M_.params); - else - error([M_.fname '_steadystate.m doesn''t match the model']); - end - end + [dr.ys,check1] = feval([M_.fname '_steadystate'],dr.ys,... + [oo_.exo_steady_state; ... + oo_.exo_det_steady_state]); + if size(dr.ys,1) < M_.endo_nbr + if length(M_.aux_vars) > 0 + dr.ys = add_auxiliary_variables_to_steadystate(dr.ys,M_.aux_vars,... + M_.fname,... + oo_.exo_steady_state,... + oo_.exo_det_steady_state,... + M_.params); + else + error([M_.fname '_steadystate.m doesn''t match the model']); + end + end else - % testing if ys isn't a steady state or if we aren't computing Ramsey policy - if options_.ramsey_policy == 0 - if options_.linear == 0 - % nonlinear models - if max(abs(feval(fh,dr.ys,[oo_.exo_steady_state; ... - oo_.exo_det_steady_state], M_.params))) > options_.dynatol - [dr.ys,check1] = dynare_solve(fh,dr.ys,options_.jacobian_flag,... - [oo_.exo_steady_state; ... - oo_.exo_det_steady_state], M_.params); - end - else - % linear models - [fvec,jacob] = feval(fh,dr.ys,[oo_.exo_steady_state;... - oo_.exo_det_steady_state], M_.params); - if max(abs(fvec)) > 1e-12 - dr.ys = dr.ys-jacob\fvec; - end + % testing if ys isn't a steady state or if we aren't computing Ramsey policy + if options_.ramsey_policy == 0 + if options_.linear == 0 + % nonlinear models + if max(abs(feval(fh,dr.ys,[oo_.exo_steady_state; ... + oo_.exo_det_steady_state], M_.params))) > options_.dynatol + [dr.ys,check1] = dynare_solve(fh,dr.ys,options_.jacobian_flag,... + [oo_.exo_steady_state; ... + oo_.exo_det_steady_state], M_.params); + end + else + % linear models + [fvec,jacob] = feval(fh,dr.ys,[oo_.exo_steady_state;... + oo_.exo_det_steady_state], M_.params); + if max(abs(fvec)) > 1e-12 + dr.ys = dr.ys-jacob\fvec; + end + end end - end end % testing for problem if check1 @@ -127,11 +127,11 @@ end dr.fbias = zeros(M_.endo_nbr,1); [dr,info,M_,options_,oo_] = dr1(dr,check_flag,M_,options_,oo_); if info(1) - return + return end if M_.exo_det_nbr > 0 - oo_.exo_det_simul = tempexdet; + oo_.exo_det_simul = tempexdet; end oo_.exo_simul = tempex; tempex = []; diff --git a/matlab/restricted_steadystate.m b/matlab/restricted_steadystate.m index f2b6f49b9a..7ddbc7ef7a 100644 --- a/matlab/restricted_steadystate.m +++ b/matlab/restricted_steadystate.m @@ -17,15 +17,15 @@ function [sR,sG] = restricted_steadystate(y,x,indx) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global options_ M_ oo_ - - inde = options_.steadystate_partial.sseqn; - - ss = oo_.steady_state; - - ss(indx) = y; - - eval(['[R,G] = ' M_.fname '_static(ss, x, M_.params);']); +global options_ M_ oo_ - sR = R(inde); - sG = G(inde,indx); \ No newline at end of file +inde = options_.steadystate_partial.sseqn; + +ss = oo_.steady_state; + +ss(indx) = y; + +eval(['[R,G] = ' M_.fname '_static(ss, x, M_.params);']); + +sR = R(inde); +sG = G(inde,indx); \ No newline at end of file diff --git a/matlab/row_header_width.m b/matlab/row_header_width.m index b013007e5b..2e07d57f5d 100644 --- a/matlab/row_header_width.m +++ b/matlab/row_header_width.m @@ -30,46 +30,46 @@ function w=row_header_width(M_,estim_params_,bayestopt_) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - np = estim_params_.np; - nvx = estim_params_.nvx; - nvn = estim_params_.nvn; - ncx = estim_params_.ncx; - ncn = estim_params_.ncn; +np = estim_params_.np; +nvx = estim_params_.nvx; +nvn = estim_params_.nvn; +ncx = estim_params_.ncx; +ncn = estim_params_.ncn; - w = 0; - if np - for i=1:np - w = max(w,length(bayestopt_.name{i})); - end +w = 0; +if np + for i=1:np + w = max(w,length(bayestopt_.name{i})); end - if nvx - for i=1:nvx - k = estim_params_.var_exo(i,1); - w = max(w,length(deblank(M_.exo_names(k,:)))); - end +end +if nvx + for i=1:nvx + k = estim_params_.var_exo(i,1); + w = max(w,length(deblank(M_.exo_names(k,:)))); end - if nvn - for i=1:nvn - k = estim_params_.var_endo(i,1); - w = max(w,length(deblank(M_.endo_names(k,:)))); - end +end +if nvn + for i=1:nvn + k = estim_params_.var_endo(i,1); + w = max(w,length(deblank(M_.endo_names(k,:)))); end - if ncx - for i=1:ncx - k1 = estim_params_.corrx(i,1); - k2 = estim_params_.corrx(i,2); - w = max(w,length(deblank(M_.exo_names(k1,:)))... - +length(deblank(M_.exo_names(k2,:)))) +end +if ncx + for i=1:ncx + k1 = estim_params_.corrx(i,1); + k2 = estim_params_.corrx(i,2); + w = max(w,length(deblank(M_.exo_names(k1,:)))... + +length(deblank(M_.exo_names(k2,:)))) - end end - if ncn - for i=1:nvn - k1 = estim_params_.corrn(i,1); - k2 = estim_params_.corrn(i,2); - w = max(w,length(deblank(M_.endo_names(k1,:)))... - +length(deblank(M_.endo_names(k2,:)))); +end +if ncn + for i=1:nvn + k1 = estim_params_.corrn(i,1); + k2 = estim_params_.corrn(i,2); + w = max(w,length(deblank(M_.endo_names(k1,:)))... + +length(deblank(M_.endo_names(k2,:)))); - end end +end diff --git a/matlab/rplot.m b/matlab/rplot.m index bc90967ddb..eb25882ac4 100644 --- a/matlab/rplot.m +++ b/matlab/rplot.m @@ -40,56 +40,56 @@ ix = [1 - M_.maximum_lag:size(oo_.endo_simul,2)-M_.maximum_lag]' ; y = []; for k=1:size(s1,1) - if isempty(strmatch(s1(k,:),M_.endo_names,'exact')) - error (['One of the variable specified does not exist']) ; - end + if isempty(strmatch(s1(k,:),M_.endo_names,'exact')) + error (['One of the variable specified does not exist']) ; + end - y = [y; oo_.endo_simul(strmatch(s1(k,:),M_.endo_names,'exact'),:)] ; + y = [y; oo_.endo_simul(strmatch(s1(k,:),M_.endo_names,'exact'),:)] ; end if options_.smpl == 0 - i = [M_.maximum_lag:size(oo_.endo_simul,2)]' ; + i = [M_.maximum_lag:size(oo_.endo_simul,2)]' ; else - i = [options_.smpl(1)+M_.maximum_lag:options_.smpl(2)+M_.maximum_lag]' ; + i = [options_.smpl(1)+M_.maximum_lag:options_.smpl(2)+M_.maximum_lag]' ; end t = ['Plot of '] ; if rplottype == 0 - for j = 1:size(y,1) - t = [t s1(j,:) ' '] ; - end - figure ; - plot(ix(i),y(:,i)) ; - title (t,'Interpreter','none') ; - xlabel('Periods') ; - if size(s1,1) > 1 - if exist('OCTAVE_VERSION') - legend(s1, 0); - else - h = legend(s1,0); - set(h, 'Interpreter', 'none'); - end - end + for j = 1:size(y,1) + t = [t s1(j,:) ' '] ; + end + figure ; + plot(ix(i),y(:,i)) ; + title (t,'Interpreter','none') ; + xlabel('Periods') ; + if size(s1,1) > 1 + if exist('OCTAVE_VERSION') + legend(s1, 0); + else + h = legend(s1,0); + set(h, 'Interpreter', 'none'); + end + end elseif rplottype == 1 - for j = 1:size(y,1) - figure ; - plot(ix(i),y(j,i)) ; - title(['Plot of ' s1(:,j)]) ; - xlabel('Periods') ; - end + for j = 1:size(y,1) + figure ; + plot(ix(i),y(j,i)) ; + title(['Plot of ' s1(:,j)]) ; + xlabel('Periods') ; + end elseif rplottype == 2 - figure ; - nl = max(1,fix(size(y,1)/4)) ; - nc = ceil(size(y,1)/nl) ; - for j = 1:size(y,1) - subplot(nl,nc,j) ; - plot(ix(i),y(j,i)) ; - hold on ; - plot(ix(i),oo_.steady_state(j)*ones(1,size(i,1)),'w:') ; - xlabel('Periods') ; - ylabel([s1(:,j)]) ; - title(['Plot of ' s1(:,j)]) ; - end + figure ; + nl = max(1,fix(size(y,1)/4)) ; + nc = ceil(size(y,1)/nl) ; + for j = 1:size(y,1) + subplot(nl,nc,j) ; + plot(ix(i),y(j,i)) ; + hold on ; + plot(ix(i),oo_.steady_state(j)*ones(1,size(i,1)),'w:') ; + xlabel('Periods') ; + ylabel([s1(:,j)]) ; + title(['Plot of ' s1(:,j)]) ; + end end % 02/28/01 MJ replaced bseastr by MATLAB's strmatch diff --git a/matlab/save_params_and_steady_state.m b/matlab/save_params_and_steady_state.m index b00211c5e0..0f8dbfe1a4 100644 --- a/matlab/save_params_and_steady_state.m +++ b/matlab/save_params_and_steady_state.m @@ -39,27 +39,27 @@ function save_params_and_steady_state(filename) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ oo_ +global M_ oo_ - fid = fopen(filename, 'w'); - if fid < 0 - error([ 'SAVE_PARAMS_AND_STEADY_STATE: Can''t open ' filename ]); - end +fid = fopen(filename, 'w'); +if fid < 0 + error([ 'SAVE_PARAMS_AND_STEADY_STATE: Can''t open ' filename ]); +end - for i = 1:M_.param_nbr - fprintf(fid, '%s %.16g\n', M_.param_names(i,:), M_.params(i)); - end - - for i = 1:M_.endo_nbr - fprintf(fid, '%s %.16g\n', M_.endo_names(i,:), oo_.steady_state(i)); - end +for i = 1:M_.param_nbr + fprintf(fid, '%s %.16g\n', M_.param_names(i,:), M_.params(i)); +end - for i = 1:M_.exo_nbr - fprintf(fid, '%s %.16g\n', M_.exo_names(i,:), oo_.exo_steady_state(i)); - end +for i = 1:M_.endo_nbr + fprintf(fid, '%s %.16g\n', M_.endo_names(i,:), oo_.steady_state(i)); +end - for i = 1:M_.exo_det_nbr - fprintf(fid, '%s %.16g\n', M_.exo_det_names(i,:), oo_.exo_det_steady_state(i)); - end +for i = 1:M_.exo_nbr + fprintf(fid, '%s %.16g\n', M_.exo_names(i,:), oo_.exo_steady_state(i)); +end - fclose(fid); +for i = 1:M_.exo_det_nbr + fprintf(fid, '%s %.16g\n', M_.exo_det_names(i,:), oo_.exo_det_steady_state(i)); +end + +fclose(fid); diff --git a/matlab/save_results.m b/matlab/save_results.m index e2f4a584c6..573e0af259 100644 --- a/matlab/save_results.m +++ b/matlab/save_results.m @@ -1,38 +1,38 @@ -function save_results(x,s_name,names) - -% function save_results(x,s_name,names) -% save results in appropriate structure -% -% INPUT -% x: matrix to be saved column by column -% s_name: name of the structure where to save the results -% names: names of the individual series -% -% OUTPUT -% none -% -% SPECIAL REQUIREMENT -% none - -% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. - - global oo_ - - for i=1:size(x,2) - eval([s_name deblank(names(i,:)) '= x(:,i);']); - end \ No newline at end of file +function save_results(x,s_name,names) + +% function save_results(x,s_name,names) +% save results in appropriate structure +% +% INPUT +% x: matrix to be saved column by column +% s_name: name of the structure where to save the results +% names: names of the individual series +% +% OUTPUT +% none +% +% SPECIAL REQUIREMENT +% none + +% Copyright (C) 2006-2008 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 <http://www.gnu.org/licenses/>. + +global oo_ + +for i=1:size(x,2) + eval([s_name deblank(names(i,:)) '= x(:,i);']); +end \ No newline at end of file diff --git a/matlab/selec_posterior_draws.m b/matlab/selec_posterior_draws.m index 0c3c9cadc4..126a1e2603 100644 --- a/matlab/selec_posterior_draws.m +++ b/matlab/selec_posterior_draws.m @@ -36,124 +36,124 @@ function SampleAddress = selec_posterior_draws(SampleSize,drsize) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - global M_ options_ estim_params_ oo_ - - % Number of parameters: - npar = estim_params_.nvx; - npar = npar + estim_params_.nvn; - npar = npar + estim_params_.ncx; - npar = npar + estim_params_.ncn; - npar = npar + estim_params_.np; - % Select one task: - switch nargin - case 1 - info = 0; - case 2 - if drsize>0 - info=2; - MAX_mega_bytes = 10;% Should be an option... - else - info=1; - end - drawsize = drsize+npar*8/1048576; - otherwise - error(['selec_posterior_draws:: Unexpected number of input arguments!']) +global M_ options_ estim_params_ oo_ + +% Number of parameters: +npar = estim_params_.nvx; +npar = npar + estim_params_.nvn; +npar = npar + estim_params_.ncx; +npar = npar + estim_params_.ncn; +npar = npar + estim_params_.np; + +% Select one task: +switch nargin + case 1 + info = 0; + case 2 + if drsize>0 + info=2; + MAX_mega_bytes = 10;% Should be an option... + else + info=1; end - - % Get informations about the mcmc: - MhDirectoryName = CheckPath('metropolis'); - fname = [ MhDirectoryName '/' M_.fname]; - load([ fname '_mh_history.mat']); - FirstMhFile = record.KeepedDraws.FirstMhFile; - FirstLine = record.KeepedDraws.FirstLine; - TotalNumberOfMhFiles = sum(record.MhDraws(:,2)); - LastMhFile = TotalNumberOfMhFiles; - TotalNumberOfMhDraws = sum(record.MhDraws(:,1)); - NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws); - MAX_nruns = ceil(options_.MaxNumberOfBytes/(npar+2)/8); - mh_nblck = options_.mh_nblck; - - % Randomly select draws in the posterior distribution: - SampleAddress = zeros(SampleSize,4); - for i = 1:SampleSize - ChainNumber = ceil(rand*mh_nblck); - DrawNumber = ceil(rand*NumberOfDraws); - SampleAddress(i,1) = DrawNumber; - SampleAddress(i,2) = ChainNumber; - if DrawNumber <= MAX_nruns-FirstLine+1 - MhFileNumber = FirstMhFile; - MhLineNumber = FirstLine+DrawNumber-1; - else - DrawNumber = DrawNumber-(MAX_nruns-FirstLine+1); - MhFileNumber = FirstMhFile+ceil(DrawNumber/MAX_nruns); - MhLineNumber = DrawNumber-(MhFileNumber-FirstMhFile-1)*MAX_nruns; - end - SampleAddress(i,3) = MhFileNumber; - SampleAddress(i,4) = MhLineNumber; + drawsize = drsize+npar*8/1048576; + otherwise + error(['selec_posterior_draws:: Unexpected number of input arguments!']) +end + +% Get informations about the mcmc: +MhDirectoryName = CheckPath('metropolis'); +fname = [ MhDirectoryName '/' M_.fname]; +load([ fname '_mh_history.mat']); +FirstMhFile = record.KeepedDraws.FirstMhFile; +FirstLine = record.KeepedDraws.FirstLine; +TotalNumberOfMhFiles = sum(record.MhDraws(:,2)); +LastMhFile = TotalNumberOfMhFiles; +TotalNumberOfMhDraws = sum(record.MhDraws(:,1)); +NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws); +MAX_nruns = ceil(options_.MaxNumberOfBytes/(npar+2)/8); +mh_nblck = options_.mh_nblck; + +% Randomly select draws in the posterior distribution: +SampleAddress = zeros(SampleSize,4); +for i = 1:SampleSize + ChainNumber = ceil(rand*mh_nblck); + DrawNumber = ceil(rand*NumberOfDraws); + SampleAddress(i,1) = DrawNumber; + SampleAddress(i,2) = ChainNumber; + if DrawNumber <= MAX_nruns-FirstLine+1 + MhFileNumber = FirstMhFile; + MhLineNumber = FirstLine+DrawNumber-1; + else + DrawNumber = DrawNumber-(MAX_nruns-FirstLine+1); + MhFileNumber = FirstMhFile+ceil(DrawNumber/MAX_nruns); + MhLineNumber = DrawNumber-(MhFileNumber-FirstMhFile-1)*MAX_nruns; end - SampleAddress = sortrows(SampleAddress,[3 2]); - - % Selected draws in the posterior distribution, and if drsize>0 - % reduced form solutions, are saved on disk. - if info - if SampleSize*drawsize <= MAX_mega_bytes% The posterior draws are saved in one file. - pdraws = cell(SampleSize,info); - old_mhfile = 0; - old_mhblck = 0; - for i = 1:SampleSize - mhfile = SampleAddress(i,3); - mhblck = SampleAddress(i,2); - if (mhfile ~= old_mhfile) | (mhblck ~= old_mhblck) - load([fname '_mh' num2str(mhfile) '_blck' num2str(mhblck) '.mat'],'x2') - end - pdraws(i,1) = {x2(SampleAddress(i,4),:)}; - if info-1 - set_parameters(pdraws{i,1}); - [dr,info] = resol(oo_.steady_state,0); - pdraws(i,2) = { dr }; - end - old_mhfile = mhfile; - old_mhblck = mhblck; + SampleAddress(i,3) = MhFileNumber; + SampleAddress(i,4) = MhLineNumber; +end +SampleAddress = sortrows(SampleAddress,[3 2]); + +% Selected draws in the posterior distribution, and if drsize>0 +% reduced form solutions, are saved on disk. +if info + if SampleSize*drawsize <= MAX_mega_bytes% The posterior draws are saved in one file. + pdraws = cell(SampleSize,info); + old_mhfile = 0; + old_mhblck = 0; + for i = 1:SampleSize + mhfile = SampleAddress(i,3); + mhblck = SampleAddress(i,2); + if (mhfile ~= old_mhfile) | (mhblck ~= old_mhblck) + load([fname '_mh' num2str(mhfile) '_blck' num2str(mhblck) '.mat'],'x2') end - clear('x2') - save([fname '_posterior_draws1'],'pdraws') - else% The posterior draws are saved in xx files. - NumberOfDrawsPerFile = fix(MAX_mega_bytes/drawsize); - NumberOfFiles = ceil(SampleSize*drawsize/MAX_mega_bytes); - NumberOfLines = SampleSize - (NumberOfFiles-1)*NumberOfDrawsPerFile; - linee = 0; - fnum = 1; - pdraws = cell(NumberOfDrawsPerFile,info); - old_mhfile = 0; - old_mhblck = 0; - for i=1:SampleSize - linee = linee+1; - mhfile = SampleAddress(i,3); - mhblck = SampleAddress(i,2); - if (mhfile ~= old_mhfile) | (mhblck ~= old_mhblck) - load([fname '_mh' num2str(mhfile) '_blck' num2str(mhblck) '.mat'],'x2') - end - pdraws(linee,1) = {x2(SampleAddress(i,4),:)}; - if info-1 - set_parameters(pdraws{linee,1}); - [dr,info] = resol(oo_.steady_state,0); - pdraws(linee,2) = { dr }; - end - old_mhfile = mhfile; - old_mhblck = mhblck; - if fnum < NumberOfFiles && linee == NumberOfDrawsPerFile - linee = 0; - save([fname '_posterior_draws' num2str(fnum)],'pdraws') - fnum = fnum+1; - if fnum < NumberOfFiles - pdraws = cell(NumberOfDrawsPerFile,info); - else - pdraws = cell(NumberOfLines,info); - end + pdraws(i,1) = {x2(SampleAddress(i,4),:)}; + if info-1 + set_parameters(pdraws{i,1}); + [dr,info] = resol(oo_.steady_state,0); + pdraws(i,2) = { dr }; + end + old_mhfile = mhfile; + old_mhblck = mhblck; + end + clear('x2') + save([fname '_posterior_draws1'],'pdraws') + else% The posterior draws are saved in xx files. + NumberOfDrawsPerFile = fix(MAX_mega_bytes/drawsize); + NumberOfFiles = ceil(SampleSize*drawsize/MAX_mega_bytes); + NumberOfLines = SampleSize - (NumberOfFiles-1)*NumberOfDrawsPerFile; + linee = 0; + fnum = 1; + pdraws = cell(NumberOfDrawsPerFile,info); + old_mhfile = 0; + old_mhblck = 0; + for i=1:SampleSize + linee = linee+1; + mhfile = SampleAddress(i,3); + mhblck = SampleAddress(i,2); + if (mhfile ~= old_mhfile) | (mhblck ~= old_mhblck) + load([fname '_mh' num2str(mhfile) '_blck' num2str(mhblck) '.mat'],'x2') + end + pdraws(linee,1) = {x2(SampleAddress(i,4),:)}; + if info-1 + set_parameters(pdraws{linee,1}); + [dr,info] = resol(oo_.steady_state,0); + pdraws(linee,2) = { dr }; + end + old_mhfile = mhfile; + old_mhblck = mhblck; + if fnum < NumberOfFiles && linee == NumberOfDrawsPerFile + linee = 0; + save([fname '_posterior_draws' num2str(fnum)],'pdraws') + fnum = fnum+1; + if fnum < NumberOfFiles + pdraws = cell(NumberOfDrawsPerFile,info); + else + pdraws = cell(NumberOfLines,info); end end - save([fname '_posterior_draws' num2str(fnum)],'pdraws') end - end \ No newline at end of file + save([fname '_posterior_draws' num2str(fnum)],'pdraws') + end +end \ No newline at end of file diff --git a/matlab/selif.m b/matlab/selif.m index 5955dce8cc..5d9f1fa7c7 100644 --- a/matlab/selif.m +++ b/matlab/selif.m @@ -18,7 +18,7 @@ function x = selif(a,b) % along with Dynare. If not, see <http://www.gnu.org/licenses/>. if size(b,2) ~= 1 - error ('The second argument in SELIF must be � column vector') ; + error ('The second argument in SELIF must be � column vector') ; end x = a(find(b == 1),:) ; diff --git a/matlab/send_endogenous_variables_to_workspace.m b/matlab/send_endogenous_variables_to_workspace.m index d78ed0c474..f1ef2b19ab 100644 --- a/matlab/send_endogenous_variables_to_workspace.m +++ b/matlab/send_endogenous_variables_to_workspace.m @@ -1,6 +1,6 @@ function send_endogenous_variables_to_workspace() % Saves all the endogenous variables in matlab's workspace. - + % Copyright (C) 2009 Dynare Team % % This file is part of Dynare. @@ -17,7 +17,7 @@ function send_endogenous_variables_to_workspace() % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ oo_ - for idx = 1:M_.endo_nbr - assignin('base',deblank(M_.endo_names(idx,:)),oo_.endo_simul(idx,:)) - end \ No newline at end of file +global M_ oo_ +for idx = 1:M_.endo_nbr + assignin('base',deblank(M_.endo_names(idx,:)),oo_.endo_simul(idx,:)) +end \ No newline at end of file diff --git a/matlab/set_all_parameters.m b/matlab/set_all_parameters.m index b57ce77808..38dca92f52 100644 --- a/matlab/set_all_parameters.m +++ b/matlab/set_all_parameters.m @@ -1,103 +1,103 @@ -function set_all_parameters(xparam1) - -% function set_all_parameters(xparam1) -% Sets parameters value -% -% INPUTS -% xparam1: vector of parameters to be estimated (initial values) -% -% OUTPUTS -% none -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2003-2008 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 <http://www.gnu.org/licenses/>. - - global estim_params_ M_ - - nvx = estim_params_.nvx; - ncx = estim_params_.ncx; - nvn = estim_params_.nvn; - ncn = estim_params_.ncn; - np = estim_params_.np; - Sigma_e = M_.Sigma_e; - H = M_.H; - - % setting shocks variance - if nvx - var_exo = estim_params_.var_exo; - for i=1:nvx - k =var_exo(i,1); - Sigma_e(k,k) = xparam1(i)^2; - end - end - % update offset - offset = nvx; - - % setting measument error variance - if nvn - var_endo = estim_params_.var_endo; - for i=1:nvn - k = var_endo(i,1); - H(k,k) = xparam1(i+offset)^2; - end - end - - % update offset - offset = nvx+nvn; - - % setting shocks covariances - if ncx - corrx = estim_params_.corrx; - for i=1:ncx - k1 = corrx(i,1); - k2 = corrx(i,2); - Sigma_e(k1,k2) = xparam1(i+offset)*sqrt(Sigma_e(k1,k1)*Sigma_e(k2,k2)); - Sigma_e(k2,k1) = Sigma_e(k1,k2); - end - end - - % update offset - offset = nvx+nvn+ncx; - % setting measurement error covariances - if ncn - corrn = estim_params_.corrn; - for i=1:ncn - k1 = corr(i,1); - k2 = corr(i,2); - H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2)); - H(k2,k1) = H(k1,k2); - end - end - - % update offset - offset = nvx+ncx+nvn+ncn; - % setting structural parameters - % - if np - M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end); - end - - % updating matrices in M_ - if nvx - M_.Sigma_e = Sigma_e; - end - if nvn - M_.H = H; - end +function set_all_parameters(xparam1) + +% function set_all_parameters(xparam1) +% Sets parameters value +% +% INPUTS +% xparam1: vector of parameters to be estimated (initial values) +% +% OUTPUTS +% none +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2003-2008 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 <http://www.gnu.org/licenses/>. + +global estim_params_ M_ + +nvx = estim_params_.nvx; +ncx = estim_params_.ncx; +nvn = estim_params_.nvn; +ncn = estim_params_.ncn; +np = estim_params_.np; +Sigma_e = M_.Sigma_e; +H = M_.H; + +% setting shocks variance +if nvx + var_exo = estim_params_.var_exo; + for i=1:nvx + k =var_exo(i,1); + Sigma_e(k,k) = xparam1(i)^2; + end +end +% update offset +offset = nvx; + +% setting measument error variance +if nvn + var_endo = estim_params_.var_endo; + for i=1:nvn + k = var_endo(i,1); + H(k,k) = xparam1(i+offset)^2; + end +end + +% update offset +offset = nvx+nvn; + +% setting shocks covariances +if ncx + corrx = estim_params_.corrx; + for i=1:ncx + k1 = corrx(i,1); + k2 = corrx(i,2); + Sigma_e(k1,k2) = xparam1(i+offset)*sqrt(Sigma_e(k1,k1)*Sigma_e(k2,k2)); + Sigma_e(k2,k1) = Sigma_e(k1,k2); + end +end + +% update offset +offset = nvx+nvn+ncx; +% setting measurement error covariances +if ncn + corrn = estim_params_.corrn; + for i=1:ncn + k1 = corr(i,1); + k2 = corr(i,2); + H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2)); + H(k2,k1) = H(k1,k2); + end +end + +% update offset +offset = nvx+ncx+nvn+ncn; +% setting structural parameters +% +if np + M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end); +end + +% updating matrices in M_ +if nvx + M_.Sigma_e = Sigma_e; +end +if nvn + M_.H = H; +end diff --git a/matlab/set_default_option.m b/matlab/set_default_option.m index 9b390c127a..ef68ae4fb6 100644 --- a/matlab/set_default_option.m +++ b/matlab/set_default_option.m @@ -31,8 +31,8 @@ function options=set_default_option(options,field,default) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if ~isfield(options,field) +if ~isfield(options,field) options.(field) = default; - end - - % 06/07/03 MJ added ; to eval expression \ No newline at end of file +end + +% 06/07/03 MJ added ; to eval expression \ No newline at end of file diff --git a/matlab/set_param_value.m b/matlab/set_param_value.m index ff516da208..669d6f324e 100644 --- a/matlab/set_param_value.m +++ b/matlab/set_param_value.m @@ -1,29 +1,29 @@ -function set_param_value(pname,value) - -% Copyright (C) 2007 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 <http://www.gnu.org/licenses/>. - - global M_ - - i = strmatch(pname,M_.param_names,'exact'); - - if isempty(i) - error(['Parameter name ' pname ' doesn''t exist']) - end - - M_.params(i) = value; - assignin('base',pname,value); \ No newline at end of file +function set_param_value(pname,value) + +% Copyright (C) 2007 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 <http://www.gnu.org/licenses/>. + +global M_ + +i = strmatch(pname,M_.param_names,'exact'); + +if isempty(i) + error(['Parameter name ' pname ' doesn''t exist']) +end + +M_.params(i) = value; +assignin('base',pname,value); \ No newline at end of file diff --git a/matlab/set_parameters.m b/matlab/set_parameters.m index b6d8bd42a6..5e6a03c1e6 100644 --- a/matlab/set_parameters.m +++ b/matlab/set_parameters.m @@ -1,73 +1,73 @@ -function set_parameters(xparam1) - -% function set_parameters(xparam1) -% Sets parameters value (except measurement errors) -% This is called for computations such as IRF and forecast -% when measurement errors aren't taken into account -% -% INPUTS -% xparam1: vector of parameters to be estimated (initial values) -% -% OUTPUTS -% none -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2003-2008 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 <http://www.gnu.org/licenses/>. - - global estim_params_ M_ - - nvx = estim_params_.nvx; - ncx = estim_params_.ncx; - nvn = estim_params_.nvn; - ncn = estim_params_.ncn; - np = estim_params_.np; - Sigma_e = M_.Sigma_e; - offset = 0; - - % stderrs of the exogenous shocks - if nvx - var_exo = estim_params_.var_exo; - for i=1:nvx - k = var_exo(i,1); - Sigma_e(k,k) = xparam1(i)^2; - end - end - % and update offset - offset = offset + nvx + nvn; - - % correlations amonx shocks (ncx) - if ncx - corrx = estim_params_.corrx; - for i=1:ncx - k1 = corrx(i,1); - k2 = corrx(i,2); - Sigma_e(k1,k2) = xparam1(i+offset)*sqrt(Sigma_e(k1,k1)*Sigma_e(k2,k2)); - Sigma_e(k2,k1) = Sigma_e(k1,k2); - end - end - % and update offset - offset = offset + ncx + ncn; - - % structural parameters - if np - M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end); - end - - M_.Sigma_e = Sigma_e; \ No newline at end of file +function set_parameters(xparam1) + +% function set_parameters(xparam1) +% Sets parameters value (except measurement errors) +% This is called for computations such as IRF and forecast +% when measurement errors aren't taken into account +% +% INPUTS +% xparam1: vector of parameters to be estimated (initial values) +% +% OUTPUTS +% none +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2003-2008 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 <http://www.gnu.org/licenses/>. + +global estim_params_ M_ + +nvx = estim_params_.nvx; +ncx = estim_params_.ncx; +nvn = estim_params_.nvn; +ncn = estim_params_.ncn; +np = estim_params_.np; +Sigma_e = M_.Sigma_e; +offset = 0; + +% stderrs of the exogenous shocks +if nvx + var_exo = estim_params_.var_exo; + for i=1:nvx + k = var_exo(i,1); + Sigma_e(k,k) = xparam1(i)^2; + end +end +% and update offset +offset = offset + nvx + nvn; + +% correlations amonx shocks (ncx) +if ncx + corrx = estim_params_.corrx; + for i=1:ncx + k1 = corrx(i,1); + k2 = corrx(i,2); + Sigma_e(k1,k2) = xparam1(i+offset)*sqrt(Sigma_e(k1,k1)*Sigma_e(k2,k2)); + Sigma_e(k2,k1) = Sigma_e(k1,k2); + end +end +% and update offset +offset = offset + ncx + ncn; + +% structural parameters +if np + M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end); +end + +M_.Sigma_e = Sigma_e; \ No newline at end of file diff --git a/matlab/set_prior.m b/matlab/set_prior.m index 62f7a91583..5f40e3ae32 100644 --- a/matlab/set_prior.m +++ b/matlab/set_prior.m @@ -34,231 +34,231 @@ function [xparam1, estim_params_, bayestopt_, lb, ub, M_]=set_prior(estim_params % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - nvx = size(estim_params_.var_exo,1); - nvn = size(estim_params_.var_endo,1); - ncx = size(estim_params_.corrx,1); - ncn = size(estim_params_.corrn,1); - np = size(estim_params_.param_vals,1); - - estim_params_.nvx = nvx; - estim_params_.nvn = nvn; - estim_params_.ncx = ncx; - estim_params_.ncn = ncn; - estim_params_.np = np; - - xparam1 = []; - ub = []; - lb = []; - bayestopt_.pshape = []; - bayestopt_.p1 = []; % prior mean - bayestopt_.p2 = []; % prior standard deviation - bayestopt_.p3 = []; % lower bound - bayestopt_.p4 = []; % upper bound - bayestopt_.p5 = []; % prior mode - bayestopt_.p6 = []; % first hyper-parameter (\alpha for the BETA and GAMMA distributions, s for the INVERSE GAMMAs, expectation for the GAUSSIAN distribution, lower bound for the UNIFORM distribution). - bayestopt_.p7 = []; % second hyper-parameter (\beta for the BETA and GAMMA distributions, \nu for the INVERSE GAMMAs, standard deviation for the GAUSSIAN distribution, upper bound for the UNIFORM distribution). - - bayestopt_.jscale = []; - bayestopt_.name = []; - if nvx - xparam1 = estim_params_.var_exo(:,2); - ub = estim_params_.var_exo(:,4); - lb = estim_params_.var_exo(:,3); - bayestopt_.pshape = estim_params_.var_exo(:,5); - bayestopt_.p1 = estim_params_.var_exo(:,6); - bayestopt_.p2 = estim_params_.var_exo(:,7); - bayestopt_.p3 = estim_params_.var_exo(:,8); - bayestopt_.p4 = estim_params_.var_exo(:,9); - bayestopt_.jscale = estim_params_.var_exo(:,10); - bayestopt_.name = cellstr(M_.exo_names(estim_params_.var_exo(:,1),:)); - end - if nvn - if M_.H == 0 - nvarobs = size(options_.varobs,1); - M_.H = zeros(nvarobs,nvarobs); - end - for i=1:nvn - estim_params_.var_endo(i,1) = strmatch(deblank(M_.endo_names(estim_params_.var_endo(i,1),:)),deblank(options_.varobs),'exact'); - end - xparam1 = [xparam1; estim_params_.var_endo(:,2)]; - ub = [ub; estim_params_.var_endo(:,4)]; - lb = [lb; estim_params_.var_endo(:,3)]; - bayestopt_.pshape = [ bayestopt_.pshape; estim_params_.var_endo(:,5)]; - bayestopt_.p1 = [ bayestopt_.p1; estim_params_.var_endo(:,6)]; - bayestopt_.p2 = [ bayestopt_.p2; estim_params_.var_endo(:,7)]; - bayestopt_.p3 = [ bayestopt_.p3; estim_params_.var_endo(:,8)]; - bayestopt_.p4 = [ bayestopt_.p4; estim_params_.var_endo(:,9)]; - bayestopt_.jscale = [ bayestopt_.jscale; estim_params_.var_endo(:,10)]; - bayestopt_.name = cellstr(strvcat(char(bayestopt_.name), M_.endo_names(estim_params_.var_endo(:,1),:))); - end - if ncx - xparam1 = [xparam1; estim_params_.corrx(:,3)]; - ub = [ub; max(min(estim_params_.corrx(:,5),1),-1)]; - lb = [lb; max(min(estim_params_.corrx(:,4),1),-1)]; - bayestopt_.pshape = [ bayestopt_.pshape; estim_params_.corrx(:,6)]; - bayestopt_.p1 = [ bayestopt_.p1; estim_params_.corrx(:,7)]; - bayestopt_.p2 = [ bayestopt_.p2; estim_params_.corrx(:,8)]; - bayestopt_.p3 = [ bayestopt_.p3; estim_params_.corrx(:,9)]; - bayestopt_.p4 = [ bayestopt_.p4; estim_params_.corrx(:,10)]; - bayestopt_.jscale = [ bayestopt_.jscale; estim_params_.corrx(:,11)]; - bayestopt_.name = cellstr(strvcat(char(bayestopt_.name), char(strcat(cellstr(M_.exo_names(estim_params_.corrx(:,1),:)), ... - ',' , cellstr(M_.exo_names(estim_params_.corrx(:,2),:)))))); - end - if ncn - if M_.H == 0 - nvarobs = size(options_.varobs,1); - M_.H = zeros(nvarobs,nvarobs); - end - xparam1 = [xparam1; estim_params_.corrn(:,3)]; - ub = [ub; max(min(estim_params_.corrn(:,5),1),-1)]; - lb = [lb; max(min(estim_params_.corrn(:,4),1),-1)]; - bayestopt_.pshape = [ bayestopt_.pshape; estim_params_.corrn(:,6)]; - bayestopt_.p1 = [ bayestopt_.p1; estim_params_.corrn(:,7)]; - bayestopt_.p2 = [ bayestopt_.p2; estim_params_.corrn(:,8)]; - bayestopt_.p3 = [ bayestopt_.p3; estim_params_.corrn(:,9)]; - bayestopt_.p4 = [ bayestopt_.p4; estim_params_.corrn(:,10)]; - bayestopt_.jscale = [ bayestopt_.jscale; estim_params_.corrn(:,11)]; - bayestopt_.name = cellstr(strvcat(char(bayestopt_.name), char(strcat(cellstr(M_.endo_names(estim_params_.corrn(:,1),:)),... - ',' , cellstr(M_.endo_names(estim_params_.corrn(:,2),:)))))); - end - if np - xparam1 = [xparam1; estim_params_.param_vals(:,2)]; - ub = [ub; estim_params_.param_vals(:,4)]; - lb = [lb; estim_params_.param_vals(:,3)]; - bayestopt_.pshape = [ bayestopt_.pshape; estim_params_.param_vals(:,5)]; - bayestopt_.p1 = [ bayestopt_.p1; estim_params_.param_vals(:,6)]; - bayestopt_.p2 = [ bayestopt_.p2; estim_params_.param_vals(:,7)]; - bayestopt_.p3 = [ bayestopt_.p3; estim_params_.param_vals(:,8)]; - bayestopt_.p4 = [ bayestopt_.p4; estim_params_.param_vals(:,9)]; - bayestopt_.jscale = [ bayestopt_.jscale; estim_params_.param_vals(:,10)]; - bayestopt_.name = cellstr(strvcat(char(bayestopt_.name),M_.param_names(estim_params_.param_vals(:,1),:))); - end - bayestopt_.ub = ub; - bayestopt_.lb = lb; - - bayestopt_.p6 = NaN(size(bayestopt_.p1)) ; - bayestopt_.p7 = bayestopt_.p6 ; - - % generalized location parameters by default for beta distribution - k = find(bayestopt_.pshape == 1); - k1 = find(isnan(bayestopt_.p3(k))); - bayestopt_.p3(k(k1)) = zeros(length(k1),1); - k1 = find(isnan(bayestopt_.p4(k))); - bayestopt_.p4(k(k1)) = ones(length(k1),1); - for i=1:length(k) - mu = (bayestopt_.p1(k(i))-bayestopt_.p3(k(i)))/(bayestopt_.p4(k(i))-bayestopt_.p3(k(i))); - stdd = bayestopt_.p2(k(i))/(bayestopt_.p4(k(i))-bayestopt_.p3(k(i))); - bayestopt_.p6(k(i)) = (1-mu)*mu^2/stdd^2 - mu ; - bayestopt_.p7(k(i)) = bayestopt_.p6(k(i))*(1/mu-1) ; - m = compute_prior_mode([ bayestopt_.p6(k(i)) , bayestopt_.p7(k(i)) , bayestopt_.p3(k(i)) , bayestopt_.p4(k(i)) ],1); - if length(m)==1 - bayestopt_.p5(k(i)) = m; - else - disp(['Prior distribution for parameter ' int2str(k(i)) ' has two modes!']) - bayestopt_.p5(k(i)) = bayestopt_.p1(k(i)) ; - end +nvx = size(estim_params_.var_exo,1); +nvn = size(estim_params_.var_endo,1); +ncx = size(estim_params_.corrx,1); +ncn = size(estim_params_.corrn,1); +np = size(estim_params_.param_vals,1); + +estim_params_.nvx = nvx; +estim_params_.nvn = nvn; +estim_params_.ncx = ncx; +estim_params_.ncn = ncn; +estim_params_.np = np; + +xparam1 = []; +ub = []; +lb = []; +bayestopt_.pshape = []; +bayestopt_.p1 = []; % prior mean +bayestopt_.p2 = []; % prior standard deviation +bayestopt_.p3 = []; % lower bound +bayestopt_.p4 = []; % upper bound +bayestopt_.p5 = []; % prior mode +bayestopt_.p6 = []; % first hyper-parameter (\alpha for the BETA and GAMMA distributions, s for the INVERSE GAMMAs, expectation for the GAUSSIAN distribution, lower bound for the UNIFORM distribution). +bayestopt_.p7 = []; % second hyper-parameter (\beta for the BETA and GAMMA distributions, \nu for the INVERSE GAMMAs, standard deviation for the GAUSSIAN distribution, upper bound for the UNIFORM distribution). + +bayestopt_.jscale = []; +bayestopt_.name = []; +if nvx + xparam1 = estim_params_.var_exo(:,2); + ub = estim_params_.var_exo(:,4); + lb = estim_params_.var_exo(:,3); + bayestopt_.pshape = estim_params_.var_exo(:,5); + bayestopt_.p1 = estim_params_.var_exo(:,6); + bayestopt_.p2 = estim_params_.var_exo(:,7); + bayestopt_.p3 = estim_params_.var_exo(:,8); + bayestopt_.p4 = estim_params_.var_exo(:,9); + bayestopt_.jscale = estim_params_.var_exo(:,10); + bayestopt_.name = cellstr(M_.exo_names(estim_params_.var_exo(:,1),:)); +end +if nvn + if M_.H == 0 + nvarobs = size(options_.varobs,1); + M_.H = zeros(nvarobs,nvarobs); end - - % generalized location parameter by default for gamma distribution - k = find(bayestopt_.pshape == 2); - k1 = find(isnan(bayestopt_.p3(k))); - k2 = find(isnan(bayestopt_.p4(k))); - bayestopt_.p3(k(k1)) = zeros(length(k1),1); - bayestopt_.p4(k(k2)) = Inf(length(k2),1); - for i=1:length(k) - mu = bayestopt_.p1(k(i))-bayestopt_.p3(k(i)); - bayestopt_.p7(k(i)) = bayestopt_.p2(k(i))^2/mu ; - bayestopt_.p6(k(i)) = mu/bayestopt_.p7(k(i)) ; - bayestopt_.p5(k(i)) = compute_prior_mode([ bayestopt_.p6(k(i)) , bayestopt_.p7(k(i)) , bayestopt_.p3(k(i)) ], 2) ; + for i=1:nvn + estim_params_.var_endo(i,1) = strmatch(deblank(M_.endo_names(estim_params_.var_endo(i,1),:)),deblank(options_.varobs),'exact'); end - - % truncation parameters by default for normal distribution - k = find(bayestopt_.pshape == 3); - k1 = find(isnan(bayestopt_.p3(k))); - bayestopt_.p3(k(k1)) = -Inf*ones(length(k1),1); - k1 = find(isnan(bayestopt_.p4(k))); - bayestopt_.p4(k(k1)) = Inf*ones(length(k1),1); - for i=1:length(k) - bayestopt_.p6(k(i)) = bayestopt_.p1(k(i)) ; - bayestopt_.p7(k(i)) = bayestopt_.p2(k(i)) ; - bayestopt_.p5(k(i)) = bayestopt_.p1(k(i)) ; + xparam1 = [xparam1; estim_params_.var_endo(:,2)]; + ub = [ub; estim_params_.var_endo(:,4)]; + lb = [lb; estim_params_.var_endo(:,3)]; + bayestopt_.pshape = [ bayestopt_.pshape; estim_params_.var_endo(:,5)]; + bayestopt_.p1 = [ bayestopt_.p1; estim_params_.var_endo(:,6)]; + bayestopt_.p2 = [ bayestopt_.p2; estim_params_.var_endo(:,7)]; + bayestopt_.p3 = [ bayestopt_.p3; estim_params_.var_endo(:,8)]; + bayestopt_.p4 = [ bayestopt_.p4; estim_params_.var_endo(:,9)]; + bayestopt_.jscale = [ bayestopt_.jscale; estim_params_.var_endo(:,10)]; + bayestopt_.name = cellstr(strvcat(char(bayestopt_.name), M_.endo_names(estim_params_.var_endo(:,1),:))); +end +if ncx + xparam1 = [xparam1; estim_params_.corrx(:,3)]; + ub = [ub; max(min(estim_params_.corrx(:,5),1),-1)]; + lb = [lb; max(min(estim_params_.corrx(:,4),1),-1)]; + bayestopt_.pshape = [ bayestopt_.pshape; estim_params_.corrx(:,6)]; + bayestopt_.p1 = [ bayestopt_.p1; estim_params_.corrx(:,7)]; + bayestopt_.p2 = [ bayestopt_.p2; estim_params_.corrx(:,8)]; + bayestopt_.p3 = [ bayestopt_.p3; estim_params_.corrx(:,9)]; + bayestopt_.p4 = [ bayestopt_.p4; estim_params_.corrx(:,10)]; + bayestopt_.jscale = [ bayestopt_.jscale; estim_params_.corrx(:,11)]; + bayestopt_.name = cellstr(strvcat(char(bayestopt_.name), char(strcat(cellstr(M_.exo_names(estim_params_.corrx(:,1),:)), ... + ',' , cellstr(M_.exo_names(estim_params_.corrx(:,2),:)))))); +end +if ncn + if M_.H == 0 + nvarobs = size(options_.varobs,1); + M_.H = zeros(nvarobs,nvarobs); end + xparam1 = [xparam1; estim_params_.corrn(:,3)]; + ub = [ub; max(min(estim_params_.corrn(:,5),1),-1)]; + lb = [lb; max(min(estim_params_.corrn(:,4),1),-1)]; + bayestopt_.pshape = [ bayestopt_.pshape; estim_params_.corrn(:,6)]; + bayestopt_.p1 = [ bayestopt_.p1; estim_params_.corrn(:,7)]; + bayestopt_.p2 = [ bayestopt_.p2; estim_params_.corrn(:,8)]; + bayestopt_.p3 = [ bayestopt_.p3; estim_params_.corrn(:,9)]; + bayestopt_.p4 = [ bayestopt_.p4; estim_params_.corrn(:,10)]; + bayestopt_.jscale = [ bayestopt_.jscale; estim_params_.corrn(:,11)]; + bayestopt_.name = cellstr(strvcat(char(bayestopt_.name), char(strcat(cellstr(M_.endo_names(estim_params_.corrn(:,1),:)),... + ',' , cellstr(M_.endo_names(estim_params_.corrn(:,2),:)))))); +end +if np + xparam1 = [xparam1; estim_params_.param_vals(:,2)]; + ub = [ub; estim_params_.param_vals(:,4)]; + lb = [lb; estim_params_.param_vals(:,3)]; + bayestopt_.pshape = [ bayestopt_.pshape; estim_params_.param_vals(:,5)]; + bayestopt_.p1 = [ bayestopt_.p1; estim_params_.param_vals(:,6)]; + bayestopt_.p2 = [ bayestopt_.p2; estim_params_.param_vals(:,7)]; + bayestopt_.p3 = [ bayestopt_.p3; estim_params_.param_vals(:,8)]; + bayestopt_.p4 = [ bayestopt_.p4; estim_params_.param_vals(:,9)]; + bayestopt_.jscale = [ bayestopt_.jscale; estim_params_.param_vals(:,10)]; + bayestopt_.name = cellstr(strvcat(char(bayestopt_.name),M_.param_names(estim_params_.param_vals(:,1),:))); +end - % inverse gamma distribution (type 1) - k = find(bayestopt_.pshape == 4); - k1 = find(isnan(bayestopt_.p3(k))); - k2 = find(isnan(bayestopt_.p4(k))); - bayestopt_.p3(k(k1)) = zeros(length(k1),1); - bayestopt_.p4(k(k2)) = Inf(length(k2),1); - for i=1:length(k) - [bayestopt_.p6(k(i)),bayestopt_.p7(k(i))] = ... - inverse_gamma_specification(bayestopt_.p1(k(i))-bayestopt_.p3(k(i)),bayestopt_.p2(k(i)),1) ; - bayestopt_.p5(k(i)) = compute_prior_mode([ bayestopt_.p6(k(i)) , bayestopt_.p7(k(i)) , bayestopt_.p3(k(i)) ], 4) ; - end - - % uniform distribution - k = find(bayestopt_.pshape == 5); - for i=1:length(k) - [bayestopt_.p1(k(i)),bayestopt_.p2(k(i)),bayestopt_.p6(k(i)),bayestopt_.p7(k(i))] = ... - uniform_specification(bayestopt_.p1(k(i)),bayestopt_.p2(k(i)),bayestopt_.p3(k(i)),bayestopt_.p4(k(i))); - bayestopt_.p3(k(i)) = bayestopt_.p6(k(i)) ; - bayestopt_.p4(k(i)) = bayestopt_.p7(k(i)) ; - bayestopt_.p5(k(i)) = NaN ; - end - - % inverse gamma distribution (type 2) - k = find(bayestopt_.pshape == 6); - k1 = find(isnan(bayestopt_.p3(k))); - k2 = find(isnan(bayestopt_.p4(k))); - bayestopt_.p3(k(k1)) = zeros(length(k1),1); - bayestopt_.p4(k(k2)) = Inf(length(k2),1); - for i=1:length(k) - [bayestopt_.p6(k(i)),bayestopt_.p7(k(i))] = ... - inverse_gamma_specification(bayestopt_.p1(k(i))-bayestopt_.p3(k(i)),bayestopt_.p2(k(i)),2); - bayestopt_.p5(k(i)) = compute_prior_mode([ bayestopt_.p6(k(i)) , bayestopt_.p7(k(i)) , bayestopt_.p3(k(i)) ], 6) ; +bayestopt_.ub = ub; +bayestopt_.lb = lb; + +bayestopt_.p6 = NaN(size(bayestopt_.p1)) ; +bayestopt_.p7 = bayestopt_.p6 ; + +% generalized location parameters by default for beta distribution +k = find(bayestopt_.pshape == 1); +k1 = find(isnan(bayestopt_.p3(k))); +bayestopt_.p3(k(k1)) = zeros(length(k1),1); +k1 = find(isnan(bayestopt_.p4(k))); +bayestopt_.p4(k(k1)) = ones(length(k1),1); +for i=1:length(k) + mu = (bayestopt_.p1(k(i))-bayestopt_.p3(k(i)))/(bayestopt_.p4(k(i))-bayestopt_.p3(k(i))); + stdd = bayestopt_.p2(k(i))/(bayestopt_.p4(k(i))-bayestopt_.p3(k(i))); + bayestopt_.p6(k(i)) = (1-mu)*mu^2/stdd^2 - mu ; + bayestopt_.p7(k(i)) = bayestopt_.p6(k(i))*(1/mu-1) ; + m = compute_prior_mode([ bayestopt_.p6(k(i)) , bayestopt_.p7(k(i)) , bayestopt_.p3(k(i)) , bayestopt_.p4(k(i)) ],1); + if length(m)==1 + bayestopt_.p5(k(i)) = m; + else + disp(['Prior distribution for parameter ' int2str(k(i)) ' has two modes!']) + bayestopt_.p5(k(i)) = bayestopt_.p1(k(i)) ; end - - k = find(isnan(xparam1)); - xparam1(k) = bayestopt_.p1(k); +end + +% generalized location parameter by default for gamma distribution +k = find(bayestopt_.pshape == 2); +k1 = find(isnan(bayestopt_.p3(k))); +k2 = find(isnan(bayestopt_.p4(k))); +bayestopt_.p3(k(k1)) = zeros(length(k1),1); +bayestopt_.p4(k(k2)) = Inf(length(k2),1); +for i=1:length(k) + mu = bayestopt_.p1(k(i))-bayestopt_.p3(k(i)); + bayestopt_.p7(k(i)) = bayestopt_.p2(k(i))^2/mu ; + bayestopt_.p6(k(i)) = mu/bayestopt_.p7(k(i)) ; + bayestopt_.p5(k(i)) = compute_prior_mode([ bayestopt_.p6(k(i)) , bayestopt_.p7(k(i)) , bayestopt_.p3(k(i)) ], 2) ; +end + +% truncation parameters by default for normal distribution +k = find(bayestopt_.pshape == 3); +k1 = find(isnan(bayestopt_.p3(k))); +bayestopt_.p3(k(k1)) = -Inf*ones(length(k1),1); +k1 = find(isnan(bayestopt_.p4(k))); +bayestopt_.p4(k(k1)) = Inf*ones(length(k1),1); +for i=1:length(k) + bayestopt_.p6(k(i)) = bayestopt_.p1(k(i)) ; + bayestopt_.p7(k(i)) = bayestopt_.p2(k(i)) ; + bayestopt_.p5(k(i)) = bayestopt_.p1(k(i)) ; +end - % I create subfolder M_.dname/prior if needed. - CheckPath('prior'); +% inverse gamma distribution (type 1) +k = find(bayestopt_.pshape == 4); +k1 = find(isnan(bayestopt_.p3(k))); +k2 = find(isnan(bayestopt_.p4(k))); +bayestopt_.p3(k(k1)) = zeros(length(k1),1); +bayestopt_.p4(k(k2)) = Inf(length(k2),1); +for i=1:length(k) + [bayestopt_.p6(k(i)),bayestopt_.p7(k(i))] = ... + inverse_gamma_specification(bayestopt_.p1(k(i))-bayestopt_.p3(k(i)),bayestopt_.p2(k(i)),1) ; + bayestopt_.p5(k(i)) = compute_prior_mode([ bayestopt_.p6(k(i)) , bayestopt_.p7(k(i)) , bayestopt_.p3(k(i)) ], 4) ; +end - % I save the prior definition if the prior has changed. - if exist([ M_.dname '/prior/definition.mat']) - old = load([M_.dname '/prior/definition.mat'],'bayestopt_'); - prior_has_changed = 0; - if length(bayestopt_.p1)==length(old.bayestopt_.p1) - if any(bayestopt_.p1-old.bayestopt_.p1) - prior_has_changed = 1; - end - if any(bayestopt_.p2-old.bayestopt_.p2) - prior_has_changed = 1; - end - if any(bayestopt_.p3-old.bayestopt_.p3) - prior_has_changed = 1; - end - if any(bayestopt_.p4-old.bayestopt_.p4) - prior_has_changed = 1; - end - if any(bayestopt_.p5-old.bayestopt_.p5) - prior_has_changed = 1; - end - if any(bayestopt_.p6-old.bayestopt_.p6) - prior_has_changed = 1; - end - if any(bayestopt_.p7-old.bayestopt_.p7) - prior_has_changed = 1; - end - else +% uniform distribution +k = find(bayestopt_.pshape == 5); +for i=1:length(k) + [bayestopt_.p1(k(i)),bayestopt_.p2(k(i)),bayestopt_.p6(k(i)),bayestopt_.p7(k(i))] = ... + uniform_specification(bayestopt_.p1(k(i)),bayestopt_.p2(k(i)),bayestopt_.p3(k(i)),bayestopt_.p4(k(i))); + bayestopt_.p3(k(i)) = bayestopt_.p6(k(i)) ; + bayestopt_.p4(k(i)) = bayestopt_.p7(k(i)) ; + bayestopt_.p5(k(i)) = NaN ; +end + +% inverse gamma distribution (type 2) +k = find(bayestopt_.pshape == 6); +k1 = find(isnan(bayestopt_.p3(k))); +k2 = find(isnan(bayestopt_.p4(k))); +bayestopt_.p3(k(k1)) = zeros(length(k1),1); +bayestopt_.p4(k(k2)) = Inf(length(k2),1); +for i=1:length(k) + [bayestopt_.p6(k(i)),bayestopt_.p7(k(i))] = ... + inverse_gamma_specification(bayestopt_.p1(k(i))-bayestopt_.p3(k(i)),bayestopt_.p2(k(i)),2); + bayestopt_.p5(k(i)) = compute_prior_mode([ bayestopt_.p6(k(i)) , bayestopt_.p7(k(i)) , bayestopt_.p3(k(i)) ], 6) ; +end + +k = find(isnan(xparam1)); +xparam1(k) = bayestopt_.p1(k); + +% I create subfolder M_.dname/prior if needed. +CheckPath('prior'); + +% I save the prior definition if the prior has changed. +if exist([ M_.dname '/prior/definition.mat']) + old = load([M_.dname '/prior/definition.mat'],'bayestopt_'); + prior_has_changed = 0; + if length(bayestopt_.p1)==length(old.bayestopt_.p1) + if any(bayestopt_.p1-old.bayestopt_.p1) prior_has_changed = 1; end - if prior_has_changed - delete([M_.dname '/prior/definition.mat']); - save([M_.dname '/prior/definition.mat'],'bayestopt_'); + if any(bayestopt_.p2-old.bayestopt_.p2) + prior_has_changed = 1; + end + if any(bayestopt_.p3-old.bayestopt_.p3) + prior_has_changed = 1; + end + if any(bayestopt_.p4-old.bayestopt_.p4) + prior_has_changed = 1; + end + if any(bayestopt_.p5-old.bayestopt_.p5) + prior_has_changed = 1; + end + if any(bayestopt_.p6-old.bayestopt_.p6) + prior_has_changed = 1; + end + if any(bayestopt_.p7-old.bayestopt_.p7) + prior_has_changed = 1; end else + prior_has_changed = 1; + end + if prior_has_changed + delete([M_.dname '/prior/definition.mat']); save([M_.dname '/prior/definition.mat'],'bayestopt_'); - end \ No newline at end of file + end +else + save([M_.dname '/prior/definition.mat'],'bayestopt_'); +end \ No newline at end of file diff --git a/matlab/set_shocks.m b/matlab/set_shocks.m index e32bddf5c3..f195e8a1a0 100644 --- a/matlab/set_shocks.m +++ b/matlab/set_shocks.m @@ -35,25 +35,25 @@ function set_shocks(flag,k,ivar,values) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global oo_ M_ - - k = k + M_.maximum_lag; - n1 = size(oo_.exo_simul,1); - n2 = size(oo_.exo_det_simul,1); - if k(end) > n1 & flag <= 1 +global oo_ M_ + +k = k + M_.maximum_lag; +n1 = size(oo_.exo_simul,1); +n2 = size(oo_.exo_det_simul,1); +if k(end) > n1 & flag <= 1 oo_.exo_simul = [oo_.exo_simul; repmat(oo_.exo_steady_state',k(end)-n1,1)]; - elseif k(end) > n2 & flag > 1 +elseif k(end) > n2 & flag > 1 oo_.exo_det_simul = [oo_.exo_det_simul; repmat(oo_.exo_det_steady_state',k(end)-n2,1)]; - end - - switch flag - case 0 +end + +switch flag + case 0 oo_.exo_simul(k,ivar) = repmat(values,length(k),1); - case 1 + case 1 oo_.exo_simul(k,ivar) = oo_.exo_simul(k,ivar).*values; - case 2 + case 2 oo_.exo_det_simul(k,ivar) = repmat(values,length(k),1); - case 3 + case 3 oo_.exo_det_simul(k,ivar) = oo_.exo_det_simul(k,ivar).*values; - end +end diff --git a/matlab/set_state_space.m b/matlab/set_state_space.m index 0a4e2547fd..5f7734d1ae 100644 --- a/matlab/set_state_space.m +++ b/matlab/set_state_space.m @@ -36,20 +36,20 @@ xlen = M_.maximum_endo_lead + M_.maximum_endo_lag + 1; klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1; if ~ M_.lead_lag_incidence(M_.maximum_endo_lag+1,:) > 0 - error ('Error in model specification: some variables don"t appear as current') ; + error ('Error in model specification: some variables don"t appear as current') ; end fwrd_var = find(any(M_.lead_lag_incidence(M_.maximum_endo_lag+2:end,:),1))'; if M_.maximum_endo_lag > 0 - pred_var = find(any(M_.lead_lag_incidence(1:M_.maximum_endo_lag,:),1))'; - both_var = intersect(pred_var,fwrd_var); - pred_var = setdiff(pred_var,both_var); - fwrd_var = setdiff(fwrd_var,both_var); - stat_var = setdiff([1:M_.endo_nbr]',union(union(pred_var,both_var),fwrd_var)); % static variables + pred_var = find(any(M_.lead_lag_incidence(1:M_.maximum_endo_lag,:),1))'; + both_var = intersect(pred_var,fwrd_var); + pred_var = setdiff(pred_var,both_var); + fwrd_var = setdiff(fwrd_var,both_var); + stat_var = setdiff([1:M_.endo_nbr]',union(union(pred_var,both_var),fwrd_var)); % static variables else - pred_var = []; - both_var = []; - stat_var = setdiff([1:M_.endo_nbr]',fwrd_var); + pred_var = []; + both_var = []; + stat_var = setdiff([1:M_.endo_nbr]',fwrd_var); end nboth = length(both_var); npred = length(pred_var); @@ -60,13 +60,13 @@ inv_order_var(order_var) = (1:M_.endo_nbr); % building kmask for z state vector in t+1 if M_.maximum_endo_lag > 0 - kmask = []; - if M_.maximum_endo_lead > 0 - kmask = [cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+2:end,order_var)),1)] ; - end - kmask = [kmask; flipud(cumsum(M_.lead_lag_incidence(1:M_.maximum_endo_lag,order_var),1))] ; + kmask = []; + if M_.maximum_endo_lead > 0 + kmask = [cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+2:end,order_var)),1)] ; + end + kmask = [kmask; flipud(cumsum(M_.lead_lag_incidence(1:M_.maximum_endo_lag,order_var),1))] ; else - kmask = cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+2:klen,order_var)),1) ; + kmask = cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+2:klen,order_var)),1) ; end kmask = kmask'; @@ -82,8 +82,8 @@ k1 = find([kmask(1:end-M_.endo_nbr) & kmask(M_.endo_nbr+1:end)] ); kad = []; kae = []; if ~isempty(k1) - kad = kmask(k1+M_.endo_nbr); - kae = kmask(k1); + kad = kmask(k1+M_.endo_nbr); + kae = kmask(k1); end % composition of state vector @@ -119,13 +119,13 @@ aux = zeros(0,1); k0 = kstate(find(kstate(:,2) <= M_.maximum_endo_lag+1),:);; i0 = find(k0(:,2) == M_.maximum_endo_lag+1); for i=M_.maximum_endo_lag:-1:2 - i1 = find(k0(:,2) == i); - n1 = size(i1,1); - j = zeros(n1,1); - for j1 = 1:n1 - j(j1) = find(k0(i0,1)==k0(i1(j1),1)); - end - aux = [aux; i0(j)]; - i0 = i1; + i1 = find(k0(:,2) == i); + n1 = size(i1,1); + j = zeros(n1,1); + for j1 = 1:n1 + j(j1) = find(k0(i0,1)==k0(i1(j1),1)); + end + aux = [aux; i0(j)]; + i0 = i1; end dr.transition_auxiliary_variables = [(1:size(aux,1))' aux]; diff --git a/matlab/shock_decomposition.m b/matlab/shock_decomposition.m index cb979810fa..9cf773ffb0 100644 --- a/matlab/shock_decomposition.m +++ b/matlab/shock_decomposition.m @@ -1,94 +1,94 @@ -function oo_ = shock_decomposition(M_,oo_,options_,varlist) -% function z = shock_decomposition(R,epsilon,varlist) -% Computes shocks contribution to a simulated trajectory -% -% INPUTS -% R: mm*rr matrix of shock impact -% epsilon: rr*nobs matrix of shocks -% varlist: list of variables -% -% OUTPUTS -% z: nvar*rr*nobs shock decomposition -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. - -% number of variables - endo_nbr = M_.endo_nbr; - - % number of shocks - nshocks = M_.exo_nbr; - - % indices of endogenous variables - [i_var,nvar] = varlist_indices(varlist); - - % reduced form - dr = oo_.dr; - - % data reordering - order_var = dr.order_var; - inv_order_var = dr.inv_order_var; - - - % coefficients - A = dr.ghx; - B = dr.ghu; - - % initialization - for i=1:nshocks - epsilon(i,:) = eval(['oo_.SmoothedShocks.' M_.exo_names(i,:)]); - end - gend = size(epsilon,2); - - z = zeros(endo_nbr,nshocks+2,gend); - for i=1:endo_nbr - z(i,end,:) = eval(['oo_.SmoothedVariables.' M_.endo_names(i,:)]); - end - - maximum_lag = M_.maximum_lag; - lead_lag_incidence = M_.lead_lag_incidence; - - k2 = dr.kstate(find(dr.kstate(:,2) <= maximum_lag+1),[1 2]); - i_state = order_var(k2(:,1))+(min(i,maximum_lag)+1-k2(:,2))*M_.endo_nbr; - for i=1:gend - if i > 1 & i <= maximum_lag+1 - lags = min(i-1,maximum_lag):-1:1; - end - - if i > 1 - tempx = permute(z(:,1:nshocks,lags),[1 3 2]); - m = min(i-1,maximum_lag); - tempx = [reshape(tempx,endo_nbr*m,nshocks); zeros(endo_nbr*(maximum_lag-i+1),nshocks)]; - z(:,1:nshocks,i) = A(inv_order_var,:)*tempx(i_state,:); - lags = lags+1; - end - - z(:,1:nshocks,i) = z(:,1:nshocks,i) + B(inv_order_var,:).*repmat(epsilon(:,i)',endo_nbr,1); - z(:,nshocks+1,i) = z(:,nshocks+2,i) - sum(z(:,1:nshocks,i),2); - end - - - oo_.shock_decomposition = z; - - options_.initial_date.freq = 1; - options_.initial_date.period = 1; - options_.initial_date.sub_period = 0; - - graph_decomp(z,M_.exo_names,varlist,options_.initial_date) +function oo_ = shock_decomposition(M_,oo_,options_,varlist) +% function z = shock_decomposition(R,epsilon,varlist) +% Computes shocks contribution to a simulated trajectory +% +% INPUTS +% R: mm*rr matrix of shock impact +% epsilon: rr*nobs matrix of shocks +% varlist: list of variables +% +% OUTPUTS +% z: nvar*rr*nobs shock decomposition +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. + +% number of variables +endo_nbr = M_.endo_nbr; + +% number of shocks +nshocks = M_.exo_nbr; + +% indices of endogenous variables +[i_var,nvar] = varlist_indices(varlist); + +% reduced form +dr = oo_.dr; + +% data reordering +order_var = dr.order_var; +inv_order_var = dr.inv_order_var; + + +% coefficients +A = dr.ghx; +B = dr.ghu; + +% initialization +for i=1:nshocks + epsilon(i,:) = eval(['oo_.SmoothedShocks.' M_.exo_names(i,:)]); +end +gend = size(epsilon,2); + +z = zeros(endo_nbr,nshocks+2,gend); +for i=1:endo_nbr + z(i,end,:) = eval(['oo_.SmoothedVariables.' M_.endo_names(i,:)]); +end + +maximum_lag = M_.maximum_lag; +lead_lag_incidence = M_.lead_lag_incidence; + +k2 = dr.kstate(find(dr.kstate(:,2) <= maximum_lag+1),[1 2]); +i_state = order_var(k2(:,1))+(min(i,maximum_lag)+1-k2(:,2))*M_.endo_nbr; +for i=1:gend + if i > 1 & i <= maximum_lag+1 + lags = min(i-1,maximum_lag):-1:1; + end + + if i > 1 + tempx = permute(z(:,1:nshocks,lags),[1 3 2]); + m = min(i-1,maximum_lag); + tempx = [reshape(tempx,endo_nbr*m,nshocks); zeros(endo_nbr*(maximum_lag-i+1),nshocks)]; + z(:,1:nshocks,i) = A(inv_order_var,:)*tempx(i_state,:); + lags = lags+1; + end + + z(:,1:nshocks,i) = z(:,1:nshocks,i) + B(inv_order_var,:).*repmat(epsilon(:,i)',endo_nbr,1); + z(:,nshocks+1,i) = z(:,nshocks+2,i) - sum(z(:,1:nshocks,i),2); +end + + +oo_.shock_decomposition = z; + +options_.initial_date.freq = 1; +options_.initial_date.period = 1; +options_.initial_date.sub_period = 0; + +graph_decomp(z,M_.exo_names,varlist,options_.initial_date) diff --git a/matlab/simk.m b/matlab/simk.m index 1767aaa1a2..d651daa13c 100644 --- a/matlab/simk.m +++ b/matlab/simk.m @@ -43,7 +43,7 @@ ny = size(M_.lead_lag_incidence,2) ; icc1 = M_.lead_lag_incidence(nk,:) > 0; for i = 1:M_.maximum_lead -1 - icc1 = [M_.lead_lag_incidence(nk-i,:) | icc1(1,:); icc1] ; + icc1 = [M_.lead_lag_incidence(nk-i,:) | icc1(1,:); icc1] ; end icc1 = find(icc1') ; @@ -57,54 +57,54 @@ ncs = size(iyr0,1) ; ky = zeros(ny,nk) ; % indices of variables at each lead or lag lky = zeros(nk,1) ; for i = 1:nk - j = find(M_.lead_lag_incidence(i,:))' ; - if isempty(j) - lky(i) = 0; - else - lky(i) = size(j,1) ; - ky(1:lky(i),i) = j ; - end + j = find(M_.lead_lag_incidence(i,:))' ; + if isempty(j) + lky(i) = 0; + else + lky(i) = size(j,1) ; + ky(1:lky(i),i) = j ; + end end jwc = find(iy(2:M_.maximum_endo_lead+1,:)') ; % indices of columns for - % triangularization - % as many rows as lags in model + % triangularization + % as many rows as lags in model if isempty(jwc) - jwc = 0 ; - ljwc = 0 ; - temp = icc1 ; + jwc = 0 ; + ljwc = 0 ; + temp = icc1 ; else - ljwc = size(jwc,1) ; % length of each row in jwc - temp = union(jwc,icc1) ; % prepares next iteration + ljwc = size(jwc,1) ; % length of each row in jwc + temp = union(jwc,icc1) ; % prepares next iteration end j1 = ky(1:lky(1),1) ; lj1 = lky(1) ; for i = 2:M_.maximum_endo_lag - [j1,lj1] = ffill(j1,lj1,selif(temp+(i-1)*ny,temp <= ny)) ; - if M_.maximum_endo_lead == 1 - if lky(i+M_.maximum_endo_lead) > 0 - [jwc,ljwc] = ffill(jwc,ljwc, ky(1:lky(i+M_.maximum_endo_lead),i+M_.maximum_endo_lead)+(M_.maximum_endo_lead-1)*ny) ; - if ljwc(i) == 0 - temp = icc1; - else - temp = union(jwc(1:ljwc(i),i),icc1) ; - end + [j1,lj1] = ffill(j1,lj1,selif(temp+(i-1)*ny,temp <= ny)) ; + if M_.maximum_endo_lead == 1 + if lky(i+M_.maximum_endo_lead) > 0 + [jwc,ljwc] = ffill(jwc,ljwc, ky(1:lky(i+M_.maximum_endo_lead),i+M_.maximum_endo_lead)+(M_.maximum_endo_lead-1)*ny) ; + if ljwc(i) == 0 + temp = icc1; + else + temp = union(jwc(1:ljwc(i),i),icc1) ; + end + else + [jwc,ljwc] = ffill(jwc,ljwc,[]) ; + temp = icc1 ; + end else - [jwc,ljwc] = ffill(jwc,ljwc,[]) ; - temp = icc1 ; + temp = temp(lj1(i)+1:size(temp,1),:) - ny ; + if lky(i+M_.maximum_endo_lead) > 0 + [jwc,ljwc] = ffill(jwc,ljwc,[temp;ky(1:lky(i+M_.maximum_endo_lead),i+M_.maximum_endo_lead)+(M_.maximum_endo_lead-1)*ny]); + else + [jwc,ljwc] = ffill(jwc,ljwc,temp) ; + end + temp = union(jwc(1:ljwc(i),i),icc1) ; end - else - temp = temp(lj1(i)+1:size(temp,1),:) - ny ; - if lky(i+M_.maximum_endo_lead) > 0 - [jwc,ljwc] = ffill(jwc,ljwc,[temp;ky(1:lky(i+M_.maximum_endo_lead),i+M_.maximum_endo_lead)+(M_.maximum_endo_lead-1)*ny]); - else - [jwc,ljwc] = ffill(jwc,ljwc,temp) ; - end - temp = union(jwc(1:ljwc(i),i),icc1) ; - end end [j1,lj1] = ffill(j1,lj1,selif(temp+M_.maximum_endo_lag*ny, temp <= ny)) ; @@ -112,12 +112,12 @@ ltemp = zeros(M_.maximum_endo_lag,1) ; jwc1 = zeros(ncc1,M_.maximum_endo_lag) ; for i = 1:M_.maximum_endo_lag - temp = union(jwc(1:ljwc(i),i),icc1) ; - ltemp(i) = size(temp,1) ; - if ljwc(i) > 0 - jwc(1:ljwc(i),i) = indnv(jwc(1:ljwc(i),i),temp) ; - end - jwc1(:,i) = indnv(icc1,temp) ; + temp = union(jwc(1:ljwc(i),i),icc1) ; + ltemp(i) = size(temp,1) ; + if ljwc(i) > 0 + jwc(1:ljwc(i),i) = indnv(jwc(1:ljwc(i),i),temp) ; + end + jwc1(:,i) = indnv(icc1,temp) ; end h1 = clock ; @@ -127,219 +127,219 @@ disp ('MODEL SIMULATION') ; fprintf ('\n') ; for iter = 1:options_.maxit_ - h2 = clock ; - oo_.endo_simul = oo_.endo_simul(:); - err_f = 0; - - fid = fopen([M_.fname '.swp'],'w+') ; - - it_ = 1+M_.maximum_lag ; - ic = [1:ny] ; - iyr = iyr0 ; - i = M_.maximum_endo_lag+1 ; - while (i>1) & (it_<=options_.periods+M_.maximum_endo_lag) - h3 = clock ; - if broyden_ & iter > 1 - %d1_ = -feval(fh,oo_.endo_simul(iyr)); - d1 = -feval([M_.fname '_dynamic'],oo_.endo_simul(iyr),z,oo_.exo_simul, M_.params, it_); - else - %jacob(func_name,oo_.endo_simul(iyr)) ; - [d1,jacobian] = feval([M_.fname '_dynamic'],oo_.endo_simul(iyr),oo_.exo_simul, M_.params, it_); - d1 = -d1 ; + h2 = clock ; + oo_.endo_simul = oo_.endo_simul(:); + err_f = 0; + + fid = fopen([M_.fname '.swp'],'w+') ; + + it_ = 1+M_.maximum_lag ; + ic = [1:ny] ; + iyr = iyr0 ; + i = M_.maximum_endo_lag+1 ; + while (i>1) & (it_<=options_.periods+M_.maximum_endo_lag) + h3 = clock ; + if broyden_ & iter > 1 + %d1_ = -feval(fh,oo_.endo_simul(iyr)); + d1 = -feval([M_.fname '_dynamic'],oo_.endo_simul(iyr),z,oo_.exo_simul, M_.params, it_); + else + %jacob(func_name,oo_.endo_simul(iyr)) ; + [d1,jacobian] = feval([M_.fname '_dynamic'],oo_.endo_simul(iyr),oo_.exo_simul, M_.params, it_); + d1 = -d1 ; + end + err_f = max(err_f,max(abs(d1))); + if lky(i) ~= 0 + j1i = ky(1:lky(i),i) ; + w0 = jacobian(:,isc(i-1)+1:isc(i)) ; + else + w0 = []; + end + ttemp = iy(i+1:i+M_.maximum_endo_lead,:)' ; + jwci = find(ttemp) ; + if ~ isempty(jwci) + w = jacobian(:,isc(i)+1:isc(i+M_.maximum_endo_lead)) ; + end + j = i ; + while j <= M_.maximum_endo_lag + if ~isempty(w0) + + ofs = ((it_-M_.maximum_lag-M_.maximum_endo_lag+j-2)*ny)*ncc*8 ; + junk = fseek(fid,ofs,-1) ; + c = fread(fid,[ncc,ny],'float64')'; + + if isempty(jwci) + w = -w0*c(j1i,1:ncc1) ; + jwci = icc1 ; + else + iz = union(jwci,icc1) ; + ix = indnv(jwci,iz) ; + iy__ = indnv(icc1,iz) ; + temp = zeros(size(w,1),size(iz,1)) ; + temp(:,ix) = w; + temp(:,iy__) = temp(:,iy__)-w0*c(j1i,1:ncc1) ; + w = temp ; + jwci = iz ; + clear temp iz ix iy__ ; + end + d1 = d1-w0*c(j1i,ncc) ; + clear c ; + end + j = j + 1 ; + if isempty(jwci) + j1i = []; + if lky(j+M_.maximum_endo_lead) ~= 0 + jwci = ky(1:lky(j+M_.maximum_endo_lead),j+M_.maximum_endo_lead) + (M_.maximum_endo_lead-1)*ny ; + w = jacobian(:,isc(j+M_.maximum_endo_lead-1)+1:isc(j+M_.maximum_endo_lead)) ; + else + jwci = [] ; + end + else + j1i = selif(jwci,jwci<(ny+1)) ; + w0 = w(:,1:size(j1i,1)) ; + if size(jwci,1) == size(j1i,1) + if lky(j+M_.maximum_endo_lead) ~= 0 + jwci = ky(1:lky(j+M_.maximum_endo_lead),j+M_.maximum_endo_lead)+(M_.maximum_endo_lead-1)*ny ; + w = jacobian(:,isc(j+M_.maximum_endo_lead-1)+1:isc(j+M_.maximum_endo_lead)) ; + else + jwci = [] ; + end + else + jwci = jwci(size(j1i,1)+1:size(jwci,1),:)-ny ; + w = w(:,size(j1i,1)+1:size(w,2)) ; + if lky(j+M_.maximum_endo_lead) ~= 0 + jwci = [ jwci; ky(1: lky(j+M_.maximum_endo_lead),j+M_.maximum_endo_lead)+(M_.maximum_endo_lead-1)*ny] ; + w = [w jacobian(:,isc(j+M_.maximum_endo_lead-1)+1:isc(j+M_.maximum_endo_lead))] ; + % else + % jwci = [] ; + end + end + end + end + jwci = [indnv(jwci,icc1);ncc] ; + w = [w d1] ; + c = zeros(ny,ncc) ; + c(:,jwci) = w0\w ; + clear w w0 ; + + junk = fseek(fid,0,1) ; + fwrite(fid,c','float64') ; + clear c ; + + it_ = it_ + 1; + ic = ic + ny ; + iyr = iyr + ny ; + i = i - 1 ; end - err_f = max(err_f,max(abs(d1))); - if lky(i) ~= 0 - j1i = ky(1:lky(i),i) ; - w0 = jacobian(:,isc(i-1)+1:isc(i)) ; - else - w0 = []; + icr0 = (it_-M_.maximum_lag-M_.maximum_endo_lag -1)*ny ; + while it_ <= options_.periods+M_.maximum_lag + if broyden_ + %d1_ = -feval(fh,oo_.endo_simul(iyr)); + d1 = -feval([M_.fname '_dynamic'],oo_.endo_simul(iyr),z,oo_.exo_simul, M_.params, it_); + else + %jacob(func_name,oo_.endo_simul(iyr)) ; + [d1,jacobian] = feval([M_.fname '_dynamic'],oo_.endo_simul(iyr),oo_.exo_simul, M_.params, it_); + d1 = -d1 ; + end + err_f = max(err_f,max(abs(d1))); + w0 = jacobian(:,1:isc(1)) ; + w = jacobian(:,isc(1)+1:isc(1+M_.maximum_endo_lead)) ; + j = 1 ; + while j <= M_.maximum_endo_lag + icr = j1(1:lj1(j),j)-(j-1)*ny ; + + ofs = ((icr0+(j-1)*ny+1)-1)*ncc*8 ; + junk = fseek(fid,ofs,-1) ; + c = fread(fid,[ncc,ny],'float64')' ; + + temp = zeros(ny,ltemp(j)) ; + if ljwc(j) > 0 + temp(:,jwc(1:ljwc(j),j)) = w ; + end + temp(:,jwc1(:,j))=temp(:,jwc1(:,j))-w0*c(icr,1:ncc1) ; + w = temp ; + clear temp ; + d1 = d1-w0*c(icr,ncc) ; + clear c ; + j = j + 1 ; + w0 = w(:,1:lj1(j)) ; + if M_.maximum_endo_lead == 1 + w = jacobian(:,isc(j+M_.maximum_endo_lead-1)+1:isc(j+M_.maximum_endo_lead)) ; + else + w = w(:,lj1(j)+1:size(w,2)) ; + + if lky(j+M_.maximum_endo_lead) > 0 + w = [w jacobian(:,isc(j+M_.maximum_endo_lead-1)+1:isc(j+M_.maximum_endo_lead))] ; + end + end + end + c = w0\[w d1] ; + d1 = [] ; + clear w w0 ; + junk = fseek(fid,0,1) ; + fwrite(fid,c','float64') ; + clear c ; + it_ = it_ + 1 ; + ic = ic + ny ; + iyr = iyr + ny ; + icr0 = icr0 + ny ; end - ttemp = iy(i+1:i+M_.maximum_endo_lead,:)' ; - jwci = find(ttemp) ; - if ~ isempty(jwci) - w = jacobian(:,isc(i)+1:isc(i+M_.maximum_endo_lead)) ; - end - j = i ; - while j <= M_.maximum_endo_lag - if ~isempty(w0) - - ofs = ((it_-M_.maximum_lag-M_.maximum_endo_lag+j-2)*ny)*ncc*8 ; - junk = fseek(fid,ofs,-1) ; - c = fread(fid,[ncc,ny],'float64')'; - - if isempty(jwci) - w = -w0*c(j1i,1:ncc1) ; - jwci = icc1 ; - else - iz = union(jwci,icc1) ; - ix = indnv(jwci,iz) ; - iy__ = indnv(icc1,iz) ; - temp = zeros(size(w,1),size(iz,1)) ; - temp(:,ix) = w; - temp(:,iy__) = temp(:,iy__)-w0*c(j1i,1:ncc1) ; - w = temp ; - jwci = iz ; - clear temp iz ix iy__ ; - end - d1 = d1-w0*c(j1i,ncc) ; - clear c ; - end - j = j + 1 ; - if isempty(jwci) - j1i = []; - if lky(j+M_.maximum_endo_lead) ~= 0 - jwci = ky(1:lky(j+M_.maximum_endo_lead),j+M_.maximum_endo_lead) + (M_.maximum_endo_lead-1)*ny ; - w = jacobian(:,isc(j+M_.maximum_endo_lead-1)+1:isc(j+M_.maximum_endo_lead)) ; - else - jwci = [] ; - end - else - j1i = selif(jwci,jwci<(ny+1)) ; - w0 = w(:,1:size(j1i,1)) ; - if size(jwci,1) == size(j1i,1) - if lky(j+M_.maximum_endo_lead) ~= 0 - jwci = ky(1:lky(j+M_.maximum_endo_lead),j+M_.maximum_endo_lead)+(M_.maximum_endo_lead-1)*ny ; - w = jacobian(:,isc(j+M_.maximum_endo_lead-1)+1:isc(j+M_.maximum_endo_lead)) ; - else - jwci = [] ; - end - else - jwci = jwci(size(j1i,1)+1:size(jwci,1),:)-ny ; - w = w(:,size(j1i,1)+1:size(w,2)) ; - if lky(j+M_.maximum_endo_lead) ~= 0 - jwci = [ jwci; ky(1: lky(j+M_.maximum_endo_lead),j+M_.maximum_endo_lead)+(M_.maximum_endo_lead-1)*ny] ; - w = [w jacobian(:,isc(j+M_.maximum_endo_lead-1)+1:isc(j+M_.maximum_endo_lead))] ; -% else -% jwci = [] ; - end - end - end + if options_.terminal_condition == 1 + + ofs = (((it_-M_.maximum_lag-2)*ny+1)-1)*ncc*8 ; + junk = fseek(fid,ofs,-1) ; + c = fread(fid,[ncc,ny],'float64')'; + + for i = 1:M_.maximum_endo_lead + w = tril(triu(ones(ny,ny+ncc1))) ; + w(:,jwc1(:,M_.maximum_endo_lag)) = w(:,jwc1(:,M_.maximum_endo_lag))+c(:,1:ncc1) ; + c = [w(:,ny+1:size(w,2))' c(:,ncc)]/w(:,1:ny) ; + + junk = fseek(fid,0,1) ; + fwrite(fid,c','float64') ; + + it_ = it_+1 ; + ic = ic + ny ; + + end end - jwci = [indnv(jwci,icc1);ncc] ; - w = [w d1] ; - c = zeros(ny,ncc) ; - c(:,jwci) = w0\w ; - clear w w0 ; - - junk = fseek(fid,0,1) ; - fwrite(fid,c','float64') ; - clear c ; - - it_ = it_ + 1; - ic = ic + ny ; - iyr = iyr + ny ; - i = i - 1 ; - end - icr0 = (it_-M_.maximum_lag-M_.maximum_endo_lag -1)*ny ; - while it_ <= options_.periods+M_.maximum_lag - if broyden_ - %d1_ = -feval(fh,oo_.endo_simul(iyr)); - d1 = -feval([M_.fname '_dynamic'],oo_.endo_simul(iyr),z,oo_.exo_simul, M_.params, it_); + oo_.endo_simul = reshape(oo_.endo_simul,ny,options_.periods+M_.maximum_lag+M_.maximum_endo_lead) ; + if options_.terminal_condition == 1 + hbacsup = clock ; + c = bksupk(ny,fid,ncc,icc1) ; + hbacsup = etime(clock,hbacsup) ; + c = reshape(c,ny,options_.periods+M_.maximum_endo_lead)' ; + y(:,1+M_.maximum_endo_lag:(options_.periods+M_.maximum_endo_lead+M_.maximum_endo_lag)) = y(:,1+M_.maximum_endo_lag:(options_.periods+M_.maximum_endo_lead+M_.maximum_endo_lag))+options_.slowc*c' ; else - %jacob(func_name,oo_.endo_simul(iyr)) ; - [d1,jacobian] = feval([M_.fname '_dynamic'],oo_.endo_simul(iyr),oo_.exo_simul, M_.params, it_); - d1 = -d1 ; + hbacsup = clock ; + c = bksupk(ny,fid,ncc,icc1) ; + hbacsup = etime(clock,hbacsup) ; + c = reshape(c,ny,options_.periods)' ; + oo_.endo_simul(:,1+M_.maximum_endo_lag:(options_.periods+M_.maximum_endo_lag)) = oo_.endo_simul(:,1+M_.maximum_endo_lag:(options_.periods+M_.maximum_endo_lag))+options_.slowc*c' ; end - err_f = max(err_f,max(abs(d1))); - w0 = jacobian(:,1:isc(1)) ; - w = jacobian(:,isc(1)+1:isc(1+M_.maximum_endo_lead)) ; - j = 1 ; - while j <= M_.maximum_endo_lag - icr = j1(1:lj1(j),j)-(j-1)*ny ; - - ofs = ((icr0+(j-1)*ny+1)-1)*ncc*8 ; - junk = fseek(fid,ofs,-1) ; - c = fread(fid,[ncc,ny],'float64')' ; - - temp = zeros(ny,ltemp(j)) ; - if ljwc(j) > 0 - temp(:,jwc(1:ljwc(j),j)) = w ; - end - temp(:,jwc1(:,j))=temp(:,jwc1(:,j))-w0*c(icr,1:ncc1) ; - w = temp ; - clear temp ; - d1 = d1-w0*c(icr,ncc) ; - clear c ; - j = j + 1 ; - w0 = w(:,1:lj1(j)) ; - if M_.maximum_endo_lead == 1 - w = jacobian(:,isc(j+M_.maximum_endo_lead-1)+1:isc(j+M_.maximum_endo_lead)) ; - else - w = w(:,lj1(j)+1:size(w,2)) ; - - if lky(j+M_.maximum_endo_lead) > 0 - w = [w jacobian(:,isc(j+M_.maximum_endo_lead-1)+1:isc(j+M_.maximum_endo_lead))] ; - end - end - end - c = w0\[w d1] ; - d1 = [] ; - clear w w0 ; - junk = fseek(fid,0,1) ; - fwrite(fid,c','float64') ; - clear c ; - it_ = it_ + 1 ; - ic = ic + ny ; - iyr = iyr + ny ; - icr0 = icr0 + ny ; - end - if options_.terminal_condition == 1 - - ofs = (((it_-M_.maximum_lag-2)*ny+1)-1)*ncc*8 ; - junk = fseek(fid,ofs,-1) ; - c = fread(fid,[ncc,ny],'float64')'; - - for i = 1:M_.maximum_endo_lead - w = tril(triu(ones(ny,ny+ncc1))) ; - w(:,jwc1(:,M_.maximum_endo_lag)) = w(:,jwc1(:,M_.maximum_endo_lag))+c(:,1:ncc1) ; - c = [w(:,ny+1:size(w,2))' c(:,ncc)]/w(:,1:ny) ; - - junk = fseek(fid,0,1) ; - fwrite(fid,c','float64') ; - - it_ = it_+1 ; - ic = ic + ny ; + fclose(fid) ; + + h2 = etime(clock,h2) ; + [junk,i1] = max(abs(c)); + [junk,i2] = max(junk); + disp(['variable ' M_.endo_names(i2,:) ' period ' num2str(i1(i2))]) + err = max(max(abs(c./options_.scalv'))) ; + disp ([num2str(iter) '- err = ' num2str(err)]) ; + disp (['err_f = ' num2str(err_f)]) + disp ([' Time of this iteration : ' num2str(h2)]) ; + if options_.timing + disp ([' Back substitution : ' num2str(hbacsup)]) ; + end + if err < options_.dynatol + h1 = etime(clock,h1) ; + fprintf ('\n') ; + disp ([' Total time of simulation : ' num2str(h1)]) ; + fprintf ('\n') ; + disp ([' Convergence achieved.']) ; + disp (['-----------------------------------------------------']) ; + fprintf ('\n') ; + return ; end - end - oo_.endo_simul = reshape(oo_.endo_simul,ny,options_.periods+M_.maximum_lag+M_.maximum_endo_lead) ; - if options_.terminal_condition == 1 - hbacsup = clock ; - c = bksupk(ny,fid,ncc,icc1) ; - hbacsup = etime(clock,hbacsup) ; - c = reshape(c,ny,options_.periods+M_.maximum_endo_lead)' ; - y(:,1+M_.maximum_endo_lag:(options_.periods+M_.maximum_endo_lead+M_.maximum_endo_lag)) = y(:,1+M_.maximum_endo_lag:(options_.periods+M_.maximum_endo_lead+M_.maximum_endo_lag))+options_.slowc*c' ; - else - hbacsup = clock ; - c = bksupk(ny,fid,ncc,icc1) ; - hbacsup = etime(clock,hbacsup) ; - c = reshape(c,ny,options_.periods)' ; - oo_.endo_simul(:,1+M_.maximum_endo_lag:(options_.periods+M_.maximum_endo_lag)) = oo_.endo_simul(:,1+M_.maximum_endo_lag:(options_.periods+M_.maximum_endo_lag))+options_.slowc*c' ; - end - - fclose(fid) ; - - h2 = etime(clock,h2) ; - [junk,i1] = max(abs(c)); - [junk,i2] = max(junk); - disp(['variable ' M_.endo_names(i2,:) ' period ' num2str(i1(i2))]) - err = max(max(abs(c./options_.scalv'))) ; - disp ([num2str(iter) '- err = ' num2str(err)]) ; - disp (['err_f = ' num2str(err_f)]) - disp ([' Time of this iteration : ' num2str(h2)]) ; - if options_.timing - disp ([' Back substitution : ' num2str(hbacsup)]) ; - end - if err < options_.dynatol - h1 = etime(clock,h1) ; - fprintf ('\n') ; - disp ([' Total time of simulation : ' num2str(h1)]) ; - fprintf ('\n') ; - disp ([' Convergence achieved.']) ; - disp (['-----------------------------------------------------']) ; - fprintf ('\n') ; - return ; - end end disp(['WARNING : the maximum number of iterations is reached.']) ; fprintf ('\n') ; diff --git a/matlab/simul.m b/matlab/simul.m index f2c3df2c89..b2d755881d 100644 --- a/matlab/simul.m +++ b/matlab/simul.m @@ -32,54 +32,54 @@ function simul(dr) global M_ options_ oo_ ys0_ if size(M_.lead_lag_incidence,2)-nnz(M_.lead_lag_incidence(M_.maximum_endo_lag+1,:)) > 0 - mess = ['DYNARE: error in model specification : variable ' M_.endo_names(find(M_.lead_lag_incidence(M_.maximum_lag+1,:)==0),:)] ; - mess = [mess ' doesn''t appear as current variable.'] ; - error (mess) ; + mess = ['DYNARE: error in model specification : variable ' M_.endo_names(find(M_.lead_lag_incidence(M_.maximum_lag+1,:)==0),:)] ; + mess = [mess ' doesn''t appear as current variable.'] ; + error (mess) ; end options_ = set_default_option(options_,'periods',0); if options_.periods == 0 - error('SIMUL: number of periods for the simulation isn''t specified') + error('SIMUL: number of periods for the simulation isn''t specified') end - if ~ options_.initval_file - if ~isfield(options_,'datafile') +if ~ options_.initval_file + if ~isfield(options_,'datafile') make_ex_; make_y_; - else - read_data_; - end - end - - if isempty(options_.scalv) | options_.scalv == 0 + else + read_data_; + end +end + +if isempty(options_.scalv) | options_.scalv == 0 options_.scalv = oo_.steady_state ; - end +end + +options_.scalv= 1 ; - options_.scalv= 1 ; +if ~options_.block && ~options_.bytecode && options_.stack_solve_algo ~= 0 + error('SIMUL: for the moment, you must use stack_solve_algo=0 when not using block nor bytecode option') +end +if options_.block && ~options_.bytecode && (options_.stack_solve_algo == 0 || options_.stack_solve_algo == 5) + error('SIMUL: for the moment, you must use stack_solve_algo={1,2,3,4} when using block without bytecode option') +end +if options_.block && options_.bytecode && options_.stack_solve_algo ~= 5 + error('SIMUL: for the moment, you must use stack_solve_algo=5 with block and bytecode option') +end - if ~options_.block && ~options_.bytecode && options_.stack_solve_algo ~= 0 - error('SIMUL: for the moment, you must use stack_solve_algo=0 when not using block nor bytecode option') - end - if options_.block && ~options_.bytecode && (options_.stack_solve_algo == 0 || options_.stack_solve_algo == 5) - error('SIMUL: for the moment, you must use stack_solve_algo={1,2,3,4} when using block without bytecode option') - end - if options_.block && options_.bytecode && options_.stack_solve_algo ~= 5 - error('SIMUL: for the moment, you must use stack_solve_algo=5 with block and bytecode option') - end - - if(options_.block) - if(options_.bytecode) - oo_.endo_simul=bytecode('dynamic'); - else - eval([M_.fname '_dynamic']); - end; - else - if M_.maximum_endo_lag ==1 & M_.maximum_endo_lead <= 1 - sim1 ; - else - simk ; - end - end; +if(options_.block) + if(options_.bytecode) + oo_.endo_simul=bytecode('dynamic'); + else + eval([M_.fname '_dynamic']); + end; +else + if M_.maximum_endo_lag ==1 & M_.maximum_endo_lead <= 1 + sim1 ; + else + simk ; + end +end; dyn2vec; diff --git a/matlab/simult.m b/matlab/simult.m index fba16268df..8f8d666264 100644 --- a/matlab/simult.m +++ b/matlab/simult.m @@ -36,15 +36,15 @@ global it_ means_ order = options_.order; replic = options_.replic; if replic == 0 - replic = 1; + replic = 1; end seed = options_.simul_seed; it_ = M_.maximum_lag + 1 ; if replic > 1 - fname = [M_.fname,'_simul']; - fh = fopen(fname,'w+'); + fname = [M_.fname,'_simul']; + fh = fopen(fname,'w+'); end % eliminate shocks with 0 variance @@ -54,22 +54,22 @@ oo_.exo_simul = zeros(M_.maximum_lag+M_.maximum_lead+options_.periods,M_.exo_nbr chol_S = chol(M_.Sigma_e(i_exo_var,i_exo_var)); for i=1:replic - if isempty(seed) - randn('state',sum(100*clock)); - else - randn('state',seed+i-1); - end - if ~isempty(M_.Sigma_e) - oo_.exo_simul(:,i_exo_var) = randn(M_.maximum_lag+M_.maximum_lead+options_.periods,nxs)*chol_S; - end - y_ = simult_(ys,dr,oo_.exo_simul,order); - if replic > 1 - fwrite(fh,y_(:,M_.maximum_lag+1:end),'float64'); - end + if isempty(seed) + randn('state',sum(100*clock)); + else + randn('state',seed+i-1); + end + if ~isempty(M_.Sigma_e) + oo_.exo_simul(:,i_exo_var) = randn(M_.maximum_lag+M_.maximum_lead+options_.periods,nxs)*chol_S; + end + y_ = simult_(ys,dr,oo_.exo_simul,order); + if replic > 1 + fwrite(fh,y_(:,M_.maximum_lag+1:end),'float64'); + end end if replic > 1 - fclose(fh); + fclose(fh); end diff --git a/matlab/simult_.m b/matlab/simult_.m index b6a6ce53bc..d156f01ab0 100644 --- a/matlab/simult_.m +++ b/matlab/simult_.m @@ -35,76 +35,76 @@ function y_=simult_(y0,dr,ex_,iorder) % along with Dynare. If not, see <http://www.gnu.org/licenses/>. global M_ options_ it_ - iter = size(ex_,1); - if ~isempty(dr.ghu) - nx = size(dr.ghu,2); - end - y_ = zeros(size(y0,1),iter+M_.maximum_lag); - - y_(:,1:M_.maximum_lag) = y0; +iter = size(ex_,1); +if ~isempty(dr.ghu) + nx = size(dr.ghu,2); +end +y_ = zeros(size(y0,1),iter+M_.maximum_lag); - if options_.k_order_solver - options_.seed = 77; - ex_ = [zeros(1,M_.exo_nbr); ex_]; - switch options_.order - case 1 - y_ = dynare_simul_(1,dr.nstatic,dr.npred-dr.nboth,dr.nboth,dr.nfwrd,M_.exo_nbr, ... - y_(dr.order_var,1),ex_',M_.Sigma_e,options_.seed,dr.ys(dr.order_var),... - zeros(M_.endo_nbr,1),dr.g_1); - case 2 - y_ = dynare_simul_(2,dr.nstatic,dr.npred-dr.nboth,dr.nboth,dr.nfwrd,M_.exo_nbr, ... - y_(dr.order_var,1),ex_',M_.Sigma_e,options_.seed,dr.ys(dr.order_var),dr.g_0, ... - dr.g_1,dr.g_2); - case 3 - y_ = dynare_simul_(3,dr.nstatic,dr.npred-dr.nboth,dr.nboth,dr.nfwrd,M_.exo_nbr, ... - y_(dr.order_var,1),ex_',M_.Sigma_e,options_.seed,dr.ys(dr.order_var),dr.g_0, ... - dr.g_1,dr.g_2,dr.g_3); - otherwise - error(['order = ' int2str(order) ' isn''t supported']) - end - y_(dr.order_var,:) = y_; - else - k1 = [M_.maximum_lag:-1:1]; - k2 = dr.kstate(find(dr.kstate(:,2) <= M_.maximum_lag+1),[1 2]); - k2 = k2(:,1)+(M_.maximum_lag+1-k2(:,2))*M_.endo_nbr; - k3 = M_.lead_lag_incidence(1:M_.maximum_lag,:)'; - k3 = find(k3(:)); - k4 = dr.kstate(find(dr.kstate(:,2) < M_.maximum_lag+1),[1 2]); - k4 = k4(:,1)+(M_.maximum_lag+1-k4(:,2))*M_.endo_nbr; - - if iorder == 1 - if ~isempty(dr.ghu) - for i = M_.maximum_lag+1: iter+M_.maximum_lag - tempx1 = y_(dr.order_var,k1); - tempx2 = tempx1-repmat(dr.ys(dr.order_var),1,M_.maximum_lag); - tempx = tempx2(k2); - y_(dr.order_var,i) = dr.ys(dr.order_var)+dr.ghx*tempx+dr.ghu* ... - ex_(i-M_.maximum_lag,:)'; - k1 = k1+1; - end - else - for i = M_.maximum_lag+1: iter+M_.maximum_lag - tempx1 = y_(dr.order_var,k1); - tempx2 = tempx1-repmat(dr.ys(dr.order_var),1,M_.maximum_lag); - tempx = tempx2(k2); - y_(dr.order_var,i) = dr.ys(dr.order_var)+dr.ghx*tempx; - k1 = k1+1; - end - end - elseif iorder == 2 - for i = M_.maximum_lag+1: iter+M_.maximum_lag - tempx1 = y_(dr.order_var,k1); - tempx2 = tempx1-repmat(dr.ys(dr.order_var),1,M_.maximum_lag); - tempx = tempx2(k2); - tempu = ex_(i-M_.maximum_lag,:)'; - tempuu = kron(tempu,tempu); - tempxx = kron(tempx,tempx); - tempxu = kron(tempx,tempu); - y_(dr.order_var,i) = dr.ys(dr.order_var)+dr.ghs2/2+dr.ghx*tempx+ ... - dr.ghu*tempu+0.5*(dr.ghxx*tempxx+dr.ghuu*tempuu)+dr.ghxu*tempxu; - k1 = k1+1; - end - end - end +y_(:,1:M_.maximum_lag) = y0; + +if options_.k_order_solver + options_.seed = 77; + ex_ = [zeros(1,M_.exo_nbr); ex_]; + switch options_.order + case 1 + y_ = dynare_simul_(1,dr.nstatic,dr.npred-dr.nboth,dr.nboth,dr.nfwrd,M_.exo_nbr, ... + y_(dr.order_var,1),ex_',M_.Sigma_e,options_.seed,dr.ys(dr.order_var),... + zeros(M_.endo_nbr,1),dr.g_1); + case 2 + y_ = dynare_simul_(2,dr.nstatic,dr.npred-dr.nboth,dr.nboth,dr.nfwrd,M_.exo_nbr, ... + y_(dr.order_var,1),ex_',M_.Sigma_e,options_.seed,dr.ys(dr.order_var),dr.g_0, ... + dr.g_1,dr.g_2); + case 3 + y_ = dynare_simul_(3,dr.nstatic,dr.npred-dr.nboth,dr.nboth,dr.nfwrd,M_.exo_nbr, ... + y_(dr.order_var,1),ex_',M_.Sigma_e,options_.seed,dr.ys(dr.order_var),dr.g_0, ... + dr.g_1,dr.g_2,dr.g_3); + otherwise + error(['order = ' int2str(order) ' isn''t supported']) + end + y_(dr.order_var,:) = y_; +else + k1 = [M_.maximum_lag:-1:1]; + k2 = dr.kstate(find(dr.kstate(:,2) <= M_.maximum_lag+1),[1 2]); + k2 = k2(:,1)+(M_.maximum_lag+1-k2(:,2))*M_.endo_nbr; + k3 = M_.lead_lag_incidence(1:M_.maximum_lag,:)'; + k3 = find(k3(:)); + k4 = dr.kstate(find(dr.kstate(:,2) < M_.maximum_lag+1),[1 2]); + k4 = k4(:,1)+(M_.maximum_lag+1-k4(:,2))*M_.endo_nbr; + + if iorder == 1 + if ~isempty(dr.ghu) + for i = M_.maximum_lag+1: iter+M_.maximum_lag + tempx1 = y_(dr.order_var,k1); + tempx2 = tempx1-repmat(dr.ys(dr.order_var),1,M_.maximum_lag); + tempx = tempx2(k2); + y_(dr.order_var,i) = dr.ys(dr.order_var)+dr.ghx*tempx+dr.ghu* ... + ex_(i-M_.maximum_lag,:)'; + k1 = k1+1; + end + else + for i = M_.maximum_lag+1: iter+M_.maximum_lag + tempx1 = y_(dr.order_var,k1); + tempx2 = tempx1-repmat(dr.ys(dr.order_var),1,M_.maximum_lag); + tempx = tempx2(k2); + y_(dr.order_var,i) = dr.ys(dr.order_var)+dr.ghx*tempx; + k1 = k1+1; + end + end + elseif iorder == 2 + for i = M_.maximum_lag+1: iter+M_.maximum_lag + tempx1 = y_(dr.order_var,k1); + tempx2 = tempx1-repmat(dr.ys(dr.order_var),1,M_.maximum_lag); + tempx = tempx2(k2); + tempu = ex_(i-M_.maximum_lag,:)'; + tempuu = kron(tempu,tempu); + tempxx = kron(tempx,tempx); + tempxu = kron(tempx,tempu); + y_(dr.order_var,i) = dr.ys(dr.order_var)+dr.ghs2/2+dr.ghx*tempx+ ... + dr.ghu*tempu+0.5*(dr.ghxx*tempxx+dr.ghuu*tempuu)+dr.ghxu*tempxu; + k1 = k1+1; + end + end +end % MJ 08/30/02 corrected bug at order 2 \ No newline at end of file diff --git a/matlab/simultxdet.m b/matlab/simultxdet.m index 949b98115a..cef7d30a53 100644 --- a/matlab/simultxdet.m +++ b/matlab/simultxdet.m @@ -31,117 +31,117 @@ function [y_,int_width]=simultxdet(y0,ex,ex_det, iorder,var_list,M_,oo_,options_ % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - dr = oo_.dr; - ykmin = M_.maximum_lag; - endo_nbr = M_.endo_nbr; - exo_det_steady_state = oo_.exo_det_steady_state; - nstatic = dr.nstatic; - npred =dr.npred; - nc = size(dr.ghx,2); - iter = size(ex,1); - if size(ex_det, 1) ~= iter+ykmin - error('Size mismatch: number of forecasting periods for stochastic exogenous and deterministic exogenous don''t match') - end - nx = size(dr.ghu,2); - y_ = zeros(size(y0,1),iter+ykmin); - y_(:,1:ykmin) = y0; - k1 = [ykmin:-1:1]; - k2 = dr.kstate(find(dr.kstate(:,2) <= ykmin+1),[1 2]); - k2 = k2(:,1)+(ykmin+1-k2(:,2))*endo_nbr; - k3 = M_.lead_lag_incidence(1:ykmin,:)'; - k3 = find(k3(:)); - k4 = dr.kstate(find(dr.kstate(:,2) < ykmin+1),[1 2]); - k4 = k4(:,1)+(ykmin+1-k4(:,2))*endo_nbr; - - nvar = size(var_list,1); - if nvar == 0 +dr = oo_.dr; +ykmin = M_.maximum_lag; +endo_nbr = M_.endo_nbr; +exo_det_steady_state = oo_.exo_det_steady_state; +nstatic = dr.nstatic; +npred =dr.npred; +nc = size(dr.ghx,2); +iter = size(ex,1); +if size(ex_det, 1) ~= iter+ykmin + error('Size mismatch: number of forecasting periods for stochastic exogenous and deterministic exogenous don''t match') +end +nx = size(dr.ghu,2); +y_ = zeros(size(y0,1),iter+ykmin); +y_(:,1:ykmin) = y0; +k1 = [ykmin:-1:1]; +k2 = dr.kstate(find(dr.kstate(:,2) <= ykmin+1),[1 2]); +k2 = k2(:,1)+(ykmin+1-k2(:,2))*endo_nbr; +k3 = M_.lead_lag_incidence(1:ykmin,:)'; +k3 = find(k3(:)); +k4 = dr.kstate(find(dr.kstate(:,2) < ykmin+1),[1 2]); +k4 = k4(:,1)+(ykmin+1-k4(:,2))*endo_nbr; + +nvar = size(var_list,1); +if nvar == 0 nvar = endo_nbr; ivar = [1:nvar]; - else +else ivar=zeros(nvar,1); for i=1:nvar - i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact'); - if isempty(i_tmp) - disp(var_list(i,:)); - error (['One of the variable specified does not exist']) ; - else - ivar(i) = i_tmp; - end + i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact'); + if isempty(i_tmp) + disp(var_list(i,:)); + error (['One of the variable specified does not exist']) ; + else + ivar(i) = i_tmp; + end end - end +end - if iorder == 1 +if iorder == 1 for i = ykmin+1: iter+ykmin - tempx1 = y_(dr.order_var,k1); - tempx2 = tempx1-repmat(dr.ys(dr.order_var),1,ykmin); - tempx = tempx2(k2); + tempx1 = y_(dr.order_var,k1); + tempx2 = tempx1-repmat(dr.ys(dr.order_var),1,ykmin); + tempx = tempx2(k2); y_(dr.order_var,i) = dr.ys(dr.order_var)+dr.ghx*tempx+dr.ghu* ... ex(i-ykmin,:)'; for j=1:min(ykmin+M_.exo_det_length+1-i,M_.exo_det_length) y_(dr.order_var,i) = y_(dr.order_var,i) + dr.ghud{j}*(ex_det(i+j-1,:)'-exo_det_steady_state); - end - - k1 = k1+1; + end + + k1 = k1+1; end - elseif iorder == 2 +elseif iorder == 2 for i = ykmin+1: iter+ykmin - tempx1 = y_(dr.order_var,k1); - tempx2 = tempx1-repmat(dr.ys(dr.order_var),1,ykmin); - tempx = tempx2(k2); - tempu = ex(i-ykmin,:)'; - tempuu = kron(tempu,tempu); + tempx1 = y_(dr.order_var,k1); + tempx2 = tempx1-repmat(dr.ys(dr.order_var),1,ykmin); + tempx = tempx2(k2); + tempu = ex(i-ykmin,:)'; + tempuu = kron(tempu,tempu); tempxx = kron(tempx,tempx); tempxu = kron(tempx,tempu); y_(dr.order_var,i) = dr.ys(dr.order_var)+dr.ghs2/2+dr.ghx*tempx+ ... dr.ghu*tempu+0.5*(dr.ghxx*tempxx+dr.ghuu*tempuu)+dr.ghxu* ... tempxu; for j=1:min(ykmin+M_.exo_det_length+1-i,M_.exo_det_length) - tempud = ex_det(i+j-1,:)'-exo_det_steady_state; - tempudud = kron(tempud,tempud); - tempxud = kron(tempx,tempud); - tempuud = kron(tempu,tempud); - y_(dr.order_var,i) = y_(dr.order_var,i) + dr.ghud{j}*tempud + ... - dr.ghxud{j}*tempxud + dr.ghuud{j}*tempuud + ... - 0.5*dr.ghudud{j,j}*tempudud; - for k=1:j-1 - tempudk = ex_det(i+k-1,:)'-exo_det_steady_state; - tempududk = kron(tempudk,tempud); - y_(dr.order_var,i) = y_(dr.order_var,i) + ... - dr.ghudud{k,j}*tempududk; - end - end - k1 = k1+1; + tempud = ex_det(i+j-1,:)'-exo_det_steady_state; + tempudud = kron(tempud,tempud); + tempxud = kron(tempx,tempud); + tempuud = kron(tempu,tempud); + y_(dr.order_var,i) = y_(dr.order_var,i) + dr.ghud{j}*tempud + ... + dr.ghxud{j}*tempxud + dr.ghuud{j}*tempuud + ... + 0.5*dr.ghudud{j,j}*tempudud; + for k=1:j-1 + tempudk = ex_det(i+k-1,:)'-exo_det_steady_state; + tempududk = kron(tempudk,tempud); + y_(dr.order_var,i) = y_(dr.order_var,i) + ... + dr.ghudud{k,j}*tempududk; + end + end + k1 = k1+1; end - end +end + +[A,B] = kalman_transition_matrix(dr,nstatic+(1:npred),1:nc,dr.transition_auxiliary_variables,M_.exo_nbr); - [A,B] = kalman_transition_matrix(dr,nstatic+(1:npred),1:nc,dr.transition_auxiliary_variables,M_.exo_nbr); +inv_order_var = dr.inv_order_var; +ghx1 = dr.ghx(inv_order_var(ivar),:); +ghu1 = dr.ghu(inv_order_var(ivar),:); - inv_order_var = dr.inv_order_var; - ghx1 = dr.ghx(inv_order_var(ivar),:); - ghu1 = dr.ghu(inv_order_var(ivar),:); +sigma_u = B*M_.Sigma_e*B'; +sigma_u1 = ghu1*M_.Sigma_e*ghu1'; +sigma_y = 0; - sigma_u = B*M_.Sigma_e*B'; - sigma_u1 = ghu1*M_.Sigma_e*ghu1'; - sigma_y = 0; - - for i=1:iter - sigma_y1 = ghx1*sigma_y*ghx1'+sigma_u1; - var_yf(i,:) = diag(sigma_y1)'; - if i == iter - break - end - sigma_u = A*sigma_u*A'; - sigma_y = sigma_y+sigma_u; - end +for i=1:iter + sigma_y1 = ghx1*sigma_y*ghx1'+sigma_u1; + var_yf(i,:) = diag(sigma_y1)'; + if i == iter + break + end + sigma_u = A*sigma_u*A'; + sigma_y = sigma_y+sigma_u; +end - fact = norminv((1-options_.conf_sig)/2,0,1); +fact = norminv((1-options_.conf_sig)/2,0,1); - int_width = zeros(iter,endo_nbr); - for i=1:nvar +int_width = zeros(iter,endo_nbr); +for i=1:nvar int_width(:,i) = fact*sqrt(var_yf(:,i)); - end - - for i=1:nvar +end + +for i=1:nvar my_subplot(i,nvar,2,3,'Forecasts'); plot([-ykmin+1:0],y0(ivar(i),1:ykmin),'b-',... @@ -150,5 +150,5 @@ function [y_,int_width]=simultxdet(y0,ex,ex_det, iorder,var_list,M_,oo_,options_ [1:iter],y_(ivar(i),ykmin+1:end)'-int_width(:,ivar(i)),'g:',... [1 iter],repmat(dr.ys(ivar(i)),1,2),'r-'); title(M_.endo_names(ivar(i),:)); - end +end diff --git a/matlab/size_of_the_reduced_form_model.m b/matlab/size_of_the_reduced_form_model.m index b573ba0c76..60dce92c3e 100644 --- a/matlab/size_of_the_reduced_form_model.m +++ b/matlab/size_of_the_reduced_form_model.m @@ -18,9 +18,9 @@ function mega = size_of_the_reduced_form_model(dr) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - names = fieldnames(dr); - number_of_scalars = 0; - for field=1:size(names,1) - number_of_scalars = number_of_scalars + prod(size(getfield(dr,names{field}))); - end - mega = 8 * number_of_scalars / 1048576 ; \ No newline at end of file +names = fieldnames(dr); +number_of_scalars = 0; +for field=1:size(names,1) + number_of_scalars = number_of_scalars + prod(size(getfield(dr,names{field}))); +end +mega = 8 * number_of_scalars / 1048576 ; \ No newline at end of file diff --git a/matlab/solve1.m b/matlab/solve1.m index e451eccbf8..7a45aeaedd 100644 --- a/matlab/solve1.m +++ b/matlab/solve1.m @@ -37,64 +37,64 @@ function [x,check] = solve1(func,x,j1,j2,jacobian_flag,bad_cond_flag,varargin) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ options_ fjac +global M_ options_ fjac - nn = length(j1); - fjac = zeros(nn,nn) ; - g = zeros(nn,1) ; +nn = length(j1); +fjac = zeros(nn,nn) ; +g = zeros(nn,1) ; - tolf = options_.solve_tolf ; - tolx = options_.solve_tolx; - tolmin = tolx ; +tolf = options_.solve_tolf ; +tolx = options_.solve_tolx; +tolmin = tolx ; - stpmx = 100 ; - maxit = options_.solve_maxit ; +stpmx = 100 ; +maxit = options_.solve_maxit ; - check = 0 ; +check = 0 ; - fvec = feval(func,x,varargin{:}); - fvec = fvec(j1); - - i = find(~isfinite(fvec)); - - if ~isempty(i) +fvec = feval(func,x,varargin{:}); +fvec = fvec(j1); + +i = find(~isfinite(fvec)); + +if ~isempty(i) disp(['STEADY: numerical initial values incompatible with the following' ... ' equations']) disp(j1(i)') - end - - f = 0.5*fvec'*fvec ; +end + +f = 0.5*fvec'*fvec ; - if max(abs(fvec)) < tolf +if max(abs(fvec)) < tolf return ; - end +end - stpmax = stpmx*max([sqrt(x'*x);nn]) ; - first_time = 1; - for its = 1:maxit +stpmax = stpmx*max([sqrt(x'*x);nn]) ; +first_time = 1; +for its = 1:maxit if jacobian_flag - [fvec,fjac] = feval(func,x,varargin{:}); - fvec = fvec(j1); - fjac = fjac(j1,j2); + [fvec,fjac] = feval(func,x,varargin{:}); + fvec = fvec(j1); + fjac = fjac(j1,j2); else - dh = max(abs(x(j2)),options_.gstep*ones(nn,1))*eps^(1/3); - - for j = 1:nn - xdh = x ; - xdh(j2(j)) = xdh(j2(j))+dh(j) ; - t = feval(func,xdh,varargin{:}); - fjac(:,j) = (t(j1) - fvec)./dh(j) ; - g(j) = fvec'*fjac(:,j) ; - end + dh = max(abs(x(j2)),options_.gstep*ones(nn,1))*eps^(1/3); + + for j = 1:nn + xdh = x ; + xdh(j2(j)) = xdh(j2(j))+dh(j) ; + t = feval(func,xdh,varargin{:}); + fjac(:,j) = (t(j1) - fvec)./dh(j) ; + g(j) = fvec'*fjac(:,j) ; + end end g = (fvec'*fjac)'; if options_.debug - disp(['cond(fjac) ' num2str(cond(fjac))]) + disp(['cond(fjac) ' num2str(cond(fjac))]) end M_.unit_root = 0; if M_.unit_root - if first_time + if first_time first_time = 0; [q,r,e]=qr(fjac); n = sum(abs(diag(r)) < 1e-12); @@ -104,22 +104,22 @@ function [x,check] = solve1(func,x,j1,j2,jacobian_flag,bad_cond_flag,varargin) disp('STEADY with unit roots:') disp(' ') if n > 0 - disp([' The following variable(s) kept their value given in INITVAL' ... - ' or ENDVAL']) - disp(char(e(:,end-n+1:end)'*M_.endo_names)) + disp([' The following variable(s) kept their value given in INITVAL' ... + ' or ENDVAL']) + disp(char(e(:,end-n+1:end)'*M_.endo_names)) + else + disp(' STEADY can''t find any unit root!') + end else - disp(' STEADY can''t find any unit root!') - end - else [q,r]=qr(fjac*e); fvec = q'*fvec; p = e*[-r(1:end-n,1:end-n)\fvec(1:end-n);zeros(n,1)]; - end + end elseif bad_cond_flag && cond(fjac) > 1/sqrt(eps) - fjac2=fjac'*fjac; - p=-(fjac2+sqrt(nn*eps)*max(sum(abs(fjac2)))*eye(nn))\(fjac'*fvec); + fjac2=fjac'*fjac; + p=-(fjac2+sqrt(nn*eps)*max(sum(abs(fjac2)))*eye(nn))\(fjac'*fvec); else - p = -fjac\fvec ; + p = -fjac\fvec ; end xold = x ; fold = f ; @@ -127,37 +127,37 @@ function [x,check] = solve1(func,x,j1,j2,jacobian_flag,bad_cond_flag,varargin) [x,f,fvec,check]=lnsrch1(xold,fold,g,p,stpmax,func,j1,j2,varargin{:}); if options_.debug - disp([its f]) - disp([xold x]) + disp([its f]) + disp([xold x]) end - + if check > 0 - den = max([f;0.5*nn]) ; - if max(abs(g).*max([abs(x(j2)') ones(1,nn)])')/den < tolmin + den = max([f;0.5*nn]) ; + if max(abs(g).*max([abs(x(j2)') ones(1,nn)])')/den < tolmin return - else + else disp (' ') disp (['SOLVE: Iteration ' num2str(its)]) disp (['Spurious convergence.']) disp (x) return - end - - if max(abs(x(j2)-xold(j2))./max([abs(x(j2)') ones(1,nn)])') < tolx - disp (' ') - disp (['SOLVE: Iteration ' num2str(its)]) - disp (['Convergence on dX.']) - disp (x) - return - end + end + + if max(abs(x(j2)-xold(j2))./max([abs(x(j2)') ones(1,nn)])') < tolx + disp (' ') + disp (['SOLVE: Iteration ' num2str(its)]) + disp (['Convergence on dX.']) + disp (x) + return + end elseif max(abs(fvec)) < tolf - return + return end - end - - check = 1; - disp(' ') - disp('SOLVE: maxit has been reached') +end + +check = 1; +disp(' ') +disp('SOLVE: maxit has been reached') % 01/14/01 MJ lnsearch is now a separate function % 01/16/01 MJ added varargin to function evaluation diff --git a/matlab/solve_one_boundary.m b/matlab/solve_one_boundary.m index f721144ba2..d694f09582 100644 --- a/matlab/solve_one_boundary.m +++ b/matlab/solve_one_boundary.m @@ -1,366 +1,366 @@ -function [y, info] = solve_one_boundary(fname, y, x, params, y_index_eq, nze, periods, is_linear, Block_Num, y_kmin, maxit_, solve_tolf, lambda, cutoff, stack_solve_algo, forward_backward, is_dynamic, verbose) -% Computes the deterministic simulation of a block of equation containing -% lead or lag variables -% -% INPUTS -% fname [string] name of the file containing the block -% to simulate -% y [matrix] All the endogenous variables of the model -% x [matrix] All the exogenous variables of the model -% params [vector] All the parameters of the model -% y_index_eq [vector of int] The index of the endogenous variables of -% the block -% nze [integer] number of non-zero elements in the -% jacobian matrix -% periods [integer] number of simulation periods -% is_linear [integer] if is_linear=1 the block is linear -% if is_linear=0 the block is not linear -% Block_Num [integer] block number -% y_kmin [integer] maximum number of lag in the model -% maxit_ [integer] maximum number of iteration in Newton -% solve_tolf [double] convergence criteria -% lambda [double] initial value of step size in -% Newton -% cutoff [double] cutoff to correct the direction in Newton in case -% of singular jacobian matrix -% stack_solve_algo [integer] linear solver method used in the -% Newton algorithm : -% - 1 sparse LU -% - 2 GMRES -% - 3 BicGStab -% - 4 Optimal path length -% forward_backward [integer] The block has to be solve forward -% (1) or backward (0) -% is_dynamic [integer] (1) The block belong to the dynamic -% file and the oo_.deterministic_simulation field has to be uptated -% (0) The block belong to the static -% file and th oo_.deteerminstic -% field remains unchanged -% verbose [integer] (0) iterations are not printed -% (1) iterations are printed -% -% OUTPUTS -% y [matrix] All endogenous variables of the model -% -% ALGORITHM -% Newton with LU or GMRES or BicGstab for dynamic block -% -% SPECIAL REQUIREMENTS -% none. -% - -% Copyright (C) 1996-2009 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 <http://www.gnu.org/licenses/>. - - - global oo_ M_ options_; - Blck_size=size(y_index_eq,2); - g2 = []; - g3 = []; - correcting_factor=0.01; - luinc_tol=1e-10; - max_resa=1e100; - reduced = 0; - if(forward_backward) - incr = 1; - start = y_kmin+1; - finish = periods+y_kmin; - else - incr = -1; - start = periods+y_kmin; - finish = y_kmin+1; - end - lambda=1; - for it_=start:incr:finish - cvg=0; - iter=0; - g1=spalloc( Blck_size, Blck_size, nze); - while ~(cvg==1 | iter>maxit_), - if(is_dynamic) - [r, y, g1, g2, g3] = feval(fname, y, x, params, it_, 0); - else - [r, y, g1, g2, g3] = feval(fname, y, x, params, 0); - end; - if(~isreal(r)) - max_res=(-(max(max(abs(r))))^2)^0.5; - else - max_res=max(max(abs(r))); - end; - %['max_res=' num2str(max_res) ' Block_Num=' int2str(Block_Num) ' it_=' int2str(it_)] - %disp(['iteration : ' int2str(iter+1) ' => ' num2str(max_res) ' time = ' int2str(it_)]); - -% fjac = zeros(Blck_size, Blck_size); -% disp(['Blck_size=' int2str(Blck_size) ' it_=' int2str(it_)]); -% dh = max(abs(y(it_, y_index_eq)),options_.gstep*ones(1, Blck_size))*eps^(1/3); -% fvec = r; -% for j = 1:Blck_size -% ydh = y ; -% ydh(it_, y_index_eq(j)) = ydh(it_, y_index_eq(j)) + dh(j) ; -% [t, y1, g11, g21, g31]=feval(fname, ydh, x, params, it_, 0); -% fjac(:,j) = (t - fvec)./dh(j) ; -% end; -% diff = g1 -fjac; -% diff -% disp('g1'); -% disp([num2str(g1,'%4.5f')]); -% disp('fjac'); -% disp([num2str(fjac,'%4.5f')]); -% [c_max, i_c_max] = max(abs(diff)); -% [l_c_max, i_r_max] = max(c_max); -% disp(['maximum element row=' int2str(i_c_max(i_r_max)) ' and column=' int2str(i_r_max) ' value = ' num2str(l_c_max)]); -% equation = i_c_max(i_r_max); -% variable = i_r_max; -% variable -% mod(variable, Blck_size) -% disp(['equation ' int2str(equation) ' and variable ' int2str(y_index_eq(variable)) ' ' M_.endo_names(y_index_eq(variable), :)]); -% disp(['g1(' int2str(equation) ', ' int2str(variable) ')=' num2str(g1(equation, variable),'%3.10f') ' fjac(' int2str(equation) ', ' int2str(variable) ')=' num2str(fjac(equation, variable), '%3.10f') ' y(' int2str(it_) ', ' int2str(variable) ')=' num2str(y(it_, variable))]); -% %return; -% %g1 = fjac; - - - - - - if(verbose==1) - disp(['iteration : ' int2str(iter+1) ' => ' num2str(max_res) ' time = ' int2str(it_)]); - if(is_dynamic) - disp([M_.endo_names(y_index_eq,:) num2str([y(it_,y_index_eq)' r g1])]); - else - disp([M_.endo_names(y_index_eq,:) num2str([y(y_index_eq) r g1])]); - end; - end; - if(~isreal(max_res) | isnan(max_res)) - cvg = 0; - elseif(is_linear & iter>0) - cvg = 1; - else - cvg=(max_res<solve_tolf); - end; - if(~cvg) - if(iter>0) - if(~isreal(max_res) | isnan(max_res) | (max_resa<max_res && iter>1)) - if(isnan(max_res)| (max_resa<max_res && iter>0)) - detJ=det(g1a); - if(abs(detJ)<1e-7) - max_factor=max(max(abs(g1a))); - ze_elem=sum(diag(g1a)<cutoff); - disp([num2str(full(ze_elem),'%d') ' elements on the Jacobian diagonal are below the cutoff (' num2str(cutoff,'%f') ')']); - if(correcting_factor<max_factor) - correcting_factor=correcting_factor*4; - disp(['The Jacobain matrix is singular, det(Jacobian)=' num2str(detJ,'%f') '.']); - disp([' trying to correct the Jacobian matrix:']); - disp([' correcting_factor=' num2str(correcting_factor,'%f') ' max(Jacobian)=' num2str(full(max_factor),'%f')]); - dx = - r/(g1+correcting_factor*speye(Blck_size)); - %dx = -b'/(g1+correcting_factor*speye(Blck_size))-ya_save; - y(it_,y_index_eq)=ya_save+lambda*dx; - continue; - else - disp('The singularity of the jacobian matrix could not be corrected'); - info = -Block_Num*10; - return; - end; - end; - elseif(lambda>1e-8) - lambda=lambda/2; - reduced = 1; - disp(['reducing the path length: lambda=' num2str(lambda,'%f')]); - if(is_dynamic) - y(it_,y_index_eq)=ya_save-lambda*dx; - else - y(y_index_eq)=ya_save-lambda*dx; - end; - continue; - else - if(cutoff == 0) - fprintf('Error in simul: Convergence not achieved in block %d, at time %d, after %d iterations.\n Increase "options_.maxit_".\n',Block_Num, it_, iter); - else - fprintf('Error in simul: Convergence not achieved in block %d, at time %d, after %d iterations.\n Increase "options_.maxit_" or set "cutoff=0" in model options.\n',Block_Num, it_, iter); - end; - if(is_dynamic) - oo_.deterministic_simulation.status = 0; - oo_.deterministic_simulation.error = max_res; - oo_.deterministic_simulation.iterations = iter; - oo_.deterministic_simulation.block(Block_Num).status = 0;% Convergency failed. - oo_.deterministic_simulation.block(Block_Num).error = max_res; - oo_.deterministic_simulation.block(Block_Num).iterations = iter; - end; - info = -Block_Num*10; - return; - end; - else - if(lambda<1) - lambda=max(lambda*2, 1); - end; - end; - end; - if(is_dynamic) - ya = y(it_,y_index_eq)'; - else - ya = y(y_index_eq); - end; - ya_save=ya; - g1a=g1; - if(~is_dynamic & options_.solve_algo == 0) - if exist('OCTAVE_VERSION') || isempty(ver('optim')) - % Note that fsolve() exists under Octave, but has a different syntax - % So we fail for the moment under Octave, until we add the corresponding code - error('DYNARE_SOLVE: you can''t use solve_algo=0 since you don''t have Matlab''s Optimization Toolbox') - end - options=optimset('fsolve'); - options.MaxFunEvals = 50000; - options.MaxIter = 2000; - options.TolFun=1e-8; - options.Display = 'iter'; - options.Jacobian = 'on'; - [yn,fval,exitval,output] = fsolve(@local_fname, y(y_index_eq), options, x, params, y, y_index_eq, fname, 0); - y(y_index_eq) = yn; - if exitval > 0 - info = 0; - else - info = -Block_Num*10; - end - elseif((~is_dynamic & options_.solve_algo==2) || (is_dynamic & stack_solve_algo==4)) - lambda=1; - stpmx = 100 ; - if (is_dynamic) - stpmax = stpmx*max([sqrt(y*y');size(y_index_eq,2)]); - else - stpmax = stpmx*max([sqrt(y'*y);size(y_index_eq,2)]); - end; - nn=1:size(y_index_eq,2); - g = (r'*g1)'; - f = 0.5*r'*r; - p = -g1\r ; - if (is_dynamic) - [y,f,r,check]=lnsrch1(y,f,g,p,stpmax,fname,nn,y_index_eq,x, params, it_, 0); - else - [y,f,r,check]=lnsrch1(y,f,g,p,stpmax,fname,nn,y_index_eq,x, params, 0); - end; - dx = ya - y(y_index_eq); - elseif(~is_dynamic & options_.solve_algo==3) - [yn,info] = csolve(@local_fname, y(y_index_eq),@local_fname,1e-6,500, x, params, y, y_index_eq, fname, 1); - dx = ya - yn; - y(y_index_eq) = yn; - elseif((stack_solve_algo==1 & is_dynamic) | (~is_dynamic & options_.solve_algo==1)), - dx = g1\r; - ya = ya - lambda*dx; - if(is_dynamic) - y(it_,y_index_eq) = ya'; - else - y(y_index_eq) = ya; - end; - elseif(stack_solve_algo==2 & is_dynamic), - flag1=1; - while(flag1>0) - [L1, U1]=luinc(g1,luinc_tol); - [za,flag1] = gmres(g1,-r,Blck_size,1e-6,Blck_size,L1,U1); - %[za,flag1] = gmres(-g1,b',Blck_size,1e-6,Blck_size,L1,U1); - if (flag1>0 | reduced) - if(flag1==1) - disp(['Error in simul: No convergence inside GMRES after ' num2str(iter,'%6d') ' iterations, in block' num2str(Block_Num,'%3d')]); - elseif(flag1==2) - disp(['Error in simul: Preconditioner is ill-conditioned, in block' num2str(Block_Num,'%3d')]); - elseif(flag1==3) - disp(['Error in simul: GMRES stagnated (Two consecutive iterates were the same.), in block' num2str(Block_Num,'%3d')]); - end; - luinc_tol = luinc_tol/10; - reduced = 0; - else - dx = za - ya; - ya = ya + lambda*dx; - if(is_dynamic) - y(it_,y_index_eq) = ya'; - else - y(y_index_eq) = ya'; - end; - end; - end; - elseif(stack_solve_algo==3 & is_dynamic), - flag1=1; - while(flag1>0) - [L1, U1]=luinc(g1,luinc_tol); - [za,flag1] = bicgstab(g1,-r,1e-7,Blck_size,L1,U1); - %[za,flag1] = bicgstab(-g1,b',1e-7,Blck_size,L1,U1); - if (flag1>0 | reduced) - if(flag1==1) - disp(['Error in simul: No convergence inside BICGSTAB after ' num2str(iter,'%6d') ' iterations, in block' num2str(Block_Num,'%3d')]); - elseif(flag1==2) - disp(['Error in simul: Preconditioner is ill-conditioned, in block' num2str(Block_Num,'%3d')]); - elseif(flag1==3) - disp(['Error in simul: GMRES stagnated (Two consecutive iterates were the same.), in block' num2str(Block_Num,'%3d')]); - end; - luinc_tol = luinc_tol/10; - reduced = 0; - else - dx = za - ya; - ya = ya + lambda*dx; - if(is_dynamic) - y(it_,y_index_eq) = ya'; - else - y(y_index_eq) = ya'; - end; - end; - end; - else - disp('unknown option : '); - if(is_dynamic) - disp(['options_.stack_solve_algo = ' num2str(stack_solve_algo) ' not implemented']); - else - disp(['options_.solve_algo = ' num2str(options_.solve_algo) ' not implemented']); - end; - info = -Block_Num*10; - return; - end; - iter=iter+1; - max_resa = max_res; - end - end - if cvg==0 - if(cutoff == 0) - fprintf('Error in simul: Convergence not achieved in block %d, at time %d, after %d iterations.\n Increase "options_.maxit_\".\n',Block_Num, it_,iter); - else - fprintf('Error in simul: Convergence not achieved in block %d, at time %d, after %d iterations.\n Increase "options_.maxit_" or set "cutoff=0" in model options.\n',Block_Num, it_,iter); - end; - if(is_dynamic) - oo_.deterministic_simulation.status = 0; - oo_.deterministic_simulation.error = max_res; - oo_.deterministic_simulation.iterations = iter; - oo_.deterministic_simulation.block(Block_Num).status = 0;% Convergency failed. - oo_.deterministic_simulation.block(Block_Num).error = max_res; - oo_.deterministic_simulation.block(Block_Num).iterations = iter; - end; - info = -Block_Num*10; - return; - end - end - info = 1; - if(is_dynamic) - oo_.deterministic_simulation.status = 1; - oo_.deterministic_simulation.error = max_res; - oo_.deterministic_simulation.iterations = iter; - oo_.deterministic_simulation.block(Block_Num).status = 1; - oo_.deterministic_simulation.block(Block_Num).error = max_res; - oo_.deterministic_simulation.block(Block_Num).iterations = iter; - end; - return; - -function [err, G]=local_fname(yl, x, params, y, y_index_eq, fname, is_csolve) - y(y_index_eq) = yl; - [err, y, G] = feval(fname, y, x, params, 0); - if(is_csolve) - G = full(G); - end; +function [y, info] = solve_one_boundary(fname, y, x, params, y_index_eq, nze, periods, is_linear, Block_Num, y_kmin, maxit_, solve_tolf, lambda, cutoff, stack_solve_algo, forward_backward, is_dynamic, verbose) +% Computes the deterministic simulation of a block of equation containing +% lead or lag variables +% +% INPUTS +% fname [string] name of the file containing the block +% to simulate +% y [matrix] All the endogenous variables of the model +% x [matrix] All the exogenous variables of the model +% params [vector] All the parameters of the model +% y_index_eq [vector of int] The index of the endogenous variables of +% the block +% nze [integer] number of non-zero elements in the +% jacobian matrix +% periods [integer] number of simulation periods +% is_linear [integer] if is_linear=1 the block is linear +% if is_linear=0 the block is not linear +% Block_Num [integer] block number +% y_kmin [integer] maximum number of lag in the model +% maxit_ [integer] maximum number of iteration in Newton +% solve_tolf [double] convergence criteria +% lambda [double] initial value of step size in +% Newton +% cutoff [double] cutoff to correct the direction in Newton in case +% of singular jacobian matrix +% stack_solve_algo [integer] linear solver method used in the +% Newton algorithm : +% - 1 sparse LU +% - 2 GMRES +% - 3 BicGStab +% - 4 Optimal path length +% forward_backward [integer] The block has to be solve forward +% (1) or backward (0) +% is_dynamic [integer] (1) The block belong to the dynamic +% file and the oo_.deterministic_simulation field has to be uptated +% (0) The block belong to the static +% file and th oo_.deteerminstic +% field remains unchanged +% verbose [integer] (0) iterations are not printed +% (1) iterations are printed +% +% OUTPUTS +% y [matrix] All endogenous variables of the model +% +% ALGORITHM +% Newton with LU or GMRES or BicGstab for dynamic block +% +% SPECIAL REQUIREMENTS +% none. +% + +% Copyright (C) 1996-2009 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 <http://www.gnu.org/licenses/>. + + +global oo_ M_ options_; +Blck_size=size(y_index_eq,2); +g2 = []; +g3 = []; +correcting_factor=0.01; +luinc_tol=1e-10; +max_resa=1e100; +reduced = 0; +if(forward_backward) + incr = 1; + start = y_kmin+1; + finish = periods+y_kmin; +else + incr = -1; + start = periods+y_kmin; + finish = y_kmin+1; +end +lambda=1; +for it_=start:incr:finish + cvg=0; + iter=0; + g1=spalloc( Blck_size, Blck_size, nze); + while ~(cvg==1 | iter>maxit_), + if(is_dynamic) + [r, y, g1, g2, g3] = feval(fname, y, x, params, it_, 0); + else + [r, y, g1, g2, g3] = feval(fname, y, x, params, 0); + end; + if(~isreal(r)) + max_res=(-(max(max(abs(r))))^2)^0.5; + else + max_res=max(max(abs(r))); + end; + %['max_res=' num2str(max_res) ' Block_Num=' int2str(Block_Num) ' it_=' int2str(it_)] + %disp(['iteration : ' int2str(iter+1) ' => ' num2str(max_res) ' time = ' int2str(it_)]); + + % fjac = zeros(Blck_size, Blck_size); + % disp(['Blck_size=' int2str(Blck_size) ' it_=' int2str(it_)]); + % dh = max(abs(y(it_, y_index_eq)),options_.gstep*ones(1, Blck_size))*eps^(1/3); + % fvec = r; + % for j = 1:Blck_size + % ydh = y ; + % ydh(it_, y_index_eq(j)) = ydh(it_, y_index_eq(j)) + dh(j) ; + % [t, y1, g11, g21, g31]=feval(fname, ydh, x, params, it_, 0); + % fjac(:,j) = (t - fvec)./dh(j) ; + % end; + % diff = g1 -fjac; + % diff + % disp('g1'); + % disp([num2str(g1,'%4.5f')]); + % disp('fjac'); + % disp([num2str(fjac,'%4.5f')]); + % [c_max, i_c_max] = max(abs(diff)); + % [l_c_max, i_r_max] = max(c_max); + % disp(['maximum element row=' int2str(i_c_max(i_r_max)) ' and column=' int2str(i_r_max) ' value = ' num2str(l_c_max)]); + % equation = i_c_max(i_r_max); + % variable = i_r_max; + % variable + % mod(variable, Blck_size) + % disp(['equation ' int2str(equation) ' and variable ' int2str(y_index_eq(variable)) ' ' M_.endo_names(y_index_eq(variable), :)]); + % disp(['g1(' int2str(equation) ', ' int2str(variable) ')=' num2str(g1(equation, variable),'%3.10f') ' fjac(' int2str(equation) ', ' int2str(variable) ')=' num2str(fjac(equation, variable), '%3.10f') ' y(' int2str(it_) ', ' int2str(variable) ')=' num2str(y(it_, variable))]); + % %return; + % %g1 = fjac; + + + + + + if(verbose==1) + disp(['iteration : ' int2str(iter+1) ' => ' num2str(max_res) ' time = ' int2str(it_)]); + if(is_dynamic) + disp([M_.endo_names(y_index_eq,:) num2str([y(it_,y_index_eq)' r g1])]); + else + disp([M_.endo_names(y_index_eq,:) num2str([y(y_index_eq) r g1])]); + end; + end; + if(~isreal(max_res) | isnan(max_res)) + cvg = 0; + elseif(is_linear & iter>0) + cvg = 1; + else + cvg=(max_res<solve_tolf); + end; + if(~cvg) + if(iter>0) + if(~isreal(max_res) | isnan(max_res) | (max_resa<max_res && iter>1)) + if(isnan(max_res)| (max_resa<max_res && iter>0)) + detJ=det(g1a); + if(abs(detJ)<1e-7) + max_factor=max(max(abs(g1a))); + ze_elem=sum(diag(g1a)<cutoff); + disp([num2str(full(ze_elem),'%d') ' elements on the Jacobian diagonal are below the cutoff (' num2str(cutoff,'%f') ')']); + if(correcting_factor<max_factor) + correcting_factor=correcting_factor*4; + disp(['The Jacobain matrix is singular, det(Jacobian)=' num2str(detJ,'%f') '.']); + disp([' trying to correct the Jacobian matrix:']); + disp([' correcting_factor=' num2str(correcting_factor,'%f') ' max(Jacobian)=' num2str(full(max_factor),'%f')]); + dx = - r/(g1+correcting_factor*speye(Blck_size)); + %dx = -b'/(g1+correcting_factor*speye(Blck_size))-ya_save; + y(it_,y_index_eq)=ya_save+lambda*dx; + continue; + else + disp('The singularity of the jacobian matrix could not be corrected'); + info = -Block_Num*10; + return; + end; + end; + elseif(lambda>1e-8) + lambda=lambda/2; + reduced = 1; + disp(['reducing the path length: lambda=' num2str(lambda,'%f')]); + if(is_dynamic) + y(it_,y_index_eq)=ya_save-lambda*dx; + else + y(y_index_eq)=ya_save-lambda*dx; + end; + continue; + else + if(cutoff == 0) + fprintf('Error in simul: Convergence not achieved in block %d, at time %d, after %d iterations.\n Increase "options_.maxit_".\n',Block_Num, it_, iter); + else + fprintf('Error in simul: Convergence not achieved in block %d, at time %d, after %d iterations.\n Increase "options_.maxit_" or set "cutoff=0" in model options.\n',Block_Num, it_, iter); + end; + if(is_dynamic) + oo_.deterministic_simulation.status = 0; + oo_.deterministic_simulation.error = max_res; + oo_.deterministic_simulation.iterations = iter; + oo_.deterministic_simulation.block(Block_Num).status = 0;% Convergency failed. + oo_.deterministic_simulation.block(Block_Num).error = max_res; + oo_.deterministic_simulation.block(Block_Num).iterations = iter; + end; + info = -Block_Num*10; + return; + end; + else + if(lambda<1) + lambda=max(lambda*2, 1); + end; + end; + end; + if(is_dynamic) + ya = y(it_,y_index_eq)'; + else + ya = y(y_index_eq); + end; + ya_save=ya; + g1a=g1; + if(~is_dynamic & options_.solve_algo == 0) + if exist('OCTAVE_VERSION') || isempty(ver('optim')) + % Note that fsolve() exists under Octave, but has a different syntax + % So we fail for the moment under Octave, until we add the corresponding code + error('DYNARE_SOLVE: you can''t use solve_algo=0 since you don''t have Matlab''s Optimization Toolbox') + end + options=optimset('fsolve'); + options.MaxFunEvals = 50000; + options.MaxIter = 2000; + options.TolFun=1e-8; + options.Display = 'iter'; + options.Jacobian = 'on'; + [yn,fval,exitval,output] = fsolve(@local_fname, y(y_index_eq), options, x, params, y, y_index_eq, fname, 0); + y(y_index_eq) = yn; + if exitval > 0 + info = 0; + else + info = -Block_Num*10; + end + elseif((~is_dynamic & options_.solve_algo==2) || (is_dynamic & stack_solve_algo==4)) + lambda=1; + stpmx = 100 ; + if (is_dynamic) + stpmax = stpmx*max([sqrt(y*y');size(y_index_eq,2)]); + else + stpmax = stpmx*max([sqrt(y'*y);size(y_index_eq,2)]); + end; + nn=1:size(y_index_eq,2); + g = (r'*g1)'; + f = 0.5*r'*r; + p = -g1\r ; + if (is_dynamic) + [y,f,r,check]=lnsrch1(y,f,g,p,stpmax,fname,nn,y_index_eq,x, params, it_, 0); + else + [y,f,r,check]=lnsrch1(y,f,g,p,stpmax,fname,nn,y_index_eq,x, params, 0); + end; + dx = ya - y(y_index_eq); + elseif(~is_dynamic & options_.solve_algo==3) + [yn,info] = csolve(@local_fname, y(y_index_eq),@local_fname,1e-6,500, x, params, y, y_index_eq, fname, 1); + dx = ya - yn; + y(y_index_eq) = yn; + elseif((stack_solve_algo==1 & is_dynamic) | (~is_dynamic & options_.solve_algo==1)), + dx = g1\r; + ya = ya - lambda*dx; + if(is_dynamic) + y(it_,y_index_eq) = ya'; + else + y(y_index_eq) = ya; + end; + elseif(stack_solve_algo==2 & is_dynamic), + flag1=1; + while(flag1>0) + [L1, U1]=luinc(g1,luinc_tol); + [za,flag1] = gmres(g1,-r,Blck_size,1e-6,Blck_size,L1,U1); + %[za,flag1] = gmres(-g1,b',Blck_size,1e-6,Blck_size,L1,U1); + if (flag1>0 | reduced) + if(flag1==1) + disp(['Error in simul: No convergence inside GMRES after ' num2str(iter,'%6d') ' iterations, in block' num2str(Block_Num,'%3d')]); + elseif(flag1==2) + disp(['Error in simul: Preconditioner is ill-conditioned, in block' num2str(Block_Num,'%3d')]); + elseif(flag1==3) + disp(['Error in simul: GMRES stagnated (Two consecutive iterates were the same.), in block' num2str(Block_Num,'%3d')]); + end; + luinc_tol = luinc_tol/10; + reduced = 0; + else + dx = za - ya; + ya = ya + lambda*dx; + if(is_dynamic) + y(it_,y_index_eq) = ya'; + else + y(y_index_eq) = ya'; + end; + end; + end; + elseif(stack_solve_algo==3 & is_dynamic), + flag1=1; + while(flag1>0) + [L1, U1]=luinc(g1,luinc_tol); + [za,flag1] = bicgstab(g1,-r,1e-7,Blck_size,L1,U1); + %[za,flag1] = bicgstab(-g1,b',1e-7,Blck_size,L1,U1); + if (flag1>0 | reduced) + if(flag1==1) + disp(['Error in simul: No convergence inside BICGSTAB after ' num2str(iter,'%6d') ' iterations, in block' num2str(Block_Num,'%3d')]); + elseif(flag1==2) + disp(['Error in simul: Preconditioner is ill-conditioned, in block' num2str(Block_Num,'%3d')]); + elseif(flag1==3) + disp(['Error in simul: GMRES stagnated (Two consecutive iterates were the same.), in block' num2str(Block_Num,'%3d')]); + end; + luinc_tol = luinc_tol/10; + reduced = 0; + else + dx = za - ya; + ya = ya + lambda*dx; + if(is_dynamic) + y(it_,y_index_eq) = ya'; + else + y(y_index_eq) = ya'; + end; + end; + end; + else + disp('unknown option : '); + if(is_dynamic) + disp(['options_.stack_solve_algo = ' num2str(stack_solve_algo) ' not implemented']); + else + disp(['options_.solve_algo = ' num2str(options_.solve_algo) ' not implemented']); + end; + info = -Block_Num*10; + return; + end; + iter=iter+1; + max_resa = max_res; + end + end + if cvg==0 + if(cutoff == 0) + fprintf('Error in simul: Convergence not achieved in block %d, at time %d, after %d iterations.\n Increase "options_.maxit_\".\n',Block_Num, it_,iter); + else + fprintf('Error in simul: Convergence not achieved in block %d, at time %d, after %d iterations.\n Increase "options_.maxit_" or set "cutoff=0" in model options.\n',Block_Num, it_,iter); + end; + if(is_dynamic) + oo_.deterministic_simulation.status = 0; + oo_.deterministic_simulation.error = max_res; + oo_.deterministic_simulation.iterations = iter; + oo_.deterministic_simulation.block(Block_Num).status = 0;% Convergency failed. + oo_.deterministic_simulation.block(Block_Num).error = max_res; + oo_.deterministic_simulation.block(Block_Num).iterations = iter; + end; + info = -Block_Num*10; + return; + end +end +info = 1; +if(is_dynamic) + oo_.deterministic_simulation.status = 1; + oo_.deterministic_simulation.error = max_res; + oo_.deterministic_simulation.iterations = iter; + oo_.deterministic_simulation.block(Block_Num).status = 1; + oo_.deterministic_simulation.block(Block_Num).error = max_res; + oo_.deterministic_simulation.block(Block_Num).iterations = iter; +end; +return; + +function [err, G]=local_fname(yl, x, params, y, y_index_eq, fname, is_csolve) +y(y_index_eq) = yl; +[err, y, G] = feval(fname, y, x, params, 0); +if(is_csolve) + G = full(G); +end; diff --git a/matlab/solve_two_boundaries.m b/matlab/solve_two_boundaries.m index 9e630d9dd3..9b54d530cf 100644 --- a/matlab/solve_two_boundaries.m +++ b/matlab/solve_two_boundaries.m @@ -1,289 +1,289 @@ -function y = solve_two_boundaries(fname, y, x, params, y_index, nze, periods, y_kmin_l, y_kmax_l, is_linear, Block_Num, y_kmin, maxit_, solve_tolf, lambda, cutoff, stack_solve_algo) -% Computes the deterministic simulation of a block of equation containing -% both lead and lag variables using relaxation methods -% -% INPUTS -% fname [string] name of the file containing the block -% to simulate -% y [matrix] All the endogenous variables of the model -% x [matrix] All the exogenous variables of the model -% params [vector] All the parameters of the model -% y_index [vector of int] The index of the endogenous variables of -% the block -% nze [integer] number of non-zero elements in the -% jacobian matrix -% periods [integer] number of simulation periods -% y_kmin_l [integer] maximum number of lag in the block -% y_kmax_l [integer] maximum number of lead in the block -% is_linear [integer] if is_linear=1 the block is linear -% if is_linear=0 the block is not linear -% Block_Num [integer] block number -% y_kmin [integer] maximum number of lag in the model -% maxit_ [integer] maximum number of iteration in Newton -% solve_tolf [double] convergence criteria -% lambda [double] initial value of step size in -% Newton -% cutoff [double] cutoff to correct the direction in Newton in case -% of singular jacobian matrix -% stack_solve_algo [integer] linear solver method used in the -% Newton algorithm : -% - 1 sprse LU -% - 2 GMRES -% - 3 BicGStab -% - 4 Optimal path length -% -% OUTPUTS -% y [matrix] All endogenous variables of the model -% -% ALGORITHM -% Newton with LU or GMRES or BicGstab -% -% SPECIAL REQUIREMENTS -% none. -% - -% Copyright (C) 1996-2009 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 <http://www.gnu.org/licenses/>. - - global oo_ M_; - cvg=0; - iter=0; - Per_u_=0; - g2 = []; - g3 = []; - Blck_size=size(y_index,2); - correcting_factor=0.01; - luinc_tol=1e-10; - max_resa=1e100; - Jacobian_Size=Blck_size*(y_kmin+y_kmax_l +periods); - g1=spalloc( Blck_size*periods, Jacobian_Size, nze*periods); - reduced = 0; - while ~(cvg==1 | iter>maxit_), - [r, y, g1, g2, g3, b]=feval(fname, y, x, params, periods, 0, y_kmin, Blck_size); -% fjac = zeros(Blck_size, Blck_size*(y_kmin_l+1+y_kmax_l)); -% disp(['Blck_size=' int2str(Blck_size) ' size(y_index)=' int2str(size(y_index,2))]); -% dh = max(abs(y(y_kmin+1-y_kmin_l:y_kmin+1+y_kmax_l, y_index)),options_.gstep*ones(y_kmin_l+1+y_kmax_l, Blck_size))*eps^(1/3); -% fvec = r; -% %for i = y_kmin+1-y_kmin_l:y_kmin+1+y_kmax_l -% i = y_kmin+1; -% i -% for j = 1:Blck_size -% ydh = y ; -% ydh(i, y_index(j)) = ydh(i, y_index(j)) + dh(i, j) ; -% if(j==11 && i==2) -% disp(['y(i,y_index(11)=' int2str(y_index(11)) ')= ' num2str(y(i,y_index(11))) ' ydh(i, y_index(j))=' num2str(ydh(i, y_index(j))) ' dh(i,j)= ' num2str(dh(i,j))]); -% end; -% [t, y1, g11, g21, g31, b1]=feval(fname, ydh, x, params, periods, 0, y_kmin, Blck_size); -% fjac(:,j+(i-(y_kmin+1-y_kmin_l))*Blck_size) = (t(:, 1+y_kmin) - fvec(:, 1+y_kmin))./dh(i, j) ; -% if(j==11 && i==2) -% disp(['fjac(:,' int2str(j+(i-(y_kmin+1-y_kmin_l))*Blck_size) ')=']); -% disp([num2str(fjac(:,j+(i-(y_kmin+1-y_kmin_l))*Blck_size))]); -% end; -% end; -% % end -% %diff = g1(1:Blck_size, 1:Blck_size*(y_kmin_l+1+y_kmax_l)) -fjac; -% diff = g1(1:Blck_size, y_kmin_l*Blck_size+1:(y_kmin_l+1)*Blck_size) -fjac(1:Blck_size, y_kmin_l*Blck_size+1:(y_kmin_l+1)*Blck_size); -% disp(diff); -% [c_max, i_c_max] = max(abs(diff)); -% [l_c_max, i_r_max] = max(c_max); -% disp(['maximum element row=' int2str(i_c_max(i_r_max)) ' and column=' int2str(i_r_max) ' value = ' num2str(l_c_max)]); -% equation = i_c_max(i_r_max); -% variable = i_r_max; -% variable -% disp(['equation ' int2str(equation) ' and variable ' int2str(y_index(mod(variable, Blck_size))) ' ' M_.endo_names(y_index(mod(variable, Blck_size)), :)]); -% disp(['g1(' int2str(equation) ', ' int2str(variable) ')=' num2str(g1(equation, y_kmin_l*Blck_size+variable),'%3.10f') ' fjac(' int2str(equation) ', ' int2str(variable) ')=' num2str(fjac(equation, y_kmin_l*Blck_size+variable), '%3.10f')]); -% return; - - - -% for i=1:periods; -% disp([sprintf('%5.14f ',[T9025(i) T1149(i) T11905(i)])]); -% end; -% return; - %residual = r(:,y_kmin+1:y_kmin+1+y_kmax_l); - %num2str(residual,' %1.6f') - %jac_ = g1(1:(y_kmin)*Blck_size, 1:(y_kmin+1+y_kmax_l)*Blck_size); - %jac_ - - g1a=g1(:, y_kmin*Blck_size+1:(periods+y_kmin)*Blck_size); - term1 = g1(:, 1:y_kmin_l*Blck_size)*reshape(y(1+y_kmin-y_kmin_l:y_kmin,y_index)',1,y_kmin_l*Blck_size)'; - term2 = g1(:, (periods+y_kmin_l)*Blck_size+1:(periods+y_kmin_l+y_kmax_l)*Blck_size)*reshape(y(periods+y_kmin+1:periods+y_kmin+y_kmax_l,y_index)',1,y_kmax_l*Blck_size)'; - b = b - term1 - term2; - -% fid = fopen(['result' num2str(iter)],'w'); -% fg1a = full(g1a); -% fprintf(fid,'%d\n',size(fg1a,1)); -% fprintf(fid,'%d\n',size(fg1a,2)); -% fprintf(fid,'%5.14f\n',fg1a); -% fprintf(fid,'%d\n',size(b,1)); -% fprintf(fid,'%5.14f\n',b); -% fclose(fid); -% return; - %ipconfigb_ = b(1:(1+y_kmin)*Blck_size); - %b_ - - - [max_res, max_indx]=max(max(abs(r'))); - if(~isreal(r)) - max_res = (-max_res^2)^0.5; - end; -% if(~isreal(r)) -% max_res=(-(max(max(abs(r))))^2)^0.5; -% else -% max_res=max(max(abs(r))); -% end; - if(~isreal(max_res) | isnan(max_res)) - cvg = 0; - elseif(is_linear & iter>0) - cvg = 1; - else - cvg=(max_res<solve_tolf); - end; - if(~cvg) - if(iter>0) - if(~isreal(max_res) | isnan(max_res) | (max_resa<max_res && iter>1)) - if(~isreal(max_res)) - disp(['Variable ' M_.endo_names(max_indx,:) ' (' int2str(max_indx) ') returns an undefined value']); - end; - if(isnan(max_res)) - detJ=det(g1aa); - if(abs(detJ)<1e-7) - max_factor=max(max(abs(g1aa))); - ze_elem=sum(diag(g1aa)<cutoff); - disp([num2str(full(ze_elem),'%d') ' elements on the Jacobian diagonal are below the cutoff (' num2str(cutoff,'%f') ')']); - if(correcting_factor<max_factor) - correcting_factor=correcting_factor*4; - disp(['The Jacobain matrix is singular, det(Jacobian)=' num2str(detJ,'%f') '.']); - disp([' trying to correct the Jacobian matrix:']); - disp([' correcting_factor=' num2str(correcting_factor,'%f') ' max(Jacobian)=' num2str(full(max_factor),'%f')]); - dx = (g1aa+correcting_factor*speye(periods*Blck_size))\ba- ya; - y(1+y_kmin:periods+y_kmin,y_index)=reshape((ya_save+lambda*dx)',length(y_index),periods)'; - continue; - else - disp('The singularity of the jacobian matrix could not be corrected'); - return; - end; - end; - elseif(lambda>1e-8) - lambda=lambda/2; - reduced = 1; - disp(['reducing the path length: lambda=' num2str(lambda,'%f')]); - y(1+y_kmin:periods+y_kmin,y_index)=reshape((ya_save+lambda*dx)',length(y_index),periods)'; - continue; - else - if(cutoff == 0) - fprintf('Error in simul: Convergence not achieved in block %d, after %d iterations.\n Increase "options_.maxit_".\n',Block_Num, iter); - else - fprintf('Error in simul: Convergence not achieved in block %d, after %d iterations.\n Increase "options_.maxit_" or set "cutoff=0" in model options.\n',Block_Num, iter); - end; - oo_.deterministic_simulation.status = 0; - oo_.deterministic_simulation.error = max_res; - oo_.deterministic_simulation.iterations = iter; - oo_.deterministic_simulation.block(Block_Num).status = 0;% Convergency failed. - oo_.deterministic_simulation.block(Block_Num).error = max_res; - oo_.deterministic_simulation.block(Block_Num).iterations = iter; - return; - end; - else - if(lambda<1) - lambda=max(lambda*2, 1); - end; - end; - end; - ya = reshape(y(y_kmin+1:y_kmin+periods,y_index)',1,periods*Blck_size)'; - ya_save=ya; - g1aa=g1a; - ba=b; - max_resa=max_res; - if(stack_solve_algo==1), - dx = g1a\b- ya; - ya = ya + lambda*dx; - y(1+y_kmin:periods+y_kmin,y_index)=reshape(ya',length(y_index),periods)'; -% v = ''; -% for i=1:(size(y_index,2)) -% v = [v ' %1.6f']; -% end; -% v = [v '\n']; -% v -% sprintf(v,y(:,y_index)') -% return; - elseif(stack_solve_algo==2), - flag1=1; - while(flag1>0) - [L1, U1]=luinc(g1a,luinc_tol); - [za,flag1] = gmres(g1a,b,Blck_size,1e-6,Blck_size*periods,L1,U1); - if (flag1>0 | reduced) - if(flag1==1) - disp(['Error in simul: No convergence inside GMRES after ' num2str(periods*10,'%6d') ' iterations, in block' num2str(Block_Size,'%3d')]); - elseif(flag1==2) - disp(['Error in simul: Preconditioner is ill-conditioned, in block' num2str(Block_Size,'%3d')]); - elseif(flag1==3) - disp(['Error in simul: GMRES stagnated (Two consecutive iterates were the same.), in block' num2str(Block_Size,'%3d')]); - end; - luinc_tol = luinc_tol/10; - reduced = 0; - else - dx = za - ya; - ya = ya + lambda*dx; - y(1+y_kmin:periods+y_kmin,y_index)=reshape(ya',length(y_index),periods)'; - end; - end; - elseif(stack_solve_algo==3), - flag1=1; - while(flag1>0) - [L1, U1]=luinc(g1a,luinc_tol); - [za,flag1] = bicgstab(g1a,b,1e-7,Blck_size*periods,L1,U1); - if (flag1>0 | reduced) - if(flag1==1) - disp(['Error in simul: No convergence inside BICGSTAB after ' num2str(periods*10,'%6d') ' iterations, in block' num2str(Block_Size,'%3d')]); - elseif(flag1==2) - disp(['Error in simul: Preconditioner is ill-conditioned, in block' num2str(Block_Size,'%3d')]); - elseif(flag1==3) - disp(['Error in simul: GMRES stagnated (Two consecutive iterates were the same.), in block' num2str(Block_Size,'%3d')]); - end; - luinc_tol = luinc_tol/10; - reduced = 0; - else - dx = za - ya; - ya = ya + lambda*dx; - y(1+y_kmin:periods+y_kmin,y_index)=reshape(ya',length(y_index),periods)'; - end; - end; - elseif(stack_solve_algo==4), - error('SOLVE_TWO_BOUNDARIES: stack_solve_algo=4 not implemented') - end; - end - iter=iter+1; - disp(['iteration: ' num2str(iter,'%d') ' error: ' num2str(max_res,'%e')]); - end; - if (iter>maxit_) - disp(['No convergence after ' num2str(iter,'%4d') ' iterations in Block ' num2str(Block_Num,'%d')]); - oo_.deterministic_simulation.status = 0; - oo_.deterministic_simulation.error = max_res; - oo_.deterministic_simulation.iterations = iter; - oo_.deterministic_simulation.block(Block_Num).status = 0;% Convergency failed. - oo_.deterministic_simulation.block(Block_Num).error = max_res; - oo_.deterministic_simulation.block(Block_Num).iterations = iter; - return; - end - oo_.deterministic_simulation.status = 1; - oo_.deterministic_simulation.error = max_res; - oo_.deterministic_simulation.iterations = iter; - oo_.deterministic_simulation.block(Block_Num).status = 1;% Convergency obtained. - oo_.deterministic_simulation.block(Block_Num).error = max_res; - oo_.deterministic_simulation.block(Block_Num).iterations = iter; - return; +function y = solve_two_boundaries(fname, y, x, params, y_index, nze, periods, y_kmin_l, y_kmax_l, is_linear, Block_Num, y_kmin, maxit_, solve_tolf, lambda, cutoff, stack_solve_algo) +% Computes the deterministic simulation of a block of equation containing +% both lead and lag variables using relaxation methods +% +% INPUTS +% fname [string] name of the file containing the block +% to simulate +% y [matrix] All the endogenous variables of the model +% x [matrix] All the exogenous variables of the model +% params [vector] All the parameters of the model +% y_index [vector of int] The index of the endogenous variables of +% the block +% nze [integer] number of non-zero elements in the +% jacobian matrix +% periods [integer] number of simulation periods +% y_kmin_l [integer] maximum number of lag in the block +% y_kmax_l [integer] maximum number of lead in the block +% is_linear [integer] if is_linear=1 the block is linear +% if is_linear=0 the block is not linear +% Block_Num [integer] block number +% y_kmin [integer] maximum number of lag in the model +% maxit_ [integer] maximum number of iteration in Newton +% solve_tolf [double] convergence criteria +% lambda [double] initial value of step size in +% Newton +% cutoff [double] cutoff to correct the direction in Newton in case +% of singular jacobian matrix +% stack_solve_algo [integer] linear solver method used in the +% Newton algorithm : +% - 1 sprse LU +% - 2 GMRES +% - 3 BicGStab +% - 4 Optimal path length +% +% OUTPUTS +% y [matrix] All endogenous variables of the model +% +% ALGORITHM +% Newton with LU or GMRES or BicGstab +% +% SPECIAL REQUIREMENTS +% none. +% + +% Copyright (C) 1996-2009 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 <http://www.gnu.org/licenses/>. + +global oo_ M_; +cvg=0; +iter=0; +Per_u_=0; +g2 = []; +g3 = []; +Blck_size=size(y_index,2); +correcting_factor=0.01; +luinc_tol=1e-10; +max_resa=1e100; +Jacobian_Size=Blck_size*(y_kmin+y_kmax_l +periods); +g1=spalloc( Blck_size*periods, Jacobian_Size, nze*periods); +reduced = 0; +while ~(cvg==1 | iter>maxit_), + [r, y, g1, g2, g3, b]=feval(fname, y, x, params, periods, 0, y_kmin, Blck_size); + % fjac = zeros(Blck_size, Blck_size*(y_kmin_l+1+y_kmax_l)); + % disp(['Blck_size=' int2str(Blck_size) ' size(y_index)=' int2str(size(y_index,2))]); + % dh = max(abs(y(y_kmin+1-y_kmin_l:y_kmin+1+y_kmax_l, y_index)),options_.gstep*ones(y_kmin_l+1+y_kmax_l, Blck_size))*eps^(1/3); + % fvec = r; + % %for i = y_kmin+1-y_kmin_l:y_kmin+1+y_kmax_l + % i = y_kmin+1; + % i + % for j = 1:Blck_size + % ydh = y ; + % ydh(i, y_index(j)) = ydh(i, y_index(j)) + dh(i, j) ; + % if(j==11 && i==2) + % disp(['y(i,y_index(11)=' int2str(y_index(11)) ')= ' num2str(y(i,y_index(11))) ' ydh(i, y_index(j))=' num2str(ydh(i, y_index(j))) ' dh(i,j)= ' num2str(dh(i,j))]); + % end; + % [t, y1, g11, g21, g31, b1]=feval(fname, ydh, x, params, periods, 0, y_kmin, Blck_size); + % fjac(:,j+(i-(y_kmin+1-y_kmin_l))*Blck_size) = (t(:, 1+y_kmin) - fvec(:, 1+y_kmin))./dh(i, j) ; + % if(j==11 && i==2) + % disp(['fjac(:,' int2str(j+(i-(y_kmin+1-y_kmin_l))*Blck_size) ')=']); + % disp([num2str(fjac(:,j+(i-(y_kmin+1-y_kmin_l))*Blck_size))]); + % end; + % end; + % % end + % %diff = g1(1:Blck_size, 1:Blck_size*(y_kmin_l+1+y_kmax_l)) -fjac; + % diff = g1(1:Blck_size, y_kmin_l*Blck_size+1:(y_kmin_l+1)*Blck_size) -fjac(1:Blck_size, y_kmin_l*Blck_size+1:(y_kmin_l+1)*Blck_size); + % disp(diff); + % [c_max, i_c_max] = max(abs(diff)); + % [l_c_max, i_r_max] = max(c_max); + % disp(['maximum element row=' int2str(i_c_max(i_r_max)) ' and column=' int2str(i_r_max) ' value = ' num2str(l_c_max)]); + % equation = i_c_max(i_r_max); + % variable = i_r_max; + % variable + % disp(['equation ' int2str(equation) ' and variable ' int2str(y_index(mod(variable, Blck_size))) ' ' M_.endo_names(y_index(mod(variable, Blck_size)), :)]); + % disp(['g1(' int2str(equation) ', ' int2str(variable) ')=' num2str(g1(equation, y_kmin_l*Blck_size+variable),'%3.10f') ' fjac(' int2str(equation) ', ' int2str(variable) ')=' num2str(fjac(equation, y_kmin_l*Blck_size+variable), '%3.10f')]); + % return; + + + + % for i=1:periods; + % disp([sprintf('%5.14f ',[T9025(i) T1149(i) T11905(i)])]); + % end; + % return; + %residual = r(:,y_kmin+1:y_kmin+1+y_kmax_l); + %num2str(residual,' %1.6f') + %jac_ = g1(1:(y_kmin)*Blck_size, 1:(y_kmin+1+y_kmax_l)*Blck_size); + %jac_ + + g1a=g1(:, y_kmin*Blck_size+1:(periods+y_kmin)*Blck_size); + term1 = g1(:, 1:y_kmin_l*Blck_size)*reshape(y(1+y_kmin-y_kmin_l:y_kmin,y_index)',1,y_kmin_l*Blck_size)'; + term2 = g1(:, (periods+y_kmin_l)*Blck_size+1:(periods+y_kmin_l+y_kmax_l)*Blck_size)*reshape(y(periods+y_kmin+1:periods+y_kmin+y_kmax_l,y_index)',1,y_kmax_l*Blck_size)'; + b = b - term1 - term2; + + % fid = fopen(['result' num2str(iter)],'w'); + % fg1a = full(g1a); + % fprintf(fid,'%d\n',size(fg1a,1)); + % fprintf(fid,'%d\n',size(fg1a,2)); + % fprintf(fid,'%5.14f\n',fg1a); + % fprintf(fid,'%d\n',size(b,1)); + % fprintf(fid,'%5.14f\n',b); + % fclose(fid); + % return; + %ipconfigb_ = b(1:(1+y_kmin)*Blck_size); + %b_ + + + [max_res, max_indx]=max(max(abs(r'))); + if(~isreal(r)) + max_res = (-max_res^2)^0.5; + end; + % if(~isreal(r)) + % max_res=(-(max(max(abs(r))))^2)^0.5; + % else + % max_res=max(max(abs(r))); + % end; + if(~isreal(max_res) | isnan(max_res)) + cvg = 0; + elseif(is_linear & iter>0) + cvg = 1; + else + cvg=(max_res<solve_tolf); + end; + if(~cvg) + if(iter>0) + if(~isreal(max_res) | isnan(max_res) | (max_resa<max_res && iter>1)) + if(~isreal(max_res)) + disp(['Variable ' M_.endo_names(max_indx,:) ' (' int2str(max_indx) ') returns an undefined value']); + end; + if(isnan(max_res)) + detJ=det(g1aa); + if(abs(detJ)<1e-7) + max_factor=max(max(abs(g1aa))); + ze_elem=sum(diag(g1aa)<cutoff); + disp([num2str(full(ze_elem),'%d') ' elements on the Jacobian diagonal are below the cutoff (' num2str(cutoff,'%f') ')']); + if(correcting_factor<max_factor) + correcting_factor=correcting_factor*4; + disp(['The Jacobain matrix is singular, det(Jacobian)=' num2str(detJ,'%f') '.']); + disp([' trying to correct the Jacobian matrix:']); + disp([' correcting_factor=' num2str(correcting_factor,'%f') ' max(Jacobian)=' num2str(full(max_factor),'%f')]); + dx = (g1aa+correcting_factor*speye(periods*Blck_size))\ba- ya; + y(1+y_kmin:periods+y_kmin,y_index)=reshape((ya_save+lambda*dx)',length(y_index),periods)'; + continue; + else + disp('The singularity of the jacobian matrix could not be corrected'); + return; + end; + end; + elseif(lambda>1e-8) + lambda=lambda/2; + reduced = 1; + disp(['reducing the path length: lambda=' num2str(lambda,'%f')]); + y(1+y_kmin:periods+y_kmin,y_index)=reshape((ya_save+lambda*dx)',length(y_index),periods)'; + continue; + else + if(cutoff == 0) + fprintf('Error in simul: Convergence not achieved in block %d, after %d iterations.\n Increase "options_.maxit_".\n',Block_Num, iter); + else + fprintf('Error in simul: Convergence not achieved in block %d, after %d iterations.\n Increase "options_.maxit_" or set "cutoff=0" in model options.\n',Block_Num, iter); + end; + oo_.deterministic_simulation.status = 0; + oo_.deterministic_simulation.error = max_res; + oo_.deterministic_simulation.iterations = iter; + oo_.deterministic_simulation.block(Block_Num).status = 0;% Convergency failed. + oo_.deterministic_simulation.block(Block_Num).error = max_res; + oo_.deterministic_simulation.block(Block_Num).iterations = iter; + return; + end; + else + if(lambda<1) + lambda=max(lambda*2, 1); + end; + end; + end; + ya = reshape(y(y_kmin+1:y_kmin+periods,y_index)',1,periods*Blck_size)'; + ya_save=ya; + g1aa=g1a; + ba=b; + max_resa=max_res; + if(stack_solve_algo==1), + dx = g1a\b- ya; + ya = ya + lambda*dx; + y(1+y_kmin:periods+y_kmin,y_index)=reshape(ya',length(y_index),periods)'; + % v = ''; + % for i=1:(size(y_index,2)) + % v = [v ' %1.6f']; + % end; + % v = [v '\n']; + % v + % sprintf(v,y(:,y_index)') + % return; + elseif(stack_solve_algo==2), + flag1=1; + while(flag1>0) + [L1, U1]=luinc(g1a,luinc_tol); + [za,flag1] = gmres(g1a,b,Blck_size,1e-6,Blck_size*periods,L1,U1); + if (flag1>0 | reduced) + if(flag1==1) + disp(['Error in simul: No convergence inside GMRES after ' num2str(periods*10,'%6d') ' iterations, in block' num2str(Block_Size,'%3d')]); + elseif(flag1==2) + disp(['Error in simul: Preconditioner is ill-conditioned, in block' num2str(Block_Size,'%3d')]); + elseif(flag1==3) + disp(['Error in simul: GMRES stagnated (Two consecutive iterates were the same.), in block' num2str(Block_Size,'%3d')]); + end; + luinc_tol = luinc_tol/10; + reduced = 0; + else + dx = za - ya; + ya = ya + lambda*dx; + y(1+y_kmin:periods+y_kmin,y_index)=reshape(ya',length(y_index),periods)'; + end; + end; + elseif(stack_solve_algo==3), + flag1=1; + while(flag1>0) + [L1, U1]=luinc(g1a,luinc_tol); + [za,flag1] = bicgstab(g1a,b,1e-7,Blck_size*periods,L1,U1); + if (flag1>0 | reduced) + if(flag1==1) + disp(['Error in simul: No convergence inside BICGSTAB after ' num2str(periods*10,'%6d') ' iterations, in block' num2str(Block_Size,'%3d')]); + elseif(flag1==2) + disp(['Error in simul: Preconditioner is ill-conditioned, in block' num2str(Block_Size,'%3d')]); + elseif(flag1==3) + disp(['Error in simul: GMRES stagnated (Two consecutive iterates were the same.), in block' num2str(Block_Size,'%3d')]); + end; + luinc_tol = luinc_tol/10; + reduced = 0; + else + dx = za - ya; + ya = ya + lambda*dx; + y(1+y_kmin:periods+y_kmin,y_index)=reshape(ya',length(y_index),periods)'; + end; + end; + elseif(stack_solve_algo==4), + error('SOLVE_TWO_BOUNDARIES: stack_solve_algo=4 not implemented') + end; + end + iter=iter+1; + disp(['iteration: ' num2str(iter,'%d') ' error: ' num2str(max_res,'%e')]); +end; +if (iter>maxit_) + disp(['No convergence after ' num2str(iter,'%4d') ' iterations in Block ' num2str(Block_Num,'%d')]); + oo_.deterministic_simulation.status = 0; + oo_.deterministic_simulation.error = max_res; + oo_.deterministic_simulation.iterations = iter; + oo_.deterministic_simulation.block(Block_Num).status = 0;% Convergency failed. + oo_.deterministic_simulation.block(Block_Num).error = max_res; + oo_.deterministic_simulation.block(Block_Num).iterations = iter; + return; +end +oo_.deterministic_simulation.status = 1; +oo_.deterministic_simulation.error = max_res; +oo_.deterministic_simulation.iterations = iter; +oo_.deterministic_simulation.block(Block_Num).status = 1;% Convergency obtained. +oo_.deterministic_simulation.block(Block_Num).error = max_res; +oo_.deterministic_simulation.block(Block_Num).iterations = iter; +return; diff --git a/matlab/steady.m b/matlab/steady.m index 785e229289..5c92f2d7cf 100644 --- a/matlab/steady.m +++ b/matlab/steady.m @@ -28,44 +28,44 @@ function steady() % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ oo_ options_ ys0_ +global M_ oo_ options_ ys0_ - options_ = set_default_option(options_,'jacobian_flag',1); - options_ = set_default_option(options_,'steadystate_flag',0); - if exist([M_.fname '_steadystate.m']) +options_ = set_default_option(options_,'jacobian_flag',1); +options_ = set_default_option(options_,'steadystate_flag',0); +if exist([M_.fname '_steadystate.m']) options_.steadystate_flag = 1; - end +end - if options_.steadystate_flag && options_.homotopy_mode +if options_.steadystate_flag && options_.homotopy_mode error('STEADY: Can''t use homotopy when providing a steady state external file'); - end - - switch options_.homotopy_mode - case 1 - homotopy1(options_.homotopy_values, options_.homotopy_steps); - case 2 - homotopy2(options_.homotopy_values, options_.homotopy_steps); - case 3 - homotopy3(options_.homotopy_values, options_.homotopy_steps); - end - - steady_; - - disp(' ') - disp('STEADY-STATE RESULTS:') - disp(' ') - endo_names = M_.endo_names; - steady_state = oo_.steady_state; - for i=1:M_.orig_endo_nbr +end + +switch options_.homotopy_mode + case 1 + homotopy1(options_.homotopy_values, options_.homotopy_steps); + case 2 + homotopy2(options_.homotopy_values, options_.homotopy_steps); + case 3 + homotopy3(options_.homotopy_values, options_.homotopy_steps); +end + +steady_; + +disp(' ') +disp('STEADY-STATE RESULTS:') +disp(' ') +endo_names = M_.endo_names; +steady_state = oo_.steady_state; +for i=1:M_.orig_endo_nbr disp(sprintf('%s \t\t %g',endo_names(i,:),steady_state(i))); - end - +end + - if isempty(ys0_) - oo_.endo_simul(:,1:M_.maximum_lag) = oo_.steady_state * ones(1, M_.maximum_lag); - %%% Unless I'm wrong, this is (should be?) done in make_y_.m +if isempty(ys0_) + oo_.endo_simul(:,1:M_.maximum_lag) = oo_.steady_state * ones(1, M_.maximum_lag); + %%% Unless I'm wrong, this is (should be?) done in make_y_.m % $$$ else % $$$ options_ =set_default_option(options_,'periods',1); % $$$ oo_.endo_simul(:,M_.maximum_lag+1:M_.maximum_lag+options_.periods+ ... % $$$ M_.maximum_lead) = oo_.steady_state * ones(1,options_.periods+M_.maximum_lead); - end \ No newline at end of file +end \ No newline at end of file diff --git a/matlab/steady_.m b/matlab/steady_.m index b8f34d9860..8593130c7e 100644 --- a/matlab/steady_.m +++ b/matlab/steady_.m @@ -27,20 +27,20 @@ function steady_() % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ oo_ it_ options_ - - if options_.bytecode && options_.solve_algo ~= 5 - error('STEADY: for the moment, you must use solve_algo=5 with bytecode option') - end - if ~options_.bytecode && options_.solve_algo == 5 - error('STEADY: you can''t yet use solve_algo=5 without bytecode option') - end - - if options_.steadystate_flag +global M_ oo_ it_ options_ + +if options_.bytecode && options_.solve_algo ~= 5 + error('STEADY: for the moment, you must use solve_algo=5 with bytecode option') +end +if ~options_.bytecode && options_.solve_algo == 5 + error('STEADY: you can''t yet use solve_algo=5 without bytecode option') +end + +if options_.steadystate_flag [ys,check] = feval([M_.fname '_steadystate'],... - oo_.steady_state,... - [oo_.exo_steady_state; ... - oo_.exo_det_steady_state]); + oo_.steady_state,... + [oo_.exo_steady_state; ... + oo_.exo_det_steady_state]); if size(ys,1) < M_.endo_nbr if length(M_.aux_vars) > 0 ys = add_auxiliary_variables_to_steadystate(ys,M_.aux_vars,... @@ -90,44 +90,44 @@ function steady_() '_steadystate.m don''t solve the static model!' ]) end if ~isempty(options_.steadystate_partial) - ssvar = options_.steadystate_partial.ssvar; - nov = length(ssvar); - indv = zeros(nov,1); - for i = 1:nov - indv(i) = strmatch(ssvar(i),M_.endo_names,'exact'); - end - [oo_.steady_state,check] = dynare_solve('restricted_steadystate',... - oo_.steady_state(indv),... - options_.jacobian_flag, ... - [oo_.exo_steady_state;oo_.exo_det_steady_state],indv); + ssvar = options_.steadystate_partial.ssvar; + nov = length(ssvar); + indv = zeros(nov,1); + for i = 1:nov + indv(i) = strmatch(ssvar(i),M_.endo_names,'exact'); + end + [oo_.steady_state,check] = dynare_solve('restricted_steadystate',... + oo_.steady_state(indv),... + options_.jacobian_flag, ... + [oo_.exo_steady_state;oo_.exo_det_steady_state],indv); end - elseif options_.block && ~options_.bytecode +elseif options_.block && ~options_.bytecode for b = 1:size(M_.blocksMFS,1) - n = size(M_.blocksMFS{b}, 1); - ss = oo_.steady_state; - if n ~= 0 - [y, check] = dynare_solve('block_mfs_steadystate', ... - ss(M_.blocksMFS{b}), ... - options_.jacobian_flag, b); - if check ~= 0 - error(['STEADY: convergence problems in block ' int2str(b)]) + n = size(M_.blocksMFS{b}, 1); + ss = oo_.steady_state; + if n ~= 0 + [y, check] = dynare_solve('block_mfs_steadystate', ... + ss(M_.blocksMFS{b}), ... + options_.jacobian_flag, b); + if check ~= 0 + error(['STEADY: convergence problems in block ' int2str(b)]) + end + ss(M_.blocksMFS{b}) = y; end - ss(M_.blocksMFS{b}) = y; - end - [r, g1, oo_.steady_state] = feval([M_.fname '_static'], b, ss, ... - [oo_.exo_steady_state; ... - oo_.exo_det_steady_state], M_.params); + [r, g1, oo_.steady_state] = feval([M_.fname '_static'], b, ss, ... + [oo_.exo_steady_state; ... + oo_.exo_det_steady_state], M_.params); end - elseif options_.block && options_.bytecode - [oo_.steady_state,check] = bytecode('static'); - else +elseif options_.block && options_.bytecode + [oo_.steady_state,check] = bytecode('static'); +else [oo_.steady_state,check] = dynare_solve([M_.fname '_static'],... - oo_.steady_state,... - options_.jacobian_flag, ... - [oo_.exo_steady_state; ... - oo_.exo_det_steady_state], M_.params); - end + oo_.steady_state,... + options_.jacobian_flag, ... + [oo_.exo_steady_state; ... + oo_.exo_det_steady_state], M_.params); +end - if check ~= 0 +if check ~= 0 error('STEADY: convergence problems') - end +end diff --git a/matlab/stoch_simul.m b/matlab/stoch_simul.m index f7c1321cb3..725b187693 100644 --- a/matlab/stoch_simul.m +++ b/matlab/stoch_simul.m @@ -17,37 +17,37 @@ function info=stoch_simul(var_list) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ options_ oo_ it_ +global M_ options_ oo_ it_ - options_old = options_; - if options_.linear - options_.order = 1; - end - if options_.order == 1 - options_.replic = 1; - elseif options_.order == 3 - options_.k_order_solver = 1; - end - +options_old = options_; +if options_.linear + options_.order = 1; +end +if options_.order == 1 + options_.replic = 1; +elseif options_.order == 3 + options_.k_order_solver = 1; +end - TeX = options_.TeX; - iter_ = max(options_.periods,1); - if M_.exo_nbr > 0 +TeX = options_.TeX; + +iter_ = max(options_.periods,1); +if M_.exo_nbr > 0 oo_.exo_simul= ones(iter_ + M_.maximum_lag + M_.maximum_lead,1) * oo_.exo_steady_state'; - end +end - check_model; +check_model; - [oo_.dr, info] = resol(oo_.steady_state,0); +[oo_.dr, info] = resol(oo_.steady_state,0); - if info(1) +if info(1) options_ = options_old; print_info(info, options_.noprint); return - end +end - if ~options_.noprint +if ~options_.noprint disp(' ') disp('MODEL SUMMARY') disp(' ') @@ -67,222 +67,222 @@ function info=stoch_simul(var_list) if options_.order <= 2 disp_dr(oo_.dr,options_.order,var_list); end - end +end - if options_.periods == 0 && options_.nomoments == 0 +if options_.periods == 0 && options_.nomoments == 0 disp_th_moments(oo_.dr,var_list); - elseif options_.periods ~= 0 +elseif options_.periods ~= 0 if options_.periods < options_.drop - disp(['STOCH_SIMUL error: The horizon of simulation is shorter' ... - ' than the number of observations to be DROPed']) - options_ =options_old; - return + disp(['STOCH_SIMUL error: The horizon of simulation is shorter' ... + ' than the number of observations to be DROPed']) + options_ =options_old; + return end oo_.endo_simul = simult(repmat(oo_.dr.ys,1,M_.maximum_lag),oo_.dr); dyn2vec; if options_.nomoments == 0 - disp_moments(oo_.endo_simul,var_list); + disp_moments(oo_.endo_simul,var_list); end - end +end - if options_.irf +if options_.irf if size(var_list,1) == 0 - var_list = M_.endo_names(1:M_.orig_endo_nbr, :); - if TeX - var_listTeX = M_.endo_names_tex(1:M_.orig_endo_nbr, :); - end + var_list = M_.endo_names(1:M_.orig_endo_nbr, :); + if TeX + var_listTeX = M_.endo_names_tex(1:M_.orig_endo_nbr, :); + end end n = size(var_list,1); - ivar=zeros(n,1); - if TeX + ivar=zeros(n,1); + if TeX var_listTeX = []; - end - for i=1:n + end + for i=1:n i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact'); if isempty(i_tmp) - error (['One of the specified variables does not exist']) ; + error (['One of the specified variables does not exist']) ; else - ivar(i) = i_tmp; - if TeX - var_listTeX = strvcat(var_listTeX,deblank(M_.endo_names_tex(i_tmp,:))); - end - end - end + ivar(i) = i_tmp; + if TeX + var_listTeX = strvcat(var_listTeX,deblank(M_.endo_names_tex(i_tmp,:))); + end + end + end if TeX - fidTeX = fopen([M_.fname '_IRF.TeX'],'w'); - fprintf(fidTeX,'%% TeX eps-loader file generated by stoch_simul.m (Dynare).\n'); - fprintf(fidTeX,['%% ' datestr(now,0) '\n']); - fprintf(fidTeX,' \n'); + fidTeX = fopen([M_.fname '_IRF.TeX'],'w'); + fprintf(fidTeX,'%% TeX eps-loader file generated by stoch_simul.m (Dynare).\n'); + fprintf(fidTeX,['%% ' datestr(now,0) '\n']); + fprintf(fidTeX,' \n'); end olditer = iter_;% Est-ce vraiment utile ? Il y a la m�me ligne dans irf... SS(M_.exo_names_orig_ord,M_.exo_names_orig_ord)=M_.Sigma_e+1e-14*eye(M_.exo_nbr); cs = transpose(chol(SS)); tit(M_.exo_names_orig_ord,:) = M_.exo_names; if TeX - titTeX(M_.exo_names_orig_ord,:) = M_.exo_names_tex; + titTeX(M_.exo_names_orig_ord,:) = M_.exo_names_tex; end for i=1:M_.exo_nbr - if SS(i,i) > 1e-13 - y=irf(oo_.dr,cs(M_.exo_names_orig_ord,i), options_.irf, options_.drop, ... - options_.replic, options_.order); - if options_.relative_irf - y = 100*y/cs(i,i); - end - irfs = []; - mylist = []; - if TeX - mylistTeX = []; - end - for j = 1:n - assignin('base',[deblank(M_.endo_names(ivar(j),:)) '_' deblank(M_.exo_names(i,:))],... - y(ivar(j),:)'); - eval(['oo_.irfs.' deblank(M_.endo_names(ivar(j),:)) '_' ... - deblank(M_.exo_names(i,:)) ' = y(ivar(j),:);']); - if max(y(ivar(j),:)) - min(y(ivar(j),:)) > 1e-10 - irfs = cat(1,irfs,y(ivar(j),:)); - mylist = strvcat(mylist,deblank(var_list(j,:))); - if TeX - mylistTeX = strvcat(mylistTeX,deblank(var_listTeX(j,:))); - end - end - end - if options_.nograph == 0 - number_of_plots_to_draw = size(irfs,1); - [nbplt,nr,nc,lr,lc,nstar] = pltorg(number_of_plots_to_draw); - if nbplt == 0 - elseif nbplt == 1 - if options_.relative_irf - hh = figure('Name',['Relative response to' ... - ' orthogonalized shock to ' tit(i,:)]); - else - hh = figure('Name',['Orthogonalized shock to' ... - ' ' tit(i,:)]); - end - for j = 1:number_of_plots_to_draw - subplot(nr,nc,j); - plot(1:options_.irf,transpose(irfs(j,:)),'-k','linewidth',1); - hold on - plot([1 options_.irf],[0 0],'-r','linewidth',0.5); - hold off - xlim([1 options_.irf]); - title(deblank(mylist(j,:)),'Interpreter','none'); - end - eval(['print -depsc2 ' M_.fname '_IRF_' deblank(tit(i,:)) '.eps']); - if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' M_.fname '_IRF_' deblank(tit(i,:))]); - saveas(hh,[M_.fname '_IRF_' deblank(tit(i,:)) '.fig']); - end - if TeX - fprintf(fidTeX,'\\begin{figure}[H]\n'); - for j = 1:number_of_plots_to_draw - fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{$%s$}\n'],deblank(mylist(j,:)),deblank(mylistTeX(j,:))); - end - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_IRF_%s}\n',M_.fname,deblank(tit(i,:))); - fprintf(fidTeX,'\\caption{Impulse response functions (orthogonalized shock to $%s$).}',titTeX(i,:)); - fprintf(fidTeX,'\\label{Fig:IRF:%s}\n',deblank(tit(i,:))); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,' \n'); - end - % close(hh) - else - for fig = 1:nbplt-1 - if options_.relative_irf == 1 - hh = figure('Name',['Relative response to orthogonalized shock' ... - ' to ' tit(i,:) ' figure ' int2str(fig)]); - else - hh = figure('Name',['Orthogonalized shock to ' tit(i,:) ... - ' figure ' int2str(fig)]); - end - for plt = 1:nstar - subplot(nr,nc,plt); - plot(1:options_.irf,transpose(irfs((fig-1)*nstar+plt,:)),'-k','linewidth',1); - hold on - plot([1 options_.irf],[0 0],'-r','linewidth',0.5); - hold off - xlim([1 options_.irf]); - title(deblank(mylist((fig-1)*nstar+plt,:)),'Interpreter','none'); - end - eval(['print -depsc2 ' M_.fname '_IRF_' deblank(tit(i,:)) int2str(fig) '.eps']); - if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' M_.fname '_IRF_' deblank(tit(i,:)) int2str(fig)]); - saveas(hh,[M_.fname '_IRF_' deblank(tit(i,:)) int2str(fig) '.fig']); + if SS(i,i) > 1e-13 + y=irf(oo_.dr,cs(M_.exo_names_orig_ord,i), options_.irf, options_.drop, ... + options_.replic, options_.order); + if options_.relative_irf + y = 100*y/cs(i,i); + end + irfs = []; + mylist = []; + if TeX + mylistTeX = []; + end + for j = 1:n + assignin('base',[deblank(M_.endo_names(ivar(j),:)) '_' deblank(M_.exo_names(i,:))],... + y(ivar(j),:)'); + eval(['oo_.irfs.' deblank(M_.endo_names(ivar(j),:)) '_' ... + deblank(M_.exo_names(i,:)) ' = y(ivar(j),:);']); + if max(y(ivar(j),:)) - min(y(ivar(j),:)) > 1e-10 + irfs = cat(1,irfs,y(ivar(j),:)); + mylist = strvcat(mylist,deblank(var_list(j,:))); + if TeX + mylistTeX = strvcat(mylistTeX,deblank(var_listTeX(j,:))); + end + end + end + if options_.nograph == 0 + number_of_plots_to_draw = size(irfs,1); + [nbplt,nr,nc,lr,lc,nstar] = pltorg(number_of_plots_to_draw); + if nbplt == 0 + elseif nbplt == 1 + if options_.relative_irf + hh = figure('Name',['Relative response to' ... + ' orthogonalized shock to ' tit(i,:)]); + else + hh = figure('Name',['Orthogonalized shock to' ... + ' ' tit(i,:)]); + end + for j = 1:number_of_plots_to_draw + subplot(nr,nc,j); + plot(1:options_.irf,transpose(irfs(j,:)),'-k','linewidth',1); + hold on + plot([1 options_.irf],[0 0],'-r','linewidth',0.5); + hold off + xlim([1 options_.irf]); + title(deblank(mylist(j,:)),'Interpreter','none'); + end + eval(['print -depsc2 ' M_.fname '_IRF_' deblank(tit(i,:)) '.eps']); + if ~exist('OCTAVE_VERSION') + eval(['print -dpdf ' M_.fname '_IRF_' deblank(tit(i,:))]); + saveas(hh,[M_.fname '_IRF_' deblank(tit(i,:)) '.fig']); + end + if TeX + fprintf(fidTeX,'\\begin{figure}[H]\n'); + for j = 1:number_of_plots_to_draw + fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{$%s$}\n'],deblank(mylist(j,:)),deblank(mylistTeX(j,:))); + end + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_IRF_%s}\n',M_.fname,deblank(tit(i,:))); + fprintf(fidTeX,'\\caption{Impulse response functions (orthogonalized shock to $%s$).}',titTeX(i,:)); + fprintf(fidTeX,'\\label{Fig:IRF:%s}\n',deblank(tit(i,:))); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,' \n'); + end + % close(hh) + else + for fig = 1:nbplt-1 + if options_.relative_irf == 1 + hh = figure('Name',['Relative response to orthogonalized shock' ... + ' to ' tit(i,:) ' figure ' int2str(fig)]); + else + hh = figure('Name',['Orthogonalized shock to ' tit(i,:) ... + ' figure ' int2str(fig)]); + end + for plt = 1:nstar + subplot(nr,nc,plt); + plot(1:options_.irf,transpose(irfs((fig-1)*nstar+plt,:)),'-k','linewidth',1); + hold on + plot([1 options_.irf],[0 0],'-r','linewidth',0.5); + hold off + xlim([1 options_.irf]); + title(deblank(mylist((fig-1)*nstar+plt,:)),'Interpreter','none'); + end + eval(['print -depsc2 ' M_.fname '_IRF_' deblank(tit(i,:)) int2str(fig) '.eps']); + if ~exist('OCTAVE_VERSION') + eval(['print -dpdf ' M_.fname '_IRF_' deblank(tit(i,:)) int2str(fig)]); + saveas(hh,[M_.fname '_IRF_' deblank(tit(i,:)) int2str(fig) '.fig']); + end + if TeX + fprintf(fidTeX,'\\begin{figure}[H]\n'); + for j = 1:nstar + fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{$%s$}\n'],deblank(mylist((fig-1)*nstar+j,:)),deblank(mylistTeX((fig-1)*nstar+j,:))); + end + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_IRF_%s%s}\n',M_.fname,deblank(tit(i,:)),int2str(fig)); + if options_.relative_irf + fprintf(fidTeX,['\\caption{Relative impulse response' ... + ' functions (orthogonalized shock to $%s$).}'],deblank(titTeX(i,:))); + else + fprintf(fidTeX,['\\caption{Impulse response functions' ... + ' (orthogonalized shock to $%s$).}'],deblank(titTeX(i,:))); + end + fprintf(fidTeX,'\\label{Fig:BayesianIRF:%s:%s}\n',deblank(tit(i,:)),int2str(fig)); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,' \n'); + end + % close(hh); + end + hh = figure('Name',['Orthogonalized shock to ' tit(i,:) ' figure ' int2str(nbplt) '.']); + m = 0; + for plt = 1:number_of_plots_to_draw-(nbplt-1)*nstar; + m = m+1; + subplot(lr,lc,m); + plot(1:options_.irf,transpose(irfs((nbplt-1)*nstar+plt,:)),'-k','linewidth',1); + hold on + plot([1 options_.irf],[0 0],'-r','linewidth',0.5); + hold off + xlim([1 options_.irf]); + title(deblank(mylist((nbplt-1)*nstar+plt,:)),'Interpreter','none'); + end + eval(['print -depsc2 ' M_.fname '_IRF_' deblank(tit(i,:)) int2str(nbplt) '.eps']); + if ~exist('OCTAVE_VERSION') + eval(['print -dpdf ' M_.fname '_IRF_' deblank(tit(i,:)) int2str(nbplt)]); + saveas(hh,[M_.fname '_IRF_' deblank(tit(i,:)) int2str(nbplt) '.fig']); + end + if TeX + fprintf(fidTeX,'\\begin{figure}[H]\n'); + for j = 1:m + fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{$%s$}\n'],deblank(mylist((nbplt-1)*nstar+j,:)),deblank(mylistTeX((nbplt-1)*nstar+j,:))); + end + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_IRF_%s%s}\n',M_.fname,deblank(tit(i,:)),int2str(nbplt)); + if options_.relative_irf + fprintf(fidTeX,['\\caption{Relative impulse response functions' ... + ' (orthogonalized shock to $%s$).}'],deblank(titTeX(i,:))); + else + fprintf(fidTeX,['\\caption{Impulse response functions' ... + ' (orthogonalized shock to $%s$).}'],deblank(titTeX(i,:))); + end + fprintf(fidTeX,'\\label{Fig:IRF:%s:%s}\n',deblank(tit(i,:)),int2str(nbplt)); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,' \n'); + end + % close(hh); + end + end + end + iter_ = olditer; + if TeX + fprintf(fidTeX,' \n'); + fprintf(fidTeX,'%% End Of TeX file. \n'); + fclose(fidTeX); end - if TeX - fprintf(fidTeX,'\\begin{figure}[H]\n'); - for j = 1:nstar - fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{$%s$}\n'],deblank(mylist((fig-1)*nstar+j,:)),deblank(mylistTeX((fig-1)*nstar+j,:))); - end - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_IRF_%s%s}\n',M_.fname,deblank(tit(i,:)),int2str(fig)); - if options_.relative_irf - fprintf(fidTeX,['\\caption{Relative impulse response' ... - ' functions (orthogonalized shock to $%s$).}'],deblank(titTeX(i,:))); - else - fprintf(fidTeX,['\\caption{Impulse response functions' ... - ' (orthogonalized shock to $%s$).}'],deblank(titTeX(i,:))); - end - fprintf(fidTeX,'\\label{Fig:BayesianIRF:%s:%s}\n',deblank(tit(i,:)),int2str(fig)); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,' \n'); - end - % close(hh); - end - hh = figure('Name',['Orthogonalized shock to ' tit(i,:) ' figure ' int2str(nbplt) '.']); - m = 0; - for plt = 1:number_of_plots_to_draw-(nbplt-1)*nstar; - m = m+1; - subplot(lr,lc,m); - plot(1:options_.irf,transpose(irfs((nbplt-1)*nstar+plt,:)),'-k','linewidth',1); - hold on - plot([1 options_.irf],[0 0],'-r','linewidth',0.5); - hold off - xlim([1 options_.irf]); - title(deblank(mylist((nbplt-1)*nstar+plt,:)),'Interpreter','none'); - end - eval(['print -depsc2 ' M_.fname '_IRF_' deblank(tit(i,:)) int2str(nbplt) '.eps']); - if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' M_.fname '_IRF_' deblank(tit(i,:)) int2str(nbplt)]); - saveas(hh,[M_.fname '_IRF_' deblank(tit(i,:)) int2str(nbplt) '.fig']); - end - if TeX - fprintf(fidTeX,'\\begin{figure}[H]\n'); - for j = 1:m - fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{$%s$}\n'],deblank(mylist((nbplt-1)*nstar+j,:)),deblank(mylistTeX((nbplt-1)*nstar+j,:))); - end - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_IRF_%s%s}\n',M_.fname,deblank(tit(i,:)),int2str(nbplt)); - if options_.relative_irf - fprintf(fidTeX,['\\caption{Relative impulse response functions' ... - ' (orthogonalized shock to $%s$).}'],deblank(titTeX(i,:))); - else - fprintf(fidTeX,['\\caption{Impulse response functions' ... - ' (orthogonalized shock to $%s$).}'],deblank(titTeX(i,:))); - end - fprintf(fidTeX,'\\label{Fig:IRF:%s:%s}\n',deblank(tit(i,:)),int2str(nbplt)); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,' \n'); - end - % close(hh); - end - end - end - iter_ = olditer; - if TeX - fprintf(fidTeX,' \n'); - fprintf(fidTeX,'%% End Of TeX file. \n'); - fclose(fidTeX); - end end - end +end - if options_.SpectralDensity == 1 - [omega,f] = UnivariateSpectralDensity(oo_.dr,var_list); - end +if options_.SpectralDensity == 1 + [omega,f] = UnivariateSpectralDensity(oo_.dr,var_list); +end options_ = options_old; diff --git a/matlab/stoch_simul_sparse.m b/matlab/stoch_simul_sparse.m index f5f47bec3c..fa13d40c5a 100644 --- a/matlab/stoch_simul_sparse.m +++ b/matlab/stoch_simul_sparse.m @@ -1,6 +1,6 @@ function info=stoch_simul_sparse(var_list) % This file is a modified version of stoch_simul.m: common parts should be factorized! - + % Copyright (C) 2001-2009 Dynare Team % % This file is part of Dynare. @@ -18,42 +18,42 @@ function info=stoch_simul_sparse(var_list) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - global M_ options_ oo_ it_ +global M_ options_ oo_ it_ + +options_old = options_; +if options_.linear + options_.order = 1; +end +if (options_.order == 1) + options_.replic = 1; +end - options_old = options_; - if options_.linear - options_.order = 1; - end - if (options_.order == 1) - options_.replic = 1; - end - - TeX = options_.TeX; +TeX = options_.TeX; - iter_ = max(options_.periods,1); - if M_.exo_nbr > 0 +iter_ = max(options_.periods,1); +if M_.exo_nbr > 0 oo_.exo_simul= ones(iter_ + M_.maximum_lag + M_.maximum_lead,1) * oo_.exo_steady_state'; - end +end - check_model; +check_model; - [oo_.dr, info] = resol(oo_.steady_state,0); +[oo_.dr, info] = resol(oo_.steady_state,0); - if info(1) +if info(1) options_ = options_old; print_info(info, options_.noprint); return - end - - oo_dr_kstate = []; - oo_dr_nstatic = 0; - for i=1:length(M_.block_structure.block) - oo_dr_kstate = [ oo_dr_kstate ; M_.block_structure.block(i).dr.kstate]; - oo_dr_nstatic = oo_dr_nstatic + M_.block_structure.block(i).dr.nstatic; - end - - if ~options_.noprint +end + +oo_dr_kstate = []; +oo_dr_nstatic = 0; +for i=1:length(M_.block_structure.block) + oo_dr_kstate = [ oo_dr_kstate ; M_.block_structure.block(i).dr.kstate]; + oo_dr_nstatic = oo_dr_nstatic + M_.block_structure.block(i).dr.nstatic; +end + +if ~options_.noprint disp(' ') disp('MODEL SUMMARY') disp(' ') @@ -62,7 +62,7 @@ function info=stoch_simul_sparse(var_list) disp([' Number of state variables: ' ... int2str(length(find(oo_dr_kstate(:,2) <= M_.maximum_lag+1)))]) disp([' Number of jumpers: ' ... - int2str(length(find(oo_dr_kstate(:,2) == M_.maximum_lag+2)))]) + int2str(length(find(oo_dr_kstate(:,2) == M_.maximum_lag+2)))]) disp([' Number of static variables: ' int2str(oo_dr_nstatic)]) my_title='MATRIX OF COVARIANCE OF EXOGENOUS SHOCKS'; labels = deblank(M_.exo_names); @@ -71,222 +71,222 @@ function info=stoch_simul_sparse(var_list) dyntable(my_title,headers,labels,M_.Sigma_e,lh,10,6); disp(' ') disp_dr_sparse(oo_.dr,options_.order,var_list); - end +end - if options_.periods == 0 && options_.nomoments == 0 +if options_.periods == 0 && options_.nomoments == 0 disp_th_moments(oo_.dr,var_list); - elseif options_.periods ~= 0 +elseif options_.periods ~= 0 if options_.periods < options_.drop - disp(['STOCH_SIMUL error: The horizon of simulation is shorter' ... - ' than the number of observations to be DROPed']) - options_ =options_old; - return + disp(['STOCH_SIMUL error: The horizon of simulation is shorter' ... + ' than the number of observations to be DROPed']) + options_ =options_old; + return end oo_.endo_simul = simult(repmat(oo_.dr.ys,1,M_.maximum_lag),oo_.dr); dyn2vec; if options_.nomoments == 0 - disp_moments(oo_.endo_simul,var_list); + disp_moments(oo_.endo_simul,var_list); end - end +end - if options_.irf +if options_.irf if size(var_list,1) == 0 - var_list = M_.endo_names(1:M_.orig_endo_nbr, :); - if TeX - var_listTeX = M_.endo_names_tex(1:M_.orig_endo_nbr, :); - end + var_list = M_.endo_names(1:M_.orig_endo_nbr, :); + if TeX + var_listTeX = M_.endo_names_tex(1:M_.orig_endo_nbr, :); + end end n = size(var_list,1); - ivar=zeros(n,1); - if TeX + ivar=zeros(n,1); + if TeX var_listTeX = []; - end - for i=1:n + end + for i=1:n i_tmp = strmatch(var_list(i,:),M_.endo_names,'exact'); if isempty(i_tmp) - error (['One of the specified variables does not exist']) ; + error (['One of the specified variables does not exist']) ; else - ivar(i) = i_tmp; - if TeX - var_listTeX = strvcat(var_listTeX,deblank(M_.endo_names_tex(i_tmp,:))); - end - end - end + ivar(i) = i_tmp; + if TeX + var_listTeX = strvcat(var_listTeX,deblank(M_.endo_names_tex(i_tmp,:))); + end + end + end if TeX - fidTeX = fopen([M_.fname '_IRF.TeX'],'w'); - fprintf(fidTeX,'%% TeX eps-loader file generated by stoch_simul.m (Dynare).\n'); - fprintf(fidTeX,['%% ' datestr(now,0) '\n']); - fprintf(fidTeX,' \n'); + fidTeX = fopen([M_.fname '_IRF.TeX'],'w'); + fprintf(fidTeX,'%% TeX eps-loader file generated by stoch_simul.m (Dynare).\n'); + fprintf(fidTeX,['%% ' datestr(now,0) '\n']); + fprintf(fidTeX,' \n'); end olditer = iter_;% Est-ce vraiment utile ? Il y a la m�me ligne dans irf... SS(M_.exo_names_orig_ord,M_.exo_names_orig_ord)=M_.Sigma_e+1e-14*eye(M_.exo_nbr); cs = transpose(chol(SS)); tit(M_.exo_names_orig_ord,:) = M_.exo_names; if TeX - titTeX(M_.exo_names_orig_ord,:) = M_.exo_names_tex; + titTeX(M_.exo_names_orig_ord,:) = M_.exo_names_tex; end for i=1:M_.exo_nbr - if SS(i,i) > 1e-13 - y=irf(oo_.dr,cs(M_.exo_names_orig_ord,i), options_.irf, options_.drop, ... - options_.replic, options_.order); - if options_.relative_irf - y = 100*y/cs(i,i); - end - irfs = []; - mylist = []; - if TeX - mylistTeX = []; - end - for j = 1:n - assignin('base',[deblank(M_.endo_names(ivar(j),:)) '_' deblank(M_.exo_names(i,:))],... - y(ivar(j),:)'); - eval(['oo_.irfs.' deblank(M_.endo_names(ivar(j),:)) '_' ... - deblank(M_.exo_names(i,:)) ' = y(ivar(j),:);']); - if max(y(ivar(j),:)) - min(y(ivar(j),:)) > 1e-10 - irfs = cat(1,irfs,y(ivar(j),:)); - mylist = strvcat(mylist,deblank(var_list(j,:))); - if TeX - mylistTeX = strvcat(mylistTeX,deblank(var_listTeX(j,:))); - end - end - end - if options_.nograph == 0 - number_of_plots_to_draw = size(irfs,1); - [nbplt,nr,nc,lr,lc,nstar] = pltorg(number_of_plots_to_draw); - if nbplt == 0 - elseif nbplt == 1 - if options_.relative_irf - hh = figure('Name',['Relative response to' ... - ' orthogonalized shock to ' tit(i,:)]); - else - hh = figure('Name',['Orthogonalized shock to' ... - ' ' tit(i,:)]); - end - for j = 1:number_of_plots_to_draw - subplot(nr,nc,j); - plot(1:options_.irf,transpose(irfs(j,:)),'-k','linewidth',1); - hold on - plot([1 options_.irf],[0 0],'-r','linewidth',0.5); - hold off - xlim([1 options_.irf]); - title(deblank(mylist(j,:)),'Interpreter','none'); - end - eval(['print -depsc2 ' M_.fname '_IRF_' deblank(tit(i,:)) '.eps']); - if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' M_.fname '_IRF_' deblank(tit(i,:))]); - saveas(hh,[M_.fname '_IRF_' deblank(tit(i,:)) '.fig']); - end - if TeX - fprintf(fidTeX,'\\begin{figure}[H]\n'); - for j = 1:number_of_plots_to_draw - fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{$%s$}\n'],deblank(mylist(j,:)),deblank(mylistTeX(j,:))); - end - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_IRF_%s}\n',M_.fname,deblank(tit(i,:))); - fprintf(fidTeX,'\\caption{Impulse response functions (orthogonalized shock to $%s$).}',titTeX(i,:)); - fprintf(fidTeX,'\\label{Fig:IRF:%s}\n',deblank(tit(i,:))); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,' \n'); - end - % close(hh) - else - for fig = 1:nbplt-1 - if options_.relative_irf == 1 - hh = figure('Name',['Relative response to orthogonalized shock' ... - ' to ' tit(i,:) ' figure ' int2str(fig)]); - else - hh = figure('Name',['Orthogonalized shock to ' tit(i,:) ... - ' figure ' int2str(fig)]); - end - for plt = 1:nstar - subplot(nr,nc,plt); - plot(1:options_.irf,transpose(irfs((fig-1)*nstar+plt,:)),'-k','linewidth',1); - hold on - plot([1 options_.irf],[0 0],'-r','linewidth',0.5); - hold off - xlim([1 options_.irf]); - title(deblank(mylist((fig-1)*nstar+plt,:)),'Interpreter','none'); - end - eval(['print -depsc2 ' M_.fname '_IRF_' deblank(tit(i,:)) int2str(fig) '.eps']); - if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' M_.fname '_IRF_' deblank(tit(i,:)) int2str(fig)]); - saveas(hh,[M_.fname '_IRF_' deblank(tit(i,:)) int2str(fig) '.fig']); + if SS(i,i) > 1e-13 + y=irf(oo_.dr,cs(M_.exo_names_orig_ord,i), options_.irf, options_.drop, ... + options_.replic, options_.order); + if options_.relative_irf + y = 100*y/cs(i,i); + end + irfs = []; + mylist = []; + if TeX + mylistTeX = []; + end + for j = 1:n + assignin('base',[deblank(M_.endo_names(ivar(j),:)) '_' deblank(M_.exo_names(i,:))],... + y(ivar(j),:)'); + eval(['oo_.irfs.' deblank(M_.endo_names(ivar(j),:)) '_' ... + deblank(M_.exo_names(i,:)) ' = y(ivar(j),:);']); + if max(y(ivar(j),:)) - min(y(ivar(j),:)) > 1e-10 + irfs = cat(1,irfs,y(ivar(j),:)); + mylist = strvcat(mylist,deblank(var_list(j,:))); + if TeX + mylistTeX = strvcat(mylistTeX,deblank(var_listTeX(j,:))); + end + end + end + if options_.nograph == 0 + number_of_plots_to_draw = size(irfs,1); + [nbplt,nr,nc,lr,lc,nstar] = pltorg(number_of_plots_to_draw); + if nbplt == 0 + elseif nbplt == 1 + if options_.relative_irf + hh = figure('Name',['Relative response to' ... + ' orthogonalized shock to ' tit(i,:)]); + else + hh = figure('Name',['Orthogonalized shock to' ... + ' ' tit(i,:)]); + end + for j = 1:number_of_plots_to_draw + subplot(nr,nc,j); + plot(1:options_.irf,transpose(irfs(j,:)),'-k','linewidth',1); + hold on + plot([1 options_.irf],[0 0],'-r','linewidth',0.5); + hold off + xlim([1 options_.irf]); + title(deblank(mylist(j,:)),'Interpreter','none'); + end + eval(['print -depsc2 ' M_.fname '_IRF_' deblank(tit(i,:)) '.eps']); + if ~exist('OCTAVE_VERSION') + eval(['print -dpdf ' M_.fname '_IRF_' deblank(tit(i,:))]); + saveas(hh,[M_.fname '_IRF_' deblank(tit(i,:)) '.fig']); + end + if TeX + fprintf(fidTeX,'\\begin{figure}[H]\n'); + for j = 1:number_of_plots_to_draw + fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{$%s$}\n'],deblank(mylist(j,:)),deblank(mylistTeX(j,:))); + end + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_IRF_%s}\n',M_.fname,deblank(tit(i,:))); + fprintf(fidTeX,'\\caption{Impulse response functions (orthogonalized shock to $%s$).}',titTeX(i,:)); + fprintf(fidTeX,'\\label{Fig:IRF:%s}\n',deblank(tit(i,:))); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,' \n'); + end + % close(hh) + else + for fig = 1:nbplt-1 + if options_.relative_irf == 1 + hh = figure('Name',['Relative response to orthogonalized shock' ... + ' to ' tit(i,:) ' figure ' int2str(fig)]); + else + hh = figure('Name',['Orthogonalized shock to ' tit(i,:) ... + ' figure ' int2str(fig)]); + end + for plt = 1:nstar + subplot(nr,nc,plt); + plot(1:options_.irf,transpose(irfs((fig-1)*nstar+plt,:)),'-k','linewidth',1); + hold on + plot([1 options_.irf],[0 0],'-r','linewidth',0.5); + hold off + xlim([1 options_.irf]); + title(deblank(mylist((fig-1)*nstar+plt,:)),'Interpreter','none'); + end + eval(['print -depsc2 ' M_.fname '_IRF_' deblank(tit(i,:)) int2str(fig) '.eps']); + if ~exist('OCTAVE_VERSION') + eval(['print -dpdf ' M_.fname '_IRF_' deblank(tit(i,:)) int2str(fig)]); + saveas(hh,[M_.fname '_IRF_' deblank(tit(i,:)) int2str(fig) '.fig']); + end + if TeX + fprintf(fidTeX,'\\begin{figure}[H]\n'); + for j = 1:nstar + fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{$%s$}\n'],deblank(mylist((fig-1)*nstar+j,:)),deblank(mylistTeX((fig-1)*nstar+j,:))); + end + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_IRF_%s%s}\n',M_.fname,deblank(tit(i,:)),int2str(fig)); + if options_.relative_irf + fprintf(fidTeX,['\\caption{Relative impulse response' ... + ' functions (orthogonalized shock to $%s$).}'],deblank(titTeX(i,:))); + else + fprintf(fidTeX,['\\caption{Impulse response functions' ... + ' (orthogonalized shock to $%s$).}'],deblank(titTeX(i,:))); + end + fprintf(fidTeX,'\\label{Fig:BayesianIRF:%s:%s}\n',deblank(tit(i,:)),int2str(fig)); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,' \n'); + end + % close(hh); + end + hh = figure('Name',['Orthogonalized shock to ' tit(i,:) ' figure ' int2str(nbplt) '.']); + m = 0; + for plt = 1:number_of_plots_to_draw-(nbplt-1)*nstar; + m = m+1; + subplot(lr,lc,m); + plot(1:options_.irf,transpose(irfs((nbplt-1)*nstar+plt,:)),'-k','linewidth',1); + hold on + plot([1 options_.irf],[0 0],'-r','linewidth',0.5); + hold off + xlim([1 options_.irf]); + title(deblank(mylist((nbplt-1)*nstar+plt,:)),'Interpreter','none'); + end + eval(['print -depsc2 ' M_.fname '_IRF_' deblank(tit(i,:)) int2str(nbplt) '.eps']); + if ~exist('OCTAVE_VERSION') + eval(['print -dpdf ' M_.fname '_IRF_' deblank(tit(i,:)) int2str(nbplt)]); + saveas(hh,[M_.fname '_IRF_' deblank(tit(i,:)) int2str(nbplt) '.fig']); + end + if TeX + fprintf(fidTeX,'\\begin{figure}[H]\n'); + for j = 1:m + fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{$%s$}\n'],deblank(mylist((nbplt-1)*nstar+j,:)),deblank(mylistTeX((nbplt-1)*nstar+j,:))); + end + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_IRF_%s%s}\n',M_.fname,deblank(tit(i,:)),int2str(nbplt)); + if options_.relative_irf + fprintf(fidTeX,['\\caption{Relative impulse response functions' ... + ' (orthogonalized shock to $%s$).}'],deblank(titTeX(i,:))); + else + fprintf(fidTeX,['\\caption{Impulse response functions' ... + ' (orthogonalized shock to $%s$).}'],deblank(titTeX(i,:))); + end + fprintf(fidTeX,'\\label{Fig:IRF:%s:%s}\n',deblank(tit(i,:)),int2str(nbplt)); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,' \n'); + end + % close(hh); + end + end + end + iter_ = olditer; + if TeX + fprintf(fidTeX,' \n'); + fprintf(fidTeX,'%% End Of TeX file. \n'); + fclose(fidTeX); end - if TeX - fprintf(fidTeX,'\\begin{figure}[H]\n'); - for j = 1:nstar - fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{$%s$}\n'],deblank(mylist((fig-1)*nstar+j,:)),deblank(mylistTeX((fig-1)*nstar+j,:))); - end - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_IRF_%s%s}\n',M_.fname,deblank(tit(i,:)),int2str(fig)); - if options_.relative_irf - fprintf(fidTeX,['\\caption{Relative impulse response' ... - ' functions (orthogonalized shock to $%s$).}'],deblank(titTeX(i,:))); - else - fprintf(fidTeX,['\\caption{Impulse response functions' ... - ' (orthogonalized shock to $%s$).}'],deblank(titTeX(i,:))); - end - fprintf(fidTeX,'\\label{Fig:BayesianIRF:%s:%s}\n',deblank(tit(i,:)),int2str(fig)); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,' \n'); - end - % close(hh); - end - hh = figure('Name',['Orthogonalized shock to ' tit(i,:) ' figure ' int2str(nbplt) '.']); - m = 0; - for plt = 1:number_of_plots_to_draw-(nbplt-1)*nstar; - m = m+1; - subplot(lr,lc,m); - plot(1:options_.irf,transpose(irfs((nbplt-1)*nstar+plt,:)),'-k','linewidth',1); - hold on - plot([1 options_.irf],[0 0],'-r','linewidth',0.5); - hold off - xlim([1 options_.irf]); - title(deblank(mylist((nbplt-1)*nstar+plt,:)),'Interpreter','none'); - end - eval(['print -depsc2 ' M_.fname '_IRF_' deblank(tit(i,:)) int2str(nbplt) '.eps']); - if ~exist('OCTAVE_VERSION') - eval(['print -dpdf ' M_.fname '_IRF_' deblank(tit(i,:)) int2str(nbplt)]); - saveas(hh,[M_.fname '_IRF_' deblank(tit(i,:)) int2str(nbplt) '.fig']); - end - if TeX - fprintf(fidTeX,'\\begin{figure}[H]\n'); - for j = 1:m - fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{$%s$}\n'],deblank(mylist((nbplt-1)*nstar+j,:)),deblank(mylistTeX((nbplt-1)*nstar+j,:))); - end - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_IRF_%s%s}\n',M_.fname,deblank(tit(i,:)),int2str(nbplt)); - if options_.relative_irf - fprintf(fidTeX,['\\caption{Relative impulse response functions' ... - ' (orthogonalized shock to $%s$).}'],deblank(titTeX(i,:))); - else - fprintf(fidTeX,['\\caption{Impulse response functions' ... - ' (orthogonalized shock to $%s$).}'],deblank(titTeX(i,:))); - end - fprintf(fidTeX,'\\label{Fig:IRF:%s:%s}\n',deblank(tit(i,:)),int2str(nbplt)); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,' \n'); - end - % close(hh); - end - end - end - iter_ = olditer; - if TeX - fprintf(fidTeX,' \n'); - fprintf(fidTeX,'%% End Of TeX file. \n'); - fclose(fidTeX); - end end - end +end - if options_.SpectralDensity == 1 - [omega,f] = UnivariateSpectralDensity(oo_.dr,var_list); - end +if options_.SpectralDensity == 1 + [omega,f] = UnivariateSpectralDensity(oo_.dr,var_list); +end options_ = options_old; diff --git a/matlab/struct2local.m b/matlab/struct2local.m index 9c101224a4..22efb25d26 100644 --- a/matlab/struct2local.m +++ b/matlab/struct2local.m @@ -1,28 +1,28 @@ -function struct2local(S), -% The argument is a structure possibly containing several fields. -% This function will create, in the workspace of the calling function, -% as many variables as there are fields in the structure, assigning -% them the value of the fields. - -% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. - -vnam = fieldnames(S); - -for j=1:length(vnam), - assignin('caller',vnam{j},getfield(S,vnam{j})); -end +function struct2local(S), +% The argument is a structure possibly containing several fields. +% This function will create, in the workspace of the calling function, +% as many variables as there are fields in the structure, assigning +% them the value of the fields. + +% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. + +vnam = fieldnames(S); + +for j=1:length(vnam), + assignin('caller',vnam{j},getfield(S,vnam{j})); +end diff --git a/matlab/subset.m b/matlab/subset.m index e7c32c3af5..a795847b14 100644 --- a/matlab/subset.m +++ b/matlab/subset.m @@ -1,97 +1,97 @@ -function jndx = subset(); - -% Copyright (C) 2006 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 <http://www.gnu.org/licenses/>. - -global options_ estim_params_ M_ - -ExcludedParamNames = options_.ExcludedParams; -VarObs = options_.varobs; -VarExo = M_.exo_names; -info = options_.ParamSubSet; - -nvx = estim_params_.nvx; -nvn = estim_params_.nvn; -ncx = estim_params_.ncx; -ncn = estim_params_.ncn; -np = estim_params_.np; -nx = nvx+nvn+ncx+ncn+np; - -if strcmpi(info,'All') - indx = (1:nx)'; -elseif strcmpi(info,'DeepParameters') - indx = (nvx+nvn+ncx+ncn+1:nx)'; -elseif strcmpi(info,'StructuralShocks') - indx = [(1:nvx),nvx+nvn+1:nvx+nvn+ncx]'; -elseif strcmpi(info,'StructuralShocksWithoutCorrelations') - indx = (1:nvx)'; -elseif strcmpi(info,'MeasurementErrors') - indx = [(nvx+1:nvx+nvn),(nvx+nvn+ncx+1:nvx+nvn+ncx+ncn)]'; -elseif strcmpi(info,'MeasurementErrorsWithoutCorrelations') - indx = (nvx+1:nvx+nvn)'; -elseif strcmpi(info,'AllWithoutMeasurementErrors') - indx = [(1:nvx),nvx+nvn+1:nvx+nvn+ncx,nvx+nvn+ncx+ncn+1:nx]'; -elseif strcmpi(info,'None') - indx = []; -end - -if isempty(ExcludedParamNames) - jndx = indx; -else - tt = []; - for i = 1:length(ExcludedParamNames) - tmp = strmatch(ExcludedParamNames{i},M_.exo_names); - if ~isempty(tmp) & ( strcmpi(info,'All') | strcmpi(info,'StructuralShocks') | ... - strcmpi(info,'StructuralShocksWithoutCorrelations') | ... - strcmpi(info,'AllWithoutMeasurementErrors') ) - % The parameter the user wants to exclude is related to the size of the structural innovations. - if ncx - disp(['I cannot exclude some of the structural variances if the']) - disp(['structural innovations are correlated...']) - error - end - tt = [tt;tmp]; - elseif isempty(tmp) & nvn - tmp = strmatch(ExcludedParamNames{i},options_.varobs); - if ~isempty(tmp) & ( strcmpi(info,'All') | strcmpi(info,'MeasurementErrors') | ... - strcmpi(info,'MeasurementErrorsWithoutCorrelations') ) - % The parameter the user wants to exclude is related to the size of the measurement errors variances. - tmp = nvx+tmp; - if ncn - disp(['I cannot exclude some the measurement error variances if the']) - disp(['measurement errors are correlated...']) - error - end - tt = [tt;tmp]; - end - else% Excluded parameters are deep parameters... - tmp = strmatch(ExcludedParamNames{i},M_.param_names(estim_params_.param_vals(:,1),:),'exact'); - if ~isempty(tmp) - tt = [tt;nvx+nvn+ncx+ncn+tmp]; - else - disp('The parameter you want to exclude is unknown!') - error - end - end - end - jndx = []; - for i=1:length(indx) - if ~any(indx(i)==tt) - jndx = [ jndx ; indx(i) ]; - end - end +function jndx = subset(); + +% Copyright (C) 2006 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 <http://www.gnu.org/licenses/>. + +global options_ estim_params_ M_ + +ExcludedParamNames = options_.ExcludedParams; +VarObs = options_.varobs; +VarExo = M_.exo_names; +info = options_.ParamSubSet; + +nvx = estim_params_.nvx; +nvn = estim_params_.nvn; +ncx = estim_params_.ncx; +ncn = estim_params_.ncn; +np = estim_params_.np; +nx = nvx+nvn+ncx+ncn+np; + +if strcmpi(info,'All') + indx = (1:nx)'; +elseif strcmpi(info,'DeepParameters') + indx = (nvx+nvn+ncx+ncn+1:nx)'; +elseif strcmpi(info,'StructuralShocks') + indx = [(1:nvx),nvx+nvn+1:nvx+nvn+ncx]'; +elseif strcmpi(info,'StructuralShocksWithoutCorrelations') + indx = (1:nvx)'; +elseif strcmpi(info,'MeasurementErrors') + indx = [(nvx+1:nvx+nvn),(nvx+nvn+ncx+1:nvx+nvn+ncx+ncn)]'; +elseif strcmpi(info,'MeasurementErrorsWithoutCorrelations') + indx = (nvx+1:nvx+nvn)'; +elseif strcmpi(info,'AllWithoutMeasurementErrors') + indx = [(1:nvx),nvx+nvn+1:nvx+nvn+ncx,nvx+nvn+ncx+ncn+1:nx]'; +elseif strcmpi(info,'None') + indx = []; +end + +if isempty(ExcludedParamNames) + jndx = indx; +else + tt = []; + for i = 1:length(ExcludedParamNames) + tmp = strmatch(ExcludedParamNames{i},M_.exo_names); + if ~isempty(tmp) & ( strcmpi(info,'All') | strcmpi(info,'StructuralShocks') | ... + strcmpi(info,'StructuralShocksWithoutCorrelations') | ... + strcmpi(info,'AllWithoutMeasurementErrors') ) + % The parameter the user wants to exclude is related to the size of the structural innovations. + if ncx + disp(['I cannot exclude some of the structural variances if the']) + disp(['structural innovations are correlated...']) + error + end + tt = [tt;tmp]; + elseif isempty(tmp) & nvn + tmp = strmatch(ExcludedParamNames{i},options_.varobs); + if ~isempty(tmp) & ( strcmpi(info,'All') | strcmpi(info,'MeasurementErrors') | ... + strcmpi(info,'MeasurementErrorsWithoutCorrelations') ) + % The parameter the user wants to exclude is related to the size of the measurement errors variances. + tmp = nvx+tmp; + if ncn + disp(['I cannot exclude some the measurement error variances if the']) + disp(['measurement errors are correlated...']) + error + end + tt = [tt;tmp]; + end + else% Excluded parameters are deep parameters... + tmp = strmatch(ExcludedParamNames{i},M_.param_names(estim_params_.param_vals(:,1),:),'exact'); + if ~isempty(tmp) + tt = [tt;nvx+nvn+ncx+ncn+tmp]; + else + disp('The parameter you want to exclude is unknown!') + error + end + end + end + jndx = []; + for i=1:length(indx) + if ~any(indx(i)==tt) + jndx = [ jndx ; indx(i) ]; + end + end end \ No newline at end of file diff --git a/matlab/symmetric_matrix_index.m b/matlab/symmetric_matrix_index.m index b10d7e12c8..1f514ec77a 100644 --- a/matlab/symmetric_matrix_index.m +++ b/matlab/symmetric_matrix_index.m @@ -17,4 +17,4 @@ function k = symmetric_matrix_index(i,j,n) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - k = (i-1)*n+j-i*(i-1)/2; \ No newline at end of file +k = (i-1)*n+j-i*(i-1)/2; \ No newline at end of file diff --git a/matlab/th_autocovariances.m b/matlab/th_autocovariances.m index 12f4fa2cd1..26e4dd5196 100644 --- a/matlab/th_autocovariances.m +++ b/matlab/th_autocovariances.m @@ -1,230 +1,229 @@ -function [Gamma_y,stationary_vars] = th_autocovariances(dr,ivar,M_,options_,nodecomposition) -% Computes the theoretical auto-covariances, Gamma_y, for an AR(p) process -% with coefficients dr.ghx and dr.ghu and shock variances Sigma_e_ -% for a subset of variables ivar (indices in lgy_) -% Theoretical HPfiltering is available as an option -% -% INPUTS -% dr: [structure] Reduced form solution of the DSGE model (decisions rules) -% ivar: [integer] Vector of indices for a subset of variables. -% M_ [structure] Global dynare's structure, description of the DSGE model. -% options_ [structure] Global dynare's structure. -% nodecomposition [integer] Scalar, if different from zero the variance decomposition is not triggered. -% -% OUTPUTS -% Gamma_y [cell] Matlab cell of nar+3 (second order approximation) or nar+2 (first order approximation) arrays, -% where nar is the order of the autocorrelation function. -% Gamma_y{1} [double] Covariance matrix. -% Gamma_y{i} [double] Autocorrelation function (for i=1,...,options_.nar). -% Gamma_y{nar+2} [double] Variance decomposition. -% Gamma_y{nar+3} [double] Expectation of the endogenous variables associated with a second -% order approximation. -% stationary_vars [integer] Vector of indices of stationary -% variables in declaration order -% -% SPECIAL REQUIREMENTS -% - -% Copyright (C) 2001-2009 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 <http://www.gnu.org/licenses/>. - - if nargin<5 - nodecomposition = 0; - end - - endo_nbr = M_.endo_nbr; - exo_names_orig_ord = M_.exo_names_orig_ord; - if exist('OCTAVE_VERSION') - warning('off', 'Octave:divide-by-zero') - else - warning off MATLAB:dividebyzero - end - nar = options_.ar; - Gamma_y = cell(nar+1,1); - if isempty(ivar) - ivar = [1:endo_nbr]'; - end - nvar = size(ivar,1); - - ghx = dr.ghx; - ghu = dr.ghu; - npred = dr.npred; - nstatic = dr.nstatic; - kstate = dr.kstate; - order_var = dr.order_var; - inv_order_var = dr.inv_order_var; - nx = size(ghx,2); - - ikx = [nstatic+1:nstatic+npred]; - - k0 = kstate(find(kstate(:,2) <= M_.maximum_lag+1),:); - i0 = find(k0(:,2) == M_.maximum_lag+1); - i00 = i0; - n0 = length(i0); - AS = ghx(:,i0); - ghu1 = zeros(nx,M_.exo_nbr); - ghu1(i0,:) = ghu(ikx,:); - for i=M_.maximum_lag:-1:2 - i1 = find(k0(:,2) == i); - n1 = size(i1,1); - j1 = zeros(n1,1); - for k1 = 1:n1 - j1(k1) = find(k0(i00,1)==k0(i1(k1),1)); - end - AS(:,j1) = AS(:,j1)+ghx(:,i1); - i0 = i1; - end - b = ghu1*M_.Sigma_e*ghu1'; - - - ipred = nstatic+(1:npred)'; - % state space representation for state variables only - [A,B] = kalman_transition_matrix(dr,ipred,1:nx,dr.transition_auxiliary_variables,M_.exo_nbr); - if options_.order == 2 | options_.hp_filter == 0 - [vx, u] = lyapunov_symm(A,B*M_.Sigma_e*B',options_.qz_criterium,options_.lyapunov_complex_threshold); - iky = inv_order_var(ivar); - stationary_vars = (1:length(ivar))'; - if ~isempty(u) - x = abs(ghx*u); - iky = iky(find(all(x(iky,:) < options_.Schur_vec_tol,2))); - stationary_vars = find(all(x(inv_order_var(ivar(stationary_vars)),:) < options_.Schur_vec_tol,2)); - end - aa = ghx(iky,:); - bb = ghu(iky,:); - if options_.order == 2 % mean correction for 2nd order - Ex = (dr.ghs2(ikx)+dr.ghxx(ikx,:)*vx(:)+dr.ghuu(ikx,:)*M_.Sigma_e(:))/2; - Ex = (eye(n0)-AS(ikx,:))\Ex; - Gamma_y{nar+3} = AS(iky,:)*Ex+(dr.ghs2(iky)+dr.ghxx(iky,:)*vx(:)+... - dr.ghuu(iky,:)*M_.Sigma_e(:))/2; - end - end - if options_.hp_filter == 0 - v = NaN*ones(nvar,nvar); - v(stationary_vars,stationary_vars) = aa*vx*aa'+ bb*M_.Sigma_e*bb'; - k = find(abs(v) < 1e-12); - v(k) = 0; - Gamma_y{1} = v; - % autocorrelations - if nar > 0 - vxy = (A*vx*aa'+ghu1*M_.Sigma_e*bb'); - sy = sqrt(diag(Gamma_y{1})); - sy = sy(stationary_vars); - sy = sy *sy'; - Gamma_y{2} = NaN*ones(nvar,nvar); - Gamma_y{2}(stationary_vars,stationary_vars) = aa*vxy./sy; - for i=2:nar - vxy = A*vxy; - Gamma_y{i+1} = NaN*ones(nvar,nvar); - Gamma_y{i+1}(stationary_vars,stationary_vars) = aa*vxy./sy; - end - end - % variance decomposition - if ~nodecomposition && M_.exo_nbr > 1 - Gamma_y{nar+2} = zeros(nvar,M_.exo_nbr); - SS(exo_names_orig_ord,exo_names_orig_ord)=M_.Sigma_e+1e-14*eye(M_.exo_nbr); - cs = chol(SS)'; - b1(:,exo_names_orig_ord) = ghu1; - b1 = b1*cs; - b2(:,exo_names_orig_ord) = ghu(iky,:); - b2 = b2*cs; - vx = lyapunov_symm(A,b1*b1',options_.qz_criterium,options_.lyapunov_complex_threshold,1); - vv = diag(aa*vx*aa'+b2*b2'); - for i=1:M_.exo_nbr - vx1 = lyapunov_symm(A,b1(:,i)*b1(:,i)',options_.qz_criterium,options_.lyapunov_complex_threshold,2); - Gamma_y{nar+2}(stationary_vars,i) = abs(diag(aa*vx1*aa'+b2(:,i)*b2(:,i)'))./vv; - end - end - else% ==> Theoretical HP filter. - if options_.order < 2 - iky = inv_order_var(ivar); - aa = ghx(iky,:); - bb = ghu(iky,:); - end - lambda = options_.hp_filter; - ngrid = options_.hp_ngrid; - freqs = 0 : ((2*pi)/ngrid) : (2*pi*(1 - .5/ngrid)); - tpos = exp( sqrt(-1)*freqs); - tneg = exp(-sqrt(-1)*freqs); - hp1 = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2); - mathp_col = []; - IA = eye(size(A,1)); - IE = eye(M_.exo_nbr); - for ig = 1:ngrid - f_omega =(1/(2*pi))*( [inv(IA-A*tneg(ig))*ghu1;IE]... - *M_.Sigma_e*[ghu1'*inv(IA-A'*tpos(ig)) ... - IE]); % state variables - g_omega = [aa*tneg(ig) bb]*f_omega*[aa'*tpos(ig); bb']; % selected variables - f_hp = hp1(ig)^2*g_omega; % spectral density of selected filtered series - mathp_col = [mathp_col ; (f_hp(:))']; % store as matrix row - % for ifft - end; - % Covariance of filtered series - imathp_col = real(ifft(mathp_col))*(2*pi); - Gamma_y{1} = reshape(imathp_col(1,:),nvar,nvar); - % Autocorrelations - if nar > 0 - sy = sqrt(diag(Gamma_y{1})); - sy = sy *sy'; - for i=1:nar - Gamma_y{i+1} = reshape(imathp_col(i+1,:),nvar,nvar)./sy; - end - end - % Variance decomposition - if ~nodecomposition && M_.exo_nbr > 1 - Gamma_y{nar+2} = zeros(nvar,M_.exo_nbr); - SS(exo_names_orig_ord,exo_names_orig_ord) = M_.Sigma_e+1e-14*eye(M_.exo_nbr); - cs = chol(SS)'; - SS = cs*cs'; - b1(:,exo_names_orig_ord) = ghu1; - b2(:,exo_names_orig_ord) = ghu(iky,:); - mathp_col = []; - IA = eye(size(A,1)); - IE = eye(M_.exo_nbr); - for ig = 1:ngrid - f_omega =(1/(2*pi))*( [inv(IA-A*tneg(ig))*b1;IE]... - *SS*[b1'*inv(IA-A'*tpos(ig)) ... - IE]); % state variables - g_omega = [aa*tneg(ig) b2]*f_omega*[aa'*tpos(ig); b2']; % selected variables - f_hp = hp1(ig)^2*g_omega; % spectral density of selected filtered series - mathp_col = [mathp_col ; (f_hp(:))']; % store as matrix row - % for ifft - end; - imathp_col = real(ifft(mathp_col))*(2*pi); - vv = diag(reshape(imathp_col(1,:),nvar,nvar)); - for i=1:M_.exo_nbr - mathp_col = []; - SSi = cs(:,i)*cs(:,i)'; - for ig = 1:ngrid - f_omega =(1/(2*pi))*( [inv(IA-A*tneg(ig))*b1;IE]... - *SSi*[b1'*inv(IA-A'*tpos(ig)) ... - IE]); % state variables - g_omega = [aa*tneg(ig) b2]*f_omega*[aa'*tpos(ig); b2']; % selected variables - f_hp = hp1(ig)^2*g_omega; % spectral density of selected filtered series - mathp_col = [mathp_col ; (f_hp(:))']; % store as matrix row - % for ifft - end; - imathp_col = real(ifft(mathp_col))*(2*pi); - Gamma_y{nar+2}(:,i) = abs(diag(reshape(imathp_col(1,:),nvar,nvar)))./vv; - end - end - end - if exist('OCTAVE_VERSION') - warning('on', 'Octave:divide-by-zero') - else - warning on MATLAB:dividebyzero - end - \ No newline at end of file +function [Gamma_y,stationary_vars] = th_autocovariances(dr,ivar,M_,options_,nodecomposition) +% Computes the theoretical auto-covariances, Gamma_y, for an AR(p) process +% with coefficients dr.ghx and dr.ghu and shock variances Sigma_e_ +% for a subset of variables ivar (indices in lgy_) +% Theoretical HPfiltering is available as an option +% +% INPUTS +% dr: [structure] Reduced form solution of the DSGE model (decisions rules) +% ivar: [integer] Vector of indices for a subset of variables. +% M_ [structure] Global dynare's structure, description of the DSGE model. +% options_ [structure] Global dynare's structure. +% nodecomposition [integer] Scalar, if different from zero the variance decomposition is not triggered. +% +% OUTPUTS +% Gamma_y [cell] Matlab cell of nar+3 (second order approximation) or nar+2 (first order approximation) arrays, +% where nar is the order of the autocorrelation function. +% Gamma_y{1} [double] Covariance matrix. +% Gamma_y{i} [double] Autocorrelation function (for i=1,...,options_.nar). +% Gamma_y{nar+2} [double] Variance decomposition. +% Gamma_y{nar+3} [double] Expectation of the endogenous variables associated with a second +% order approximation. +% stationary_vars [integer] Vector of indices of stationary +% variables in declaration order +% +% SPECIAL REQUIREMENTS +% + +% Copyright (C) 2001-2009 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 <http://www.gnu.org/licenses/>. + +if nargin<5 + nodecomposition = 0; +end + +endo_nbr = M_.endo_nbr; +exo_names_orig_ord = M_.exo_names_orig_ord; +if exist('OCTAVE_VERSION') + warning('off', 'Octave:divide-by-zero') +else + warning off MATLAB:dividebyzero +end +nar = options_.ar; +Gamma_y = cell(nar+1,1); +if isempty(ivar) + ivar = [1:endo_nbr]'; +end +nvar = size(ivar,1); + +ghx = dr.ghx; +ghu = dr.ghu; +npred = dr.npred; +nstatic = dr.nstatic; +kstate = dr.kstate; +order_var = dr.order_var; +inv_order_var = dr.inv_order_var; +nx = size(ghx,2); + +ikx = [nstatic+1:nstatic+npred]; + +k0 = kstate(find(kstate(:,2) <= M_.maximum_lag+1),:); +i0 = find(k0(:,2) == M_.maximum_lag+1); +i00 = i0; +n0 = length(i0); +AS = ghx(:,i0); +ghu1 = zeros(nx,M_.exo_nbr); +ghu1(i0,:) = ghu(ikx,:); +for i=M_.maximum_lag:-1:2 + i1 = find(k0(:,2) == i); + n1 = size(i1,1); + j1 = zeros(n1,1); + for k1 = 1:n1 + j1(k1) = find(k0(i00,1)==k0(i1(k1),1)); + end + AS(:,j1) = AS(:,j1)+ghx(:,i1); + i0 = i1; +end +b = ghu1*M_.Sigma_e*ghu1'; + + +ipred = nstatic+(1:npred)'; +% state space representation for state variables only +[A,B] = kalman_transition_matrix(dr,ipred,1:nx,dr.transition_auxiliary_variables,M_.exo_nbr); +if options_.order == 2 | options_.hp_filter == 0 + [vx, u] = lyapunov_symm(A,B*M_.Sigma_e*B',options_.qz_criterium,options_.lyapunov_complex_threshold); + iky = inv_order_var(ivar); + stationary_vars = (1:length(ivar))'; + if ~isempty(u) + x = abs(ghx*u); + iky = iky(find(all(x(iky,:) < options_.Schur_vec_tol,2))); + stationary_vars = find(all(x(inv_order_var(ivar(stationary_vars)),:) < options_.Schur_vec_tol,2)); + end + aa = ghx(iky,:); + bb = ghu(iky,:); + if options_.order == 2 % mean correction for 2nd order + Ex = (dr.ghs2(ikx)+dr.ghxx(ikx,:)*vx(:)+dr.ghuu(ikx,:)*M_.Sigma_e(:))/2; + Ex = (eye(n0)-AS(ikx,:))\Ex; + Gamma_y{nar+3} = AS(iky,:)*Ex+(dr.ghs2(iky)+dr.ghxx(iky,:)*vx(:)+... + dr.ghuu(iky,:)*M_.Sigma_e(:))/2; + end +end +if options_.hp_filter == 0 + v = NaN*ones(nvar,nvar); + v(stationary_vars,stationary_vars) = aa*vx*aa'+ bb*M_.Sigma_e*bb'; + k = find(abs(v) < 1e-12); + v(k) = 0; + Gamma_y{1} = v; + % autocorrelations + if nar > 0 + vxy = (A*vx*aa'+ghu1*M_.Sigma_e*bb'); + sy = sqrt(diag(Gamma_y{1})); + sy = sy(stationary_vars); + sy = sy *sy'; + Gamma_y{2} = NaN*ones(nvar,nvar); + Gamma_y{2}(stationary_vars,stationary_vars) = aa*vxy./sy; + for i=2:nar + vxy = A*vxy; + Gamma_y{i+1} = NaN*ones(nvar,nvar); + Gamma_y{i+1}(stationary_vars,stationary_vars) = aa*vxy./sy; + end + end + % variance decomposition + if ~nodecomposition && M_.exo_nbr > 1 + Gamma_y{nar+2} = zeros(nvar,M_.exo_nbr); + SS(exo_names_orig_ord,exo_names_orig_ord)=M_.Sigma_e+1e-14*eye(M_.exo_nbr); + cs = chol(SS)'; + b1(:,exo_names_orig_ord) = ghu1; + b1 = b1*cs; + b2(:,exo_names_orig_ord) = ghu(iky,:); + b2 = b2*cs; + vx = lyapunov_symm(A,b1*b1',options_.qz_criterium,options_.lyapunov_complex_threshold,1); + vv = diag(aa*vx*aa'+b2*b2'); + for i=1:M_.exo_nbr + vx1 = lyapunov_symm(A,b1(:,i)*b1(:,i)',options_.qz_criterium,options_.lyapunov_complex_threshold,2); + Gamma_y{nar+2}(stationary_vars,i) = abs(diag(aa*vx1*aa'+b2(:,i)*b2(:,i)'))./vv; + end + end +else% ==> Theoretical HP filter. + if options_.order < 2 + iky = inv_order_var(ivar); + aa = ghx(iky,:); + bb = ghu(iky,:); + end + lambda = options_.hp_filter; + ngrid = options_.hp_ngrid; + freqs = 0 : ((2*pi)/ngrid) : (2*pi*(1 - .5/ngrid)); + tpos = exp( sqrt(-1)*freqs); + tneg = exp(-sqrt(-1)*freqs); + hp1 = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2); + mathp_col = []; + IA = eye(size(A,1)); + IE = eye(M_.exo_nbr); + for ig = 1:ngrid + f_omega =(1/(2*pi))*( [inv(IA-A*tneg(ig))*ghu1;IE]... + *M_.Sigma_e*[ghu1'*inv(IA-A'*tpos(ig)) ... + IE]); % state variables + g_omega = [aa*tneg(ig) bb]*f_omega*[aa'*tpos(ig); bb']; % selected variables + f_hp = hp1(ig)^2*g_omega; % spectral density of selected filtered series + mathp_col = [mathp_col ; (f_hp(:))']; % store as matrix row + % for ifft + end; + % Covariance of filtered series + imathp_col = real(ifft(mathp_col))*(2*pi); + Gamma_y{1} = reshape(imathp_col(1,:),nvar,nvar); + % Autocorrelations + if nar > 0 + sy = sqrt(diag(Gamma_y{1})); + sy = sy *sy'; + for i=1:nar + Gamma_y{i+1} = reshape(imathp_col(i+1,:),nvar,nvar)./sy; + end + end + % Variance decomposition + if ~nodecomposition && M_.exo_nbr > 1 + Gamma_y{nar+2} = zeros(nvar,M_.exo_nbr); + SS(exo_names_orig_ord,exo_names_orig_ord) = M_.Sigma_e+1e-14*eye(M_.exo_nbr); + cs = chol(SS)'; + SS = cs*cs'; + b1(:,exo_names_orig_ord) = ghu1; + b2(:,exo_names_orig_ord) = ghu(iky,:); + mathp_col = []; + IA = eye(size(A,1)); + IE = eye(M_.exo_nbr); + for ig = 1:ngrid + f_omega =(1/(2*pi))*( [inv(IA-A*tneg(ig))*b1;IE]... + *SS*[b1'*inv(IA-A'*tpos(ig)) ... + IE]); % state variables + g_omega = [aa*tneg(ig) b2]*f_omega*[aa'*tpos(ig); b2']; % selected variables + f_hp = hp1(ig)^2*g_omega; % spectral density of selected filtered series + mathp_col = [mathp_col ; (f_hp(:))']; % store as matrix row + % for ifft + end; + imathp_col = real(ifft(mathp_col))*(2*pi); + vv = diag(reshape(imathp_col(1,:),nvar,nvar)); + for i=1:M_.exo_nbr + mathp_col = []; + SSi = cs(:,i)*cs(:,i)'; + for ig = 1:ngrid + f_omega =(1/(2*pi))*( [inv(IA-A*tneg(ig))*b1;IE]... + *SSi*[b1'*inv(IA-A'*tpos(ig)) ... + IE]); % state variables + g_omega = [aa*tneg(ig) b2]*f_omega*[aa'*tpos(ig); b2']; % selected variables + f_hp = hp1(ig)^2*g_omega; % spectral density of selected filtered series + mathp_col = [mathp_col ; (f_hp(:))']; % store as matrix row + % for ifft + end; + imathp_col = real(ifft(mathp_col))*(2*pi); + Gamma_y{nar+2}(:,i) = abs(diag(reshape(imathp_col(1,:),nvar,nvar)))./vv; + end + end +end +if exist('OCTAVE_VERSION') + warning('on', 'Octave:divide-by-zero') +else + warning on MATLAB:dividebyzero +end diff --git a/matlab/threads/multi/set_dynare_threads.m b/matlab/threads/multi/set_dynare_threads.m index a3706f9474..3ddbba0a3c 100644 --- a/matlab/threads/multi/set_dynare_threads.m +++ b/matlab/threads/multi/set_dynare_threads.m @@ -8,7 +8,7 @@ function not = set_dynare_threads(n) % o not [integer] scalar, number of threads. % % REMARKS The default value of n is the number of processors on the platform. - + % Copyright (C) 2009 Dynare Team % % This file is part of Dynare. @@ -26,48 +26,48 @@ function not = set_dynare_threads(n) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - not = 1; - if ~isopenmp()% This version of Dynare does not use multithreaded mex files! - disp(' ') - disp('Multithreading is not available on your platform!') - disp(' ') - return - end - MaxNumberOfThreads = maxNumCompThreads(); - if ~nargin% Default. - not = MaxNumberOfThreads; - setenv('DYNARE_NUM_THREADS',int2str(MaxNumberOfThreads)); - else - if (n>MaxNumberOfThreads) - disp(['You want to use ' int2str(n) ' threads but your platform has only ' int2str(MaxNumberOfThreads) ' processors!']) - reply = input(['Do you really want to use ' int2str(n) ' threads ? Yes/[No]: '],'s'); - if isempty(reply) - reply = 'No'; +not = 1; +if ~isopenmp()% This version of Dynare does not use multithreaded mex files! + disp(' ') + disp('Multithreading is not available on your platform!') + disp(' ') + return +end +MaxNumberOfThreads = maxNumCompThreads(); +if ~nargin% Default. + not = MaxNumberOfThreads; + setenv('DYNARE_NUM_THREADS',int2str(MaxNumberOfThreads)); +else + if (n>MaxNumberOfThreads) + disp(['You want to use ' int2str(n) ' threads but your platform has only ' int2str(MaxNumberOfThreads) ' processors!']) + reply = input(['Do you really want to use ' int2str(n) ' threads ? Yes/[No]: '],'s'); + if isempty(reply) + reply = 'No'; + end + if strcmpi(reply,'No') + nn = input(['Choose a number of threads between 1 and [' int2str(MaxNumberOfThreads) ']: ']); + if isempty(nn) + nn = MaxNumberOfThreads; end - if strcmpi(reply,'No') - nn = input(['Choose a number of threads between 1 and [' int2str(MaxNumberOfThreads) ']: ']); - if isempty(nn) - nn = MaxNumberOfThreads; - end - if (nn>MaxNumberOfThreads) - disp(['To my knowledge ' int2str(nn) ' is greater than ' int2str(MaxNumberOfThreads) '!...']) - disp(' ') - not = set_dynare_threads(n); - return - end - not = nn; - setenv('DYNARE_NUM_THREADS',int2str(nn)); - elseif strcmpi(reply,'Yes') - not = n; - setenv('DYNARE_NUM_THREADS',int2str(n)); - else - disp(['You have to answer by Yes or No...']) + if (nn>MaxNumberOfThreads) + disp(['To my knowledge ' int2str(nn) ' is greater than ' int2str(MaxNumberOfThreads) '!...']) disp(' ') not = set_dynare_threads(n); return end - else + not = nn; + setenv('DYNARE_NUM_THREADS',int2str(nn)); + elseif strcmpi(reply,'Yes') not = n; - setenv('DYNARE_NUM_THREADS',int2str(n)); + setenv('DYNARE_NUM_THREADS',int2str(n)); + else + disp(['You have to answer by Yes or No...']) + disp(' ') + not = set_dynare_threads(n); + return end - end \ No newline at end of file + else + not = n; + setenv('DYNARE_NUM_THREADS',int2str(n)); + end +end \ No newline at end of file diff --git a/matlab/threads/single/isopmenmp.m b/matlab/threads/single/isopmenmp.m index 073330c909..285204839a 100644 --- a/matlab/threads/single/isopmenmp.m +++ b/matlab/threads/single/isopmenmp.m @@ -1,6 +1,6 @@ -function i = isopenmp() +function i = isopmenmp() % This file is called only if the mex files are not compiled with the openmp flag (mutithreaded computations). - + % Copyright (C) 2009 Dynare Team % % This file is part of Dynare. @@ -17,4 +17,4 @@ function i = isopenmp() % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - i = 0; \ No newline at end of file +i = 0; \ No newline at end of file diff --git a/matlab/trace_plot.m b/matlab/trace_plot.m index 38748f41cb..59a68afbc7 100644 --- a/matlab/trace_plot.m +++ b/matlab/trace_plot.m @@ -33,7 +33,7 @@ function trace_plot(options_,M_,estim_params_,type,blck,name1,name2) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - + % Cet the column index: if nargin<7 column = name2index(options_, M_, estim_params_, type, name1); diff --git a/matlab/transition_matrix.m b/matlab/transition_matrix.m index b3f8b7e977..389c5f2790 100644 --- a/matlab/transition_matrix.m +++ b/matlab/transition_matrix.m @@ -1,64 +1,63 @@ -function [A,B] = transition_matrix(dr, varargin) -% function [A,B] = transition_matrix(dr, varargin) -% Makes transition matrices out of ghx and ghu -% -% INPUTS -% dr: structure of decision rules for stochastic simulations -% varargin: {1}: M_ -% -% OUTPUTS -% A: matrix of effects of predetermined variables in linear solution (ghx) -% B: matrix of effects of shocks in linear solution (ghu) -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2003-2008 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 <http://www.gnu.org/licenses/>. - - if(length(varargin)<=0) - global M_ - else - M_=varargin{1}; - end; - - exo_nbr = M_.exo_nbr; - ykmin_ = M_.maximum_endo_lag; - - nx = size(dr.ghx,2); - kstate = dr.kstate; - ikx = [dr.nstatic+1:dr.nstatic+dr.npred]; - - A = zeros(nx,nx); - k0 = kstate(find(kstate(:,2) <= ykmin_+1),:); - i0 = find(k0(:,2) == ykmin_+1); - A(i0,:) = dr.ghx(ikx,:); - B = zeros(nx,exo_nbr); - if(isfield(dr,'ghu')) - B(i0,:) = dr.ghu(ikx,:); - end; - for i=ykmin_:-1:2 - i1 = find(k0(:,2) == i); - n1 = size(i1,1); - j = zeros(n1,1); - for j1 = 1:n1 - j(j1) = find(k0(i0,1)==k0(i1(j1),1)); - end - A(i1,i0(j))=eye(n1); - i0 = i1; - end - \ No newline at end of file +function [A,B] = transition_matrix(dr, varargin) +% function [A,B] = transition_matrix(dr, varargin) +% Makes transition matrices out of ghx and ghu +% +% INPUTS +% dr: structure of decision rules for stochastic simulations +% varargin: {1}: M_ +% +% OUTPUTS +% A: matrix of effects of predetermined variables in linear solution (ghx) +% B: matrix of effects of shocks in linear solution (ghu) +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2003-2008 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 <http://www.gnu.org/licenses/>. + +if(length(varargin)<=0) + global M_ +else + M_=varargin{1}; +end; + +exo_nbr = M_.exo_nbr; +ykmin_ = M_.maximum_endo_lag; + +nx = size(dr.ghx,2); +kstate = dr.kstate; +ikx = [dr.nstatic+1:dr.nstatic+dr.npred]; + +A = zeros(nx,nx); +k0 = kstate(find(kstate(:,2) <= ykmin_+1),:); +i0 = find(k0(:,2) == ykmin_+1); +A(i0,:) = dr.ghx(ikx,:); +B = zeros(nx,exo_nbr); +if(isfield(dr,'ghu')) + B(i0,:) = dr.ghu(ikx,:); +end; +for i=ykmin_:-1:2 + i1 = find(k0(:,2) == i); + n1 = size(i1,1); + j = zeros(n1,1); + for j1 = 1:n1 + j(j1) = find(k0(i0,1)==k0(i1(j1),1)); + end + A(i1,i0(j))=eye(n1); + i0 = i1; +end diff --git a/matlab/uniform_specification.m b/matlab/uniform_specification.m index c45f942435..e3e2233214 100644 --- a/matlab/uniform_specification.m +++ b/matlab/uniform_specification.m @@ -1,44 +1,44 @@ -function [m,s,p6,p7] = uniform_specification(m,s,p3,p4) -% Specification of the uniform density function parameters -% -% INPUTS -% m: mean -% s: standard deviation -% p3: lower bound -% p4: upper bound - -% OUTPUTS -% m: mean -% s: standard deviation -% p1: lower bound -% p2: upper bound -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2004-2009 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 <http://www.gnu.org/licenses/>. - - if ~(isnan(p3) | isnan(p4)) - p6 = p3; - p7 = p4; - m = (p3+p4)/2; - s = (p4-p3)/(sqrt(12)); - else - p6 = m-s*sqrt(3); - p7 = m+s*sqrt(3); - end \ No newline at end of file +function [m,s,p6,p7] = uniform_specification(m,s,p3,p4) +% Specification of the uniform density function parameters +% +% INPUTS +% m: mean +% s: standard deviation +% p3: lower bound +% p4: upper bound + +% OUTPUTS +% m: mean +% s: standard deviation +% p1: lower bound +% p2: upper bound +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2004-2009 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 <http://www.gnu.org/licenses/>. + +if ~(isnan(p3) | isnan(p4)) + p6 = p3; + p7 = p4; + m = (p3+p4)/2; + s = (p4-p3)/(sqrt(12)); +else + p6 = m-s*sqrt(3); + p7 = m+s*sqrt(3); +end \ No newline at end of file diff --git a/matlab/unvech.m b/matlab/unvech.m index f986b1d1cc..b5a2bdc1e5 100644 --- a/matlab/unvech.m +++ b/matlab/unvech.m @@ -23,13 +23,13 @@ function Matrix = unvech(Vector) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - m = length(Vector); - n = (sqrt(1+8*m)-1)/2; - b = 0; - Matrix = NaN(n,n); - for col = 1:n - idx = 1:col; - Matrix(1:col,col) = Vector(b+idx); - Matrix(col,1:col) = transpose(Matrix(1:col,col)); - b = b+length(idx); - end \ No newline at end of file +m = length(Vector); +n = (sqrt(1+8*m)-1)/2; +b = 0; +Matrix = NaN(n,n); +for col = 1:n + idx = 1:col; + Matrix(1:col,col) = Vector(b+idx); + Matrix(col,1:col) = transpose(Matrix(1:col,col)); + b = b+length(idx); +end \ No newline at end of file diff --git a/matlab/var_sample_moments.m b/matlab/var_sample_moments.m index 490954058d..46de57c4da 100644 --- a/matlab/var_sample_moments.m +++ b/matlab/var_sample_moments.m @@ -1,117 +1,117 @@ -function [YtY,XtY,YtX,XtX,Y,X] = ... - var_sample_moments(FirstObservation,LastObservation,qlag,var_trend_order,datafile,varobs,xls_sheet,xls_range) -% Computes the sample moments of a VAR model. -% -% The VAR(p) model is defined by: -% -% y_t = \sum_{k=1}^p y_{t-k} A_k + z_t C + e_t for t = 1,...,T -% -% where y_t is a 1*m vector of observed endogenous variables, p is the -% number of lags, A_k is an m*m real matrix, z_t is a 1*q vector of -% exogenous (deterministic) variables, C is a q*m real matrix and -% e_t is a vector of exogenous stochastic shocks. T is the number -% of observations. The deterministic exogenous variables are assumed to -% be a polynomial trend of order q = "var_trend_order". -% -% We define: -% -% <> Y = (y_1',y_2',...,y_T')' a T*m matrix, -% -% <> x_t = (y_{t-1},y_{t-2},...,y_{t-p},z_t) a 1*(mp+q) row vector, -% -% <> X = (x_1',x_2',...,x_T')' a T*(mp+q) matrix, -% -% <> E = (e_1',e_2',...,e_T')' a T*m matrix and -% -% <> A = (A_1',A_2',...,A_p',C')' an (mp+q)*m matrix of coefficients. -% -% So that we can equivalently write the VAR(p) model using the following -% matrix representation: -% -% Y = X * A +E -% -% -% INPUTS -% o FirstObservation [integer] First observation. -% o LastObservation [integer] Last observation. -% o qlag [integer] Number of lags in the VAR model. -% o var_trend_order [integer] Order of the polynomial exogenous trend: -% = -1 no constant and no linear trend, -% = 0 constant and no linear trend, -% = 1 constant and linear trend. -% -% OUTPUTS -% o YtY [double] Y'*Y an m*m matrix. -% o XtY [double] X'*Y an (mp+q)*m matrix. -% o YtX [double] Y'*X an m*(mp+q) matrix. -% o XtX [double] X'*X an (mp+q)*(mp+q) matrix. -% o Y [double] Y a T*m matrix. -% o X [double] X a T*(mp+q) matrix. -% -% SPECIAL REQUIREMENTS -% None. - -% Copyright (C) 2007 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 <http://www.gnu.org/licenses/>. - -X = []; -Y = []; -YtY = []; -YtX = []; -XtY = []; -XtX = []; - -data = read_variables(datafile,varobs,[],xls_sheet,xls_range); - -if qlag > FirstObservation - disp('VarSampleMoments :: not enough data to initialize! Try to increase FirstObservation.') - return -end - -NumberOfObservations = LastObservation-FirstObservation+1;% This is T. -NumberOfVariables = size(varobs,1);% This is m. -if var_trend_order == -1% No constant no linear trend case. - X = zeros(NumberOfObservations,NumberOfVariables*qlag); -elseif var_trend_order == 0% Constant and no linear trend case. - X = ones(NumberOfObservations,NumberOfVariables*qlag+1); - indx = NumberOfVariables*qlag+1; -elseif var_trend_order == 1;% Constant and linear trend case. - X = ones(NumberOfObservations,NumberOfVariables*qlag+2); - indx = NumberOfVariables*qlag+1:NumberOfVariables*qlag+2; -else - disp('var_sample_moments :: trend must be equal to -1,0 or 1!') - return -end - -% I build matrices Y and X -Y = data(FirstObservation:LastObservation,:); - -for t=1:NumberOfObservations - line = t + FirstObservation-1; - for lag = 1:qlag - X(t,(lag-1)*NumberOfVariables+1:lag*NumberOfVariables) = data(line-lag,:); - end -end - -if (var_trend_order == 1) - X(:,end) = transpose(1:NumberOfObservations) -end - -YtY = Y'*Y; -YtX = Y'*X; -XtY = X'*Y; +function [YtY,XtY,YtX,XtX,Y,X] = ... + var_sample_moments(FirstObservation,LastObservation,qlag,var_trend_order,datafile,varobs,xls_sheet,xls_range) +% Computes the sample moments of a VAR model. +% +% The VAR(p) model is defined by: +% +% y_t = \sum_{k=1}^p y_{t-k} A_k + z_t C + e_t for t = 1,...,T +% +% where y_t is a 1*m vector of observed endogenous variables, p is the +% number of lags, A_k is an m*m real matrix, z_t is a 1*q vector of +% exogenous (deterministic) variables, C is a q*m real matrix and +% e_t is a vector of exogenous stochastic shocks. T is the number +% of observations. The deterministic exogenous variables are assumed to +% be a polynomial trend of order q = "var_trend_order". +% +% We define: +% +% <> Y = (y_1',y_2',...,y_T')' a T*m matrix, +% +% <> x_t = (y_{t-1},y_{t-2},...,y_{t-p},z_t) a 1*(mp+q) row vector, +% +% <> X = (x_1',x_2',...,x_T')' a T*(mp+q) matrix, +% +% <> E = (e_1',e_2',...,e_T')' a T*m matrix and +% +% <> A = (A_1',A_2',...,A_p',C')' an (mp+q)*m matrix of coefficients. +% +% So that we can equivalently write the VAR(p) model using the following +% matrix representation: +% +% Y = X * A +E +% +% +% INPUTS +% o FirstObservation [integer] First observation. +% o LastObservation [integer] Last observation. +% o qlag [integer] Number of lags in the VAR model. +% o var_trend_order [integer] Order of the polynomial exogenous trend: +% = -1 no constant and no linear trend, +% = 0 constant and no linear trend, +% = 1 constant and linear trend. +% +% OUTPUTS +% o YtY [double] Y'*Y an m*m matrix. +% o XtY [double] X'*Y an (mp+q)*m matrix. +% o YtX [double] Y'*X an m*(mp+q) matrix. +% o XtX [double] X'*X an (mp+q)*(mp+q) matrix. +% o Y [double] Y a T*m matrix. +% o X [double] X a T*(mp+q) matrix. +% +% SPECIAL REQUIREMENTS +% None. + +% Copyright (C) 2007 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 <http://www.gnu.org/licenses/>. + +X = []; +Y = []; +YtY = []; +YtX = []; +XtY = []; +XtX = []; + +data = read_variables(datafile,varobs,[],xls_sheet,xls_range); + +if qlag > FirstObservation + disp('VarSampleMoments :: not enough data to initialize! Try to increase FirstObservation.') + return +end + +NumberOfObservations = LastObservation-FirstObservation+1;% This is T. +NumberOfVariables = size(varobs,1);% This is m. +if var_trend_order == -1% No constant no linear trend case. + X = zeros(NumberOfObservations,NumberOfVariables*qlag); +elseif var_trend_order == 0% Constant and no linear trend case. +X = ones(NumberOfObservations,NumberOfVariables*qlag+1); +indx = NumberOfVariables*qlag+1; +elseif var_trend_order == 1;% Constant and linear trend case. +X = ones(NumberOfObservations,NumberOfVariables*qlag+2); +indx = NumberOfVariables*qlag+1:NumberOfVariables*qlag+2; +else + disp('var_sample_moments :: trend must be equal to -1,0 or 1!') + return +end + +% I build matrices Y and X +Y = data(FirstObservation:LastObservation,:); + +for t=1:NumberOfObservations + line = t + FirstObservation-1; + for lag = 1:qlag + X(t,(lag-1)*NumberOfVariables+1:lag*NumberOfVariables) = data(line-lag,:); + end +end + +if (var_trend_order == 1) + X(:,end) = transpose(1:NumberOfObservations) +end + +YtY = Y'*Y; +YtX = Y'*X; +XtY = X'*Y; XtX = X'*X; \ No newline at end of file diff --git a/matlab/variance_decomposition_mc_analysis.m b/matlab/variance_decomposition_mc_analysis.m index b84005c4dc..77d371a8d1 100644 --- a/matlab/variance_decomposition_mc_analysis.m +++ b/matlab/variance_decomposition_mc_analysis.m @@ -19,73 +19,73 @@ function oo_ = variance_decomposition_mc_analysis(NumberOfSimulations,type,dname % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if strcmpi(type,'posterior') - TYPE = 'Posterior'; - PATH = [dname '/metropolis/']; - else - TYPE = 'Prior'; - PATH = [dname '/prior/moments/']; - end +if strcmpi(type,'posterior') + TYPE = 'Posterior'; + PATH = [dname '/metropolis/']; +else + TYPE = 'Prior'; + PATH = [dname '/prior/moments/']; +end - indx = check_name(vartan,var); - if isempty(indx) - disp([ type '_analysis:: ' var ' is not a stationary endogenous variable!']) - return - end - jndx = check_name(exonames,exo); - if isempty(jndx) - disp([ type '_analysis:: ' exo ' is not a declared exogenous variable!']) - return - end +indx = check_name(vartan,var); +if isempty(indx) + disp([ type '_analysis:: ' var ' is not a stationary endogenous variable!']) + return +end +jndx = check_name(exonames,exo); +if isempty(jndx) + disp([ type '_analysis:: ' exo ' is not a declared exogenous variable!']) + return +end - name = [ var '.' exo ]; - if isfield(oo_, [ TYPE 'TheoreticalMoments']) - eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;']) - if isfield(temporary_structure,'dsge') - eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;']) - if isfield(temporary_structure,'VarianceDecomposition') - eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge.VarianceDecomposition.mean;']) - if isfield(temporary_structure,name) - % Nothing to do. - return - end +name = [ var '.' exo ]; +if isfield(oo_, [ TYPE 'TheoreticalMoments']) + eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments;']) + if isfield(temporary_structure,'dsge') + eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge;']) + if isfield(temporary_structure,'VarianceDecomposition') + eval(['temporary_structure = oo_.' TYPE 'TheoreticalMoments.dsge.VarianceDecomposition.mean;']) + if isfield(temporary_structure,name) + % Nothing to do. + return end end end +end - ListOfFiles = dir([ PATH fname '_' TYPE 'VarianceDecomposition*.mat']); - i1 = 1; tmp = zeros(NumberOfSimulations,1); - indice = (indx-1)*rows(exonames)+jndx; - for file = 1:length(ListOfFiles) - load([ PATH ListOfFiles(file).name ]); - i2 = i1 + rows(Decomposition_array) - 1; - tmp(i1:i2) = Decomposition_array(:,indice); - i1 = i2+1; - end +ListOfFiles = dir([ PATH fname '_' TYPE 'VarianceDecomposition*.mat']); +i1 = 1; tmp = zeros(NumberOfSimulations,1); +indice = (indx-1)*rows(exonames)+jndx; +for file = 1:length(ListOfFiles) + load([ PATH ListOfFiles(file).name ]); + i2 = i1 + rows(Decomposition_array) - 1; + tmp(i1:i2) = Decomposition_array(:,indice); + i1 = i2+1; +end - t1 = min(tmp); t2 = max(tmp); - t3 = t2-t1;% How to normalize ? t1 and t2 may be zero... - if t3<1.0e-12 - if t1<1.0e-12 - t1 = 0; - end - if abs(t1-1)<1.0e-12 - t1 = 1; - end - p_mean = t1; - p_median = t1; - p_var = 0; - hpd_interval = NaN(2,1); - p_deciles = NaN(9,1); - density = NaN; - else - [p_mean, p_median, p_var, hpd_interval, p_deciles, density] = ... - posterior_moments(tmp,1,mh_conf_sig); +t1 = min(tmp); t2 = max(tmp); +t3 = t2-t1;% How to normalize ? t1 and t2 may be zero... +if t3<1.0e-12 + if t1<1.0e-12 + t1 = 0; end - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.VarianceDecomposition.mean.' name ' = p_mean;']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.VarianceDecomposition.median.' name ' = p_median;']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.VarianceDecomposition.variance.' name ' = p_var;']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.VarianceDecomposition.hpdinf.' name ' = hpd_interval(1);']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.VarianceDecomposition.hpdsup.' name ' = hpd_interval(2);']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.VarianceDecomposition.deciles.' name ' = p_deciles;']); - eval(['oo_.' TYPE 'TheoreticalMoments.dsge.VarianceDecomposition.density.' name ' = density;']); \ No newline at end of file + if abs(t1-1)<1.0e-12 + t1 = 1; + end + p_mean = t1; + p_median = t1; + p_var = 0; + hpd_interval = NaN(2,1); + p_deciles = NaN(9,1); + density = NaN; +else + [p_mean, p_median, p_var, hpd_interval, p_deciles, density] = ... + posterior_moments(tmp,1,mh_conf_sig); +end +eval(['oo_.' TYPE 'TheoreticalMoments.dsge.VarianceDecomposition.mean.' name ' = p_mean;']); +eval(['oo_.' TYPE 'TheoreticalMoments.dsge.VarianceDecomposition.median.' name ' = p_median;']); +eval(['oo_.' TYPE 'TheoreticalMoments.dsge.VarianceDecomposition.variance.' name ' = p_var;']); +eval(['oo_.' TYPE 'TheoreticalMoments.dsge.VarianceDecomposition.hpdinf.' name ' = hpd_interval(1);']); +eval(['oo_.' TYPE 'TheoreticalMoments.dsge.VarianceDecomposition.hpdsup.' name ' = hpd_interval(2);']); +eval(['oo_.' TYPE 'TheoreticalMoments.dsge.VarianceDecomposition.deciles.' name ' = p_deciles;']); +eval(['oo_.' TYPE 'TheoreticalMoments.dsge.VarianceDecomposition.density.' name ' = density;']); \ No newline at end of file diff --git a/matlab/varlist_indices.m b/matlab/varlist_indices.m index 7ce0f21f1b..480fb20c2b 100644 --- a/matlab/varlist_indices.m +++ b/matlab/varlist_indices.m @@ -1,47 +1,47 @@ -function [i_var,nvar] = varlist_indices(varlist) -% function [i_var,nvar] = varlist_indices(varlist) -% returns the indices of a list of endogenous variables -% -% INPUT -% varlist: (character area) list of variables -% -% OUTPUT -% i_var: variable indices in M_.endo_names -% nvar: number of variables in varlist -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. - - global M_ - - endo_nbr = M_.endo_nbr; - - if isempty(varlist) - varlist = M_.endo_names(1:M_.orig_endo_nbr,:); - end - i_var = []; - for i=1:size(varlist,1) - tmp = strmatch(varlist(i,:),M_.endo_names,'exact'); - if isempty(tmp) - error([tmp ' isn''t an endogenous variable']) - end - i_var = [i_var; tmp]; - end - nvar = length(i_var); +function [i_var,nvar] = varlist_indices(varlist) +% function [i_var,nvar] = varlist_indices(varlist) +% returns the indices of a list of endogenous variables +% +% INPUT +% varlist: (character area) list of variables +% +% OUTPUT +% i_var: variable indices in M_.endo_names +% nvar: number of variables in varlist +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. + +global M_ + +endo_nbr = M_.endo_nbr; + +if isempty(varlist) + varlist = M_.endo_names(1:M_.orig_endo_nbr,:); +end +i_var = []; +for i=1:size(varlist,1) + tmp = strmatch(varlist(i,:),M_.endo_names,'exact'); + if isempty(tmp) + error([tmp ' isn''t an endogenous variable']) + end + i_var = [i_var; tmp]; +end +nvar = length(i_var); diff --git a/matlab/vech.m b/matlab/vech.m index b42385b8cd..b483767185 100644 --- a/matlab/vech.m +++ b/matlab/vech.m @@ -23,11 +23,11 @@ function Vector = vech(Matrix) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - n = length(Matrix); - b = 0; - Vector = NaN(n*(n+1)/2,1); - for col = 1:n - idx = transpose(1:col); - Vector(b+idx) = Matrix((col-1)*n+idx); - b = b+length(idx); - end \ No newline at end of file +n = length(Matrix); +b = 0; +Vector = NaN(n*(n+1)/2,1); +for col = 1:n + idx = transpose(1:col); + Vector(b+idx) = Matrix((col-1)*n+idx); + b = b+length(idx); +end \ No newline at end of file diff --git a/matlab/vnorm.m b/matlab/vnorm.m index 1973a822dc..4e6b651145 100644 --- a/matlab/vnorm.m +++ b/matlab/vnorm.m @@ -1,87 +1,87 @@ -function y = vnorm(A,varargin) -% VNORM - Return the vector norm along specified dimension of A -% -% VNORM(A) returns the 2-norm along the first non-singleton -% dimension of A -% VNORM(A,dim) return the 2-norm along the dimension 'dim' -% VNORM(A,dim,normtype) returns the norm specified by normtype -% along the dimension 'dim' -% VNORM(A,[],normtype) returns the norm specified by normtype along -% the first non-singleton dimension of A -% -% normtype may be one of {inf,-inf,positive integer}. -% For a given vector, v, these norms are defined as -% inf: max(abs(v)) -% -inf: min(abs(v)) -% p (where p is a positive integer): sum(abs(v).^p)^(1/p) -% -% Examples: -% A = [8 1 6; 3 5 7; 4 -9 2]; -% -% %Columnwise 2-norm (Euclidean norm) -% vnorm(A,1) = [9.4340 10.3441 9.4340]; -% vnorm(A,[],2) % Same as above (since first non-singleton dimensions -% % is columnwise and default norm is 2-norm. -% vnorm(A,[],[])% Again, same as above -% -% % Row-wise maximum of absolute values -% vnorm(A,2,inf) = [8 7 9]'; -% -% % Columnwise minimum of absolute values -% vnorm(A,[],-inf) = [3 1 2]; -% -% % Error: Use the inf type and not the string 'inf' -% vnorm(A,[],'inf') % Wrong -% vnorm(A,[],inf) % Correct -% -% -% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. -dim = []; -ntype = []; - -if nargin>1 - dim = varargin{1}; - if isempty(dim) - idx = find(size(A)~=1); - dim = idx(1); - elseif dim~=floor(dim) || dim<1 - error('Dimension must be positive integer'); - end - if nargin>2 - ntype = varargin{2}; - end -end - - -if isempty(ntype) - y = sqrt(sum( abs(A).^2 , dim) ); -elseif ntype==1 - y = sum( abs(A) , dim ); -elseif isinf(ntype) - if ntype > 0 - y=max(abs(A), [], dim); - else - y=min(abs(A), [], dim); - end -elseif ntype~=floor(ntype) || ntype<1 - error(['Norm type must be one of inf,-inf or a positive ' ... - 'integer']); -else - y = (sum( abs(A).^ntype , dim) ).^(1/ntype); -end - +function y = vnorm(A,varargin) +% VNORM - Return the vector norm along specified dimension of A +% +% VNORM(A) returns the 2-norm along the first non-singleton +% dimension of A +% VNORM(A,dim) return the 2-norm along the dimension 'dim' +% VNORM(A,dim,normtype) returns the norm specified by normtype +% along the dimension 'dim' +% VNORM(A,[],normtype) returns the norm specified by normtype along +% the first non-singleton dimension of A +% +% normtype may be one of {inf,-inf,positive integer}. +% For a given vector, v, these norms are defined as +% inf: max(abs(v)) +% -inf: min(abs(v)) +% p (where p is a positive integer): sum(abs(v).^p)^(1/p) +% +% Examples: +% A = [8 1 6; 3 5 7; 4 -9 2]; +% +% %Columnwise 2-norm (Euclidean norm) +% vnorm(A,1) = [9.4340 10.3441 9.4340]; +% vnorm(A,[],2) % Same as above (since first non-singleton dimensions +% % is columnwise and default norm is 2-norm. +% vnorm(A,[],[])% Again, same as above +% +% % Row-wise maximum of absolute values +% vnorm(A,2,inf) = [8 7 9]'; +% +% % Columnwise minimum of absolute values +% vnorm(A,[],-inf) = [3 1 2]; +% +% % Error: Use the inf type and not the string 'inf' +% vnorm(A,[],'inf') % Wrong +% vnorm(A,[],inf) % Correct +% +% +% Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. +dim = []; +ntype = []; + +if nargin>1 + dim = varargin{1}; + if isempty(dim) + idx = find(size(A)~=1); + dim = idx(1); + elseif dim~=floor(dim) || dim<1 + error('Dimension must be positive integer'); + end + if nargin>2 + ntype = varargin{2}; + end +end + + +if isempty(ntype) + y = sqrt(sum( abs(A).^2 , dim) ); +elseif ntype==1 + y = sum( abs(A) , dim ); +elseif isinf(ntype) + if ntype > 0 + y=max(abs(A), [], dim); + else + y=min(abs(A), [], dim); + end +elseif ntype~=floor(ntype) || ntype<1 + error(['Norm type must be one of inf,-inf or a positive ' ... + 'integer']); +else + y = (sum( abs(A).^ntype , dim) ).^(1/ntype); +end + diff --git a/matlab/warning_config.m b/matlab/warning_config.m index a7a9a31af7..801c2e01c2 100644 --- a/matlab/warning_config.m +++ b/matlab/warning_config.m @@ -27,19 +27,19 @@ function warning_config() % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - warning on; - if exist('OCTAVE_VERSION') - warning('off', 'Octave:separator-insert'); - warning('off', 'Octave:matlab-incompatible'); - warning('off', 'Octave:single-quote-string'); - warning('off', 'Octave:missing-semicolon'); - warning('off', 'Octave:empty-list-elements'); - warning('off', 'Octave:num-to-str'); - warning('off', 'Octave:resize-on-range-error'); - warning('off', 'Octave:str-to-num'); - warning('off', 'Octave:string-concat'); - warning('off', 'Octave:variable-switch-label'); - warning('off', 'Octave:fortran-indexing'); - else - warning backtrace; - end +warning on; +if exist('OCTAVE_VERSION') + warning('off', 'Octave:separator-insert'); + warning('off', 'Octave:matlab-incompatible'); + warning('off', 'Octave:single-quote-string'); + warning('off', 'Octave:missing-semicolon'); + warning('off', 'Octave:empty-list-elements'); + warning('off', 'Octave:num-to-str'); + warning('off', 'Octave:resize-on-range-error'); + warning('off', 'Octave:str-to-num'); + warning('off', 'Octave:string-concat'); + warning('off', 'Octave:variable-switch-label'); + warning('off', 'Octave:fortran-indexing'); +else + warning backtrace; +end diff --git a/matlab/writedata.m b/matlab/writedata.m index 44ae0c4e36..9e48bc4855 100644 --- a/matlab/writedata.m +++ b/matlab/writedata.m @@ -1,52 +1,52 @@ -function writedata(fname) -% function writedata(fname) -% store endogenous and exogenous variables in a XLS spreadsheet file -% INPUT -% fname: name of the XLS file -% OUTPUT -% none -% ALGORITHM -% none -% SPECIAL REQUIREMENT -% none - -% Copyright (C) 2007 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 <http://www.gnu.org/licenses/>. - - global M_ oo_ - - % xlswrite doesn't exist on Octave, and appeared in MATLAB 7.0 - if exist('OCTAVE_VERSION') || matlab_ver_less_than('7.0') - error('Function not supported on your version of MATLAB or Octave') - end - - S=[fname '_endo.xls']; - n=size(oo_.endo_simul,2); - delete(S); - S=upper(cellstr(M_.endo_names)); - S1=cellstr([num2str((1:n)') char(65*ones(1,n))']); - xlswrite([fname '_endo'], S', 'endogenous', 'B1'); - xlswrite([fname '_endo'], S1, 'endogenous', 'A2'); - xlswrite([fname '_endo'], oo_.endo_simul', 'endogenous', 'B2'); - S=[fname '_exo.xls']; - n=size(oo_.exo_simul,1); - delete(S); - S=upper(cellstr(M_.exo_names)); - S1=cellstr([num2str((1:n)') char(65*ones(1,n))']); - xlswrite([fname '_exo'], S','exogenous', 'B1'); - xlswrite([fname '_exo'], S1, 'exogenous', 'A2'); - xlswrite([fname '_exo'], oo_.exo_simul,'exogenous', 'B2'); +function writedata(fname) +% function writedata(fname) +% store endogenous and exogenous variables in a XLS spreadsheet file +% INPUT +% fname: name of the XLS file +% OUTPUT +% none +% ALGORITHM +% none +% SPECIAL REQUIREMENT +% none + +% Copyright (C) 2007 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 <http://www.gnu.org/licenses/>. + +global M_ oo_ + +% xlswrite doesn't exist on Octave, and appeared in MATLAB 7.0 +if exist('OCTAVE_VERSION') || matlab_ver_less_than('7.0') + error('Function not supported on your version of MATLAB or Octave') +end + +S=[fname '_endo.xls']; +n=size(oo_.endo_simul,2); +delete(S); +S=upper(cellstr(M_.endo_names)); +S1=cellstr([num2str((1:n)') char(65*ones(1,n))']); +xlswrite([fname '_endo'], S', 'endogenous', 'B1'); +xlswrite([fname '_endo'], S1, 'endogenous', 'A2'); +xlswrite([fname '_endo'], oo_.endo_simul', 'endogenous', 'B2'); +S=[fname '_exo.xls']; +n=size(oo_.exo_simul,1); +delete(S); +S=upper(cellstr(M_.exo_names)); +S1=cellstr([num2str((1:n)') char(65*ones(1,n))']); +xlswrite([fname '_exo'], S','exogenous', 'B1'); +xlswrite([fname '_exo'], S1, 'exogenous', 'A2'); +xlswrite([fname '_exo'], oo_.exo_simul,'exogenous', 'B2'); diff --git a/matlab/writedata_text.m b/matlab/writedata_text.m index ac05b864ac..1559676f25 100644 --- a/matlab/writedata_text.m +++ b/matlab/writedata_text.m @@ -1,54 +1,54 @@ -function writedata_text(fname) -% function writedata(fname) -% store endogenous and exogenous variables in a text file -% INPUT -% fname: name of the text file -% OUTPUT -% none -% ALGORITHM -% none -% SPECIAL REQUIREMENT -% none - -% Copyright (C) 2007 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 <http://www.gnu.org/licenses/>. - - global M_ oo_ - S=[fname '_endo.dat']; - fid = fopen(S,'w'); - for i = 1:size(M_.endo_names,1) - fprintf(fid,'%s ',M_.endo_names(i,:)'); - end; - fprintf(fid,'\n'); - for i = 1:size(oo_.endo_simul,2) - fprintf(fid,'%15.7f ',oo_.endo_simul(:,i)); - fprintf(fid,'\n'); - end - fclose(fid); - - S=[fname '_exo.dat']; - fid = fopen(S,'w'); - for i = 1:size(M_.exo_names,1) - fprintf(fid,'%s ',M_.exo_names(i,:)); - end; - fprintf(fid,'\n'); - for i = 1:size(oo_.exo_simul,1) - fprintf(fid,'%15.7f ',oo_.exo_simul(i,:)); - fprintf(fid,'\n'); - end - fclose(fid); +function writedata_text(fname) +% function writedata(fname) +% store endogenous and exogenous variables in a text file +% INPUT +% fname: name of the text file +% OUTPUT +% none +% ALGORITHM +% none +% SPECIAL REQUIREMENT +% none + +% Copyright (C) 2007 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 <http://www.gnu.org/licenses/>. + +global M_ oo_ +S=[fname '_endo.dat']; +fid = fopen(S,'w'); +for i = 1:size(M_.endo_names,1) + fprintf(fid,'%s ',M_.endo_names(i,:)'); +end; +fprintf(fid,'\n'); +for i = 1:size(oo_.endo_simul,2) + fprintf(fid,'%15.7f ',oo_.endo_simul(:,i)); + fprintf(fid,'\n'); +end +fclose(fid); + +S=[fname '_exo.dat']; +fid = fopen(S,'w'); +for i = 1:size(M_.exo_names,1) + fprintf(fid,'%s ',M_.exo_names(i,:)); +end; +fprintf(fid,'\n'); +for i = 1:size(oo_.exo_simul,1) + fprintf(fid,'%15.7f ',oo_.exo_simul(i,:)); + fprintf(fid,'\n'); +end +fclose(fid); return; \ No newline at end of file -- GitLab