From 5417b27ac748d4cd458674a8231defbc14e313da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Adjemian=20=28Charybdis=29?= <stephane.adjemian@univ-lemans.fr> Date: Tue, 16 May 2017 15:10:20 +0200 Subject: [PATCH] Fixed indentation of matlab files. --- matlab/AHessian.m | 183 +- matlab/AIM/SPAimerr.m | 2 +- matlab/AIM/SPAmalg.m | 24 +- matlab/AIM/SPBuild_a.m | 16 +- matlab/AIM/SPCopy_w.m | 8 +- matlab/AIM/SPEigensystem.m | 38 +- matlab/AIM/SPExact_shift.m | 13 +- matlab/AIM/SPNumeric_shift.m | 20 +- matlab/AIM/SPObstruct.m | 14 +- matlab/AIM/SPReduced_form.m | 3 +- matlab/AIM/SPShiftright.m | 2 +- matlab/AIM/dynAIMsolver1.m | 48 +- matlab/AIM_first_order_solver.m | 55 +- matlab/CheckPath.m | 2 +- matlab/CutSample.m | 2 +- matlab/DsgeSmoother.m | 84 +- matlab/GetAllPosteriorDraws.m | 8 +- matlab/GetOneDraw.m | 4 +- matlab/GetPosteriorMeanVariance.m | 64 +- matlab/GetPosteriorParametersStatistics.m | 34 +- matlab/MakeAllFigures.m | 12 +- matlab/PlotPosteriorDistributions.m | 24 +- matlab/PosteriorIRF.m | 158 +- matlab/PosteriorIRF_core2.m | 8 +- matlab/ReshapeMatFiles.m | 14 +- matlab/TaRB_optimizer_wrapper.m | 11 +- matlab/Tracing.m | 6 +- matlab/UnivariateSpectralDensity.m | 24 +- matlab/WriteShockDecomp2Excel.m | 25 +- matlab/add_filter_subtitle.m | 4 +- matlab/add_path_to_mex_files.m | 4 +- matlab/annualized_shock_decomposition.m | 229 +- matlab/autoregressive_process_specification.m | 24 +- matlab/backward_model_inversion.m | 6 +- matlab/basic_plan.m | 114 +- matlab/bksup0.m | 2 +- matlab/bksup1.m | 3 +- matlab/bksupk.m | 2 +- matlab/bseastr.m | 7 +- matlab/bvar_density.m | 12 +- matlab/bvar_forecast.m | 28 +- matlab/bvar_irf.m | 14 +- matlab/bvar_toolbox.m | 18 +- matlab/cartesian_product_of_sets.m | 2 +- matlab/cellofchar2mfile.m | 4 +- matlab/check_for_calibrated_covariances.m | 5 +- matlab/check_list_of_variables.m | 18 +- matlab/check_matlab_path.m | 70 +- matlab/check_posterior_analysis_data.m | 12 +- matlab/check_posterior_sampler_options.m | 625 ++- matlab/check_prior_analysis_data.m | 18 +- matlab/check_prior_bounds.m | 2 +- matlab/chol_SE.m | 55 +- matlab/clear_persistent_variables.m | 2 +- matlab/cli/prior.m | 14 +- matlab/collect_latex_files.m | 28 +- matlab/compute_Pinf_Pstar.m | 23 +- matlab/compute_mh_covariance_matrix.m | 12 +- matlab/compute_model_moments.m | 4 +- matlab/compute_moments_varendo.m | 10 +- matlab/compute_overall_acceptance_ratio.m | 6 +- matlab/conditional_variance_decomposition.m | 12 +- ...ional_variance_decomposition_mc_analysis.m | 4 +- .../convergence_diagnostics/McMCDiagnostics.m | 77 +- .../McMCDiagnostics_core.m | 12 +- .../geweke_chi2_test.m | 35 +- .../convergence_diagnostics/geweke_moments.m | 23 +- matlab/convergence_diagnostics/mcmc_ifac.m | 142 +- .../convergence_diagnostics/raftery_lewis.m | 68 +- matlab/convert_dyn_45_to_44.m | 22 +- matlab/convert_oo_.m | 2 +- matlab/correlation_mc_analysis.m | 2 +- matlab/cosn.m | 3 - matlab/covariance_mc_analysis.m | 12 +- matlab/csolve.m | 4 +- matlab/cubature_with_gaussian_weight.m | 32 +- matlab/cycle_reduction.m | 4 +- matlab/datatomfile.m | 15 +- matlab/dcompare.m | 2 - matlab/delete_mh_history_files.m | 2 +- matlab/discretionary_policy_1.m | 54 +- matlab/discretionary_policy_engine.m | 30 +- matlab/disp_dr.m | 20 +- matlab/disp_identification.m | 90 +- matlab/disp_model_summary.m | 3 +- matlab/disp_moments.m | 30 +- matlab/disp_steady_state.m | 4 +- matlab/disp_th_moments.m | 24 +- ...splay_conditional_variance_decomposition.m | 18 +- matlab/display_estimation_results_table.m | 170 +- matlab/display_problematic_vars_Jacobian.m | 74 +- matlab/distributions/beta_specification.m | 6 +- matlab/distributions/compute_prior_mode.m | 16 +- matlab/distributions/gamma_specification.m | 4 +- .../inverse_gamma_specification.m | 6 +- matlab/distributions/lpdfgweibull.m | 28 +- .../distributions/mode_and_variance_to_mean.m | 16 +- .../distributions/multivariate_normal_pdf.m | 16 +- .../distributions/multivariate_student_pdf.m | 12 +- matlab/distributions/rand_inverse_wishart.m | 8 +- matlab/distributions/rand_matrix_normal.m | 6 +- .../distributions/rand_multivariate_normal.m | 10 +- .../distributions/rand_multivariate_student.m | 16 +- matlab/distributions/weibull_specification.m | 11 +- matlab/do_parameter_initialization.m | 29 +- matlab/dr_block.m | 196 +- matlab/draw_prior_density.m | 14 +- matlab/dsample.m | 6 +- matlab/dsge_likelihood.m | 140 +- .../dsge_simulated_theoretical_correlation.m | 2 +- ...lated_theoretical_variance_decomposition.m | 10 +- matlab/dsge_var_likelihood.m | 24 +- matlab/dy_date.m | 1 - matlab/dyn2vec.m | 7 +- matlab/dyn_diag_vech.m | 8 +- matlab/dyn_first_order_solver.m | 16 +- matlab/dyn_forecast.m | 28 +- matlab/dyn_latex_table.m | 2 +- matlab/dyn_ramsey_static.m | 25 +- matlab/dyn_risky_steadystate_solver.m | 972 ++-- matlab/dyn_saveas.m | 18 +- matlab/dyn_second_order_solver.m | 264 +- matlab/dyn_unvech.m | 8 +- matlab/dyn_vech.m | 8 +- matlab/dyn_waitbar.m | 5 +- matlab/dyn_waitbar_close.m | 4 +- matlab/dynare.m | 18 +- matlab/dynare_config.m | 4 +- matlab/dynare_estimation.m | 34 +- matlab/dynare_estimation_1.m | 214 +- matlab/dynare_estimation_init.m | 28 +- matlab/dynare_gradient.m | 8 +- matlab/dynare_graph.m | 6 +- matlab/dynare_graph_close.m | 3 +- matlab/dynare_graph_init.m | 2 +- matlab/dynare_identification.m | 170 +- matlab/dynare_sensitivity.m | 136 +- matlab/dynare_solve.m | 11 +- matlab/dynare_solve_block_or_bytecode.m | 4 +- matlab/dynare_squeeze.m | 2 +- matlab/dynatype.m | 6 +- matlab/dyntable.m | 12 +- matlab/endogenous_prior.m | 13 +- matlab/endogenous_prior_restrictions.m | 344 +- matlab/ep/ep_problem_2.m | 8 +- matlab/ep/euler_equation_error.m | 4 +- matlab/ep/extended_path.m | 6 +- matlab/ep/extended_path_core.m | 10 +- matlab/ep/extended_path_homotopy.m | 2 +- matlab/ep/extended_path_initialization.m | 9 +- matlab/ep/extended_path_mc.m | 6 +- matlab/ep/setup_integration_nodes.m | 72 +- ...tochastic_perfect_foresight_model_solver.m | 3 +- ...solve_stochastic_perfect_foresight_model.m | 350 +- ...lve_stochastic_perfect_foresight_model_1.m | 2 +- matlab/ep/stroud_judd_7.5.8.m | 18 +- matlab/ep_residuals.m | 18 +- matlab/evaluate_max_dynamic_residual.m | 2 +- matlab/evaluate_planner_objective.m | 10 +- matlab/evaluate_posterior_kernel.m | 12 +- matlab/evaluate_prior.m | 8 +- matlab/evaluate_smoother.m | 4 +- matlab/evaluate_static_model.m | 50 +- matlab/evaluate_steady_state.m | 480 +- matlab/evaluate_steady_state_file.m | 220 +- matlab/expand_group.m | 4 +- matlab/fastgensylv.m | 8 +- matlab/ff1_.m | 7 +- matlab/ffill.m | 4 +- matlab/flip_plan.m | 120 +- matlab/forcst.m | 4 +- matlab/forcst2.m | 6 +- matlab/forcst2a.m | 3 +- matlab/forecast_graphs.m | 18 +- matlab/ftest.m | 4 +- matlab/gauss_hermite_weights_and_nodes.m | 6 +- matlab/gauss_legendre_weights_and_nodes.m | 2 +- matlab/gcompare.m | 5 +- matlab/gensylv/gensylv.m | 10 +- matlab/gensylv_fp.m | 10 +- matlab/getH.m | 302 +- matlab/getIrfShocksIndx.m | 2 +- matlab/getJJ.m | 24 +- matlab/get_Hessian.m | 317 +- matlab/get_all_parameters.m | 10 +- matlab/get_dynare_random_generator_state.m | 36 +- matlab/get_file_extension.m | 8 +- matlab/get_moments_size.m | 4 +- matlab/get_name_of_the_last_mh_file.m | 12 +- matlab/get_optimal_policy_discount_factor.m | 8 +- matlab/get_param_by_name.m | 2 +- matlab/get_posterior_parameters.m | 12 +- matlab/get_subsamples_range_indx.m | 2 +- matlab/get_variables_list.m | 14 +- matlab/get_variance_of_endogenous_variables.m | 7 +- matlab/global_initialization.m | 17 +- matlab/graph_decomp.m | 12 +- matlab/graph_decomp_detail.m | 166 +- matlab/gsa/Morris_Measure_Groups.m | 86 +- matlab/gsa/Sampling_Function_2.m | 110 +- matlab/gsa/cumplot.m | 2 +- matlab/gsa/filt_mc_.m | 255 +- matlab/gsa/ghx2transition.m | 38 +- matlab/gsa/gsa_plotmatrix.m | 54 +- matlab/gsa/gsa_skewness.m | 8 +- matlab/gsa/gsa_speed.m | 38 +- matlab/gsa/log_trans_.m | 94 +- matlab/gsa/map_calibration.m | 26 +- matlab/gsa/map_ident_.m | 2906 +++++----- matlab/gsa/mc_moments.m | 28 +- matlab/gsa/mcf_analysis.m | 168 +- matlab/gsa/myboxplot.m | 140 +- matlab/gsa/myprctilecol.m | 10 +- matlab/gsa/pick.m | 178 +- matlab/gsa/prior_draw_gsa.m | 88 +- matlab/gsa/read_data.m | 12 +- matlab/gsa/redform_map.m | 198 +- matlab/gsa/redform_screen.m | 171 +- matlab/gsa/scatter_analysis.m | 2 +- matlab/gsa/scatter_callback.m | 14 +- matlab/gsa/scatter_mcf.m | 364 +- matlab/gsa/scatter_plots.m | 22 +- matlab/gsa/set_shocks_param.m | 8 +- matlab/gsa/smirnov.m | 6 +- matlab/gsa/stab_map_.m | 66 +- matlab/gsa/stab_map_1.m | 26 +- matlab/gsa/stab_map_2.m | 106 +- matlab/gsa/stand_.m | 6 +- matlab/gsa/tcrit.m | 210 +- matlab/gsa/teff.m | 48 +- matlab/gsa/th_moments.m | 2 - matlab/gsa/trank.m | 4 +- matlab/hessian.m | 24 +- matlab/hessian_sparse.m | 22 +- matlab/histvalf.m | 1 - matlab/homotopy1.m | 2 +- matlab/homotopy2.m | 2 +- matlab/homotopy3.m | 10 +- matlab/ident_bruteforce.m | 10 +- matlab/identification_analysis.m | 128 +- matlab/identification_checks.m | 57 +- matlab/imcforecast.m | 26 +- matlab/indnv.m | 3 - matlab/init_plan.m | 51 +- matlab/initial_condition_decomposition.m | 94 +- matlab/initial_estimation_checks.m | 26 +- matlab/initialize_from_mode.m | 7 +- matlab/initvalf.m | 28 +- matlab/interpret_resol_info.m | 8 +- matlab/irf.m | 6 +- matlab/isolder.m | 10 +- matlab/k_order_pert.m | 36 +- matlab/kalman/build_selection_matrix.m | 2 +- matlab/kalman/likelihood/computeDLIK.m | 210 +- matlab/kalman/likelihood/kalman_filter.m | 4 +- matlab/kalman/likelihood/kalman_filter_d.m | 54 +- matlab/kalman/likelihood/kalman_filter_fast.m | 8 +- .../missing_observations_kalman_filter.m | 22 +- .../missing_observations_kalman_filter_d.m | 40 +- .../likelihood/univariate_computeDLIK.m | 28 +- .../likelihood/univariate_computeDstate.m | 12 +- .../likelihood/univariate_kalman_filter.m | 24 +- .../likelihood/univariate_kalman_filter_d.m | 16 +- .../likelihood/univariate_kalman_filter_ss.m | 4 +- matlab/kalman/steady_state_kalman_gain.m | 14 +- matlab/kalman_transition_matrix.m | 7 +- matlab/kernel_density_estimate.m | 38 +- matlab/list_of_parameters_calibrated_as_NaN.m | 8 +- matlab/lmmcp/catstruct.m | 345 +- matlab/lmmcp/dyn_lmmcp_func.m | 59 +- matlab/lmmcp/get_complementarity_conditions.m | 21 +- matlab/lmmcp/lmmcp.m | 1250 ++--- matlab/lnsrch1.m | 8 +- matlab/lnsrch1_wrapper_one_boundary.m | 8 +- matlab/lnsrch1_wrapper_two_boundaries.m | 8 +- matlab/load_first_mh_history_file.m | 2 +- matlab/load_last_mh_history_file.m | 8 +- matlab/load_m_file_data_legacy.m | 144 +- matlab/load_mat_file_data_legacy.m | 8 +- matlab/lpdfgam.m | 8 +- matlab/lpdfgbeta.m | 18 +- matlab/lpdfig1.m | 15 +- matlab/lpdfig2.m | 14 +- matlab/lpdfnorm.m | 16 +- matlab/lyapunov_solver.m | 12 +- matlab/lyapunov_symm.m | 16 +- matlab/marginal_density.m | 24 +- matlab/matlab_ver_less_than.m | 2 +- matlab/maximize_prior_density.m | 8 +- matlab/mcforecast3.m | 6 +- matlab/mcompare.m | 4 +- matlab/mcp_func.m | 6 +- matlab/metropolis_draw.m | 24 +- matlab/metropolis_hastings_initialization.m | 72 +- matlab/metropolis_run_analysis.m | 6 +- matlab/mex/k_order_perturbation.m | 2 +- matlab/mex/qmc_sequence.m | 4 +- matlab/mh_autocorrelation_function.m | 16 +- matlab/mh_optimal_bandwidth.m | 60 +- matlab/minus_logged_prior_density.m | 14 +- matlab/missing/corrcoef/corrcoef.m | 285 +- .../missing/corrcoef/flag_implicit_skip_nan.m | 17 +- matlab/missing/corrcoef/sumskipnan.m | 39 +- matlab/missing/corrcoef/tcdf.m | 4 +- matlab/missing/ilu/ilu.m | 30 +- matlab/missing/issquare/issquare.m | 4 +- matlab/missing/stats/betacdf.m | 1 - matlab/missing/stats/betarnd.m | 12 +- matlab/missing/stats/corr.m | 10 +- matlab/missing/stats/exprnd.m | 12 +- matlab/missing/stats/gamrnd.m | 26 +- matlab/missing/stats/quantile.m | 58 +- matlab/missing/stats/stdnormal_inv.m | 1 - matlab/missing/stats/wblcdf.m | 9 +- matlab/missing/stats/wblinv.m | 7 +- matlab/missing/stats/wblrnd.m | 4 +- matlab/missing/struct2array/struct2array.m | 4 +- matlab/missing/vec/vec.m | 8 +- matlab/missing_DiffuseKalmanSmootherH1_Z.m | 42 +- matlab/missing_DiffuseKalmanSmootherH3_Z.m | 72 +- matlab/mode_check.m | 4 +- matlab/model_comparison.m | 20 +- matlab/model_diagnostics.m | 37 +- matlab/model_info.m | 31 +- matlab/model_inversion.m | 14 +- matlab/moment_function.m | 12 +- matlab/moments.m | 2 +- .../clean_files_for_second_type_of_mex.m | 16 +- matlab/ms-sbvar/dyn_save_graph.m | 72 +- matlab/ms-sbvar/identification/exclusions.m | 32 +- .../ms-sbvar/identification/lower_cholesky.m | 16 +- .../ms-sbvar/identification/upper_cholesky.m | 18 +- matlab/ms-sbvar/ms_estimation.m | 2 +- matlab/ms-sbvar/ms_forecast.m | 16 +- matlab/ms-sbvar/ms_irf.m | 16 +- matlab/ms-sbvar/ms_mardd.m | 196 +- matlab/ms-sbvar/ms_sbvar_setup.m | 14 +- matlab/ms-sbvar/ms_variance_decomposition.m | 4 +- matlab/ms-sbvar/ms_write_markov_file.m | 240 +- matlab/ms-sbvar/ms_write_mhm_input.m | 60 +- matlab/ms-sbvar/msstart2.m | 1104 ++-- matlab/ms-sbvar/msstart_setup.m | 93 +- matlab/ms-sbvar/plot_ms_forecast.m | 202 +- matlab/ms-sbvar/plot_ms_irf.m | 168 +- matlab/ms-sbvar/plot_ms_probabilities.m | 36 +- .../ms-sbvar/plot_ms_variance_decomposition.m | 232 +- ...ot_ms_variance_decomposition_error_bands.m | 12 +- .../svar_global_identification_check.m | 2 +- matlab/mult_elimination.m | 6 +- matlab/multivariate_sample_autocovariance.m | 10 +- matlab/myboxplot.m | 6 +- matlab/name2index.m | 8 +- matlab/non_linear_dsge_likelihood.m | 5 +- matlab/occbin/call_solve_one_constraint.m | 42 +- matlab/occbin/call_solve_two_constraints.m | 42 +- matlab/occbin/get_deriv.m | 165 +- matlab/occbin/get_pq.m | 54 +- matlab/occbin/makechart.m | 162 +- matlab/occbin/makechart9.m | 272 +- matlab/occbin/map_regime.m | 49 +- matlab/occbin/mkdata.m | 124 +- matlab/occbin/mkdatap_anticipated.m | 248 +- .../occbin/mkdatap_anticipated_2constraints.m | 358 +- matlab/occbin/pickaxes.m | 32 +- matlab/occbin/process_constraint.m | 74 +- matlab/occbin/setss.m | 27 +- matlab/occbin/solve_no_constraint.m | 99 +- matlab/occbin/solve_no_constraint_noclear.m | 95 +- matlab/occbin/solve_one_constraint.1.m | 384 +- matlab/occbin/solve_one_constraint.m | 400 +- matlab/occbin/solve_two_constraints.m | 609 ++- matlab/occbin/strmerge.m | 16 +- matlab/occbin/tokenize.m | 109 +- matlab/octave_ver_less_than.m | 2 +- matlab/one_sided_hp_filter.m | 26 +- matlab/optimization/apprgrdn.m | 10 +- matlab/optimization/bfgsi1.m | 10 +- matlab/optimization/cmaes.m | 4729 ++++++++--------- matlab/optimization/csminit1.m | 16 +- matlab/optimization/csminwel1.m | 44 +- .../optimization/dynare_minimize_objective.m | 62 +- matlab/optimization/gmhmaxlik.m | 2 +- matlab/optimization/gmhmaxlik_core.m | 50 +- matlab/optimization/mr_gstep.m | 2 - matlab/optimization/mr_hessian.m | 16 +- matlab/optimization/newrat.m | 34 +- .../optimization/penalty_objective_function.m | 4 +- .../simplex_optimization_routine.m | 80 +- matlab/optimization/simpsa.m | 186 +- matlab/optimization/simpsaget.m | 69 +- matlab/optimization/simpsaset.m | 122 +- matlab/optimization/simulated_annealing.m | 42 +- matlab/optimization/solvopt.m | 216 +- matlab/options2cell.m | 14 +- matlab/osr.m | 14 +- matlab/osr1.m | 48 +- matlab/osr_obj.m | 6 +- .../AnalyseComputationalEnvironment.m | 1314 ++--- matlab/parallel/CreateTimeString.m | 2 +- matlab/parallel/GiveCPUnumber.m | 152 +- .../InitializeComputationalEnvironment.m | 2 +- matlab/parallel/closeSlave.m | 14 +- matlab/parallel/distributeJobs.m | 64 +- matlab/parallel/dynareParallelDelete.m | 6 +- .../parallel/dynareParallelDeleteNewFiles.m | 13 +- matlab/parallel/dynareParallelDir.m | 12 +- matlab/parallel/dynareParallelFindNewFiles.m | 23 +- matlab/parallel/dynareParallelGetFiles.m | 8 +- matlab/parallel/dynareParallelGetNewFiles.m | 5 +- matlab/parallel/dynareParallelListAllFiles.m | 20 +- matlab/parallel/dynareParallelMkDir.m | 4 +- matlab/parallel/dynareParallelRmDir.m | 4 +- matlab/parallel/dynareParallelSendFiles.m | 30 +- matlab/parallel/dynareParallelSnapshot.m | 4 +- matlab/parallel/fMessageStatus.m | 11 +- matlab/parallel/fParallel.m | 6 +- matlab/parallel/masterParallel.m | 494 +- matlab/parallel/slaveParallel.m | 32 +- matlab/parallel/storeGlobalVars.m | 2 +- matlab/parallel/struct2local.m | 2 +- .../partial_information/PCL_Part_info_irf.m | 28 +- .../PCL_Part_info_moments.m | 30 +- matlab/partial_information/PCL_resol.m | 10 +- matlab/partial_information/PI_gensys.m | 34 +- .../partial_information/PI_gensys_singularC.m | 4 +- .../partial_information/disc_riccati_fast.m | 52 +- matlab/partial_information/disclyap_fast.m | 64 +- matlab/partial_information/dr1_PI.m | 58 +- .../det_cond_forecast.m | 198 +- .../linear_approximation_accuracy.m | 4 +- .../linear_perfect_foresight_problem.m | 10 +- matlab/perfect-foresight-models/make_ex_.m | 8 +- matlab/perfect-foresight-models/make_y_.m | 10 +- .../perfect_foresight_mcp_problem.m | 24 +- .../perfect_foresight_problem.m | 88 +- .../perfect_foresight_setup.m | 22 +- .../perfect_foresight_solver.m | 14 +- .../perfect_foresight_solver_core.m | 10 +- .../private/check_input_arguments.m | 2 +- .../private/initialize_stacked_problem.m | 8 +- .../private/simulation_core.m | 4 +- matlab/perfect-foresight-models/sim1.m | 196 +- matlab/perfect-foresight-models/sim1_lbj.m | 2 +- matlab/perfect-foresight-models/sim1_linear.m | 8 +- .../sim1_purely_backward.m | 4 +- .../sim1_purely_forward.m | 2 +- .../solve_stacked_linear_problem.m | 10 +- .../solve_stacked_problem.m | 8 +- matlab/plot_icforecast.m | 6 +- matlab/plot_identification.m | 56 +- matlab/plot_shock_decomposition.m | 228 +- matlab/pltorg.m | 10 +- matlab/pm3.m | 176 +- matlab/pm3_core.m | 16 +- matlab/posterior_analysis.m | 8 +- matlab/posterior_moments.m | 14 +- matlab/posterior_sampler.m | 14 +- matlab/posterior_sampler_core.m | 10 +- matlab/posterior_sampler_initialization.m | 98 +- matlab/posterior_sampler_iteration.m | 344 +- matlab/print_bytecode_dynamic_model.m | 4 +- matlab/print_bytecode_static_model.m | 4 +- matlab/print_info.m | 20 +- matlab/print_moments_implied_prior.m | 2 +- matlab/print_table_prior.m | 48 +- matlab/printline.m | 8 +- matlab/prior_analysis.m | 2 +- matlab/prior_bounds.m | 4 +- matlab/prior_draw.m | 16 +- matlab/prior_posterior_statistics.m | 40 +- matlab/prior_posterior_statistics_core.m | 63 +- matlab/priordens.m | 18 +- matlab/qr2.m | 14 +- matlab/quadratic_matrix_equation_solver.m | 46 +- matlab/qz/mjdgges.m | 10 +- matlab/qzdiv.m | 10 +- matlab/ramsey_policy.m | 2 +- matlab/read_data_.m | 2 +- matlab/read_key_value_string.m | 16 +- matlab/read_variables.m | 90 +- matlab/realtime_shock_decomposition.m | 54 +- matlab/recursive_moments.m | 18 +- matlab/reduced_rank_cholesky.m | 4 +- matlab/resid.m | 10 +- matlab/rotated_slice_sampler.m | 367 +- matlab/row_header_width.m | 15 +- matlab/rplot.m | 26 +- matlab/sample_autocovariance.m | 12 +- matlab/sample_hp_filter.m | 14 +- matlab/save_params_and_steady_state.m | 4 +- matlab/score.m | 153 +- matlab/selif.m | 3 +- matlab/set_all_parameters.m | 4 +- matlab/set_default_option.m | 8 +- matlab/set_dynare_random_generator_state.m | 66 +- matlab/set_dynare_seed.m | 4 +- matlab/set_parameters.m | 8 +- matlab/set_prior.m | 24 +- matlab/shock_decomposition.m | 10 +- matlab/simul_backward_linear_model.m | 4 +- matlab/simul_backward_model.m | 9 +- matlab/simul_backward_nonlinear_model.m | 6 +- matlab/simulated_moment_uncertainty.m | 4 +- matlab/simulated_moments_estimation.m | 24 +- matlab/simult_.m | 10 +- matlab/simultxdet.m | 6 +- matlab/skipline.m | 8 +- matlab/slice_sampler.m | 246 +- matlab/smm_objective.m | 14 +- matlab/smoother2histval.m | 6 +- matlab/solve1.m | 16 +- matlab/solve_one_boundary.m | 14 +- matlab/solve_perfect_foresight_model.m | 170 +- matlab/solve_two_boundaries.m | 10 +- matlab/steady.m | 12 +- matlab/steady_.m | 6 +- matlab/step_length_correction.m | 10 +- matlab/stoch_simul.m | 6 +- matlab/stochastic_solvers.m | 89 +- matlab/store_smoother_results.m | 24 +- matlab/subset.m | 8 +- matlab/symmetric_matrix_index.m | 4 +- matlab/test_for_deep_parameters_calibration.m | 10 +- matlab/th_autocovariances.m | 40 +- matlab/thet2tau.m | 2 +- matlab/trace_plot.m | 7 +- matlab/trust_region.m | 1 - matlab/uniform_specification.m | 14 +- matlab/update_last_mh_history_file.m | 2 +- matlab/user_has_matlab_license.m | 18 +- .../dataset/descriptive_statistics.m | 22 +- matlab/utilities/dataset/initialize_dataset.m | 2 +- matlab/utilities/dataset/lagged.m | 66 +- matlab/utilities/dataset/makedataset.m | 4 +- matlab/utilities/dataset/nanvariance.m | 16 +- matlab/utilities/dataset/quarterly2annual.m | 271 +- matlab/utilities/doc/get_internal_doc_block.m | 18 +- matlab/utilities/general/compare_vectors.m | 8 +- matlab/utilities/general/delete_stale_file.m | 1 - matlab/utilities/general/demean.m | 16 +- matlab/utilities/general/disp_verbose.m | 2 +- matlab/utilities/general/dyn_mex.m | 52 +- ...ll_variables_but_lagged_leaded_exogenous.m | 4 +- ...ndices_lagged_leaded_exogenous_variables.m | 2 +- matlab/utilities/general/isconst.m | 2 +- matlab/utilities/general/isdiagonal.m | 2 - .../general/isinestimationobjective.m | 6 +- matlab/utilities/general/isint.m | 12 +- matlab/utilities/general/ispd.m | 2 +- matlab/utilities/general/log_variable.m | 2 +- matlab/utilities/general/ndim.m | 12 +- .../general/remove_fractional_xticks.m | 2 +- matlab/utilities/graphics/colorspace.m | 438 +- .../graphics/distinguishable_colors.m | 10 +- matlab/variance_decomposition_mc_analysis.m | 2 +- matlab/varlist_indices.m | 2 +- matlab/vnorm.m | 3 +- matlab/warning_config.m | 4 +- matlab/write_latex_definitions.m | 6 +- matlab/write_latex_parameter_table.m | 28 +- matlab/write_latex_prior_table.m | 90 +- matlab/write_mh_history_file.m | 2 +- matlab/writecellofchar.m | 48 +- matlab/writedata.m | 2 +- matlab/writedata_text.m | 2 +- matlab/writematrixofchar.m | 8 +- 566 files changed, 18547 insertions(+), 18711 deletions(-) diff --git a/matlab/AHessian.m b/matlab/AHessian.m index 2a632e7fd7..f9d9db6e0c 100644 --- a/matlab/AHessian.m +++ b/matlab/AHessian.m @@ -26,107 +26,107 @@ function [AHess, DLIK, LIK] = AHessian(T,R,Q,H,P,Y,DT,DYss,DOm,DH,DP,start,mf,ka % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - k = size(DT,3); % number of structural parameters - smpl = size(Y,2); % Sample size. - pp = size(Y,1); % Maximum number of observed variables. - mm = size(T,2); % Number of state variables. - a = zeros(mm,1); % State vector. - Om = R*Q*transpose(R); % Variance of R times the vector of structural innovations. - t = 0; % Initialization of the time index. - oldK = 0; - notsteady = 1; % Steady state flag. - F_singular = 1; +k = size(DT,3); % number of structural parameters +smpl = size(Y,2); % Sample size. +pp = size(Y,1); % Maximum number of observed variables. +mm = size(T,2); % Number of state variables. +a = zeros(mm,1); % State vector. +Om = R*Q*transpose(R); % Variance of R times the vector of structural innovations. +t = 0; % Initialization of the time index. +oldK = 0; +notsteady = 1; % Steady state flag. +F_singular = 1; lik = zeros(smpl,1); % Initialization of the vector gathering the densities. LIK = Inf; % Default value of the log likelihood. if nargout > 1 DLIK = zeros(k,1); % Initialization of the score. end - AHess = zeros(k,k); % Initialization of the Hessian - Da = zeros(mm,k); % State vector. - Dv = zeros(length(mf),k); - +AHess = zeros(k,k); % Initialization of the Hessian +Da = zeros(mm,k); % State vector. +Dv = zeros(length(mf),k); + % for ii = 1:k -% DOm = DR(:,:,ii)*Q*transpose(R) + R*DQ(:,:,ii)*transpose(R) + R*Q*transpose(DR(:,:,ii)); +% DOm = DR(:,:,ii)*Q*transpose(R) + R*DQ(:,:,ii)*transpose(R) + R*Q*transpose(DR(:,:,ii)); % 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 - a = T*a; - P = T*P*transpose(T)+Om; - 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; - iF = inv(F); - K = P(:,mf)*iF; - lik(t) = log(det(F))+transpose(v)*iF*v; - - [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K); - - for ii = 1:k - Dv(:,ii) = -Da(mf,ii) - DYss(mf,ii); - Da(:,ii) = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii)); - if t>=start && nargout > 1 - DLIK(ii,1) = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v; - end - end - vecDPmf = reshape(DP(mf,mf,:),[],k); -% iPmf = inv(P(mf,mf)); - if t>=start - AHess = AHess + Dv'*iF*Dv + .5*(vecDPmf' * kron(iF,iF) * vecDPmf); - end - a = T*(a+K*v); - P = T*(P-K*P(mf,:))*transpose(T)+Om; - DP = DP1; + a = T*a; + P = T*P*transpose(T)+Om; end - notsteady = max(max(abs(K-oldK))) > riccati_tol; - oldK = K; - end + else + F_singular = 0; + iF = inv(F); + K = P(:,mf)*iF; + lik(t) = log(det(F))+transpose(v)*iF*v; - if F_singular - error('The variance of the forecast error remains singular until the end of the sample') - end + [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K); - - if t < smpl - t0 = t+1; - while t < smpl - t = t+1; - v = Y(:,t)-a(mf); - for ii = 1:k - Dv(:,ii) = -Da(mf,ii)-DYss(mf,ii); - Da(:,ii) = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii)); - if t>=start && nargout >1 - DLIK(ii,1) = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v; - end - end - if t>=start - AHess = AHess + Dv'*iF*Dv; - end - a = T*(a+K*v); - lik(t) = transpose(v)*iF*v; + for ii = 1:k + Dv(:,ii) = -Da(mf,ii) - DYss(mf,ii); + Da(:,ii) = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii)); + if t>=start && nargout > 1 + DLIK(ii,1) = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v; + end + end + vecDPmf = reshape(DP(mf,mf,:),[],k); + % iPmf = inv(P(mf,mf)); + if t>=start + AHess = AHess + Dv'*iF*Dv + .5*(vecDPmf' * kron(iF,iF) * vecDPmf); end - AHess = AHess + .5*(smpl-t0+1)*(vecDPmf' * kron(iF,iF) * vecDPmf); - if nargout > 1 + a = T*(a+K*v); + P = T*(P-K*P(mf,:))*transpose(T)+Om; + DP = DP1; + 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') +end + + +if t < smpl + t0 = t+1; + while t < smpl + t = t+1; + v = Y(:,t)-a(mf); for ii = 1:k -% DLIK(ii,1) = DLIK(ii,1) + (smpl-t0+1)*trace( iF*DF(:,:,ii) ); + Dv(:,ii) = -Da(mf,ii)-DYss(mf,ii); + Da(:,ii) = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii)); + if t>=start && nargout >1 + DLIK(ii,1) = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v; + end + end + if t>=start + AHess = AHess + Dv'*iF*Dv; end + a = T*(a+K*v); + lik(t) = transpose(v)*iF*v; + end + AHess = AHess + .5*(smpl-t0+1)*(vecDPmf' * kron(iF,iF) * vecDPmf); + if nargout > 1 + for ii = 1:k + % DLIK(ii,1) = DLIK(ii,1) + (smpl-t0+1)*trace( iF*DF(:,:,ii) ); end - lik(t0:smpl) = lik(t0:smpl) + log(det(F)); -% for ii = 1:k; -% for jj = 1:ii -% H(ii,jj) = trace(iPmf*(.5*DP(mf,mf,ii)*iPmf*DP(mf,mf,jj) + Dv(:,ii)*Dv(:,jj)')); -% end -% end - end - -AHess = -AHess; + end + lik(t0:smpl) = lik(t0:smpl) + log(det(F)); + % for ii = 1:k; + % for jj = 1:ii + % H(ii,jj) = trace(iPmf*(.5*DP(mf,mf,ii)*iPmf*DP(mf,mf,jj) + Dv(:,ii)*Dv(:,jj)')); + % end + % end +end + +AHess = -AHess; if nargout > 1 DLIK = DLIK/2; end @@ -134,15 +134,15 @@ end lik = (lik + pp*log(2*pi))/2; LIK = sum(lik(start:end)); % Minus the log-likelihood. -% end of main function - + % end of main function + function [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K) - k = size(DT,3); - tmp = P-K*P(mf,:); +k = size(DT,3); +tmp = P-K*P(mf,:); for ii = 1:k - DF(:,:,ii) = DP(mf,mf,ii) + DH(:,:,ii); + DF(:,:,ii) = DP(mf,mf,ii) + DH(:,:,ii); DiF(:,:,ii) = -iF*DF(:,:,ii)*iF; DK(:,:,ii) = DP(:,mf,ii)*iF + P(:,mf)*DiF(:,:,ii); Dtmp = DP(:,:,ii) - DK(:,:,ii)*P(mf,:) - K*DP(mf,:,ii); @@ -150,6 +150,3 @@ for ii = 1:k end % end of computeDKalman - - - \ No newline at end of file diff --git a/matlab/AIM/SPAimerr.m b/matlab/AIM/SPAimerr.m index 9bffb54aa9..6467479287 100644 --- a/matlab/AIM/SPAimerr.m +++ b/matlab/AIM/SPAimerr.m @@ -29,7 +29,7 @@ function e = SPAimerr(c) % Journal of Economic Dynamics and Control, 2010, vol. 34, issue 3, % pages 472-489 - if(c==1) e='Aim: unique solution.'; +if(c==1) e='Aim: unique solution.'; elseif(c==2) e='Aim: roots not correctly computed by real_schur.'; elseif(c==3) e='Aim: too many big roots.'; elseif(c==35) e='Aim: too many big roots, and q(:,right) is singular.'; diff --git a/matlab/AIM/SPAmalg.m b/matlab/AIM/SPAmalg.m index 6da8ac5242..c371a91b0f 100644 --- a/matlab/AIM/SPAmalg.m +++ b/matlab/AIM/SPAmalg.m @@ -1,5 +1,5 @@ function [b,rts,ia,nexact,nnumeric,lgroots,aimcode] = ... - SPAmalg(h,neq,nlag,nlead,condn,uprbnd) + SPAmalg(h,neq,nlag,nlead,condn,uprbnd) % [b,rts,ia,nexact,nnumeric,lgroots,aimcode] = ... % SPAmalg(h,neq,nlag,nlead,condn,uprbnd) % @@ -8,9 +8,9 @@ function [b,rts,ia,nexact,nnumeric,lgroots,aimcode] = ... % roots. This procedure will fail if the companion matrix is % defective and does not have a linearly independent set of % eigenvectors associated with the big roots. -% +% % Input arguments: -% +% % h Structural coefficient matrix (neq,neq*(nlag+1+nlead)). % neq Number of equations. % nlag Number of lags. @@ -19,9 +19,9 @@ function [b,rts,ia,nexact,nnumeric,lgroots,aimcode] = ... % by numeric_shift and reduced_form. % uprbnd Inclusive upper bound for the modulus of roots % allowed in the reduced form. -% +% % Output arguments: -% +% % b Reduced form coefficient matrix (neq,neq*nlag). % rts Roots returned by eig. % ia Dimension of companion matrix (number of non-trivial @@ -57,7 +57,7 @@ function [b,rts,ia,nexact,nnumeric,lgroots,aimcode] = ... % pages 472-489 b=[];rts=[];ia=[];nexact=[];nnumeric=[];lgroots=[];aimcode=[]; -if(nlag<1 || nlead<1) +if(nlag<1 || nlead<1) error('Aim_eig: model must have at least one lag and one lead'); end % Initialization. @@ -75,17 +75,17 @@ if (iq>qrows) end [a,ia,js] = SPBuild_a(h,qcols,neq); if (ia ~= 0) - if any(any(isnan(a))) || any(any(isinf(a))) + if any(any(isnan(a))) || any(any(isinf(a))) disp('A is NAN or INF') - aimcode=63; - return - end + aimcode=63; + return + end [w,rts,lgroots,flag_trouble]=SPEigensystem(a,uprbnd,min(length(js),qrows-iq+1)); if flag_trouble==1 - disp('Problem in SPEIG'); + disp('Problem in SPEIG'); aimcode=64; return - end + end q = SPCopy_w(q,w,js,iq,qrows); end test=nexact+nnumeric+lgroots; diff --git a/matlab/AIM/SPBuild_a.m b/matlab/AIM/SPBuild_a.m index eb12473a8a..5701d3bf11 100644 --- a/matlab/AIM/SPBuild_a.m +++ b/matlab/AIM/SPBuild_a.m @@ -41,9 +41,9 @@ hs(:,left) = -hs(:,right)\hs(:,left); a = zeros(qcols,qcols); if(qcols > neq) - eyerows = 1:qcols-neq; - eyecols = neq+1:qcols; - a(eyerows,eyecols) = eye(qcols-neq); + eyerows = 1:qcols-neq; + eyecols = neq+1:qcols; + a(eyerows,eyecols) = eye(qcols-neq); end hrows = qcols-neq+1:qcols; a(hrows,:) = hs(:,left); @@ -51,14 +51,14 @@ a(hrows,:) = hs(:,left); % Delete inessential lags and build index array js. js indexes the % columns in the big transition matrix that correspond to the % essential lags in the model. They are the columns of q that will -% get the unstable left eigenvectors. +% get the unstable left eigenvectors. js = 1:qcols; zerocols = sum(abs(a)) == 0; while( any(zerocols) ) - a(:,zerocols) = []; - a(zerocols,:) = []; - js(zerocols) = []; - zerocols = sum(abs(a)) == 0; + a(:,zerocols) = []; + a(zerocols,:) = []; + js(zerocols) = []; + zerocols = sum(abs(a)) == 0; end ia = length(js); diff --git a/matlab/AIM/SPCopy_w.m b/matlab/AIM/SPCopy_w.m index 714a1e2746..82dafe40ab 100644 --- a/matlab/AIM/SPCopy_w.m +++ b/matlab/AIM/SPCopy_w.m @@ -2,7 +2,7 @@ function q = SPCopy_w(q,w,js,iq,qrows) % q = SPCopy_w(q,w,js,iq,qrows) % % Copy the eigenvectors corresponding to the largest roots into the -% remaining empty rows and columns js of q +% remaining empty rows and columns js of q % Author: Gary Anderson % Original file downloaded from: @@ -30,7 +30,7 @@ function q = SPCopy_w(q,w,js,iq,qrows) if(iq < qrows) - lastrows = iq+1:qrows; - wrows = 1:length(lastrows); - q(lastrows,js) = w(:,wrows)'; + lastrows = iq+1:qrows; + wrows = 1:length(lastrows); + q(lastrows,js) = w(:,wrows)'; end diff --git a/matlab/AIM/SPEigensystem.m b/matlab/AIM/SPEigensystem.m index 16855401a5..61dd460690 100644 --- a/matlab/AIM/SPEigensystem.m +++ b/matlab/AIM/SPEigensystem.m @@ -30,7 +30,7 @@ function [w,rts,lgroots,flag_trouble] = SPEigensystem(a,uprbnd,rowsLeft) % Journal of Economic Dynamics and Control, 2010, vol. 34, issue 3, % pages 472-489 -opts.disp=0; +opts.disp=0; % next block is commented out because eigs() intermitently returns different rts %try % [w,d] = eigs(a',rowsLeft,'LM',opts); @@ -39,24 +39,24 @@ opts.disp=0; % [mag,k] = sort(-mag); % rts = rts(k); %catch - %disp('Catch in SPE'); - %pause(0.5); - %aStr=datestr(clock); - %eval(['save ' regexprep(aStr,' ','') ' a']); - try - [w,d]=eig(a'); - catch - lasterr - w=[];rts=[];lgroots=[]; - flag_trouble=1; - return - end - rts = diag(d); - mag = abs(rts); - [mag,k] = sort(-mag); - rts = rts(k); +%disp('Catch in SPE'); +%pause(0.5); +%aStr=datestr(clock); +%eval(['save ' regexprep(aStr,' ','') ' a']); +try + [w,d]=eig(a'); +catch + lasterr + w=[];rts=[];lgroots=[]; + flag_trouble=1; + return +end +rts = diag(d); +mag = abs(rts); +[mag,k] = sort(-mag); +rts = rts(k); %end -flag_trouble=0; +flag_trouble=0; %ws=SPSparse(w); ws=sparse(w); @@ -65,7 +65,7 @@ ws = ws(:,k); % Given a complex conjugate pair of vectors W = [w1,w2], there is a % nonsingular matrix D such that W*D = real(W) + imag(W). That is to % say, W and real(W)+imag(W) span the same subspace, which is all -% that aim cares about. +% that aim cares about. ws = real(ws) + imag(ws); diff --git a/matlab/AIM/SPExact_shift.m b/matlab/AIM/SPExact_shift.m index c9034e319b..5ba49aa114 100644 --- a/matlab/AIM/SPExact_shift.m +++ b/matlab/AIM/SPExact_shift.m @@ -36,12 +36,11 @@ right = qcols+1:qcols+neq; zerorows = find( sum(abs( hs(:,right)' ))==0 ); while( any(zerorows) && iq <= qrows ) - nz = length(zerorows); - q(iq+1:iq+nz,:) = hs(zerorows,left); - hs(zerorows,:) = SPShiftright(hs(zerorows,:),neq); - iq = iq + nz; - nexact = nexact + nz; - zerorows = find( sum(abs( hs(:,right)' ))==0 ); + nz = length(zerorows); + q(iq+1:iq+nz,:) = hs(zerorows,left); + hs(zerorows,:) = SPShiftright(hs(zerorows,:),neq); + iq = iq + nz; + nexact = nexact + nz; + zerorows = find( sum(abs( hs(:,right)' ))==0 ); end h=full(hs); - diff --git a/matlab/AIM/SPNumeric_shift.m b/matlab/AIM/SPNumeric_shift.m index cc1e1825f7..27049ca0cc 100644 --- a/matlab/AIM/SPNumeric_shift.m +++ b/matlab/AIM/SPNumeric_shift.m @@ -37,14 +37,14 @@ right = qcols+1:qcols+neq; zerorows = find( abs(diag(R)) <= condn ); while( any(zerorows) && iq <= qrows ) - h=sparse(h); - Q=sparse(Q); - h = Q'*h; - nz = length(zerorows); - q(iq+1:iq+nz,:) = h(zerorows,left); - h(zerorows,:) = SPShiftright( h(zerorows,:), neq ); - iq = iq + nz; - nnumeric = nnumeric + nz; - [Q,R,E] = qr( full(h(:,right)) ); - zerorows = find( abs(diag(R)) <= condn ); + h=sparse(h); + Q=sparse(Q); + h = Q'*h; + nz = length(zerorows); + q(iq+1:iq+nz,:) = h(zerorows,left); + h(zerorows,:) = SPShiftright( h(zerorows,:), neq ); + iq = iq + nz; + nnumeric = nnumeric + nz; + [Q,R,E] = qr( full(h(:,right)) ); + zerorows = find( abs(diag(R)) <= condn ); end diff --git a/matlab/AIM/SPObstruct.m b/matlab/AIM/SPObstruct.m index 8620ca1b9b..9d9206501f 100644 --- a/matlab/AIM/SPObstruct.m +++ b/matlab/AIM/SPObstruct.m @@ -2,7 +2,7 @@ function scof = SPObstruct(cof,cofb,neq,nlag,nlead) % scof = SPObstruct(cof,cofb,neq,nlag,nlead) % % Construct the coefficients in the observable structure. -% +% % Input arguments: % % cof structural coefficients @@ -51,17 +51,17 @@ qs=sparse(q); qs(1:rc,1:cc) = sparse(cofb); qcols = neq*(nlag+nlead); -if( nlead > 1 ) - for i = 1:nlead-1 - rows = i*neq + (1:neq); - qs(rows,:) = SPShiftright( qs((rows-neq),:), neq ); - end +if( nlead > 1 ) + for i = 1:nlead-1 + rows = i*neq + (1:neq); + qs(rows,:) = SPShiftright( qs((rows-neq),:), neq ); + end end l = (1: neq*nlag); r = (neq*nlag+1: neq*(nlag+nlead)); - qs(:,l) = - qs(:,r) \ qs(:,l); +qs(:,l) = - qs(:,r) \ qs(:,l); minus = 1: neq*(nlag+1); plus = neq*(nlag+1)+1: neq*(nlag+1+nlead); diff --git a/matlab/AIM/SPReduced_form.m b/matlab/AIM/SPReduced_form.m index 79ab3711db..e7d60a1801 100644 --- a/matlab/AIM/SPReduced_form.m +++ b/matlab/AIM/SPReduced_form.m @@ -38,7 +38,7 @@ if(nonsing) b = qs(1:neq,1:bcols); b = full(b); else %rescale by dividing row by maximal qr element - %'inverse condition number small, rescaling ' + %'inverse condition number small, rescaling ' themax=max(abs(qs(:,right)),[],2); oneover = diag(1 ./ themax); nonsing = rcond(full(oneover *qs(:,right))) > condn; @@ -48,4 +48,3 @@ else %rescale by dividing row by maximal qr element b = full(b); end end - diff --git a/matlab/AIM/SPShiftright.m b/matlab/AIM/SPShiftright.m index 8299ce516b..7049084843 100644 --- a/matlab/AIM/SPShiftright.m +++ b/matlab/AIM/SPShiftright.m @@ -3,7 +3,7 @@ function [y] = SPShiftright(x,n) % [y] = shiftright(x,n) % % Shift the rows of x to the right by n columns, leaving zeros in the -% first n columns. +% first n columns. % Original author: Gary Anderson % Original file downloaded from: diff --git a/matlab/AIM/dynAIMsolver1.m b/matlab/AIM/dynAIMsolver1.m index 2e23e02220..3589153951 100644 --- a/matlab/AIM/dynAIMsolver1.m +++ b/matlab/AIM/dynAIMsolver1.m @@ -1,20 +1,20 @@ 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 +% 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, . . . ,? +% 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'= � +% 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 +% jacobia_ [matrix] 1st order derivative of the model % dr [matlab structure] Decision rules for stochastic simulations. -% M_ [matlab structure] Definition of the model. -% +% M_ [matlab structure] Definition of the model. +% % OUTPUTS % dr [matlab structure] Decision rules for stochastic simulations. % aimcode [integer] 1: the model defines variables uniquely @@ -31,20 +31,20 @@ function [dr,aimcode,rts]=dynAIMsolver1(jacobia_,M_,dr) % (c==63) e='Aim: A is NAN or INF.'; % (c==64) e='Aim: Problem in SPEIG.'; % else e='Aimerr: return code not properly specified'; -% +% % SPECIAL REQUIREMENTS -% Dynare use: +% 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 +% 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 +% 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-2012 Dynare Team % @@ -69,8 +69,8 @@ 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 +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 @@ -102,7 +102,7 @@ if aimcode==1 %if OK 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 @@ -117,7 +117,7 @@ if aimcode==1 %if OK %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);% + 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; @@ -137,8 +137,8 @@ else if aimcode < 1 || aimcode > 5 % too big exception, use mjdgges error('Error in AIM: aimcode=%d ; %s', aimcode, err); end - % if aimcode > 5 + % if aimcode > 5 % disp(['Error in AIM: aimcode=' sprintf('%d : %s',aimcode, err)]); % aimcode=5; - % end + % end end diff --git a/matlab/AIM_first_order_solver.m b/matlab/AIM_first_order_solver.m index eabe791738..893deefb0c 100644 --- a/matlab/AIM_first_order_solver.m +++ b/matlab/AIM_first_order_solver.m @@ -67,35 +67,34 @@ function [dr,info]=AIM_first_order_solver(jacobia,M,dr,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/>. - - info = 0; - - [dr,aimcode]=dynAIMsolver1(jacobia,M,dr); - if aimcode ~=1 - info(1) = convertAimCodeToInfo(aimCode); %convert to be in the 100 range - info(2) = 1.0e+8; - return - end - A = kalman_transition_matrix(dr,M.nstatic+(1:M.nspred), 1:M.nspred,... - M.exo_nbr); - dr.eigval = eig(A); - disp(dr.eigval) - nd = size(dr.kstate,1); - nba = nd-sum( abs(dr.eigval) < qz_criterium ); +info = 0; - nsfwrd = M.nsfwrd; +[dr,aimcode]=dynAIMsolver1(jacobia,M,dr); - if nba ~= nsfwrd - temp = sort(abs(dr.eigval)); - if nba > nsfwrd - temp = temp(nd-nba+1:nd-nsfwrd)-1-qz_criterium; - info(1) = 3; - elseif nba < nsfwrd - temp = temp(nd-nsfwrd+1:nd-nba)-1-qz_criterium; - info(1) = 4; - end - info(2) = temp'*temp; - return - end +if aimcode ~=1 + info(1) = convertAimCodeToInfo(aimCode); %convert to be in the 100 range + info(2) = 1.0e+8; + return +end +A = kalman_transition_matrix(dr,M.nstatic+(1:M.nspred), 1:M.nspred,... + M.exo_nbr); +dr.eigval = eig(A); +disp(dr.eigval) +nd = size(dr.kstate,1); +nba = nd-sum( abs(dr.eigval) < qz_criterium ); +nsfwrd = M.nsfwrd; + +if nba ~= nsfwrd + temp = sort(abs(dr.eigval)); + if nba > nsfwrd + temp = temp(nd-nba+1:nd-nsfwrd)-1-qz_criterium; + info(1) = 3; + elseif nba < nsfwrd + temp = temp(nd-nsfwrd+1:nd-nba)-1-qz_criterium; + info(1) = 4; + end + info(2) = temp'*temp; + return +end diff --git a/matlab/CheckPath.m b/matlab/CheckPath.m index c830055130..bd770e0eb0 100644 --- a/matlab/CheckPath.m +++ b/matlab/CheckPath.m @@ -2,7 +2,7 @@ function [DirectoryName, info] = CheckPath(type,dname) % Creates the subfolder "./M_.dname/type" if it does not exist yet. % % INPUTS -% type [string] Name of the subfolder. +% type [string] Name of the subfolder. % dname [string] Name of the directory % % OUTPUTS diff --git a/matlab/CutSample.m b/matlab/CutSample.m index 5ec0881a86..697e560710 100644 --- a/matlab/CutSample.m +++ b/matlab/CutSample.m @@ -66,7 +66,7 @@ if (TotalNumberOfMhFiles-1)-(FirstMhFile+1)+1 > 0 elseif TotalNumberOfMhFiles == 1 record.KeepedDraws.Distribution = []; elseif TotalNumberOfMhFiles == 2 && FirstMhFile > 1 - record.KeepedDraws.Distribution = [MAX_nruns-FirstLine+1 ; record.MhDraws(end,3)]; + record.KeepedDraws.Distribution = [MAX_nruns-FirstLine+1 ; record.MhDraws(end,3)]; end % Save updated mh-history file. diff --git a/matlab/DsgeSmoother.m b/matlab/DsgeSmoother.m index b25dcf1ef2..997904afcf 100644 --- a/matlab/DsgeSmoother.m +++ b/matlab/DsgeSmoother.m @@ -1,8 +1,8 @@ function [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T,R,P,PK,decomp,trend_addition,state_uncertainty,M_,oo_,options_,bayestopt_] = DsgeSmoother(xparam1,gend,Y,data_index,missing_value,M_,oo_,options_,bayestopt_,estim_params_) -% Estimation of the smoothed variables and innovations. -% -% INPUTS -% o xparam1 [double] (p*1) vector of (estimated) parameters. +% Estimation of the smoothed variables and innovations. +% +% INPUTS +% o xparam1 [double] (p*1) vector of (estimated) parameters. % o gend [integer] scalar specifying the number of observations ==> varargin{1}. % o data [double] (n*T) matrix of data. % o data_index [cell] 1*smpl cell of column vectors of indices. @@ -12,7 +12,7 @@ function [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T,R,P,PK,de % o options_ [structure] describing the options % o bayestopt_ [structure] describing the priors % o estim_params_ [structure] characterizing parameters to be estimated -% +% % OUTPUTS % o alphahat [double] (m*T) matrix, smoothed endogenous variables (a_{t|T}) (decision-rule order) % o etahat [double] (r*T) matrix, smoothed structural shocks (r>=n is the number of shocks). @@ -29,31 +29,31 @@ function [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T,R,P,PK,de % matrices (meaningless for periods 1:d) (decision-rule order) % o decomp (K*m*r*(T+K)) 4D array of shock decomposition of k-step ahead % filtered variables (decision-rule order) -% o trend_addition [double] (n*T) pure trend component; stored in options_.varobs order +% o trend_addition [double] (n*T) pure trend component; stored in options_.varobs order % o state_uncertainty [double] (K,K,T) array, storing the uncertainty % about the smoothed state (decision-rule order) % o M_ [structure] decribing the model % o oo_ [structure] storing the results % o options_ [structure] describing the options % o bayestopt_ [structure] describing the priors -% +% % Notes: % m: number of endogenous variables (M_.endo_nbr) % T: number of Time periods (options_.nobs) % r: number of strucural shocks (M_.exo_nbr) % n: number of observables (length(options_.varobs)) % K: maximum forecast horizon (max(options_.nk)) -% +% % To get variables that are stored in decision rule order in order of declaration % as in M_.endo_names, ones needs code along the lines of: % variables_declaration_order(dr.order_var,:) = alphahat -% -% Defines bayestopt_.mf = bayestopt_.smoother_mf (positions of observed variables -% and requested smoothed variables in decision rules (decision rule order)) and +% +% Defines bayestopt_.mf = bayestopt_.smoother_mf (positions of observed variables +% and requested smoothed variables in decision rules (decision rule order)) and % passes it back via global variable -% -% ALGORITHM -% Diffuse Kalman filter (Durbin and Koopman) +% +% ALGORITHM +% Diffuse Kalman filter (Durbin and Koopman) % % SPECIAL REQUIREMENTS % None @@ -97,7 +97,7 @@ end %------------------------------------------------------------------------------ % 2. call model setup & reduction program %------------------------------------------------------------------------------ -oldoo.restrict_var_list = oo_.dr.restrict_var_list; +oldoo.restrict_var_list = oo_.dr.restrict_var_list; oldoo.restrict_columns = oo_.dr.restrict_columns; oo_.dr.restrict_var_list = bayestopt_.smoother_var_list; oo_.dr.restrict_columns = bayestopt_.smoother_restrict_columns; @@ -133,8 +133,8 @@ mf = bayestopt_.mf; % ------------------------------------------------------------------------------ % 3. Initial condition of the Kalman filter % ------------------------------------------------------------------------------ -% -% Here, Pinf and Pstar are determined. If the model is stationary, determine +% +% Here, Pinf and Pstar are determined. If the model is stationary, determine % Pstar as the solution of the Lyapunov equation and set Pinf=[] (Notation follows % Koopman/Durbin (2003), Journal of Time Series Analysis 24(1)) % @@ -169,7 +169,7 @@ elseif options_.lik_init == 3 % Diffuse Kalman filter kalman_algo = 3; else if ~all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal... - %Augment state vector (follows Section 6.4.3 of DK (2012)) + %Augment state vector (follows Section 6.4.3 of DK (2012)) expanded_state_vector_for_univariate_filter=1; T = blkdiag(T,zeros(vobs)); np = size(T,1); @@ -240,32 +240,32 @@ if kalman_algo == 1 || kalman_algo == 3 end if kalman_algo == 2 || kalman_algo == 4 - if ~all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal... - if ~expanded_state_vector_for_univariate_filter - %Augment state vector (follows Section 6.4.3 of DK (2012)) - expanded_state_vector_for_univariate_filter=1; - Z = [Z, eye(vobs)]; - ST = blkdiag(ST,zeros(vobs)); - np = size(ST,1); - Q = blkdiag(Q,H); - R1 = blkdiag(R,eye(vobs)); - if kalman_algo == 4 - %recompute Schur state space transformation with - %expanded state space - [Pstar,Pinf] = compute_Pinf_Pstar(mf,ST,R1,Q,options_.qz_criterium); - else - Pstar = blkdiag(Pstar,H); - if ~isempty(Pinf) - Pinf = blkdiag(Pinf,zeros(vobs)); - end - end - %now reset H to 0 - H = zeros(vobs,vobs); + if ~all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal... + if ~expanded_state_vector_for_univariate_filter + %Augment state vector (follows Section 6.4.3 of DK (2012)) + expanded_state_vector_for_univariate_filter=1; + Z = [Z, eye(vobs)]; + ST = blkdiag(ST,zeros(vobs)); + np = size(ST,1); + Q = blkdiag(Q,H); + R1 = blkdiag(R,eye(vobs)); + if kalman_algo == 4 + %recompute Schur state space transformation with + %expanded state space + [Pstar,Pinf] = compute_Pinf_Pstar(mf,ST,R1,Q,options_.qz_criterium); else - %do nothing, state vector was already expanded + Pstar = blkdiag(Pstar,H); + if ~isempty(Pinf) + Pinf = blkdiag(Pinf,zeros(vobs)); + end end + %now reset H to 0 + H = zeros(vobs,vobs); + else + %do nothing, state vector was already expanded end - + end + [alphahat,epsilonhat,etahat,ahat,P,aK,PK,decomp,state_uncertainty] = missing_DiffuseKalmanSmootherH3_Z(ST, ... Z,R1,Q,diag(H), ... Pinf,Pstar,data1,vobs,np,smpl,data_index, ... @@ -282,7 +282,7 @@ if expanded_state_vector_for_univariate_filter && (kalman_algo == 2 || kalman_al ahat = ahat(k,:); aK = aK(:,k,:,:); epsilonhat=etahat(end-vobs+1:end,:); - etahat=etahat(1:end-vobs,:); + etahat=etahat(1:end-vobs,:); if ~isempty(PK) PK = PK(:,k,k,:); end diff --git a/matlab/GetAllPosteriorDraws.m b/matlab/GetAllPosteriorDraws.m index 88e80f9182..d1019fb66c 100644 --- a/matlab/GetAllPosteriorDraws.m +++ b/matlab/GetAllPosteriorDraws.m @@ -5,14 +5,14 @@ function Draws = GetAllPosteriorDraws(column, FirstMhFile, FirstLine, TotalNumbe % % INPUTS % column: column -% FirstMhFile: first mh file +% FirstMhFile: first mh file % FirstLine: first line -% TotalNumberOfMhFile: total number of mh file +% TotalNumberOfMhFile: total number of mh file % NumberOfDraws: number of draws % OUTPUTS % Draws: draws from posterior distribution -% +% % SPECIAL REQUIREMENTS % none @@ -55,7 +55,7 @@ if nblck>1 && nargin<6 iline = 1; end end - else + else for blck = 1:nblck iline=iline0; for file = FirstMhFile:TotalNumberOfMhFile diff --git a/matlab/GetOneDraw.m b/matlab/GetOneDraw.m index 82d4c088fa..a3e0f9f4b2 100644 --- a/matlab/GetOneDraw.m +++ b/matlab/GetOneDraw.m @@ -5,11 +5,11 @@ function [xparams, logpost] = GetOneDraw(type) % INPUTS % type: [string] 'posterior': draw from MCMC draws % 'prior': draw from prior -% +% % OUTPUTS % xparams: vector of estimated parameters (drawn from posterior or prior distribution) % logpost: log of the posterior density of this parameter vector -% +% % SPECIAL REQUIREMENTS % none diff --git a/matlab/GetPosteriorMeanVariance.m b/matlab/GetPosteriorMeanVariance.m index d1e2935873..285b944802 100644 --- a/matlab/GetPosteriorMeanVariance.m +++ b/matlab/GetPosteriorMeanVariance.m @@ -16,38 +16,38 @@ function [mean,variance] = GetPosteriorMeanVariance(M,drop) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - MetropolisFolder = CheckPath('metropolis',M.dname); - FileName = M.fname; - BaseName = [MetropolisFolder filesep FileName]; - load_last_mh_history_file(MetropolisFolder, FileName); - NbrDraws = sum(record.MhDraws(:,1)); - NbrFiles = sum(record.MhDraws(:,2)); - NbrBlocks = record.Nblck; - mean = 0; - variance = 0; - - NbrKeptDraws = 0; - for i=1:NbrBlocks - NbrDrawsCurrentBlock = 0; - for j=1:NbrFiles - o = load([BaseName '_mh' int2str(j) '_blck' int2str(i),'.mat']); - NbrDrawsCurrentFile = size(o.x2,1); - if NbrDrawsCurrentBlock + NbrDrawsCurrentFile <= drop*NbrDraws - NbrDrawsCurrentBlock = NbrDrawsCurrentBlock + NbrDrawsCurrentFile; - continue - elseif NbrDrawsCurrentBlock < drop*NbrDraws - FirstDraw = ceil(drop*NbrDraws - NbrDrawsCurrentBlock + 1); - x2 = o.x2(FirstDraw:end,:); - else - x2 = o.x2; - end - NbrKeptDrawsCurrentFile = size(x2,1); - %recursively compute mean and variance - mean = (NbrKeptDraws*mean + sum(x2)')/(NbrKeptDraws+NbrKeptDrawsCurrentFile); - x2Demeaned = bsxfun(@minus,x2,mean'); - variance = (NbrKeptDraws*variance + x2Demeaned'*x2Demeaned)/(NbrKeptDraws+NbrKeptDrawsCurrentFile); + +MetropolisFolder = CheckPath('metropolis',M.dname); +FileName = M.fname; +BaseName = [MetropolisFolder filesep FileName]; +load_last_mh_history_file(MetropolisFolder, FileName); +NbrDraws = sum(record.MhDraws(:,1)); +NbrFiles = sum(record.MhDraws(:,2)); +NbrBlocks = record.Nblck; +mean = 0; +variance = 0; + +NbrKeptDraws = 0; +for i=1:NbrBlocks + NbrDrawsCurrentBlock = 0; + for j=1:NbrFiles + o = load([BaseName '_mh' int2str(j) '_blck' int2str(i),'.mat']); + NbrDrawsCurrentFile = size(o.x2,1); + if NbrDrawsCurrentBlock + NbrDrawsCurrentFile <= drop*NbrDraws NbrDrawsCurrentBlock = NbrDrawsCurrentBlock + NbrDrawsCurrentFile; - NbrKeptDraws = NbrKeptDraws + NbrKeptDrawsCurrentFile; + continue + elseif NbrDrawsCurrentBlock < drop*NbrDraws + FirstDraw = ceil(drop*NbrDraws - NbrDrawsCurrentBlock + 1); + x2 = o.x2(FirstDraw:end,:); + else + x2 = o.x2; end + NbrKeptDrawsCurrentFile = size(x2,1); + %recursively compute mean and variance + mean = (NbrKeptDraws*mean + sum(x2)')/(NbrKeptDraws+NbrKeptDrawsCurrentFile); + x2Demeaned = bsxfun(@minus,x2,mean'); + variance = (NbrKeptDraws*variance + x2Demeaned'*x2Demeaned)/(NbrKeptDraws+NbrKeptDrawsCurrentFile); + NbrDrawsCurrentBlock = NbrDrawsCurrentBlock + NbrDrawsCurrentFile; + NbrKeptDraws = NbrKeptDraws + NbrKeptDrawsCurrentFile; end +end diff --git a/matlab/GetPosteriorParametersStatistics.m b/matlab/GetPosteriorParametersStatistics.m index 1ad0bd0271..6bea8d66a1 100644 --- a/matlab/GetPosteriorParametersStatistics.m +++ b/matlab/GetPosteriorParametersStatistics.m @@ -1,17 +1,17 @@ function oo_ = GetPosteriorParametersStatistics(estim_params_, M_, options_, bayestopt_, oo_, pnames) % This function prints and saves posterior estimates after the mcmc -% (+updates of oo_ & TeX output). -% -% INPUTS -% estim_params_ [structure] +% (+updates of oo_ & TeX output). +% +% INPUTS +% estim_params_ [structure] % M_ [structure] % options_ [structure] % bayestopt_ [structure] % oo_ [structure] % pnames [char] Array of char, names of the prior shapes available -% -% OUTPUTS -% oo_ [structure] +% +% OUTPUTS +% oo_ [structure] % % SPECIAL REQUIREMENTS % None. @@ -34,7 +34,7 @@ function oo_ = GetPosteriorParametersStatistics(estim_params_, M_, options_, bay % along with Dynare. If not, see <http://www.gnu.org/licenses/>. %if ~options_.mh_replic && options_.load_mh_file -% load([M_.fname '_results.mat'],'oo_'); +% load([M_.fname '_results.mat'],'oo_'); %end TeX = options_.TeX; @@ -48,7 +48,7 @@ nx = nvx+nvn+ncx+ncn+np; MetropolisFolder = CheckPath('metropolis',M_.dname); OutputFolder = CheckPath('Output',M_.dname); -FileName = M_.fname; +FileName = M_.fname; load_last_mh_history_file(MetropolisFolder,FileName); @@ -108,14 +108,14 @@ if np [post_mean, post_median, post_var, hpd_interval, post_deciles, ... density] = posterior_moments(Draws,1,options_.mh_conf_sig); name = bayestopt_.name{ip}; - oo_ = Filloo(oo_,name,type,post_mean,hpd_interval,post_median,post_var,post_deciles,density); + oo_ = Filloo(oo_,name,type,post_mean,hpd_interval,post_median,post_var,post_deciles,density); end end disp(sprintf(pformat,header_width,name,bayestopt_.p1(ip),... post_mean, ... hpd_interval, ... pnames(bayestopt_.pshape(ip)+1,:), ... - bayestopt_.p2(ip))); + bayestopt_.p2(ip))); if TeX k = estim_params_.param_vals(i,1); name = deblank(M_.param_names_tex(k,:)); @@ -171,7 +171,7 @@ if nvx ip = ip+1; end if TeX - TeXEnd(fid,2,'standard deviation of structural shocks'); + TeXEnd(fid,2,'standard deviation of structural shocks'); end end if nvn @@ -213,7 +213,7 @@ if nvn ip = ip+1; end if TeX - TeXEnd(fid,3,'standard deviation of measurement errors'); + TeXEnd(fid,3,'standard deviation of measurement errors'); end end if ncx @@ -314,12 +314,12 @@ if ncn if TeX name = ['(',deblank(M_.endo_names_tex(k1,:)) ',' deblank(M_.endo_names_tex(k2,:)),')']; TeXCore(fid,name,deblank(pnames(bayestopt_.pshape(ip)+1,:)),bayestopt_.p1(ip),... - bayestopt_.p2(ip),post_mean,sqrt(post_var),hpd_interval); + bayestopt_.p2(ip),post_mean,sqrt(post_var),hpd_interval); end ip = ip+1; end if TeX - TeXEnd(fid,5,'correlation of measurement errors'); + TeXEnd(fid,5,'correlation of measurement errors'); end end @@ -359,7 +359,7 @@ 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'],... +fprintf(fid,['$%s$ & %s & %7.3f & %6.4f & %7.3f& %6.4f & %7.4f & %7.4f \\\\ \n'],... name,... shape,... priormean,... @@ -371,7 +371,7 @@ fprintf(fid,['$%s$ & %s & %7.3f & %6.4f & %7.3f& %6.4f & %7.4f & %7.4f \\\\ \n'] function TeXEnd(fid,fnum,title) -fprintf(fid,'\\end{longtable}\n '); +fprintf(fid,'\\end{longtable}\n '); fprintf(fid,'\\end{center}\n'); fprintf(fid,'%% End of TeX file.\n'); fclose(fid); diff --git a/matlab/MakeAllFigures.m b/matlab/MakeAllFigures.m index d24f4fadac..74e94e4cbe 100644 --- a/matlab/MakeAllFigures.m +++ b/matlab/MakeAllFigures.m @@ -19,11 +19,11 @@ function MakeAllFigures(NumberOfPlots,Caption,FigureProperties,Info) global M_ options_ -FigHandle = figure('Name',FigureProperties.Name); +FigHandle = figure('Name',FigureProperties.Name); NAMES = cell(NumberOfPlots,1); if options_.TeX - TeXNAMES = cell(NumberOfPlots,1); + TeXNAMES = cell(NumberOfPlots,1); end if NumberOfPlots == 9 @@ -53,7 +53,7 @@ elseif NumberOfPlots == 2 elseif NumberOfPlots == 1 nr = 1; nc = 1; -end +end for plt = 1:NumberOfPlots eval(['NumberOfCurves = Info.Box' int2str(plt) '.Number;']) @@ -138,7 +138,7 @@ for plt = 1:NumberOfPlots set(hh,'Color','r','LineStyle','-','LineWidth',2) % % - end + end end axis([xmin xmax ymin ymax]) title(NAMES{plt}) @@ -150,14 +150,14 @@ 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']); + eval(['print -depsc2 ' M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name '.eps']); end end if Info.SaveFormat.Pdf && ~isoctave 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]); + eval(['print -dpdf ' M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name]); end end if Info.SaveFormat.Fig && ~isoctave diff --git a/matlab/PlotPosteriorDistributions.m b/matlab/PlotPosteriorDistributions.m index 4358b07e4a..84ff775ea3 100644 --- a/matlab/PlotPosteriorDistributions.m +++ b/matlab/PlotPosteriorDistributions.m @@ -4,15 +4,15 @@ function oo_ = PlotPosteriorDistributions(estim_params_, M_, options_, bayestopt % plots posterior distributions % % INPUTS -% estim_params_ [structure] +% estim_params_ [structure] % M_ [structure] -% options_ [structure] +% options_ [structure] % bayestopt_ [structure] % oo_ [structure] -% +% % OUTPUTS -% oo_ [structure] -% +% oo_ [structure] +% % SPECIAL REQUIREMENTS % none @@ -49,7 +49,7 @@ nn = sqrt(MaxNumberOfPlotPerFigure); figurename = 'Priors and posteriors'; -if TeX && any(strcmp('eps',cellstr(options_.graph_format))) +if TeX && any(strcmp('eps',cellstr(options_.graph_format))) 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']); @@ -78,9 +78,9 @@ for i=1:npar end end [x2,f2,abscissa,dens,binf2,bsup2] = draw_prior_density(i,bayestopt_); - top2 = max(f2); + top2 = max(f2); if i <= nvx - name = deblank(M_.exo_names(estim_params_.var_exo(i,1),:)); + name = deblank(M_.exo_names(estim_params_.var_exo(i,1),:)); x1 = oo_.posterior_density.shocks_std.(name)(:,1); f1 = oo_.posterior_density.shocks_std.(name)(:,2); oo_.prior_density.shocks_std.(name)(:,1) = x2; @@ -96,18 +96,18 @@ for i=1:npar oo_.prior_density.measurement_errors_std.(name)(:,2) = f2; if ~options_.mh_posterior_mode_estimation pmod = oo_.posterior_mode.measurement_errors_std.(name); - end + 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,:))]; + name = [deblank(M_.exo_names(k1,:)) '_' deblank(M_.exo_names(k2,:))]; x1 = oo_.posterior_density.shocks_corr.(name)(:,1); f1 = oo_.posterior_density.shocks_corr.(name)(:,2); oo_.prior_density.shocks_corr.(name)(:,1) = x2; oo_.prior_density.shocks_corr.(name)(:,2) = f2; if ~options_.mh_posterior_mode_estimation - pmod = oo_.posterior_mode.shocks_corr.(name); + pmod = oo_.posterior_mode.shocks_corr.(name); end elseif i <= nvx+nvn+ncx+ncn j = i - (nvx+nvn+ncx); @@ -157,7 +157,7 @@ for i=1:npar 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 + end fprintf(fidTeX,'\\centering\n'); fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s/%s_PriorsAndPosteriors%s}\n',options_.figures.textwidth*min(subplotnum/nn,1),OutputDirectoryName,M_.fname,int2str(figunumber)); fprintf(fidTeX,'\\caption{Priors and posteriors.}'); diff --git a/matlab/PosteriorIRF.m b/matlab/PosteriorIRF.m index 1aeba91cf7..157a5e3a13 100644 --- a/matlab/PosteriorIRF.m +++ b/matlab/PosteriorIRF.m @@ -368,101 +368,101 @@ end % PosteriorIRF_core2.m function. if ~options_.nograph && ~options_.no_graph.posterior -% Save the local variables. -localVars=[]; + % Save the local variables. + localVars=[]; -Check=options_.TeX; -if (Check) - localVars.varlist_TeX=varlist_TeX; -end + Check=options_.TeX; + if (Check) + localVars.varlist_TeX=varlist_TeX; + end -localVars.nvar=nvar; -localVars.MeanIRF=MeanIRF; -localVars.tit=tit; -localVars.nn=nn; -localVars.MAX_nirfs_dsgevar=MAX_nirfs_dsgevar; -localVars.HPDIRF=HPDIRF; -localVars.varlist=varlist; -localVars.MaxNumberOfPlotPerFigure=MaxNumberOfPlotPerFigure; -if options_.dsge_var - localVars.HPDIRFdsgevar=HPDIRFdsgevar; - localVars.MeanIRFdsgevar = MeanIRFdsgevar; -end + localVars.nvar=nvar; + localVars.MeanIRF=MeanIRF; + localVars.tit=tit; + localVars.nn=nn; + localVars.MAX_nirfs_dsgevar=MAX_nirfs_dsgevar; + localVars.HPDIRF=HPDIRF; + localVars.varlist=varlist; + localVars.MaxNumberOfPlotPerFigure=MaxNumberOfPlotPerFigure; + if options_.dsge_var + localVars.HPDIRFdsgevar=HPDIRFdsgevar; + localVars.MeanIRFdsgevar = MeanIRFdsgevar; + end -% The files .TeX are genereted in sequential way always! - -% The files .TeX are generated in sequential way always! -subplotnum = 0; -tit_TeX(M_.exo_names_orig_ord,:) = M_.exo_names_tex; -if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) - fidTeX = fopen([DirectoryName filesep 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; - - for ii=irf_shocks_indx - figunumber = 0; - - for jj=1:nvar - if max(abs(MeanIRF(:,jj,ii))) >= options_.impulse_responses.plot_threshold - subplotnum = subplotnum+1; - - if subplotnum == 1 - fprintf(fidTeX,'\\begin{figure}[H]\n'); + % The files .TeX are genereted in sequential way always! + + % The files .TeX are generated in sequential way always! + subplotnum = 0; + tit_TeX(M_.exo_names_orig_ord,:) = M_.exo_names_tex; + if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) + fidTeX = fopen([DirectoryName filesep 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; + + for ii=irf_shocks_indx + figunumber = 0; + + for jj=1:nvar + if max(abs(MeanIRF(:,jj,ii))) >= options_.impulse_responses.plot_threshold + subplotnum = subplotnum+1; + + if subplotnum == 1 + fprintf(fidTeX,'\\begin{figure}[H]\n'); + end + name = deblank(varlist(jj,:)); + texname = deblank(varlist_TeX(jj,:)); + fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{%s}\n'],name,['$' texname '$']); end - name = deblank(varlist(jj,:)); - texname = deblank(varlist_TeX(jj,:)); - fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{%s}\n'],name,['$' texname '$']); - end - if subplotnum == MaxNumberOfPlotPerFigure || (jj == nvar && subplotnum> 0) - figunumber = figunumber+1; - - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s/%s_Bayesian_IRF_%s_%d}\n',options_.figures.textwidth*min(subplotnum/nn,1),DirectoryName,M_.fname,deblank(tit(ii,:)),figunumber); - if options_.relative_irf - fprintf(fidTeX,['\\caption{Bayesian relative IRF.}']); - else - fprintf(fidTeX,'\\caption{Bayesian IRF: Orthogonalized shock to $%s$.}\n',deblank(tit_TeX(ii,:))); + if subplotnum == MaxNumberOfPlotPerFigure || (jj == nvar && subplotnum> 0) + figunumber = figunumber+1; + + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s/%s_Bayesian_IRF_%s_%d}\n',options_.figures.textwidth*min(subplotnum/nn,1),DirectoryName,M_.fname,deblank(tit(ii,:)),figunumber); + if options_.relative_irf + fprintf(fidTeX,['\\caption{Bayesian relative IRF.}']); + else + fprintf(fidTeX,'\\caption{Bayesian IRF: Orthogonalized shock to $%s$.}\n',deblank(tit_TeX(ii,:))); + end + fprintf(fidTeX,'\\label{Fig:BayesianIRF:%s:%d}\n',deblank(tit(ii,:)),figunumber); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,' \n'); + + subplotnum = 0; end - fprintf(fidTeX,'\\label{Fig:BayesianIRF:%s:%d}\n',deblank(tit(ii,:)),figunumber); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,' \n'); - - subplotnum = 0; - end + end end + fprintf(fidTeX,'%% End of TeX file.\n'); + fclose(fidTeX); end - fprintf(fidTeX,'%% End of TeX file.\n'); - fclose(fidTeX); -end -% The others file format are generated in parallel by PosteriorIRF_core2! + % The others file format are generated in parallel by PosteriorIRF_core2! -% Comment for testing! -if ~isoctave - if isnumeric(options_.parallel) || (M_.exo_nbr*ceil(size(varlist,1)/MaxNumberOfPlotPerFigure))<8 - [fout] = PosteriorIRF_core2(localVars,1,M_.exo_nbr,0); - else - isRemoteOctave = 0; - for indPC=1:length(options_.parallel) - isRemoteOctave = isRemoteOctave + (findstr(options_.parallel(indPC).MatlabOctavePath, 'octave')); - end - if isRemoteOctave + % Comment for testing! + if ~isoctave + if isnumeric(options_.parallel) || (M_.exo_nbr*ceil(size(varlist,1)/MaxNumberOfPlotPerFigure))<8 [fout] = PosteriorIRF_core2(localVars,1,M_.exo_nbr,0); else - globalVars = struct('M_',M_, ... - 'options_', options_); + isRemoteOctave = 0; + for indPC=1:length(options_.parallel) + isRemoteOctave = isRemoteOctave + (findstr(options_.parallel(indPC).MatlabOctavePath, 'octave')); + end + if isRemoteOctave + [fout] = PosteriorIRF_core2(localVars,1,M_.exo_nbr,0); + else + globalVars = struct('M_',M_, ... + 'options_', options_); - [fout] = masterParallel(options_.parallel, 1, M_.exo_nbr,NamFileInput,'PosteriorIRF_core2', localVars, globalVars, options_.parallel_info); + [fout] = masterParallel(options_.parallel, 1, M_.exo_nbr,NamFileInput,'PosteriorIRF_core2', localVars, globalVars, options_.parallel_info); + end end + else + [fout] = PosteriorIRF_core2(localVars,1,M_.exo_nbr,0); end -else - [fout] = PosteriorIRF_core2(localVars,1,M_.exo_nbr,0); -end -% END parallel code! + % END parallel code! end diff --git a/matlab/PosteriorIRF_core2.m b/matlab/PosteriorIRF_core2.m index 9f922a409c..09e003c430 100644 --- a/matlab/PosteriorIRF_core2.m +++ b/matlab/PosteriorIRF_core2.m @@ -2,10 +2,10 @@ function myoutput=PosteriorIRF_core2(myinputs,fpar,npar,whoiam,ThisMatlab) % function myoutput=PosteriorIRF_core2(myinputs,fpar,npar,whoiam, ThisMatlab) % Generates the Posterior IRFs plot from the IRFs generated in % PosteriorIRF_core1 -% +% % PARALLEL CONTEXT % Performs in parallel execution a portion of the PosteriorIRF.m code. -% For more information, see the comment in posterior_sampler_core.m +% For more information, see the comment in posterior_sampler_core.m % function. % % INPUTS @@ -135,7 +135,7 @@ for i=fpar:npar plot(1:options_.irf,HPDIRFdsgevar(:,1,j,i),'--k','linewidth',1) plot(1:options_.irf,HPDIRFdsgevar(:,2,j,i),'--k','linewidth',1) end - % plot([1 options_.irf],[0 0],'-r','linewidth',0.5); + % plot([1 options_.irf],[0 0],'-r','linewidth',0.5); box on axis tight xlim([1 options_.irf]); @@ -162,7 +162,7 @@ for i=fpar:npar if whoiam fprintf('Done! \n'); waitbarString = [ 'Exog. shocks ' int2str(i) '/' int2str(npar) ' done.']; -% fMessageStatus((i-fpar+1)/(npar-fpar+1),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab)); + % fMessageStatus((i-fpar+1)/(npar-fpar+1),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab)); dyn_waitbar((i-fpar+1)/(npar-fpar+1),[],waitbarString); end end% loop over exo_var diff --git a/matlab/ReshapeMatFiles.m b/matlab/ReshapeMatFiles.m index 81054379f3..1d127a67ba 100644 --- a/matlab/ReshapeMatFiles.m +++ b/matlab/ReshapeMatFiles.m @@ -18,9 +18,9 @@ function ReshapeMatFiles(type, type2) % posterior % gsa % prior -% +% % OUTPUTS: -% none +% none % % SPECIAL REQUIREMENTS % none @@ -61,17 +61,17 @@ else end else MhDirectoryName = [CheckPath('prior',M_.dname) filesep ]; - end + end end switch type case 'irf_dsge' CAPtype = 'IRF_DSGE'; TYPEsize = [ options_.irf , size(options_.varlist,1) , M_.exo_nbr ]; - TYPEarray = 4; + TYPEarray = 4; case 'irf_bvardsge' CAPtype = 'IRF_BVARDSGE'; TYPEsize = [ options_.irf , length(options_.varobs) , M_.exo_nbr ]; - TYPEarray = 4; + TYPEarray = 4; case 'smooth' CAPtype = 'SMOOTH'; TYPEsize = [ M_.endo_nbr , options_.nobs ]; @@ -134,7 +134,7 @@ switch TYPEarray 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]); + save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(NumberOfTYPEfiles-foffset+1) '.mat'],['STOCK_' CAPtype]); end else load([MhDirectoryName M_.fname '_' type '1.mat']); @@ -176,7 +176,7 @@ switch TYPEarray 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 ]); + 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 diff --git a/matlab/TaRB_optimizer_wrapper.m b/matlab/TaRB_optimizer_wrapper.m index 4d29add34a..fe62c57333 100644 --- a/matlab/TaRB_optimizer_wrapper.m +++ b/matlab/TaRB_optimizer_wrapper.m @@ -3,15 +3,15 @@ function [fval,info,exit_flag,DLIK,Hess,SteadyState,trend_coeff] = TaRB_optimiz % Wrapper function for target function used in TaRB algorithm; reassembles % full parameter vector before calling target function % -% INPUTS -% o optpar [double] (p_opt*1) vector of subset of parameters to be considered -% o par_vector [double] (p*1) full vector of parameters +% INPUTS +% o optpar [double] (p_opt*1) vector of subset of parameters to be considered +% o par_vector [double] (p*1) full vector of parameters % o parameterindices [double] (p_opt*1) index of optpar entries in % par_vector % o TargetFun [char] string specifying the name of the objective % function (posterior kernel). % o varargin [structure] other inputs of target function -% +% % OUTPUTS % o fval [scalar] value of (minus) the likelihood. % o info [double] (p*2) error code vector @@ -20,7 +20,7 @@ function [fval,info,exit_flag,DLIK,Hess,SteadyState,trend_coeff] = TaRB_optimiz % o Hess [double] (p*p) asymptotic Hessian matrix. % o SteadyState [double] Vector of doubles, steady state level for the endogenous variables. % o trend_coeff [double] Matrix of doubles, coefficients of the deterministic trend in the measurement equation -% +% % Copyright (C) 2015-16 Dynare Team % % This file is part of Dynare. @@ -40,4 +40,3 @@ function [fval,info,exit_flag,DLIK,Hess,SteadyState,trend_coeff] = TaRB_optimiz par_vector(parameterindices,:)=optpar; %reassemble parameter [fval,info,exit_flag,DLIK,Hess,SteadyState,trend_coeff] = feval(TargetFun,par_vector,varargin{:}); %call target function - diff --git a/matlab/Tracing.m b/matlab/Tracing.m index 7d0e947c97..4d5348ad0d 100644 --- a/matlab/Tracing.m +++ b/matlab/Tracing.m @@ -2,15 +2,15 @@ function [] = Tracing() % DESCRIPTION % This function is used to test the correct execution of a matlab section % on remote machine. -% +% % If no error happen the function simply create a file. % % INPUTS % ... -% +% % OUTPUTS % ... -% +% % SPECIAL REQUIREMENTS % none diff --git a/matlab/UnivariateSpectralDensity.m b/matlab/UnivariateSpectralDensity.m index d5a37f24f8..41b67c4031 100644 --- a/matlab/UnivariateSpectralDensity.m +++ b/matlab/UnivariateSpectralDensity.m @@ -1,15 +1,15 @@ function [oo_] = UnivariateSpectralDensity(M_,oo_,options_,var_list) % This function computes the theoretical spectral density of each -% endogenous variable declared in var_list. Results are stored in -% oo_.SpectralDensity and may be plotted. Plots are saved into the -% graphs-folder. -% +% endogenous variable declared in var_list. Results are stored in +% oo_.SpectralDensity and may be plotted. Plots are saved into the +% graphs-folder. +% % INPUTS % M_ [structure] Dynare's model structure % oo_ [structure] Dynare's results structure % options_ [structure] Dynare's options structure % var_list [integer] Vector of indices for a subset of variables. -% +% % OUTPUTS % oo_ [structure] Dynare's results structure, % containing the subfield @@ -17,7 +17,7 @@ function [oo_] = UnivariateSpectralDensity(M_,oo_,options_,var_list) % and density, which are of size nvar*ngrid. % -% Adapted from th_autocovariances.m. +% Adapted from th_autocovariances.m. % Copyright (C) 2006-2017 Dynare Team % @@ -38,7 +38,7 @@ function [oo_] = UnivariateSpectralDensity(M_,oo_,options_,var_list) if options_.order > 1 - disp('UnivariateSpectralDensity :: I Cannot compute the theoretical spectral density') + disp('UnivariateSpectralDensity :: I Cannot compute the theoretical spectral density') disp('with a second order approximation of the DSGE model!') disp('Please set order = 1. I abort') return @@ -102,7 +102,7 @@ if ~isempty(u) ivar = oo_.dr.order_var(iky); end -iky = iv(ivar); +iky = iv(ivar); aa = ghx(iky,:); bb = ghu(iky,:); ngrid = options_.hp_ngrid; %number of grid points @@ -112,7 +112,7 @@ tneg = exp(-sqrt(-1)*freqs); %negative frequencies if options_.one_sided_hp_filter error('UnivariateSpectralDensity:: spectral density estimate not available with one-sided HP filter') elseif options_.hp_filter == 0 && ~options_.bandpass.indicator %do not filter - filter_gain=ones(ngrid,1); + filter_gain=ones(ngrid,1); elseif ~(options_.hp_filter == 0 && ~options_.bandpass.indicator) && options_.bandpass.indicator %filter with bandpass filter_gain = zeros(1,ngrid); lowest_periodicity=options_.bandpass.passband(2); @@ -122,7 +122,7 @@ elseif ~(options_.hp_filter == 0 && ~options_.bandpass.indicator) && options_.ba filter_gain(freqs<=-2*pi/lowest_periodicity+2*pi & freqs>=-2*pi/highest_periodicity+2*pi)=1; elseif ~(options_.hp_filter == 0 && ~options_.bandpass.indicator) && ~options_.bandpass.indicator %filter with HP-filter lambda = options_.hp_filter; - filter_gain = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2); + filter_gain = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2); end mathp_col = NaN(ngrid,length(ivar)^2); @@ -139,7 +139,7 @@ end f = zeros(nvar,ngrid); for i=1:nvar f(i,:) = real(mathp_col(:,(i-1)*nvar+i)); %read out spectral density -end +end oo_.SpectralDensity.freqs=freqs; oo_.SpectralDensity.density=f; @@ -164,7 +164,7 @@ if options_.nograph == 0 xlabel('0 \leq \omega \leq \pi') ylabel('f(\omega)') box on - axis tight + axis tight dyn_saveas(hh,[M_.fname ,filesep,'graphs', filesep, 'SpectralDensity_' deblank(M_.endo_names(ivar(i),:))],options_.nodisplay,options_.graph_format) end end diff --git a/matlab/WriteShockDecomp2Excel.m b/matlab/WriteShockDecomp2Excel.m index 618a6b064b..5417e5250b 100644 --- a/matlab/WriteShockDecomp2Excel.m +++ b/matlab/WriteShockDecomp2Excel.m @@ -1,7 +1,7 @@ function WriteShockDecomp2Excel(z,shock_names,endo_names,i_var,initial_date,DynareModel,DynareOptions,opts_decomp) %function WriteShockDecomp2Excel(z,shock_names,endo_names,i_var,initial_date,DynareModel,DynareOptions) % Saves the results from the shock_decomposition command to xls -% +% % Inputs % z [n_var*(nshock+2)*nperiods] shock decomposition array, see shock_decomposition.m for details % shock_names [endo_nbr*string length] shock names from M_.exo_names @@ -48,8 +48,8 @@ if nargin==8 end if isfield(opts_decomp,'fig_mode') && ~isempty(opts_decomp.fig_mode) fig_mode = opts_decomp.fig_mode; - fig_mode1 = ['_' fig_mode]; - fig_mode = [fig_mode '_']; + fig_mode1 = ['_' fig_mode]; + fig_mode = [fig_mode '_']; end if isfield(opts_decomp,'screen_shocks') if use_shock_groups @@ -60,15 +60,15 @@ if nargin==8 end if isfield(opts_decomp,'fig_name') fig_name = opts_decomp.fig_name; -% fig_name = ['_' fig_name]; - fig_name1 = [fig_name]; - fig_name = [fig_name '_']; + % fig_name = ['_' fig_name]; + fig_name1 = [fig_name]; + fig_name = [fig_name '_']; end if screen_shocks - fig_name1 = [fig_name1 '_screen']; - fig_name = [fig_name 'screen_']; + fig_name1 = [fig_name1 '_screen']; + fig_name = [fig_name 'screen_']; end -end +end gend = size(z,3); @@ -99,7 +99,7 @@ for j=1:nvar z1 = [z1(isort(1:16),:); zres; z1(comp_nbr0:end,:)]; comp_nbr=18; end - + d0(1,:)=[{'Decomposition'} cellstr(labels(1:comp_nbr,:))' {'Smoot Var'}]; d0=[d0; num2cell([x' z1'])]; LastRow=size(d0,1); @@ -112,7 +112,7 @@ for j=1:nvar d0(LastRow+2+ic,2:1+length(group_members))=group_members; end end - + warning off if ~ismac [STATUS,MESSAGE] = xlswrite([DynareModel.fname,'_shock_decomposition',fig_mode,fig_name1],d0,deblank(endo_names(i_var(j),:))); @@ -122,6 +122,5 @@ for j=1:nvar warning on clear d0 - -end +end diff --git a/matlab/add_filter_subtitle.m b/matlab/add_filter_subtitle.m index 6525875179..689b8a5acf 100644 --- a/matlab/add_filter_subtitle.m +++ b/matlab/add_filter_subtitle.m @@ -1,7 +1,7 @@ function title=add_filter_subtitle(title,options_) if ~options_.hp_filter && ~options_.one_sided_hp_filter && ~options_.bandpass.indicator %do not filter - %nothing to add here + %nothing to add here elseif ~options_.hp_filter && ~options_.one_sided_hp_filter && options_.bandpass.indicator title = [title ' (Bandpass filter, (' ... num2str(options_.bandpass.passband(1)),' ',num2str(options_.bandpass.passband(2)), '))']; @@ -10,6 +10,6 @@ elseif options_.hp_filter && ~options_.one_sided_hp_filter && ~options_.bandpas num2str(options_.hp_filter) ')']; elseif ~options_.hp_filter && options_.one_sided_hp_filter && ~options_.bandpass.indicator title = [title ' (One-sided HP filter, lambda = ' ... - num2str(options_.one_sided_hp_filter) ')']; + num2str(options_.one_sided_hp_filter) ')']; end end \ No newline at end of file diff --git a/matlab/add_path_to_mex_files.m b/matlab/add_path_to_mex_files.m index e35d29a6b9..13140bba5b 100644 --- a/matlab/add_path_to_mex_files.m +++ b/matlab/add_path_to_mex_files.m @@ -1,5 +1,5 @@ function mexpath = add_path_to_mex_files(dynareroot, modifypath) - + % Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. @@ -20,7 +20,7 @@ function mexpath = add_path_to_mex_files(dynareroot, modifypath) if nargin<2 modifypath = true; end - + if exist('OCTAVE_VERSION') if ispc() && strcmpi(computer(), 'i686-w64-mingw32') mexpath = {[dynareroot '../mex/octave32/']}; diff --git a/matlab/annualized_shock_decomposition.m b/matlab/annualized_shock_decomposition.m index f5ee9c8e62..4972edb307 100644 --- a/matlab/annualized_shock_decomposition.m +++ b/matlab/annualized_shock_decomposition.m @@ -1,28 +1,28 @@ function [z, endo_names, endo_names_tex, steady_state, i_var, oo_] = annualized_shock_decomposition(oo_, M_, options_, i_var, t0, t1, realtime_, vintage_, steady_state, q2a, cumfix) % function oo_ = annualized_shock_decomposition(oo_,t0,options_.nobs); % Computes annualized shocks contribution to a simulated trajectory. The fields set are -% oo_.annualized_shock_decomposition, oo_.annualized_realtime_shock_decomposition, -% oo_.annualized_realtime_conditional_shock_decomposition and oo_.annualized_realtime_forecast_shock_decomposition. +% oo_.annualized_shock_decomposition, oo_.annualized_realtime_shock_decomposition, +% oo_.annualized_realtime_conditional_shock_decomposition and oo_.annualized_realtime_forecast_shock_decomposition. % Subfields are arrays n_var by nshock+2 by nperiods. The % first nshock columns store the respective shock contributions, column n+1 % stores the role of the initial conditions, while column n+2 stores the -% value of the smoothed variables. Both the variables and shocks are stored +% value of the smoothed variables. Both the variables and shocks are stored % in the order of endo_names and M_.exo_names, respectively. % % INPUTS % oo_: [structure] Storage of results % M_: [structure] Storage of model -% opts: [structure] options for shock decomp +% opts: [structure] options for shock decomp % i_var: [array] index of vars % t0: [integer] first period % t1: [integer] last period -% realtime_: [integer] +% realtime_: [integer] % vintage_: [integer] % steady_state: [array] steady state value of quarterly (log-) level vars % q2a: [structure] info on q2a % % OUTPUTS -% z: [matrix] shock decomp to plot +% z: [matrix] shock decomp to plot % endo_names: [char] updated var names % endo_names_tex: [char] updated TeX var names % steady_state: [array] updated stady state of vars @@ -57,13 +57,13 @@ islog = q2a.islog; aux = q2a.aux; aux0 = aux; cumfix = q2a.cumfix; -% usual shock decomp +% usual shock decomp if isstruct(oo_) -% z = oo_.shock_decomposition; - myopts=options_; - myopts.plot_shock_decomp.type='qoq'; - myopts.plot_shock_decomp.realtime=0; - [z, junk] = plot_shock_decomposition(M_,oo_,myopts,[]); + % z = oo_.shock_decomposition; + myopts=options_; + myopts.plot_shock_decomp.type='qoq'; + myopts.plot_shock_decomp.realtime=0; + [z, junk] = plot_shock_decomposition(M_,oo_,myopts,[]); else z = oo_; end @@ -177,147 +177,147 @@ end % realtime if realtime_ && isstruct(oo_) && isfield(oo_, 'realtime_shock_decomposition') -init=1; -for i=t0:4:t1 - yr=floor(i/4); - za=[]; - gza=[]; + init=1; + for i=t0:4:t1 + yr=floor(i/4); + za=[]; + gza=[]; myopts=options_; myopts.plot_shock_decomp.type='qoq'; myopts.plot_shock_decomp.realtime=1; myopts.plot_shock_decomp.vintage=i; [z, steady_state_aux] = plot_shock_decomposition(M_,oo_,myopts,[]); z = z(i_var,:,:); -if isstruct(aux) - if ischar(aux0.y) - [y_aux, steady_state_aux] = plot_shock_decomposition(M_,oo_,myopts,aux0.y); - aux.y=y_aux; - aux.yss=steady_state_aux; - end - yaux=aux.y; -end + if isstruct(aux) + if ischar(aux0.y) + [y_aux, steady_state_aux] = plot_shock_decomposition(M_,oo_,myopts,aux0.y); + aux.y=y_aux; + aux.yss=steady_state_aux; + end + yaux=aux.y; + end nterms = size(z,2); - -% z = oo_.realtime_shock_decomposition.(['time_' int2str(i)]); -% z = z(i_var,:,:); - - for j=1:nvar - for k =nterms:-1:1 -% if k<nterms -% ztmp = squeeze(sum(z(j,[1:k-1,k+1:end-1],t0-4:end))); -% else + + % z = oo_.realtime_shock_decomposition.(['time_' int2str(i)]); + % z = z(i_var,:,:); + + for j=1:nvar + for k =nterms:-1:1 + % if k<nterms + % ztmp = squeeze(sum(z(j,[1:k-1,k+1:end-1],t0-4:end))); + % else ztmp = squeeze(z(j,k,min((t0-3):-4:1):end)); -% end - if isstruct(aux) - aux.y = squeeze(yaux(j,k,min((t0-3):-4:1):end)); + % end + if isstruct(aux) + aux.y = squeeze(yaux(j,k,min((t0-3):-4:1):end)); + end + [za(j,k,:), steady_state_a(j,1), gza(j,k,:), steady_state_ga(j,1)] = ... + quarterly2annual(ztmp,steady_state(j),GYTREND0,var_type,islog,aux); + % if k<nterms + % za(j,k,:) = za(j,end,:) - za(j,k,:); + % gza(j,k,:) = gza(j,end,:) - gza(j,k,:); + % end + end - [za(j,k,:), steady_state_a(j,1), gza(j,k,:), steady_state_ga(j,1)] = ... - quarterly2annual(ztmp,steady_state(j),GYTREND0,var_type,islog,aux); -% if k<nterms -% za(j,k,:) = za(j,end,:) - za(j,k,:); -% gza(j,k,:) = gza(j,end,:) - gza(j,k,:); -% end - + + ztmp=squeeze(za(j,:,:)); + + if cumfix==0 + zscale = sum(ztmp(1:end-1,:))./ztmp(end,:); + ztmp(1:end-1,:) = ztmp(1:end-1,:)./repmat(zscale,[nterms-1,1]); + else + zres = ztmp(end,:)-sum(ztmp(1:end-1,:)); + ztmp(end-1,:) = ztmp(end-1,:) + zres; + end + + gztmp=squeeze(gza(j,:,:)); + if cumfix==0 + gscale = sum(gztmp(1:end-1,:))./ gztmp(end,:); + gztmp(1:end-1,:) = gztmp(1:end-1,:)./repmat(gscale,[nterms-1,1]); + else + gres = gztmp(end,:) - sum(gztmp(1:end-1,:)); + gztmp(end-1,:) = gztmp(end-1,:)+gres; + end + + za(j,:,:) = ztmp; + gza(j,:,:) = gztmp; end - - ztmp=squeeze(za(j,:,:)); - if cumfix==0 - zscale = sum(ztmp(1:end-1,:))./ztmp(end,:); - ztmp(1:end-1,:) = ztmp(1:end-1,:)./repmat(zscale,[nterms-1,1]); + if q2a.plot ==1 + z=gza; + elseif q2a.plot == 2 + z=za; else - zres = ztmp(end,:)-sum(ztmp(1:end-1,:)); - ztmp(end-1,:) = ztmp(end-1,:) + zres; + z=cat(1,za,gza); end - - gztmp=squeeze(gza(j,:,:)); - if cumfix==0 - gscale = sum(gztmp(1:end-1,:))./ gztmp(end,:); - gztmp(1:end-1,:) = gztmp(1:end-1,:)./repmat(gscale,[nterms-1,1]); + + if init==1 + oo_.annualized_realtime_shock_decomposition.pool = z; else - gres = gztmp(end,:) - sum(gztmp(1:end-1,:)); - gztmp(end-1,:) = gztmp(end-1,:)+gres; + oo_.annualized_realtime_shock_decomposition.pool(:,:,yr) = z(:,:,end-nfrcst); end - - za(j,:,:) = ztmp; - gza(j,:,:) = gztmp; - end - - if q2a.plot ==1 - z=gza; - elseif q2a.plot == 2 - z=za; - else - z=cat(1,za,gza); - end - - if init==1 - oo_.annualized_realtime_shock_decomposition.pool = z; - else - oo_.annualized_realtime_shock_decomposition.pool(:,:,yr) = z(:,:,end-nfrcst); - end - oo_.annualized_realtime_shock_decomposition.(['yr_' int2str(yr)]) = z; - - if opts.forecast - oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr)]) = z(:,:,end-nfrcst:end); - if init>nfrcst - oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-nfrcst)]) = ... - oo_.annualized_realtime_shock_decomposition.pool(:,:,yr-nfrcst:end) - ... - oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr-nfrcst)]); - % fix others - oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-nfrcst)])(:,end-1,:) = ... - oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-nfrcst)])(:,end-1,:) + ... - oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr-nfrcst)])(:,end,:); - % fix total - oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-nfrcst)])(:,end,:) = ... - oo_.annualized_realtime_shock_decomposition.pool(:,end,yr-nfrcst:end); - if i==t1 - for my_forecast_=(nfrcst-1):-1:1 - oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-my_forecast_)]) = ... - oo_.annualized_realtime_shock_decomposition.pool(:,:,yr-my_forecast_:yr) - ... - oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr-my_forecast_)])(:,:,1:my_forecast_+1); - oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-my_forecast_)])(:,end-1,:) = ... - oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr-my_forecast_)])(:,end,1:my_forecast_+1); - oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-my_forecast_)])(:,end,:) = ... - oo_.annualized_realtime_shock_decomposition.pool(:,end,yr-my_forecast_:yr); + oo_.annualized_realtime_shock_decomposition.(['yr_' int2str(yr)]) = z; + + if opts.forecast + oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr)]) = z(:,:,end-nfrcst:end); + if init>nfrcst + oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-nfrcst)]) = ... + oo_.annualized_realtime_shock_decomposition.pool(:,:,yr-nfrcst:end) - ... + oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr-nfrcst)]); + % fix others + oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-nfrcst)])(:,end-1,:) = ... + oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-nfrcst)])(:,end-1,:) + ... + oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr-nfrcst)])(:,end,:); + % fix total + oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-nfrcst)])(:,end,:) = ... + oo_.annualized_realtime_shock_decomposition.pool(:,end,yr-nfrcst:end); + if i==t1 + for my_forecast_=(nfrcst-1):-1:1 + oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-my_forecast_)]) = ... + oo_.annualized_realtime_shock_decomposition.pool(:,:,yr-my_forecast_:yr) - ... + oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr-my_forecast_)])(:,:,1:my_forecast_+1); + oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-my_forecast_)])(:,end-1,:) = ... + oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr-my_forecast_)])(:,end,1:my_forecast_+1); + oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-my_forecast_)])(:,end,:) = ... + oo_.annualized_realtime_shock_decomposition.pool(:,end,yr-my_forecast_:yr); + end end end end - end -% ztmp=oo_.realtime_shock_decomposition.pool(:,:,21:29)-oo_.realtime_forecast_shock_decomposition.time_21; + % ztmp=oo_.realtime_shock_decomposition.pool(:,:,21:29)-oo_.realtime_forecast_shock_decomposition.time_21; - init=init+1; -end + init=init+1; + end + + switch realtime_ -switch realtime_ - - case 0 + case 0 z = oo_.annualized_shock_decomposition; - - case 1 % realtime + + case 1 % realtime if vintage_ z = oo_.annualized_realtime_shock_decomposition.(['yr_' int2str(floor(vintage_/4))]); else z = oo_.annualized_realtime_shock_decomposition.pool; end - - case 2 % conditional + + case 2 % conditional if vintage_ z = oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(floor(vintage_/4))]); else error(); end - - case 3 % forecast + + case 3 % forecast if vintage_ z = oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(floor(vintage_/4))]); else error() end -end + end end if q2a.plot ==0 @@ -331,4 +331,3 @@ else steady_state = steady_state_a; end end - diff --git a/matlab/autoregressive_process_specification.m b/matlab/autoregressive_process_specification.m index 7cc34db27d..3c909a9b42 100644 --- a/matlab/autoregressive_process_specification.m +++ b/matlab/autoregressive_process_specification.m @@ -2,43 +2,43 @@ function [InnovationVariance,AutoregressiveParameters] = autoregressive_process_ % This function computes the parameters of an AR(p) process from the variance and the autocorrelation function % (the first p terms) of this process. % -% INPUTS +% INPUTS % [1] Variance [double] scalar, variance of the variable. % [2] Rho [double] p*1 vector, the autocorelation function: \rho(1), \rho(2), ..., \rho(p). % [3] p [double] scalar, the number of lags in the AR process. % -% OUTPUTS +% OUTPUTS % [1] InnovationVariance [double] scalar, the variance of the innovation. % [2] AutoregressiveParameters [double] p*1 vector of autoregressive parameters. % -% NOTES +% NOTES % % The AR(p) model for {y_t} is: -% -% y_t = \phi_1 * y_{t-1} + \phi_2 * y_{t-2} + ... + \phi_p * y_{t-p} + e_t +% +% y_t = \phi_1 * y_{t-1} + \phi_2 * y_{t-2} + ... + \phi_p * y_{t-p} + e_t % % Let \gamma(0) and \rho(1), ..., \rho(2) be the variance and the autocorrelation function of {y_t}. This function -% compute the variance of {e_t} and the \phi_i (i=1,...,p) from the variance and the autocorrelation function of {y_t}. +% compute the variance of {e_t} and the \phi_i (i=1,...,p) from the variance and the autocorrelation function of {y_t}. % We know that: -% +% % \gamma(0) = \phi_1 \gamma(1) + ... + \phi_p \gamma(p) + \sigma^2 % % where \sigma^2 is the variance of {e_t}. Equivalently we have: % -% \sigma^2 = \gamma(0) (1-\rho(1)\phi_1 - ... - \rho(p)\phi_p) +% \sigma^2 = \gamma(0) (1-\rho(1)\phi_1 - ... - \rho(p)\phi_p) % % We also have for any integer h>0: -% +% % \rho(h) = \phi_1 \rho(h-1) + ... + \phi_p \rho(h-p) % % We can write the equations for \rho(1), ..., \rho(p) using matrices. Let R be the p*p autocorelation -% matrix and v be the p*1 vector gathering the first p terms of the autocorrelation function. We have: +% matrix and v be the p*1 vector gathering the first p terms of the autocorrelation function. We have: % % v = R*PHI -% +% % where PHI is a p*1 vector with the autoregressive parameters of the AR(p) process. We can recover the autoregressive % parameters by inverting the autocorrelation matrix: PHI = inv(R)*v. -% +% % This function first computes the vector PHI by inverting R and computes the variance of the innovation by evaluating % % \sigma^2 = \gamma(0)*(1-PHI'*v) diff --git a/matlab/backward_model_inversion.m b/matlab/backward_model_inversion.m index c94b8403b2..5e305ae559 100644 --- a/matlab/backward_model_inversion.m +++ b/matlab/backward_model_inversion.m @@ -1,6 +1,6 @@ function [endogenousvariables, exogenousvariables] = backward_model_inversion(constraints, exogenousvariables, initialconditions, endo_names, exo_names, freeinnovations, DynareModel, DynareOptions, DynareOutput) -% INPUTS +% INPUTS % - constraints [dseries] with N constrained endogenous variables from t1 to t2. % - exogenousvariables [dseries] with Q exogenous variables. % - initialconditions [dseries] with M endogenous variables starting before t1 (M initialcond must contain at least the state variables). @@ -8,11 +8,11 @@ function [endogenousvariables, exogenousvariables] = backward_model_inversion(co % - exo_names [cell] list of exogenous variable names. % - freeinstruments [cell] list of exogenous variable names used to control the constrained endogenous variables. % -% OUTPUTS +% OUTPUTS % - endogenous [dseries] % - exogenous [dseries] % -% REMARKS +% REMARKS % Copyright (C) 2017 Dynare Team % diff --git a/matlab/basic_plan.m b/matlab/basic_plan.m index 390b2076e9..ae7d6bcbf6 100644 --- a/matlab/basic_plan.m +++ b/matlab/basic_plan.m @@ -31,60 +31,60 @@ function plan = basic_plan(plan, exogenous, expectation_type, date, value) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if ~ischar(expectation_type) || size(expectation_type,1) ~= 1 - error(['in basic_plan the third argument should be a string containing the simulation type (''perfect_foresight'' or ''surprise'')']); - end - exogenous = strtrim(exogenous); - ix = find(strcmp(exogenous, plan.exo_names)); - if isempty(ix) - error(['in basic_plan the second argument ' exogenous ' is not an exogenous variable']); - end - sdate = length(date); - if sdate > 1 - if date(1) < plan.date(1) || date(end) > plan.date(end) - error(['in basic_plan the fourth argument (date=' date ') must lay inside the plan.date ' plan.date]); - end - else - if date < plan.date(1) || date > plan.date(end) - error(['in basic_plan the fourth argument (date=' date ') must lay iside the plan.date ' plan.date]); - end - end - if length(date) ~= length(value) - error(['in basic_plan the number of dates (' int2str(length(date)) ') is not equal to the numbers of shock (' int2str(length(value)) ') for exogenous variable ' exogenous]); - end - if ~isempty(plan.options_cond_fcst_.controlled_varexo) - common_var = find(ix == plan.options_cond_fcst_.controlled_varexo); - if ~isempty(common_var) - common_date = intersect(date, plan.constrained_date_{common_var}); - if ~isempty(common_date) - [date_, i_date] = setdiff(date, common_date); - value = value(i_date); - if common_date.length > 1 - the_dates = [cell2mat(strings(common_date(1))) ':' cell2mat(strings(common_date(end)))]; - else - the_dates = cell2mat(strings(common_date)); - end - warning(['Impossible case: ' plan.exo_names{plan.options_cond_fcst_.controlled_varexo(common_var)} ' is used both as a shock and as an endogenous variable to control the path of ' plan.endo_names{plan.constrained_vars_(common_var)} ' at the dates ' the_dates]); - warning('This shock will not be considered'); - end - end - end - if isempty(plan.shock_vars_) - plan.shock_vars_ = ix; - if strcmp(expectation_type, 'perfect_foresight') - plan.shock_perfect_foresight_ = 1; - else - plan.shock_perfect_foresight_ = 0; - end - else - plan.shock_vars_ = [plan.shock_vars_ ; ix]; - if strcmp(expectation_type, 'perfect_foresight') - plan.shock_perfect_foresight_ = [plan.shock_perfect_foresight_ ; 1]; - else - plan.shock_perfect_foresight_ = [plan.shock_perfect_foresight_ ; 0]; - end - end - plan.shock_date_{length(plan.shock_date_) + 1} = date; - plan.shock_str_date_{length(plan.shock_str_date_) + 1} = strings(date); - plan.shock_int_date_{length(plan.shock_int_date_) + 1} = date - plan.date(1) + 1; - plan.shock_paths_{length(plan.shock_paths_) + 1} = value; +if ~ischar(expectation_type) || size(expectation_type,1) ~= 1 + error(['in basic_plan the third argument should be a string containing the simulation type (''perfect_foresight'' or ''surprise'')']); +end +exogenous = strtrim(exogenous); +ix = find(strcmp(exogenous, plan.exo_names)); +if isempty(ix) + error(['in basic_plan the second argument ' exogenous ' is not an exogenous variable']); +end +sdate = length(date); +if sdate > 1 + if date(1) < plan.date(1) || date(end) > plan.date(end) + error(['in basic_plan the fourth argument (date=' date ') must lay inside the plan.date ' plan.date]); + end +else + if date < plan.date(1) || date > plan.date(end) + error(['in basic_plan the fourth argument (date=' date ') must lay iside the plan.date ' plan.date]); + end +end +if length(date) ~= length(value) + error(['in basic_plan the number of dates (' int2str(length(date)) ') is not equal to the numbers of shock (' int2str(length(value)) ') for exogenous variable ' exogenous]); +end +if ~isempty(plan.options_cond_fcst_.controlled_varexo) + common_var = find(ix == plan.options_cond_fcst_.controlled_varexo); + if ~isempty(common_var) + common_date = intersect(date, plan.constrained_date_{common_var}); + if ~isempty(common_date) + [date_, i_date] = setdiff(date, common_date); + value = value(i_date); + if common_date.length > 1 + the_dates = [cell2mat(strings(common_date(1))) ':' cell2mat(strings(common_date(end)))]; + else + the_dates = cell2mat(strings(common_date)); + end + warning(['Impossible case: ' plan.exo_names{plan.options_cond_fcst_.controlled_varexo(common_var)} ' is used both as a shock and as an endogenous variable to control the path of ' plan.endo_names{plan.constrained_vars_(common_var)} ' at the dates ' the_dates]); + warning('This shock will not be considered'); + end + end +end +if isempty(plan.shock_vars_) + plan.shock_vars_ = ix; + if strcmp(expectation_type, 'perfect_foresight') + plan.shock_perfect_foresight_ = 1; + else + plan.shock_perfect_foresight_ = 0; + end +else + plan.shock_vars_ = [plan.shock_vars_ ; ix]; + if strcmp(expectation_type, 'perfect_foresight') + plan.shock_perfect_foresight_ = [plan.shock_perfect_foresight_ ; 1]; + else + plan.shock_perfect_foresight_ = [plan.shock_perfect_foresight_ ; 0]; + end +end +plan.shock_date_{length(plan.shock_date_) + 1} = date; +plan.shock_str_date_{length(plan.shock_str_date_) + 1} = strings(date); +plan.shock_int_date_{length(plan.shock_int_date_) + 1} = date - plan.date(1) + 1; +plan.shock_paths_{length(plan.shock_paths_) + 1} = value; diff --git a/matlab/bksup0.m b/matlab/bksup0.m index c304b42a48..82dfaab944 100644 --- a/matlab/bksup0.m +++ b/matlab/bksup0.m @@ -4,7 +4,7 @@ function d = bksup0(c,ny,jcf,iyf,icf,periods) % INPUTS % ny: number of endogenous variables % jcf: variables index forward -% +% % OUTPUTS % d: vector of backsubstitution results % diff --git a/matlab/bksup1.m b/matlab/bksup1.m index a6bcb3b9f3..4a7340976b 100644 --- a/matlab/bksup1.m +++ b/matlab/bksup1.m @@ -5,7 +5,7 @@ function d = bksup1(c,ny,jcf,iyf,periods) % INPUTS % ny: number of endogenous variables % jcf: variables index forward -% +% % OUTPUTS % d: vector of backsubstitution results % @@ -40,4 +40,3 @@ for i = 2:periods end d = c(:,jcf) ; - diff --git a/matlab/bksupk.m b/matlab/bksupk.m index 33f9c18b00..c33f0a551d 100644 --- a/matlab/bksupk.m +++ b/matlab/bksupk.m @@ -68,7 +68,7 @@ while i <= options_.periods c = fread(fid,[jcf,ny],'float64')' ; d1(ir) = c(:,jcf)-c(:,icf)*d1(irf) ; - ir = ir-ny ; + ir = ir-ny ; irf = irf-ny ; i = i+1; end diff --git a/matlab/bseastr.m b/matlab/bseastr.m index 2ab688e0b8..7222e2a7bc 100644 --- a/matlab/bseastr.m +++ b/matlab/bseastr.m @@ -33,16 +33,15 @@ for im = 1:m for i = 1:min(length(key),length(temp)) if temp(i) > key(i) h = mid - 1 ; - break + break else l = mid + 1 ; - break + break end end else x(im) = mid ; - break + break end end end - diff --git a/matlab/bvar_density.m b/matlab/bvar_density.m index b147834ed6..53eebebd1d 100644 --- a/matlab/bvar_density.m +++ b/matlab/bvar_density.m @@ -37,16 +37,16 @@ for nlags = 1:maxnlags [ny, nx, posterior, prior] = bvar_toolbox(nlags); oo_.bvar.posterior{nlags}=posterior; oo_.bvar.prior{nlags}=prior; - + 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); - + oo_.bvar.log_marginal_data_density(nlags)=log_dnsty; - + skipline() fprintf('The marginal log density of the BVAR(%g) model is equal to %10.4f\n', ... nlags, log_dnsty); @@ -61,7 +61,7 @@ function w = matrictint(S, df, XXi) % S: parameter of inverse-Wishart distribution % df: number of degrees of freedom of inverse-Wishart distribution % XXi: first component of VCV matrix of matrix-normal distribution -% +% % Computes the integral over (Phi, Sigma) of: % % det(Sigma)^(-k/2)*exp(-0.5*Tr((Phi-PhiHat)'*(XXi)^(-1)*(Phi-PhiHat)*Sigma^(-1)))* diff --git a/matlab/bvar_forecast.m b/matlab/bvar_forecast.m index d070884b4b..55fdf9ce95 100644 --- a/matlab/bvar_forecast.m +++ b/matlab/bvar_forecast.m @@ -54,7 +54,7 @@ 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 @@ -62,15 +62,15 @@ while d <= options_.bvar_replic 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,:)'; + 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 @@ -80,7 +80,7 @@ while d <= options_.bvar_replic lags_data(end,:) = y; sims_no_shock(t, :, d) = y; end - + % With shocks lags_data = forecast_data.initval; for t = 1:options_.forecast @@ -120,9 +120,9 @@ dyn_graph=dynare_graph_init(sprintf('BVAR forecasts (nlags = %d)', nlags), ny, { for i = 1:ny dyn_graph=dynare_graph(dyn_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}); + 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 dyn_saveas(dyn_graph.fh,[OutputDirectoryName '/' M_.fname '_BVAR_forecast_',num2str(nlags)],options_.nodisplay,options_.graph_format) @@ -130,9 +130,9 @@ dyn_saveas(dyn_graph.fh,[OutputDirectoryName '/' M_.fname '_BVAR_forecast_',num2 % Compute RMSE 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, :) ]; @@ -141,14 +141,14 @@ if ~isempty(forecast_data.realized_val) lags_data(end,:) = y; sq_err_cumul = sq_err_cumul + (y - forecast_data.realized_val(t, :)) .^ 2; end - + rmse = sqrt(sq_err_cumul / size(forecast_data.realized_val, 1)); - + fprintf('RMSE of BVAR(%d):\n', nlags); - + for i = 1:length(options_.varobs) fprintf('%s: %10.4f\n', options_.varobs{i}, rmse(i)); - end + end end % Store results diff --git a/matlab/bvar_irf.m b/matlab/bvar_irf.m index c3f6dfc7ab..408eb55443 100644 --- a/matlab/bvar_irf.m +++ b/matlab/bvar_irf.m @@ -54,7 +54,7 @@ p = 0; sampled_irfs = NaN(ny, ny, options_.irf, options_.bvar_replic); 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); @@ -62,10 +62,10 @@ for draw=1: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); - + % Form the companion matrix. - Companion_matrix(1:ny,:) = transpose(Phi(1:ny*nlags,:)); - + 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))); @@ -78,7 +78,7 @@ for draw=1:options_.bvar_replic elseif strcmpi(identification,'SquareRoot') StructuralMat = sqrtm(Sigma); end - + % Build the IRFs... lags_data = zeros(ny,ny*nlags) ; sampled_irfs(:,:,1,draw) = Sigma_lower_chol ; @@ -88,7 +88,7 @@ for draw=1:options_.bvar_replic lags_data(:,ny+1:end) = lags_data(:,1:end-ny) ; lags_data(:,1:ny) = sampled_irfs(:,:,t,draw) ; end - + end if p > 0 @@ -106,7 +106,7 @@ sort_idx = round((0.5 + [-options_.bvar.conf_sig, options_.bvar.conf_sig, .0]/2) 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)); +posterior_median_irfs = sorted_irfs(:,:,:,sort_idx(3)); number_of_columns = fix(sqrt(ny)); number_of_rows = ceil(ny / number_of_columns) ; diff --git a/matlab/bvar_toolbox.m b/matlab/bvar_toolbox.m index 76c95ef9de..67d505f001 100644 --- a/matlab/bvar_toolbox.m +++ b/matlab/bvar_toolbox.m @@ -29,7 +29,7 @@ function [ny, nx, posterior, prior, forecast_data] = bvar_toolbox(nlags) % forecasting, of size options_.forecast*nx (actually only % contains "1" values for the constant term if nx ~= 0) % - realized_val: only non-empty if options_.nobs doesn't point -% to the end of sample +% to the end of sample % In that case, contains values of endogenous variables after % options_.nobs and up to the end of the sample % - realized_xdata: contains values of exogenous variables after @@ -67,7 +67,7 @@ options_ = set_default_option(options_, 'nobs', size(dataset,1)-options_.first_o if (options_.first_obs+options_.nobs-1)> size(dataset,1) fprintf('Incorrect or missing specification of the number of observations. nobs can be at most %4u\n',size(dataset,1)-options_.first_obs+1); - error('Inconsistent number of observations.') + error('Inconsistent number of observations.') end % Parameters for prior @@ -160,7 +160,7 @@ function [ydum,xdum,breaks]=varprior(nv,nx,lags,mnprior,vprior) %function [ydum,xdum,breaks]=varprior(nv,nx,lags,mnprior,vprior) % ydum, xdum: dummy observation data that implement the prior % breaks: vector of points in the dummy data after which new dummy obs's start -% Set breaks=T+[0;breaks], ydata=[ydata;ydum], xdum=[xdata;xdum], where +% Set breaks=T+[0;breaks], ydata=[ydata;ydum], xdum=[xdata;xdum], where % actual data matrix has T rows, in preparing input for rfvar3 % nv,nx,lags: VAR dimensions % mnprior.tight:Overall tightness of Minnesota prior @@ -175,8 +175,8 @@ function [ydum,xdum,breaks]=varprior(nv,nx,lags,mnprior,vprior) % taken to include the sum-of-coefficients and co-persistence components % that are implemented directly in rfvar3.m. The diagonal prior on v, combined % with sum-of-coefficients and co-persistence components and with the unit own-first-lag -% prior mean generates larger prior variances for own than for cross-effects even in -% this formulation, but here there is no way to shrink toward a set of unconstrained +% prior mean generates larger prior variances for own than for cross-effects even in +% this formulation, but here there is no way to shrink toward a set of unconstrained % univariate AR's. % Original file downloaded from: @@ -228,9 +228,9 @@ function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu) % discontinuities in the data (e.g. war years) and for the possibility of % adding dummy observations to implement a prior. This must be a column vector. % Note that a single dummy observation becomes lags+1 rows of the data matrix, -% with a break separating it from the rest of the data. The function treats the +% with a break separating it from the rest of the data. The function treats the % first lags observations at the top and after each "break" in ydata and xdata as -% initial conditions. +% initial conditions. % lambda: weight on "co-persistence" prior dummy observations. This expresses % belief that when data on *all* y's are stable at their initial levels, they will % tend to persist at that level. lambda=5 is a reasonable first try. With lambda<0, @@ -243,7 +243,7 @@ function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu) % one of these for each variable. A reasonable first guess is mu=2. % The program assumes that the first lags rows of ydata and xdata are real data, not dummies. % Dummy observations should go at the end, if any. If pre-sample x's are not available, -% repeating the initial xdata(lags+1,:) row or copying xdata(lags+1:2*lags,:) into +% repeating the initial xdata(lags+1,:) row or copying xdata(lags+1:2*lags,:) into % xdata(1:lags,:) are reasonable subsititutes. These values are used in forming the % persistence priors. @@ -280,7 +280,7 @@ for is = 1:length(smpl) end X = [X(:,:) xdata(smpl,:)]; y = ydata(smpl,:); -% Everything now set up with input data for y=Xb+e +% Everything now set up with input data for y=Xb+e % Add persistence dummies if lambda ~= 0 || mu > 0 diff --git a/matlab/cartesian_product_of_sets.m b/matlab/cartesian_product_of_sets.m index 8901886ff4..7362ba671f 100644 --- a/matlab/cartesian_product_of_sets.m +++ b/matlab/cartesian_product_of_sets.m @@ -5,7 +5,7 @@ function cprod = cartesian_product_of_sets(varargin) %! @deftypefn {Function File} {@var{cprod} =} cartesian_product_of_sets (@var{a},@var{b}, ...) %! @anchor{cartesian_product_of_sets} %! @sp 1 -%! Computes A_1 * A_2 * .... * A_n with a generic set A_i = {e_1,e_2,e_3,...} where e_i is a string +%! Computes A_1 * A_2 * .... * A_n with a generic set A_i = {e_1,e_2,e_3,...} where e_i is a string %! or a number. It is assumed that each element e_i is unique in set A_i. %! @sp 2 %! @strong{Inputs} diff --git a/matlab/cellofchar2mfile.m b/matlab/cellofchar2mfile.m index 6cfce7c5fc..206a6bbcea 100644 --- a/matlab/cellofchar2mfile.m +++ b/matlab/cellofchar2mfile.m @@ -2,11 +2,11 @@ function cellofchar2mfile(fname, c, cname) % Write a cell of char in a matlab script. % -% INPUTS +% INPUTS % - fname [string] name of the file where c is to be saved. % - c [cell] a two dimensional cell of char. % -% OUTPUTS +% OUTPUTS % None. % Copyright (C) 2015 Dynare Team diff --git a/matlab/check_for_calibrated_covariances.m b/matlab/check_for_calibrated_covariances.m index b6d960c2b6..ecc5d85fe3 100644 --- a/matlab/check_for_calibrated_covariances.m +++ b/matlab/check_for_calibrated_covariances.m @@ -42,7 +42,7 @@ calibrated_covariance_pos=covariance_pos(~ismember(covariance_pos,correlation_po if any(calibrated_covariance_pos) [rows, columns]=ind2sub(size(M.Sigma_e),calibrated_covariance_pos); %find linear indices of lower triangular covariance entries estim_params.calibrated_covariances.position=[calibrated_covariance_pos;sub2ind(size(M.Sigma_e),columns,rows)]; %get linear entries of upper triangular parts - estim_params.calibrated_covariances.cov_value=Sigma_e_calibrated(estim_params.calibrated_covariances.position); + estim_params.calibrated_covariances.cov_value=Sigma_e_calibrated(estim_params.calibrated_covariances.position); end correlation_pos_ME=find(tril(M.Correlation_matrix_ME,-1)); %off-diagonal elements set by correlations after accounting for estimation @@ -50,6 +50,5 @@ calibrated_covariance_pos_ME=covariance_pos_ME(~ismember(covariance_pos_ME,corre if any(calibrated_covariance_pos_ME) [rows, columns]=ind2sub(size(M.H),calibrated_covariance_pos_ME); %find linear indices of lower triangular covariance entries estim_params.calibrated_covariances_ME.position=[calibrated_covariance_pos_ME;sub2ind(size(M.H),columns,rows)]; %get linear entries of upper triangular parts - estim_params.calibrated_covariances_ME.cov_value=H_calibrated(estim_params.calibrated_covariances_ME.position); + estim_params.calibrated_covariances_ME.cov_value=H_calibrated(estim_params.calibrated_covariances_ME.position); end - diff --git a/matlab/check_list_of_variables.m b/matlab/check_list_of_variables.m index be821719f0..7bf05e4783 100644 --- a/matlab/check_list_of_variables.m +++ b/matlab/check_list_of_variables.m @@ -1,17 +1,17 @@ function varlist = check_list_of_variables(options_, M_, varlist) % This function defines, if necessary, the list of endogenous variables -% for which the posterior statistics have to be computed. -% +% for which the posterior statistics have to be computed. % -% INPUTS +% +% INPUTS % % options_ [structure] Dynare structure. % M_ [structure] Dynare structure (related to model definition). % varlist [string] Array of strings with name of the endogenous variables. -% -% OUTPUTS -% varlist [string] -% +% +% OUTPUTS +% varlist [string] +% % SPECIAL REQUIREMENTS % Copyright (C) 2003-2017 Dynare Team @@ -63,7 +63,7 @@ if ~isempty(varlist) && ~isempty(options_.endo_vars_for_moment_computations_in_e error('You cannot use the consider_all_endogenous or consider_all_observed options when listing variables after the estimation command') elseif isempty(varlist) && ~isempty(options_.endo_vars_for_moment_computations_in_estimation) if strcmp(options_.endo_vars_for_moment_computations_in_estimation,'all_endogenous_variables') - varlist = M_.endo_names(1:M_.orig_endo_nbr, :); + varlist = M_.endo_names(1:M_.orig_endo_nbr, :); elseif strcmp(options_.endo_vars_for_moment_computations_in_estimation,'only_observed_variables') varlist = char(options_.varobs'); else @@ -106,7 +106,7 @@ elseif isempty(varlist) && isempty(options_.endo_vars_for_moment_computations_in 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....']; + string = [ string ' of your model, this can be very long....']; format_text(string, 10) if options_.nointeractive % Default behaviour is to consider all the endogenous variables. diff --git a/matlab/check_matlab_path.m b/matlab/check_matlab_path.m index 3817def6be..e98988da12 100644 --- a/matlab/check_matlab_path.m +++ b/matlab/check_matlab_path.m @@ -1,5 +1,5 @@ function check_matlab_path(change_path_flag) - + % Copyright (C) 2015-2016 Dynare Team % % This file is part of Dynare. @@ -82,7 +82,7 @@ else warning(msg); skipline() rmpath(DYNARE_PATH) - addpath(DYNARE_PATH) + addpath(DYNARE_PATH) end warning on backtrace end @@ -90,7 +90,7 @@ else else % Check that the user did not put all the subfolders in the path. % => If DYNARE_PATH/qz is in the path while mjdgges dll is available - % it most likely means that user wrongly put all subfolders in the + % it most likely means that user wrongly put all subfolders in the % matlab's path! mexpath = add_path_to_mex_files([DYNARE_PATH filesep], false); MATLAB_PATH = path2cell(MATLAB_PATH); @@ -107,40 +107,40 @@ else end function q = path2cell(p) - % Converts the output of path() to a cell - s = strfind(p,pathsep); - n = length(s)+1; - q = cell(n,1); - q(1) = {p(1:s(1)-1)}; - q(n) = {p(s(end)+1:end)}; - for i=2:n-1 - q(i) = {p(s(i-1)+1:s(i)-1)}; - end - +% Converts the output of path() to a cell +s = strfind(p,pathsep); +n = length(s)+1; +q = cell(n,1); +q(1) = {p(1:s(1)-1)}; +q(n) = {p(s(end)+1:end)}; +for i=2:n-1 + q(i) = {p(s(i-1)+1:s(i)-1)}; +end + function flist = getallroutinenames(p, excludedsubfolders) - if nargin<2 - excludedsubfolders = {}; - end - flist={}; - %get m-files in this directory - dd = dir([p,filesep '*.m']); - temp=struct2cell(dd); - flist=[flist temp(1,:)]; - %deal with subdirectories - dlist=getalldirectories(p,excludedsubfolders); %first call with excluded directories - for ii=1:length(dlist) - flist=[flist getallroutinenames([ p filesep dlist{ii}])]; %recursive calls without subfolders - end - +if nargin<2 + excludedsubfolders = {}; +end +flist={}; +%get m-files in this directory +dd = dir([p,filesep '*.m']); +temp=struct2cell(dd); +flist=[flist temp(1,:)]; +%deal with subdirectories +dlist=getalldirectories(p,excludedsubfolders); %first call with excluded directories +for ii=1:length(dlist) + flist=[flist getallroutinenames([ p filesep dlist{ii}])]; %recursive calls without subfolders +end + function dlist = getalldirectories(p,excluded_directories) - if nargin<2 - excluded_directories = {}; - end - dd = dir(p); - dir_result=struct2cell(dd); - directory_indicator=cell2mat(dir_result(4,:)); - dlist = dir_result(1,directory_indicator==1 & ~strcmp('.',dir_result(1,:)) & ~strcmp('..',dir_result(1,:)) & ~ismember(dir_result(1,:),excluded_directories)); +if nargin<2 + excluded_directories = {}; +end +dd = dir(p); +dir_result=struct2cell(dd); +directory_indicator=cell2mat(dir_result(4,:)); +dlist = dir_result(1,directory_indicator==1 & ~strcmp('.',dir_result(1,:)) & ~strcmp('..',dir_result(1,:)) & ~ismember(dir_result(1,:),excluded_directories)); function n = position(i, currentpath) - n = length(strfind(currentpath(1:i), pathsep)); \ No newline at end of file +n = length(strfind(currentpath(1:i), pathsep)); \ No newline at end of file diff --git a/matlab/check_posterior_analysis_data.m b/matlab/check_posterior_analysis_data.m index b1d25b3d13..2e8ac01010 100644 --- a/matlab/check_posterior_analysis_data.m +++ b/matlab/check_posterior_analysis_data.m @@ -1,13 +1,13 @@ function [info,description] = check_posterior_analysis_data(type,M_) % function [info,description] = check_posterior_analysis_data(type,M_) -% Checks the status of posterior analysis and in particular if files need to be +% Checks the status of posterior analysis and in particular if files need to be % created or updated; called by posterior_analysis.m -% +% % Inputs: % type [string] name of the posterior moment considered % M_ [structure] Dynare model structure -% -% Outputs: +% +% Outputs: % info [scalar] return code % info = 1; % select_posterior_draws has to be called first. % info = 2; % _posterior_draws files have to be updated. @@ -99,7 +99,7 @@ else number_of_the_last_post_data_file = length(pdfinfo); name_of_the_last_post_data_file = ... [ pwd filesep MetropolisFolder filesep ... - M_.fname '_' ... + M_.fname '_' ... generic_post_data_file_name ... int2str(number_of_the_last_post_data_file) ... '.mat' ]; @@ -108,7 +108,7 @@ else info = 5; % posterior data files have to be updated. if nargout>1 description = 'posterior data files have to be updated.'; - end + end else info = 6; % Ok (nothing to do ;-) if nargout>1 diff --git a/matlab/check_posterior_sampler_options.m b/matlab/check_posterior_sampler_options.m index cb555ea1a1..4683639f3a 100644 --- a/matlab/check_posterior_sampler_options.m +++ b/matlab/check_posterior_sampler_options.m @@ -40,339 +40,339 @@ if init % set default options and user defined options posterior_sampler_options.posterior_sampling_method = options_.posterior_sampler_options.posterior_sampling_method; posterior_sampler_options.bounds = bounds; - + switch posterior_sampler_options.posterior_sampling_method - - case 'random_walk_metropolis_hastings' - posterior_sampler_options.parallel_bar_refresh_rate=50; - posterior_sampler_options.serial_bar_refresh_rate=3; - posterior_sampler_options.parallel_bar_title='RWMH'; - posterior_sampler_options.serial_bar_title='RW Metropolis-Hastings'; - - % default options - posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.rwmh); - - % user defined options - if ~isempty(options_.posterior_sampler_options.sampling_opt) - options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt); - for i=1:rows(options_list) - switch options_list{i,1} - - case 'proposal_distribution' - if ~(strcmpi(options_list{i,2}, 'rand_multivariate_student') || ... - strcmpi(options_list{i,2}, 'rand_multivariate_normal')) - error(['initial_estimation_checks:: the proposal_distribution option to estimation takes either ' ... - 'rand_multivariate_student or rand_multivariate_normal as options']); - else - posterior_sampler_options.proposal_distribution=options_list{i,2}; - end - - - case 'student_degrees_of_freedom' - if options_list{i,2} <= 0 - error('initial_estimation_checks:: the student_degrees_of_freedom takes a positive integer argument'); - else - posterior_sampler_options.student_degrees_of_freedom=options_list{i,2}; - end - - case 'use_mh_covariance_matrix' - % indicates to use the covariance matrix from previous iterations to - % define the covariance of the proposal distribution - % default = 0 - posterior_sampler_options.use_mh_covariance_matrix = options_list{i,2}; - options_.use_mh_covariance_matrix = options_list{i,2}; - case 'scale_file' - % load optimal_mh_scale parameter if previous run was with mode_compute=6 - % will overwrite jscale from set_prior.m - if exist(options_list{i,2},'file') || exist([options_list{i,2},'.mat'],'file') - tmp = load(options_list{i,2},'Scale'); - global bayestopt_ - bayestopt_.mh_jscale = tmp.Scale; - options_.mh_jscale = tmp.Scale; - bayestopt_.jscale = ones(size(bounds.lb,1),1)*tmp.Scale; -% options_.mh_init_scale = 2*options_.mh_jscale; - else - error('initial_estimation_checks:: The specified mh_scale_file does not exist.') - end - case 'save_tmp_file' - posterior_sampler_options.save_tmp_file = options_list{i,2}; - otherwise - warning(['rwmh_sampler: Unknown option (' options_list{i,1} ')!']) + + case 'random_walk_metropolis_hastings' + posterior_sampler_options.parallel_bar_refresh_rate=50; + posterior_sampler_options.serial_bar_refresh_rate=3; + posterior_sampler_options.parallel_bar_title='RWMH'; + posterior_sampler_options.serial_bar_title='RW Metropolis-Hastings'; + + % default options + posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.rwmh); + + % user defined options + if ~isempty(options_.posterior_sampler_options.sampling_opt) + options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt); + for i=1:rows(options_list) + switch options_list{i,1} + + case 'proposal_distribution' + if ~(strcmpi(options_list{i,2}, 'rand_multivariate_student') || ... + strcmpi(options_list{i,2}, 'rand_multivariate_normal')) + error(['initial_estimation_checks:: the proposal_distribution option to estimation takes either ' ... + 'rand_multivariate_student or rand_multivariate_normal as options']); + else + posterior_sampler_options.proposal_distribution=options_list{i,2}; + end + + + case 'student_degrees_of_freedom' + if options_list{i,2} <= 0 + error('initial_estimation_checks:: the student_degrees_of_freedom takes a positive integer argument'); + else + posterior_sampler_options.student_degrees_of_freedom=options_list{i,2}; + end + + case 'use_mh_covariance_matrix' + % indicates to use the covariance matrix from previous iterations to + % define the covariance of the proposal distribution + % default = 0 + posterior_sampler_options.use_mh_covariance_matrix = options_list{i,2}; + options_.use_mh_covariance_matrix = options_list{i,2}; + case 'scale_file' + % load optimal_mh_scale parameter if previous run was with mode_compute=6 + % will overwrite jscale from set_prior.m + if exist(options_list{i,2},'file') || exist([options_list{i,2},'.mat'],'file') + tmp = load(options_list{i,2},'Scale'); + global bayestopt_ + bayestopt_.mh_jscale = tmp.Scale; + options_.mh_jscale = tmp.Scale; + bayestopt_.jscale = ones(size(bounds.lb,1),1)*tmp.Scale; + % options_.mh_init_scale = 2*options_.mh_jscale; + else + error('initial_estimation_checks:: The specified mh_scale_file does not exist.') end + case 'save_tmp_file' + posterior_sampler_options.save_tmp_file = options_list{i,2}; + otherwise + warning(['rwmh_sampler: Unknown option (' options_list{i,1} ')!']) end end - - case 'tailored_random_block_metropolis_hastings' - posterior_sampler_options.parallel_bar_refresh_rate=5; - posterior_sampler_options.serial_bar_refresh_rate=1; - posterior_sampler_options.parallel_bar_title='TaRB-MH'; - posterior_sampler_options.serial_bar_title='TaRB Metropolis-Hastings'; - - % default options - posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.tarb); - - % user defined options - if ~isempty(options_.posterior_sampler_options.sampling_opt) - options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt); - for i=1:rows(options_list) - - switch options_list{i,1} - - case 'proposal_distribution' - if ~(strcmpi(options_list{i,2}, 'rand_multivariate_student') || ... - strcmpi(options_list{i,2}, 'rand_multivariate_normal')) - error(['initial_estimation_checks:: the proposal_distribution option to estimation takes either ' ... - 'rand_multivariate_student or rand_multivariate_normal as options']); - else - posterior_sampler_options.proposal_distribution=options_list{i,2}; - end - - - case 'student_degrees_of_freedom' - if options_list{i,2} <= 0 - error('initial_estimation_checks:: the student_degrees_of_freedom takes a positive integer argument'); - else - posterior_sampler_options.student_degrees_of_freedom=options_list{i,2}; - end - - case 'mode_compute' - posterior_sampler_options.mode_compute=options_list{i,2}; - - case 'optim' - posterior_sampler_options.optim_opt=options_list{i,2}; - - case 'new_block_probability' - if options_list{i,2}<0 || options_list{i,2}>1 - error('check_posterior_sampler_options:: The tarb new_block_probability must be between 0 and 1!') - else - posterior_sampler_options.new_block_probability=options_list{i,2}; - end - case 'scale_file' - % load optimal_mh_scale parameter if previous run was with mode_compute=6 - % will overwrite jscale from set_prior.m - if exist(options_list{i,2},'file') || exist([options_list{i,2},'.mat'],'file') - tmp = load(options_list{i,2},'Scale'); - global bayestopt_ - bayestopt_.mh_jscale = tmp.Scale; - options_.mh_jscale = tmp.Scale; - bayestopt_.jscale = ones(size(bounds.lb,1),1)*tmp.Scale; -% options_.mh_init_scale = 2*options_.mh_jscale; - else - error('initial_estimation_checks:: The specified scale_file does not exist.') - end - case 'save_tmp_file' - posterior_sampler_options.save_tmp_file = options_list{i,2}; - - otherwise - warning(['tarb_sampler: Unknown option (' options_list{i,1} ')!']) - + end + + case 'tailored_random_block_metropolis_hastings' + posterior_sampler_options.parallel_bar_refresh_rate=5; + posterior_sampler_options.serial_bar_refresh_rate=1; + posterior_sampler_options.parallel_bar_title='TaRB-MH'; + posterior_sampler_options.serial_bar_title='TaRB Metropolis-Hastings'; + + % default options + posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.tarb); + + % user defined options + if ~isempty(options_.posterior_sampler_options.sampling_opt) + options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt); + for i=1:rows(options_list) + + switch options_list{i,1} + + case 'proposal_distribution' + if ~(strcmpi(options_list{i,2}, 'rand_multivariate_student') || ... + strcmpi(options_list{i,2}, 'rand_multivariate_normal')) + error(['initial_estimation_checks:: the proposal_distribution option to estimation takes either ' ... + 'rand_multivariate_student or rand_multivariate_normal as options']); + else + posterior_sampler_options.proposal_distribution=options_list{i,2}; end - + + + case 'student_degrees_of_freedom' + if options_list{i,2} <= 0 + error('initial_estimation_checks:: the student_degrees_of_freedom takes a positive integer argument'); + else + posterior_sampler_options.student_degrees_of_freedom=options_list{i,2}; + end + + case 'mode_compute' + posterior_sampler_options.mode_compute=options_list{i,2}; + + case 'optim' + posterior_sampler_options.optim_opt=options_list{i,2}; + + case 'new_block_probability' + if options_list{i,2}<0 || options_list{i,2}>1 + error('check_posterior_sampler_options:: The tarb new_block_probability must be between 0 and 1!') + else + posterior_sampler_options.new_block_probability=options_list{i,2}; + end + case 'scale_file' + % load optimal_mh_scale parameter if previous run was with mode_compute=6 + % will overwrite jscale from set_prior.m + if exist(options_list{i,2},'file') || exist([options_list{i,2},'.mat'],'file') + tmp = load(options_list{i,2},'Scale'); + global bayestopt_ + bayestopt_.mh_jscale = tmp.Scale; + options_.mh_jscale = tmp.Scale; + bayestopt_.jscale = ones(size(bounds.lb,1),1)*tmp.Scale; + % options_.mh_init_scale = 2*options_.mh_jscale; + else + error('initial_estimation_checks:: The specified scale_file does not exist.') + end + case 'save_tmp_file' + posterior_sampler_options.save_tmp_file = options_list{i,2}; + + otherwise + warning(['tarb_sampler: Unknown option (' options_list{i,1} ')!']) + end - + end - - case 'independent_metropolis_hastings' - posterior_sampler_options.parallel_bar_refresh_rate=50; - posterior_sampler_options.serial_bar_refresh_rate=3; - posterior_sampler_options.parallel_bar_title='IMH'; - posterior_sampler_options.serial_bar_title='Ind. Metropolis-Hastings'; - - % default options - posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.imh); - - % user defined options - if ~isempty(options_.posterior_sampler_options.sampling_opt) - options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt); - for i=1:rows(options_list) - switch options_list{i,1} - - case 'proposal_distribution' - if ~(strcmpi(options_list{i,2}, 'rand_multivariate_student') || ... - strcmpi(options_list{i,2}, 'rand_multivariate_normal')) - error(['initial_estimation_checks:: the proposal_distribution option to estimation takes either ' ... - 'rand_multivariate_student or rand_multivariate_normal as options']); - else - posterior_sampler_options.proposal_distribution=options_list{i,2}; - end - - - case 'student_degrees_of_freedom' - if options_list{i,2} <= 0 - error('initial_estimation_checks:: the student_degrees_of_freedom takes a positive integer argument'); - else - posterior_sampler_options.student_degrees_of_freedom=options_list{i,2}; - end - - case 'use_mh_covariance_matrix' - % indicates to use the covariance matrix from previous iterations to - % define the covariance of the proposal distribution - % default = 0 - posterior_sampler_options.use_mh_covariance_matrix = options_list{i,2}; - options_.use_mh_covariance_matrix = options_list{i,2}; - - case 'save_tmp_file' - posterior_sampler_options.save_tmp_file = options_list{i,2}; - - otherwise - warning(['imh_sampler: Unknown option (' options_list{i,1} ')!']) + + end + + case 'independent_metropolis_hastings' + posterior_sampler_options.parallel_bar_refresh_rate=50; + posterior_sampler_options.serial_bar_refresh_rate=3; + posterior_sampler_options.parallel_bar_title='IMH'; + posterior_sampler_options.serial_bar_title='Ind. Metropolis-Hastings'; + + % default options + posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.imh); + + % user defined options + if ~isempty(options_.posterior_sampler_options.sampling_opt) + options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt); + for i=1:rows(options_list) + switch options_list{i,1} + + case 'proposal_distribution' + if ~(strcmpi(options_list{i,2}, 'rand_multivariate_student') || ... + strcmpi(options_list{i,2}, 'rand_multivariate_normal')) + error(['initial_estimation_checks:: the proposal_distribution option to estimation takes either ' ... + 'rand_multivariate_student or rand_multivariate_normal as options']); + else + posterior_sampler_options.proposal_distribution=options_list{i,2}; end + + + case 'student_degrees_of_freedom' + if options_list{i,2} <= 0 + error('initial_estimation_checks:: the student_degrees_of_freedom takes a positive integer argument'); + else + posterior_sampler_options.student_degrees_of_freedom=options_list{i,2}; + end + + case 'use_mh_covariance_matrix' + % indicates to use the covariance matrix from previous iterations to + % define the covariance of the proposal distribution + % default = 0 + posterior_sampler_options.use_mh_covariance_matrix = options_list{i,2}; + options_.use_mh_covariance_matrix = options_list{i,2}; + + case 'save_tmp_file' + posterior_sampler_options.save_tmp_file = options_list{i,2}; + + otherwise + warning(['imh_sampler: Unknown option (' options_list{i,1} ')!']) end end - - - case 'slice' - posterior_sampler_options.parallel_bar_refresh_rate=1; - posterior_sampler_options.serial_bar_refresh_rate=1; - posterior_sampler_options.parallel_bar_title='SLICE'; - posterior_sampler_options.serial_bar_title='SLICE'; - - % default options - posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.slice); - - % user defined options - if ~isempty(options_.posterior_sampler_options.sampling_opt) - options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt); - for i=1:rows(options_list) - switch options_list{i,1} - case 'rotated' - % triggers rotated slice iterations using a covariance - % matrix from initial burn-in iterations - % must be associated with: - % <use_mh_covariance_matrix> or <slice_initialize_with_mode> - % default = 0 - posterior_sampler_options.rotated = options_list{i,2}; - - case 'mode' - % for multimodal posteriors, provide the list of modes as a - % matrix, ordered by column, i.e. [x1 x2 x3] for three - % modes x1 x2 x3 - % MR note: not sure this is possible with the - % read_key_value_string ??? - % if this is not possible <mode_files> does to job in any case - % This will automatically trigger <rotated> - % default = [] - tmp_mode = options_list{i,2}; - for j=1:size(tmp_mode,2) - posterior_sampler_options.mode(j).m = tmp_mode(:,j); - end - - case 'mode_files' - % for multimodal posteriors provide the name of - % a file containing a variable array xparams = [nparam * nmodes] - % one column per mode. With this info, the code will automatically - % set the <mode> option. - % This will automatically trigger <rotated> - % default = [] - posterior_sampler_options.mode_files = options_list{i,2}; - - case 'slice_initialize_with_mode' - % the default for slice is to set mode_compute = 0 in the - % preprocessor and start the chain(s) from a random location in the prior. - % This option first runs the optimizer and then starts the - % chain from the mode. Associated with optios <rotated>, it will - % use invhess from the mode to perform rotated slice - % iterations. - % default = 0 - posterior_sampler_options.slice_initialize_with_mode = options_list{i,2}; - - case 'initial_step_size' - % sets the initial size of the interval in the STEPPING-OUT PROCEDURE - % the initial_step_size must be a real number in [0, 1], - % and it sets the size as a proportion of the prior bounds, - % i.e. the size will be initial_step_size*(UB-LB) - % slice sampler requires prior_truncation > 0! - % default = 0.8 - if options_list{i,2}<=0 || options_list{i,2}>=1 - error('check_posterior_sampler_options:: slice initial_step_size must be between 0 and 1') - else - posterior_sampler_options.initial_step_size=options_list{i,2}; - end - case 'use_mh_covariance_matrix' - % in association with <rotated> indicates to use the - % covariance matrix from previous iterations to define the - % rotated slice - % default = 0 - posterior_sampler_options.use_mh_covariance_matrix = options_list{i,2}; - options_.use_mh_covariance_matrix = options_list{i,2}; - - case 'save_tmp_file' - posterior_sampler_options.save_tmp_file = options_list{i,2}; - - otherwise - warning(['slice_sampler: Unknown option (' options_list{i,1} ')!']) + end + + + case 'slice' + posterior_sampler_options.parallel_bar_refresh_rate=1; + posterior_sampler_options.serial_bar_refresh_rate=1; + posterior_sampler_options.parallel_bar_title='SLICE'; + posterior_sampler_options.serial_bar_title='SLICE'; + + % default options + posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.slice); + + % user defined options + if ~isempty(options_.posterior_sampler_options.sampling_opt) + options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt); + for i=1:rows(options_list) + switch options_list{i,1} + case 'rotated' + % triggers rotated slice iterations using a covariance + % matrix from initial burn-in iterations + % must be associated with: + % <use_mh_covariance_matrix> or <slice_initialize_with_mode> + % default = 0 + posterior_sampler_options.rotated = options_list{i,2}; + + case 'mode' + % for multimodal posteriors, provide the list of modes as a + % matrix, ordered by column, i.e. [x1 x2 x3] for three + % modes x1 x2 x3 + % MR note: not sure this is possible with the + % read_key_value_string ??? + % if this is not possible <mode_files> does to job in any case + % This will automatically trigger <rotated> + % default = [] + tmp_mode = options_list{i,2}; + for j=1:size(tmp_mode,2) + posterior_sampler_options.mode(j).m = tmp_mode(:,j); + end + + case 'mode_files' + % for multimodal posteriors provide the name of + % a file containing a variable array xparams = [nparam * nmodes] + % one column per mode. With this info, the code will automatically + % set the <mode> option. + % This will automatically trigger <rotated> + % default = [] + posterior_sampler_options.mode_files = options_list{i,2}; + + case 'slice_initialize_with_mode' + % the default for slice is to set mode_compute = 0 in the + % preprocessor and start the chain(s) from a random location in the prior. + % This option first runs the optimizer and then starts the + % chain from the mode. Associated with optios <rotated>, it will + % use invhess from the mode to perform rotated slice + % iterations. + % default = 0 + posterior_sampler_options.slice_initialize_with_mode = options_list{i,2}; + + case 'initial_step_size' + % sets the initial size of the interval in the STEPPING-OUT PROCEDURE + % the initial_step_size must be a real number in [0, 1], + % and it sets the size as a proportion of the prior bounds, + % i.e. the size will be initial_step_size*(UB-LB) + % slice sampler requires prior_truncation > 0! + % default = 0.8 + if options_list{i,2}<=0 || options_list{i,2}>=1 + error('check_posterior_sampler_options:: slice initial_step_size must be between 0 and 1') + else + posterior_sampler_options.initial_step_size=options_list{i,2}; end + case 'use_mh_covariance_matrix' + % in association with <rotated> indicates to use the + % covariance matrix from previous iterations to define the + % rotated slice + % default = 0 + posterior_sampler_options.use_mh_covariance_matrix = options_list{i,2}; + options_.use_mh_covariance_matrix = options_list{i,2}; + + case 'save_tmp_file' + posterior_sampler_options.save_tmp_file = options_list{i,2}; + + otherwise + warning(['slice_sampler: Unknown option (' options_list{i,1} ')!']) end end - - % slice posterior sampler does not require mode or hessian to run - % needs to be set to 1 to skip parts in dynare_estimation_1.m - % requiring posterior maximization/calibrated smoother before MCMC - options_.mh_posterior_mode_estimation=1; - - if ~ posterior_sampler_options.slice_initialize_with_mode + end + + % slice posterior sampler does not require mode or hessian to run + % needs to be set to 1 to skip parts in dynare_estimation_1.m + % requiring posterior maximization/calibrated smoother before MCMC + options_.mh_posterior_mode_estimation=1; + + if ~ posterior_sampler_options.slice_initialize_with_mode % by default, slice sampler should trigger % mode_compute=0 and % mh_replic=100 (much smaller than the default mh_replic=20000 of RWMH) - options_.mode_compute = 0; - options_.cova_compute = 0; - else - if (isequal(options_.mode_compute,0) && isempty(options_.mode_file) ) - skipline() - disp('check_posterior_sampler_options:: You have specified the option "slice_initialize_with_mode"') - disp('check_posterior_sampler_options:: to initialize the slice sampler using mode information') - disp('check_posterior_sampler_options:: but no mode file nor posterior maximization is selected,') - error('check_posterior_sampler_options:: The option "slice_initialize_with_mode" is inconsistent with mode_compute=0 or empty mode_file.') - else - options_.mh_posterior_mode_estimation=0; - end - end - - if any(isinf(bounds.lb)) || any(isinf(bounds.ub)) + options_.mode_compute = 0; + options_.cova_compute = 0; + else + if (isequal(options_.mode_compute,0) && isempty(options_.mode_file) ) skipline() - disp('some priors are unbounded and prior_trunc is set to zero') - error('The option "slice" is inconsistent with prior_trunc=0.') + disp('check_posterior_sampler_options:: You have specified the option "slice_initialize_with_mode"') + disp('check_posterior_sampler_options:: to initialize the slice sampler using mode information') + disp('check_posterior_sampler_options:: but no mode file nor posterior maximization is selected,') + error('check_posterior_sampler_options:: The option "slice_initialize_with_mode" is inconsistent with mode_compute=0 or empty mode_file.') + else + options_.mh_posterior_mode_estimation=0; end - - % moreover slice must be associated to: - % options_.mh_posterior_mode_estimation = 0; - % this is done below, but perhaps preprocessing should do this? - - if ~isempty(posterior_sampler_options.mode) - % multimodal case - posterior_sampler_options.rotated = 1; - posterior_sampler_options.WR=[]; + end + + if any(isinf(bounds.lb)) || any(isinf(bounds.ub)) + skipline() + disp('some priors are unbounded and prior_trunc is set to zero') + error('The option "slice" is inconsistent with prior_trunc=0.') + end + + % moreover slice must be associated to: + % options_.mh_posterior_mode_estimation = 0; + % this is done below, but perhaps preprocessing should do this? + + if ~isempty(posterior_sampler_options.mode) + % multimodal case + posterior_sampler_options.rotated = 1; + posterior_sampler_options.WR=[]; + end + % posterior_sampler_options = set_default_option(posterior_sampler_options,'mode_files',[]); + + + posterior_sampler_options.W1=posterior_sampler_options.initial_step_size*(bounds.ub-bounds.lb); + if options_.load_mh_file + posterior_sampler_options.slice_initialize_with_mode = 0; + else + if ~posterior_sampler_options.slice_initialize_with_mode + posterior_sampler_options.invhess=[]; end - % posterior_sampler_options = set_default_option(posterior_sampler_options,'mode_files',[]); - - - posterior_sampler_options.W1=posterior_sampler_options.initial_step_size*(bounds.ub-bounds.lb); - if options_.load_mh_file - posterior_sampler_options.slice_initialize_with_mode = 0; - else - if ~posterior_sampler_options.slice_initialize_with_mode - posterior_sampler_options.invhess=[]; - end + end + + if ~isempty(posterior_sampler_options.mode_files) % multimodal case + modes = posterior_sampler_options.mode_files; % these can be also mean files from previous parallel slice chains + load(modes, 'xparams') + if size(xparams,2)<2 + error(['check_posterior_sampler_options:: Variable xparams loaded in file <' modes '> has size [' int2str(size(xparams,1)) 'x' int2str(size(xparams,2)) ']: it must contain at least two columns, to allow multi-modal sampling.']) end - - if ~isempty(posterior_sampler_options.mode_files) % multimodal case - modes = posterior_sampler_options.mode_files; % these can be also mean files from previous parallel slice chains - load(modes, 'xparams') - if size(xparams,2)<2 - error(['check_posterior_sampler_options:: Variable xparams loaded in file <' modes '> has size [' int2str(size(xparams,1)) 'x' int2str(size(xparams,2)) ']: it must contain at least two columns, to allow multi-modal sampling.']) - end - for j=1:size(xparams,2) - mode(j).m=xparams(:,j); - end - posterior_sampler_options.mode = mode; - posterior_sampler_options.rotated = 1; - posterior_sampler_options.WR=[]; + for j=1:size(xparams,2) + mode(j).m=xparams(:,j); end - - otherwise - error('check_posterior_sampler_options:: Unknown posterior_sampling_method option %s ',posterior_sampler_options.posterior_sampling_method); + posterior_sampler_options.mode = mode; + posterior_sampler_options.rotated = 1; + posterior_sampler_options.WR=[]; + end + + otherwise + error('check_posterior_sampler_options:: Unknown posterior_sampling_method option %s ',posterior_sampler_options.posterior_sampling_method); end - + return end @@ -434,6 +434,3 @@ fnam = fieldnames(sampler_options); for j=1:length(fnam) posterior_sampler_options.(fnam{j}) = sampler_options.(fnam{j}); end - - - diff --git a/matlab/check_prior_analysis_data.m b/matlab/check_prior_analysis_data.m index 1ad6a252c3..81d11c519e 100644 --- a/matlab/check_prior_analysis_data.m +++ b/matlab/check_prior_analysis_data.m @@ -1,13 +1,13 @@ function [info,description] = check_prior_analysis_data(type,M_) % function [info,description] = check_prior_analysis_data(type,M_) -% Checks the status of prior analysis and in particular if files need to be +% Checks the status of prior analysis and in particular if files need to be % created or updated; called by prior_analysis.m -% +% % Inputs: % type [string] name of the posterior moment considered % M_ [structure] Dynare model structure -% -% Outputs: +% +% Outputs: % info [scalar] return code % info = 1; % prior_sampler has to be called first. % info = 2; % _prior_draws files have to be updated. @@ -40,7 +40,7 @@ if nargout>1 description = ''; end -%% Get informations about prior draws files. +%% 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 @@ -65,7 +65,7 @@ else end return else - info = 3; % Nothing to do! + info = 3; % Nothing to do! if nargout>1 description = 'prior draws files are up to date.'; end @@ -98,9 +98,9 @@ else 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!!! + % 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 diff --git a/matlab/check_prior_bounds.m b/matlab/check_prior_bounds.m index b6bdc6ece5..41a16e790c 100644 --- a/matlab/check_prior_bounds.m +++ b/matlab/check_prior_bounds.m @@ -5,7 +5,7 @@ function check_prior_bounds(xparam1,bounds,M_,estim_params_,options_,bayestopt_) % -xparam1 [double] vector of parameters to be estimated (initial values) % -bounds [vector] vector containing the lower and upper % bounds -% -M_ [structure] characterizing the model. +% -M_ [structure] characterizing the model. % -estim_params_ [structure] characterizing parameters to be estimated % -options_ [structure] characterizing the options % -bayestopt_ [structure] characterizing priors diff --git a/matlab/chol_SE.m b/matlab/chol_SE.m index ae02493f0f..992d88a81d 100644 --- a/matlab/chol_SE.m +++ b/matlab/chol_SE.m @@ -1,17 +1,17 @@ function [R,indef, E, P]=chol_SE(A,pivoting) % [R,indef, E, P]=chol_SE(A,pivoting) -% Performs a (modified) Cholesky factorization of the form -% +% Performs a (modified) Cholesky factorization of the form +% % P'*A*P + E = R'*R -% +% % As detailed in Schnabel/Eskow (1990), the factorization has 2 phases: % Phase 1: While A can still be positive definite, pivot on the maximum diagonal element. % Check that the standard Cholesky update would result in a positive diagonal -% at the current iteration. If so, continue with the normal Cholesky update. -% Otherwise switch to phase 2. -% If A is safely positive definite, stage 1 is never left, resulting in -% the standard Cholesky decomposition. -% +% at the current iteration. If so, continue with the normal Cholesky update. +% Otherwise switch to phase 2. +% If A is safely positive definite, stage 1 is never left, resulting in +% the standard Cholesky decomposition. +% % Phase 2: Pivot on the minimum of the negatives of the lower Gershgorin bound % estimates. To prevent negative diagonals, compute the amount to add to the % pivot element and add this. Then, do the Cholesky update and update the estimates of the @@ -21,18 +21,18 @@ function [R,indef, E, P]=chol_SE(A,pivoting) % - During factorization, L=R' is stored in the lower triangle of the original matrix A, % miminizing the memory requirements % - Conforming with the original Schnabel/Eskow (1990) algorithm: -% - at each iteration the updated Gershgorin bounds are estimated instead of recomputed, +% - at each iteration the updated Gershgorin bounds are estimated instead of recomputed, % reducing the computational requirements from o(n^3) to o (n^2) % - For the last 2 by 2 submatrix, an eigenvalue-based decomposition is used -% - While pivoting is not necessary, it improves the size of E, the add-on on to the diagonal. But this comes at +% - While pivoting is not necessary, it improves the size of E, the add-on on to the diagonal. But this comes at % the cost of introduding a permutation. -% % -% Inputs +% +% Inputs % A [n*n] Matrix to be factorized % pivoting [scalar] dummy whether pivoting is used -% -% Outputs +% +% Outputs % R [n*n] originally stored in lower triangular portion of A, including the main diagonal % % E [n*1] Elements added to the diagonal of A @@ -40,18 +40,18 @@ function [R,indef, E, P]=chol_SE(A,pivoting) % performing the decomposition % % REFERENCES: -% This implementation is based on +% This implementation is based on % % Robert B. Schnabel and Elizabeth Eskow. 1990. "A New Modified Cholesky % Factorization," SIAM Journal of Scientific Statistical Computating, % 11, 6: 1136-58. -% +% % Elizabeth Eskow and Robert B. Schnabel 1991. "Algorithm 695 - Software for a New Modified Cholesky % Factorization," ACM Transactions on Mathematical Software, Vol 17, No 3: 306-312 -% -% +% +% % Author: Johannes Pfeifer based on Eskow/Schnabel (1991) -% +% % Copyright (C) 2015 Johannes Pfeifer % Copyright (C) 2015 Dynare Team % This file is part of Dynare. @@ -148,7 +148,7 @@ for j = 1:n-1 % Swap elements of the permutation vector itemp = P(j); P(j) = P(imaxd); - P(imaxd) = itemp; + P(imaxd) = itemp; end end % check to see whether the normal Cholesky update for this @@ -183,13 +183,13 @@ for j = 1:n-1 g=gersh_nested(A,j,n); end end - + % PHASE 2 if ~phase1 if j ~= n-1 if pivoting % Find the minimum negative Gershgorin bound - [tmp,iming] = min(g(j:n)); + [tmp,iming] = min(g(j:n)); iming=iming+j-1; % Pivot to the top the row and column with the % minimum negative Gershgorin bound @@ -229,9 +229,9 @@ for j = 1:n-1 end % Calculate delta and add to the diagonal. delta=max{0,-A(j,j) + max{normj,taugam},delta_previous} % where normj=sum of |A(i,j)|,for i=1,n, delta_previous is the delta computed at the previous iter and taugam is tau1*gamma. - + normj=sum(abs(A(j+1:n,j))); - + delta = max([0;delta;-A(j,j)+normj;-A(j,j)+taugam]); % get adjustment based on formula on bottom of p. 309 of Eskow/Schnabel (1991) E(j) = delta; @@ -259,9 +259,9 @@ for j = 1:n-1 % Find eigenvalues of final 2 by 2 submatrix % Find delta such that: % 1. the l2 condition number of the final 2X2 submatrix + delta*I <= tau2 - % 2. delta >= previous delta, + % 2. delta >= previous delta, % 3. min(eigvals) + delta >= tau2 * gamma, where min(eigvals) is the smallest eigenvalue of the final 2X2 submatrix - + A(n-1,n)=A(n,n-1); %set value above diagonal for computation of eigenvalues eigvals = eig(A(n-1:n,n-1:n)); delta = max([ 0 ; delta ; -min(eigvals)+tau2*max((max(eigvals)-min(eigvals))/(1-tau1),gammma) ]); %Formula 5.3.2 of Schnabel/Eskow (1990) @@ -272,7 +272,7 @@ for j = 1:n-1 E(n-1) = delta; E(n) = delta; end - + % Final update A(n-1,n-1) = sqrt(A(n-1,n-1)); A(n,n-1) = A(n,n-1)/A(n-1,n-1); @@ -306,4 +306,3 @@ for ii = j:n g(ii) = sum_up_to_i + sum_after_i- A(ii,ii); end end - diff --git a/matlab/clear_persistent_variables.m b/matlab/clear_persistent_variables.m index e2fe5666f6..acc7cd56cb 100644 --- a/matlab/clear_persistent_variables.m +++ b/matlab/clear_persistent_variables.m @@ -58,5 +58,5 @@ if writelistofroutinestobecleared return end -list_of_functions_to_be_cleared; +list_of_functions_to_be_cleared; clear(list_of_functions{:}); \ No newline at end of file diff --git a/matlab/cli/prior.m b/matlab/cli/prior.m index 9e04450664..843d646892 100644 --- a/matlab/cli/prior.m +++ b/matlab/cli/prior.m @@ -42,7 +42,7 @@ if isempty(varargin) || ( isequal(length(varargin), 1) && isequal(varargin{1},'h return end -global options_ M_ estim_params_ bayestopt_ oo_ +global options_ M_ estim_params_ bayestopt_ oo_ donesomething = false; @@ -53,11 +53,11 @@ end if (size(estim_params_.var_endo,1) || size(estim_params_.corrn,1)) % Prior over measurement errors are defined... - if ((isfield(options_,'varobs') && isempty(options_.varobs)) || ~isfield(options_,'varobs')) - % ... But the list of observed variabled is not yet defined. - warning('Prior detected on measurement erros, but no list of observed variables (varobs is missing)!') - return - end + if ((isfield(options_,'varobs') && isempty(options_.varobs)) || ~isfield(options_,'varobs')) + % ... But the list of observed variabled is not yet defined. + warning('Prior detected on measurement erros, but no list of observed variables (varobs is missing)!') + return + end end % Fill or update bayestopt_ structure @@ -114,7 +114,7 @@ if ismember('optimize', varargin) % Prior optimization. end if ismember('moments', varargin) % Prior simulations (2nd order moments). - % Set estimated parameters to the prior mode... + % Set estimated parameters to the prior mode... xparam1 = BayesOptions.p5; % ... Except for uniform priors (use the prior mean)! k = find(isnan(xparam1)); diff --git a/matlab/collect_latex_files.m b/matlab/collect_latex_files.m index 5c4f2b7d64..e150baab50 100644 --- a/matlab/collect_latex_files.m +++ b/matlab/collect_latex_files.m @@ -1,10 +1,10 @@ function collect_latex_files % function collect_LaTeX_Files; % Creates TeX-File embedding all eps-loaders created for current mod-file -% +% % Inputs: none -% -% Notes: +% +% Notes: % - The packages loaded enable pdflatex to run % - The _dynamic and _static TeX-model files are not included as they are standalone TeX-files @@ -45,11 +45,11 @@ TeX_Files=dir([M_.fname,'*.tex']); for ii=1:length(TeX_Files) [pathstr,f_name,ext] = fileparts(TeX_Files(ii).name); if ~strcmp(TeX_Files(ii).name,f_name_binder) && ... - ~strcmp(TeX_Files(ii).name,[M_.fname,'_dynamic.tex']) && ... - ~strcmp(TeX_Files(ii).name,[M_.fname,'_static.tex']) && ... - ~strcmp(TeX_Files(ii).name,[M_.fname,'_original.tex']) && ... - ~strcmp(TeX_Files(ii).name,[M_.fname,'_TeX_binder.tex']) - fprintf(fid,'%s \n',['\include{',f_name,'}']); + ~strcmp(TeX_Files(ii).name,[M_.fname,'_dynamic.tex']) && ... + ~strcmp(TeX_Files(ii).name,[M_.fname,'_static.tex']) && ... + ~strcmp(TeX_Files(ii).name,[M_.fname,'_original.tex']) && ... + ~strcmp(TeX_Files(ii).name,[M_.fname,'_TeX_binder.tex']) + fprintf(fid,'%s \n',['\include{',f_name,'}']); end end @@ -58,7 +58,7 @@ TeX_Files=dir([M_.dname filesep 'Output' filesep M_.fname '*.tex']); for ii=1:length(TeX_Files) [pathstr,f_name,ext] = fileparts(TeX_Files(ii).name); if ~strcmp(TeX_Files(ii).name,f_name_binder) - fprintf(fid,'%s \n',['\include{', M_.dname '/Output' '/',f_name,'}']); + fprintf(fid,'%s \n',['\include{', M_.dname '/Output' '/',f_name,'}']); end end @@ -67,7 +67,7 @@ TeX_Files=dir([M_.dname filesep 'graphs' filesep M_.fname '*.tex']); for ii=1:length(TeX_Files) [pathstr,f_name,ext] = fileparts(TeX_Files(ii).name); if ~strcmp(TeX_Files(ii).name,f_name_binder) - fprintf(fid,'%s \n',['\include{', M_.dname '/graphs' '/',f_name,'}']); + fprintf(fid,'%s \n',['\include{', M_.dname '/graphs' '/',f_name,'}']); end end @@ -76,7 +76,7 @@ TeX_Files=dir([M_.dname filesep 'identification' filesep M_.fname '*.tex']); for ii=1:length(TeX_Files) [pathstr,f_name,ext] = fileparts(TeX_Files(ii).name); if ~strcmp(TeX_Files(ii).name,f_name_binder) - fprintf(fid,'%s \n',['\include{', M_.dname '/identification' '/',f_name,'}']); + fprintf(fid,'%s \n',['\include{', M_.dname '/identification' '/',f_name,'}']); end end @@ -86,7 +86,7 @@ TeX_Files=dir([M_.dname filesep 'identification' filesep 'Output' filesep M_.fna for ii=1:length(TeX_Files) [pathstr,f_name,ext] = fileparts(TeX_Files(ii).name); if ~strcmp(TeX_Files(ii).name,f_name_binder) - fprintf(fid,'%s \n',['\include{', M_.dname '/identification/Output' '/',f_name,'}']); + fprintf(fid,'%s \n',['\include{', M_.dname '/identification/Output' '/',f_name,'}']); end end @@ -95,7 +95,7 @@ TeX_Files=dir([M_.dname filesep 'gsa' filesep M_.fname '*.tex']); for ii=1:length(TeX_Files) [pathstr,f_name,ext] = fileparts(TeX_Files(ii).name); if ~strcmp(TeX_Files(ii).name,f_name_binder) - fprintf(fid,'%s \n',['\include{', M_.dname '/gsa' '/',f_name,'}']); + fprintf(fid,'%s \n',['\include{', M_.dname '/gsa' '/',f_name,'}']); end end @@ -104,7 +104,7 @@ TeX_Files=dir([M_.dname filesep 'gsa' filesep 'Output' filesep M_.fname '*.tex' for ii=1:length(TeX_Files) [pathstr,f_name,ext] = fileparts(TeX_Files(ii).name); if ~strcmp(TeX_Files(ii).name,f_name_binder) - fprintf(fid,'%s \n',['\include{', M_.dname '/gsa/Output' '/',f_name,'}']); + fprintf(fid,'%s \n',['\include{', M_.dname '/gsa/Output' '/',f_name,'}']); end end diff --git a/matlab/compute_Pinf_Pstar.m b/matlab/compute_Pinf_Pstar.m index 3ab4ace579..d847ffacc2 100644 --- a/matlab/compute_Pinf_Pstar.m +++ b/matlab/compute_Pinf_Pstar.m @@ -1,30 +1,30 @@ function [Pstar,Pinf] = compute_Pinf_Pstar(mf,T,R,Q,qz_criterium, restrict_columns) % function [Z,ST,QT,R1,Pstar,Pinf] = schur_statespace_transformation(mf,T,R,Q,qz_criterium, restrict_columns) % Kitagawa transformation of state space system with a quasi-triangular -% transition matrix with unit roots at the top, but excluding zero columns of the transition matrix. +% transition matrix with unit roots at the top, but excluding zero columns of the transition matrix. % Computation of Pstar and Pinf for Durbin and Koopman Diffuse filter % -% The transformed state space is +% The transformed state space is % y = [ss; z; x]; % s = static variables (zero columns of T) % z = unit roots % x = stable roots % ss = s - z = stationarized static variables -% -% INPUTS +% +% INPUTS % mf [integer] vector of indices of observed variables in % state vector % T [double] matrix of transition % R [double] matrix of structural shock effects % Q [double] matrix of covariance of structural shocks -% qz_criterium [double] numerical criterium for unit roots -% -% OUTPUTS +% qz_criterium [double] numerical criterium for unit roots +% +% OUTPUTS % Pstar [double] matrix of covariance of stationary part % Pinf [double] matrix of covariance initialization for -% nonstationary part -% -% ALGORITHM +% nonstationary part +% +% ALGORITHM % Real Schur transformation of transition equation % % SPECIAL REQUIREMENTS @@ -49,7 +49,7 @@ function [Pstar,Pinf] = compute_Pinf_Pstar(mf,T,R,Q,qz_criterium, restrict_colum np = size(T,1); -% perform Kitagawa transformation +% perform Kitagawa transformation [QT,ST] = schur(T); e1 = abs(ordeig(ST)) > 2-qz_criterium; [QT,ST] = ordschur(QT,ST,e1); @@ -112,4 +112,3 @@ end Pinf = QT*Pinf*QT'; Pstar = QT*Pstar*QT'; - diff --git a/matlab/compute_mh_covariance_matrix.m b/matlab/compute_mh_covariance_matrix.m index 28064d970c..c13eb28bf1 100644 --- a/matlab/compute_mh_covariance_matrix.m +++ b/matlab/compute_mh_covariance_matrix.m @@ -1,15 +1,15 @@ function [posterior_mean,posterior_covariance,posterior_mode,posterior_kernel_at_the_mode] = compute_mh_covariance_matrix() % Estimation of the posterior covariance matrix, posterior mean, posterior mode and evaluation of the posterior kernel at the % estimated mode, using the draws from a metropolis-hastings. The estimated posterior mode and covariance matrix are saved in -% a file <M_.fname>_mh_mode.mat. -% -% INPUTS +% a file <M_.fname>_mh_mode.mat. +% +% INPUTS % None. -% +% % OUTPUTS % o posterior_mean [double] (n*1) vector, posterior expectation of the parameters. % o posterior_covariance [double] (n*n) matrix, posterior covariance of the parameters (computed from previous metropolis hastings). -% o posterior_mode [double] (n*1) vector, posterior mode of the parameters. +% o posterior_mode [double] (n*1) vector, posterior mode of the parameters. % o posterior_kernel_at_the_mode [double] scalar. % % SPECIAL REQUIREMENTS @@ -62,7 +62,7 @@ offset = 0; for b=1:nblck first_line = FirstLine; for n = FirstMhFile:TotalNumberOfMhFiles - load([ BaseName '_mh' int2str(n) '_blck' int2str(b) '.mat'],'x2','logpo2'); + load([ BaseName '_mh' int2str(n) '_blck' int2str(b) '.mat'],'x2','logpo2'); [tmp,idx] = max(logpo2); if tmp>posterior_kernel_at_the_mode posterior_kernel_at_the_mode = tmp; diff --git a/matlab/compute_model_moments.m b/matlab/compute_model_moments.m index c3b51ad833..64894e6ec3 100644 --- a/matlab/compute_model_moments.m +++ b/matlab/compute_model_moments.m @@ -4,10 +4,10 @@ function moments=compute_model_moments(dr,M_,options_) % dr: structure describing model solution % M_: structure of Dynare options % options_ -% +% % OUTPUTS % moments: a cell array containing requested moments -% +% % SPECIAL REQUIREMENTS % none diff --git a/matlab/compute_moments_varendo.m b/matlab/compute_moments_varendo.m index d8a5c868b1..a811a12a68 100644 --- a/matlab/compute_moments_varendo.m +++ b/matlab/compute_moments_varendo.m @@ -2,14 +2,14 @@ function oo_ = compute_moments_varendo(type,options_,M_,oo_,var_list_) % Computes the second order moments (autocorrelation function, covariance % matrix and variance decomposition) distributions for all the endogenous variables selected in % var_list_. The results are saved in oo_ -% +% % INPUTS: % type [string] 'posterior' or 'prior' % options_ [structure] Dynare structure. % M_ [structure] Dynare structure (related to model definition). % oo_ [structure] Dynare structure (results). % var_list_ [string] Array of string with endogenous variable names. -% +% % OUTPUTS % oo_ [structure] Dynare structure (results). % @@ -31,7 +31,7 @@ function oo_ = compute_moments_varendo(type,options_,M_,oo_,var_list_) % 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/>. +% along with Dynare. If not, see <http://www.gnu.org/licenses/>. fprintf('Estimation::compute_moments_varendo: I''m computing endogenous moments (this may take a while)... '); @@ -129,7 +129,7 @@ if M_.exo_nbr > 1 headers = char(' ',headers); lh = size(deblank(var_list_),2)+2; dyntable(options_,title,headers,deblank(var_list_),100* ... - temp,lh,8,2); + temp,lh,8,2); if options_.TeX headers=M_.exo_names_tex; headers = char(' ',headers); @@ -166,7 +166,7 @@ if M_.exo_nbr > 1 headers = char(' ',headers); lh = size(deblank(var_list_),2)+2; dyntable(options_,title_print,headers,deblank(var_list_),100* ... - temp(:,:,step_iter),lh,8,2); + temp(:,:,step_iter),lh,8,2); if options_.TeX headers=M_.exo_names_tex; headers = char(' ',headers); diff --git a/matlab/compute_overall_acceptance_ratio.m b/matlab/compute_overall_acceptance_ratio.m index d3b323eb30..448fac02b9 100644 --- a/matlab/compute_overall_acceptance_ratio.m +++ b/matlab/compute_overall_acceptance_ratio.m @@ -16,7 +16,7 @@ function overallacceptanceratio = compute_overall_acceptance_ratio(MetropolisFol % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - + BaseName = [MetropolisFolder filesep ModelName]; mh_history_files = dir([BaseName '_mh_history_*.mat']); @@ -24,12 +24,12 @@ n = length(mh_history_files); load([BaseName '_mh_history_' num2str(0)]); TotalNumberOfDraws = record.MhDraws(end,1); -TotalNumberOfAcceptedProposals = record.AcceptanceRatio*record.MhDraws(end,1); +TotalNumberOfAcceptedProposals = record.AcceptanceRatio*record.MhDraws(end,1); for i=2:n load([BaseName '_mh_history_' num2str(i-1)]); TotalNumberOfDraws = TotalNumberOfDraws + record.MhDraws(end,1); - TotalNumberOfAcceptedProposals = TotalNumberOfAcceptedProposals + record.AcceptanceRatio*record.MhDraws(end,1); + TotalNumberOfAcceptedProposals = TotalNumberOfAcceptedProposals + record.AcceptanceRatio*record.MhDraws(end,1); end overallacceptanceratio = TotalNumberOfAcceptedProposals/TotalNumberOfDraws; \ No newline at end of file diff --git a/matlab/conditional_variance_decomposition.m b/matlab/conditional_variance_decomposition.m index 3ecf744103..25b236b054 100644 --- a/matlab/conditional_variance_decomposition.m +++ b/matlab/conditional_variance_decomposition.m @@ -1,14 +1,14 @@ function ConditionalVarianceDecomposition = conditional_variance_decomposition(StateSpaceModel, Steps, SubsetOfVariables,sigma_e_is_diagonal) % This function computes the conditional variance decomposition of a given state space model % for a subset of endogenous variables. -% -% INPUTS +% +% INPUTS % StateSpaceModel [structure] Specification of the state space model. % Steps [integer] 1*h vector of dates. % SubsetOfVariables [integer] 1*q vector of indices. -% -% OUTPUTS -% ConditionalVarianceDecomposition [double] [n h p] array, where +% +% OUTPUTS +% ConditionalVarianceDecomposition [double] [n h p] array, where % n is equal to length(SubsetOfVariables) % h is the number of Steps % p is the number of state innovations and @@ -77,7 +77,7 @@ for h = 1:length(Steps) SumOfVariances(:,h) = sum(ConditionalVariance(:,h,:),3); end -ConditionalVarianceDecomposition = zeros(NumberOfVariables,length(Steps),number_of_state_innovations); +ConditionalVarianceDecomposition = zeros(NumberOfVariables,length(Steps),number_of_state_innovations); for i=1:number_of_state_innovations for h = 1:length(Steps) ConditionalVarianceDecomposition(:,h,i) = squeeze(ConditionalVariance(:,h,i))./SumOfVariances(:,h); diff --git a/matlab/conditional_variance_decomposition_mc_analysis.m b/matlab/conditional_variance_decomposition_mc_analysis.m index 68fbeb6b7f..7d41766c52 100644 --- a/matlab/conditional_variance_decomposition_mc_analysis.m +++ b/matlab/conditional_variance_decomposition_mc_analysis.m @@ -9,7 +9,7 @@ function oo_ = ... % dname [string] directory name where to save % fname [string] name of the mod-file % Steps [integers] horizons at which to conduct decomposition -% exonames [string] (n_exo*char_length) character array with names of exogenous variables +% exonames [string] (n_exo*char_length) character array with names of exogenous variables % exo [string] name of current exogenous % variable % var_list [string] (n_endo*char_length) character array with name @@ -106,7 +106,7 @@ for i=1:length(Steps) p_density(:,:,i) = pp_density; else [pp_mean, pp_median, pp_var, hpd_interval, pp_deciles] = ... - posterior_moments(tmp(:,i),0,mh_conf_sig); + posterior_moments(tmp(:,i),0,mh_conf_sig); end p_mean(i) = pp_mean; p_median(i) = pp_median; diff --git a/matlab/convergence_diagnostics/McMCDiagnostics.m b/matlab/convergence_diagnostics/McMCDiagnostics.m index 769b70d35f..a3fa70fd90 100644 --- a/matlab/convergence_diagnostics/McMCDiagnostics.m +++ b/matlab/convergence_diagnostics/McMCDiagnostics.m @@ -1,14 +1,14 @@ function oo_ = McMCDiagnostics(options_, estim_params_, M_, oo_) % function McMCDiagnostics -% Computes convergence tests -% -% INPUTS +% Computes convergence tests +% +% INPUTS % options_ [structure] % estim_params_ [structure] % M_ [structure] % -% OUTPUTS -% oo_ [structure] +% OUTPUTS +% oo_ [structure] % % SPECIAL REQUIREMENTS % none @@ -82,12 +82,12 @@ param_name_tex=[]; for jj=1:npar if options_.TeX [par_name_temp,par_name_tex_temp]=get_the_name(jj,options_.TeX,M_,estim_params_,options_); - param_name = strvcat(param_name,par_name_temp); + param_name = strvcat(param_name,par_name_temp); par_name_tex_temp = strrep(par_name_tex_temp,'$',''); param_name_tex = strvcat(param_name_tex,par_name_tex_temp); else [par_name_temp]=get_the_name(jj,options_.TeX,M_,estim_params_,options_); - param_name = strvcat(param_name,par_name_temp); + param_name = strvcat(param_name,par_name_temp); end Draws = GetAllPosteriorDraws(jj,FirstMhFile,FirstLine,TotalNumberOfMhFiles,NumberOfDraws); Draws = reshape(Draws,[NumberOfDraws nblck]); @@ -130,7 +130,7 @@ end if nblck == 1 % Brooks and Gelman tests need more than one block convergence_diagnostics_geweke=zeros(npar,4+2*length(options_.convergence.geweke.taper_steps)); if any(options_.convergence.geweke.geweke_interval<0) || any(options_.convergence.geweke.geweke_interval>1) || length(options_.convergence.geweke.geweke_interval)~=2 ... - || (options_.convergence.geweke.geweke_interval(2)-options_.convergence.geweke.geweke_interval(1)<0) + || (options_.convergence.geweke.geweke_interval(2)-options_.convergence.geweke.geweke_interval(1)<0) fprintf('\nCONVERGENCE DIAGNOSTICS: Invalid option for geweke_interval. Using the default of [0.2 0.5].\n') options_.convergence.geweke.geweke_interval=[0.2 0.5]; end @@ -139,9 +139,9 @@ if nblck == 1 % Brooks and Gelman tests need more than one block first_obs_end_sample = first_obs_begin_sample+round(options_.convergence.geweke.geweke_interval(2)*NumberOfDraws*(1-options_.mh_drop)); param_name=[]; if options_.TeX - param_name_tex=[]; + param_name_tex=[]; end - for jj=1:npar + for jj=1:npar if options_.TeX [param_name_temp, param_name_tex_temp]= get_the_name(jj,options_.TeX,M_,estim_params_,options_); param_name_tex = strvcat(param_name_tex,strrep(param_name_tex_temp,'$','')); @@ -152,7 +152,7 @@ if nblck == 1 % Brooks and Gelman tests need more than one block end end fprintf('\nGeweke (1992) Convergence Tests, based on means of draws %d to %d vs %d to %d.\n',first_obs_begin_sample,last_obs_begin_sample,first_obs_end_sample,NumberOfDraws); - fprintf('p-values are for Chi2-test for equality of means.\n'); + fprintf('p-values are for Chi2-test for equality of means.\n'); Geweke_header=char('Parameter', 'Post. Mean', 'Post. Std', 'p-val No Taper'); for ii=1:length(options_.convergence.geweke.taper_steps) Geweke_header=char(Geweke_header,['p-val ' num2str(options_.convergence.geweke.taper_steps(ii)),'% Taper']); @@ -168,12 +168,12 @@ if nblck == 1 % Brooks and Gelman tests need more than one block end [results_vec, results_struct] = geweke_moments(param_draws,options_); convergence_diagnostics_geweke(jj,:)=results_vec; - + param_draws1 = param_draws(first_obs_begin_sample:last_obs_begin_sample,:); param_draws2 = param_draws(first_obs_end_sample:end,:); [results_vec1] = geweke_moments(param_draws1,options_); [results_vec2] = geweke_moments(param_draws2,options_); - + results_struct = geweke_chi2_test(results_vec1,results_vec2,results_struct,options_); eval(['oo_.convergence.geweke.',param_name(jj,:),'=results_struct;']) datamat(jj,:)=[results_struct.posteriormean,results_struct.posteriorstd,results_struct.prob_chi2_test]; @@ -183,29 +183,29 @@ if nblck == 1 % Brooks and Gelman tests need more than one block if options_.TeX Geweke_tex_header=char('Parameter', 'Mean', 'Std', 'No\ Taper'); additional_header={[' & \multicolumn{2}{c}{Posterior} & \multicolumn{',num2str(1+length(options_.convergence.geweke.taper_steps)),'}{c}{p-values} \\'], - ['\cmidrule(r{.75em}){2-3} \cmidrule(r{.75em}){4-',num2str(4+length(options_.convergence.geweke.taper_steps)),'}']}; + ['\cmidrule(r{.75em}){2-3} \cmidrule(r{.75em}){4-',num2str(4+length(options_.convergence.geweke.taper_steps)),'}']}; for ii=1:length(options_.convergence.geweke.taper_steps) Geweke_tex_header=char(Geweke_tex_header,[num2str(options_.convergence.geweke.taper_steps(ii)),'\%%\ Taper']); end headers = char(Geweke_tex_header); lh = size(param_name_tex,2)+2; my_title=sprintf('Geweke (1992) Convergence Tests, based on means of draws %d to %d vs %d to %d. p-values are for $\\\\chi^2$-test for equality of means.',first_obs_begin_sample,last_obs_begin_sample,first_obs_end_sample,NumberOfDraws); - dyn_latex_table(M_,options_,my_title,'geweke',headers,param_name_tex,datamat,lh,12,4,additional_header); + dyn_latex_table(M_,options_,my_title,'geweke',headers,param_name_tex,datamat,lh,12,4,additional_header); end skipline(2); - + if options_.convergence.rafterylewis.indicator if any(options_.convergence.rafterylewis.qrs<0) || any(options_.convergence.rafterylewis.qrs>1) || length(options_.convergence.rafterylewis.qrs)~=3 ... - || (options_.convergence.rafterylewis.qrs(1)-options_.convergence.rafterylewis.qrs(2)<=0) + || (options_.convergence.rafterylewis.qrs(1)-options_.convergence.rafterylewis.qrs(2)<=0) fprintf('\nCONVERGENCE DIAGNOSTICS: Invalid option for raftery_lewis_qrs. Using the default of [0.025 0.005 0.95].\n') options_.convergence.rafterylewis.qrs=[0.025 0.005 0.95]; - end + end Raftery_Lewis_q=options_.convergence.rafterylewis.qrs(1); Raftery_Lewis_r=options_.convergence.rafterylewis.qrs(2); Raftery_Lewis_s=options_.convergence.rafterylewis.qrs(3); oo_.Raftery_Lewis = raftery_lewis(x2,Raftery_Lewis_q,Raftery_Lewis_r,Raftery_Lewis_s); oo_.Raftery_Lewis.parameter_names=param_name; - my_title=sprintf('Raftery/Lewis (1992) Convergence Diagnostics, based on quantile q=%4.3f with precision r=%4.3f with probability s=%4.3f.',Raftery_Lewis_q,Raftery_Lewis_r,Raftery_Lewis_s); + my_title=sprintf('Raftery/Lewis (1992) Convergence Diagnostics, based on quantile q=%4.3f with precision r=%4.3f with probability s=%4.3f.',Raftery_Lewis_q,Raftery_Lewis_r,Raftery_Lewis_s); headers = char('Variables','M (burn-in)','N (req. draws)','N+M (total draws)','k (thinning)'); raftery_data_mat=[oo_.Raftery_Lewis.M_burn,oo_.Raftery_Lewis.N_prec,oo_.Raftery_Lewis.N_total,oo_.Raftery_Lewis.k_thin]; @@ -217,15 +217,15 @@ if nblck == 1 % Brooks and Gelman tests need more than one block labels_Raftery_Lewis_tex=char(param_name_tex,'Maximum'); lh = size(labels_Raftery_Lewis_tex,2)+2; dyn_latex_table(M_,options_,my_title,'raftery_lewis',headers,labels_Raftery_Lewis_tex,raftery_data_mat,lh,10,0); - end + end end - + return end Origin = 1000; -StepSize = ceil((NumberOfDraws-Origin)/100);% So that the computational time does not -ALPHA = 0.2; % increase too much with the number of simulations. +StepSize = ceil((NumberOfDraws-Origin)/100);% So that the computational time does not +ALPHA = 0.2; % increase too much with the number of simulations. time = 1:NumberOfDraws; xx = Origin:StepSize:NumberOfDraws; NumberOfLines = length(xx); @@ -273,7 +273,7 @@ else ModelName = [ModelName '_bvar']; end NamFileInput={[M_.dname '/metropolis/'],[ModelName '_mh*_blck*.mat']}; - + [fout, nBlockPerCPU, totCPU] = masterParallel(options_.parallel, 1, npar,NamFileInput,'McMCDiagnostics_core', localVars, [], options_.parallel_info); UDIAG = fout(1).UDIAG; for j=2:totCPU @@ -283,9 +283,9 @@ end UDIAG(:,[2 4 6],:) = UDIAG(:,[2 4 6],:)/nblck; skipline() -clear pmet temp moyenne CSUP CINF csup cinf n linea iter tmp; +clear pmet temp moyenne CSUP CINF csup cinf n linea iter tmp; pages = floor(npar/3); -k = 0; +k = 0; for i = 1:pages h=dyn_figure(options_.nodisplay,'Name','MCMC univariate convergence diagnostic (Brooks and Gelman,1998)'); boxplot = 1; @@ -296,12 +296,12 @@ for i = 1:pages if crit == 1 plt1 = UDIAG(:,1,k); plt2 = UDIAG(:,2,k); - namnam = [nam , ' (Interval)']; + namnam = [nam , ' (Interval)']; elseif crit == 2 plt1 = UDIAG(:,3,k); plt2 = UDIAG(:,4,k); namnam = [nam , ' (m2)']; - elseif crit == 3 + elseif crit == 3 plt1 = UDIAG(:,5,k); plt2 = UDIAG(:,6,k); namnam = [nam , ' (m3)']; @@ -330,7 +330,7 @@ for i = 1:pages 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 + end fprintf(fidTeX,'\\centering \n'); fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_udiag%s}\n',options_.figures.textwidth*min((boxplot-1)/3,1),[OutputFolder '/' ModelName],int2str(i)); fprintf(fidTeX,'\\caption{Univariate convergence diagnostics for the Metropolis-Hastings.\n'); @@ -359,12 +359,12 @@ if reste if crit == 1 plt1 = UDIAG(:,1,k); plt2 = UDIAG(:,2,k); - namnam = [nam , ' (Interval)']; + namnam = [nam , ' (Interval)']; elseif crit == 2 plt1 = UDIAG(:,3,k); plt2 = UDIAG(:,4,k); namnam = [nam , ' (m2)']; - elseif crit == 3 + elseif crit == 3 plt1 = UDIAG(:,5,k); plt2 = UDIAG(:,6,k); namnam = [nam , ' (m3)']; @@ -393,7 +393,7 @@ if reste 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 + end fprintf(fidTeX,'\\centering \n'); fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_udiag%s}\n',options_.figures.textwidth*min((boxplot-1)/nc,1),[OutputFolder '/' ModelName],int2str(pages+1)); if reste == 2 @@ -435,7 +435,7 @@ for b = 1:nblck end clear logpo2; tmp(:,2) = kron(transpose(1:nblck),ones(NumberOfDraws,1)); -tmp(:,3) = kron(ones(nblck,1),time'); +tmp(:,3) = kron(ones(nblck,1),time'); tmp = sortrows(tmp,1); ligne = 0; for iter = Origin:StepSize:NumberOfDraws @@ -454,12 +454,12 @@ for iter = Origin:StepSize:NumberOfDraws for i=1:nblck pmet = temp(find(temp(:,2)==i)); MDIAG(ligne,2) = MDIAG(ligne,2) + pmet(csup,1)-pmet(cinf,1); - moyenne = mean(pmet,1); %% Within mean. + moyenne = mean(pmet,1); %% Within mean. MDIAG(ligne,4) = MDIAG(ligne,4) + sum((pmet(:,1)-moyenne).^2)/(n-1); MDIAG(ligne,6) = MDIAG(ligne,6) + sum(abs(pmet(:,1)-moyenne).^3)/(n-1); end end -MDIAG(:,[2 4 6],:) = MDIAG(:,[2 4 6],:)/nblck; +MDIAG(:,[2 4 6],:) = MDIAG(:,[2 4 6],:)/nblck; h = dyn_figure(options_.nodisplay,'Name','Multivariate convergence diagnostic'); boxplot = 1; @@ -467,12 +467,12 @@ for crit = 1:3 if crit == 1 plt1 = MDIAG(:,1); plt2 = MDIAG(:,2); - namnam = 'Interval'; + namnam = 'Interval'; elseif crit == 2 plt1 = MDIAG(:,3); plt2 = MDIAG(:,4); namnam = 'm2'; - elseif crit == 3 + elseif crit == 3 plt1 = MDIAG(:,5); plt2 = MDIAG(:,6); namnam = 'm3'; @@ -499,7 +499,7 @@ if TeX && any(strcmp('eps',cellstr(options_.graph_format))) fprintf(fidTeX,'\\begin{figure}[H]\n'); for jj = 1:3 fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),' '); - end + end fprintf(fidTeX,'\\centering \n'); fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s_mdiag}\n',[OutputFolder '/' ModelName]); fprintf(fidTeX,'\\caption{Multivariate convergence diagnostics for the Metropolis-Hastings.\n'); @@ -512,4 +512,3 @@ if TeX && any(strcmp('eps',cellstr(options_.graph_format))) fprintf(fidTeX,'%% End Of TeX file.'); fclose(fidTeX); end - diff --git a/matlab/convergence_diagnostics/McMCDiagnostics_core.m b/matlab/convergence_diagnostics/McMCDiagnostics_core.m index c9eda9a3bc..283e6ada10 100644 --- a/matlab/convergence_diagnostics/McMCDiagnostics_core.m +++ b/matlab/convergence_diagnostics/McMCDiagnostics_core.m @@ -2,12 +2,12 @@ function myoutput = McMCDiagnostics_core(myinputs,fpar,npar,whoiam, ThisMatlab) % function myoutput = McMCDiagnostics_core(myinputs,fpar,npar,whoiam, ThisMatlab) % Computes the Brooks/Gelman (1998) convergence diagnostics, both the % parameteric and the non-parameteric versions -% +% % PARALLEL CONTEXT % Core functionality for MCMC Diagnostics, which can be parallelized. % See also the comment in posterior_sampler_core.m funtion. -% -% +% +% % INPUTS % See See the comment in posterior_sampler_core.m funtion. @@ -25,10 +25,10 @@ function myoutput = McMCDiagnostics_core(myinputs,fpar,npar,whoiam, ThisMatlab) % % ALGORITHM % Computes part of the convergence diagnostics, the rest is computed in McMCDiagnostics.m . -% The methodology and terminology is based on: Brooks/Gelman (1998): General -% Methods for Monitoring Convergence of Iterative Simulations, Journal of Computational +% The methodology and terminology is based on: Brooks/Gelman (1998): General +% Methods for Monitoring Convergence of Iterative Simulations, Journal of Computational % and Graphical Statistics, Volume 7, Number 4, Pages 434-455 -% +% % % SPECIAL REQUIREMENTS. % None. diff --git a/matlab/convergence_diagnostics/geweke_chi2_test.m b/matlab/convergence_diagnostics/geweke_chi2_test.m index 6f0860af28..8acf673993 100644 --- a/matlab/convergence_diagnostics/geweke_chi2_test.m +++ b/matlab/convergence_diagnostics/geweke_chi2_test.m @@ -2,7 +2,7 @@ function results_struct = geweke_chi2_test(results1,results2,results_struct,opti % results_struct = geweke_chi2_test(results1,results2,results_struct,options) % PURPOSE: computes Geweke's chi-squared test for two sets of MCMC sample draws % -% INPUTS +% INPUTS % results1 [1 by (4+n_taper*2) vector] vector with post. mean, % std, NSE_iid, RNE_iid, and tapered NSE and RNE % for chain part 1 @@ -12,7 +12,7 @@ function results_struct = geweke_chi2_test(results1,results2,results_struct,opti % results_struct [structure] results structure generated by geweke_moments % Dynareoptions [structure] % -% OUTPUTS +% OUTPUTS % results_struct [structure] containing the following fields: % pooled_mean Pooled mean of the chain parts, weighted % with precision @@ -49,26 +49,25 @@ function results_struct = geweke_chi2_test(results1,results2,results_struct,opti % J.M. Bernardo, A.P. Dawid, and A.F.M. Smith (eds.) Proceedings of % the Fourth Valencia International Meeting on Bayesian Statistics, % pp. 169-194, Oxford University Press -% Geweke (1999): `Using simulation methods for Bayesian econometric models: +% Geweke (1999): `Using simulation methods for Bayesian econometric models: % Inference, development and communication', Econometric Reviews, 18(1), % 1-73 -% written by: Johannes Pfeifer, -% based on code by James P. LeSage, who in turn -% drew on MATLAB programs written by Siddartha Chib +% written by: Johannes Pfeifer, +% based on code by James P. LeSage, who in turn +% drew on MATLAB programs written by Siddartha Chib for k=1:length(options.convergence.geweke.taper_steps)+1 - NSE=[results1(:,3+(k-1)*2) results2(:,3+(k-1)*2)]; - means=[results1(:,1) results2(:,1)]; - diff_Means=means(:,1)-means(:,2); - sum_of_weights=sum(1./(NSE.^2),2); - pooled_mean=sum(means./(NSE.^2),2)./sum_of_weights; - pooled_NSE=1./sqrt(sum_of_weights); + NSE=[results1(:,3+(k-1)*2) results2(:,3+(k-1)*2)]; + means=[results1(:,1) results2(:,1)]; + diff_Means=means(:,1)-means(:,2); + sum_of_weights=sum(1./(NSE.^2),2); + pooled_mean=sum(means./(NSE.^2),2)./sum_of_weights; + pooled_NSE=1./sqrt(sum_of_weights); - test_stat=diff_Means.^2./sum(NSE.^2,2); - p = 1-chi2cdf(test_stat,1); - results_struct.pooled_mean(:,k) = pooled_mean; - results_struct.pooled_nse(:,k) = pooled_NSE; - results_struct.prob_chi2_test(:,k) = p; + test_stat=diff_Means.^2./sum(NSE.^2,2); + p = 1-chi2cdf(test_stat,1); + results_struct.pooled_mean(:,k) = pooled_mean; + results_struct.pooled_nse(:,k) = pooled_NSE; + results_struct.prob_chi2_test(:,k) = p; end - diff --git a/matlab/convergence_diagnostics/geweke_moments.m b/matlab/convergence_diagnostics/geweke_moments.m index 27204dd09a..61c22979fb 100644 --- a/matlab/convergence_diagnostics/geweke_moments.m +++ b/matlab/convergence_diagnostics/geweke_moments.m @@ -1,13 +1,13 @@ function [results_vec, results_struct] = geweke_moments(draws,Dynareoptions) %[results_vec, results_struct] = geweke_moments(draws,Dynareoptions) -% PURPOSE: computes Gewke's convergence diagnostics NSE and RNE +% PURPOSE: computes Gewke's convergence diagnostics NSE and RNE % (numerical std error and relative numerical efficiencies) -% INPUTS -% draws [ndraws by 1 vector] +% INPUTS +% draws [ndraws by 1 vector] % Dynareoptions [structure] -% -% OUTPUTS +% +% OUTPUTS % results_vec % results_struct [structure] containing the following fields: % posteriormean= posterior parameter mean @@ -44,16 +44,16 @@ function [results_vec, results_struct] = geweke_moments(draws,Dynareoptions) % J.M. Bernardo, A.P. Dawid, and A.F.M. Smith (eds.) Proceedings of % the Fourth Valencia International Meeting on Bayesian Statistics, % pp. 169-194, Oxford University Press -% Geweke (1999): `Using simulation methods for Bayesian econometric models: +% Geweke (1999): `Using simulation methods for Bayesian econometric models: % Inference, development and communication', Econometric Reviews, 18(1), % 1-73 % ----------------------------------------------------------------- -% written by: Johannes Pfeifer, -% based on code by James P. LeSage, who in turn -% drew on MATLAB programs written by Siddartha Chib +% written by: Johannes Pfeifer, +% based on code by James P. LeSage, who in turn +% drew on MATLAB programs written by Siddartha Chib + - ndraw = size(draws,1); n_groups=100; taper_steps=Dynareoptions.convergence.geweke.taper_steps; @@ -66,7 +66,7 @@ window_means= zeros(n_groups,1); window_uncentered_variances= zeros(n_groups,1); for ig=1:n_groups window_means(ig,1)=sum(draws((ig-1)*ns+1:ig*ns,1))/ns; - window_uncentered_variances(ig,1)=sum(draws((ig-1)*ns+1:ig*ns,1).^2)/ns; + window_uncentered_variances(ig,1)=sum(draws((ig-1)*ns+1:ig*ns,1).^2)/ns; end %for ig total_mean=mean(window_means); total_variance=mean(window_uncentered_variances)-total_mean^2; @@ -106,4 +106,3 @@ for taper_index=1:length(taper_steps) eval(['results_struct.nse_taper_',num2str(taper),'= NSE_taper;']); eval(['results_struct.rne_taper_',num2str(taper),'= total_variance/(n_draws_used*NSE_taper^2);']); end % end of for mm loop - diff --git a/matlab/convergence_diagnostics/mcmc_ifac.m b/matlab/convergence_diagnostics/mcmc_ifac.m index 7537e62eb1..faf7d16598 100644 --- a/matlab/convergence_diagnostics/mcmc_ifac.m +++ b/matlab/convergence_diagnostics/mcmc_ifac.m @@ -1,71 +1,71 @@ -function Ifac = mcmc_ifac(X, Nc) -% function Ifac = mcmc_ifac(X, Nc) -% Compute inefficiency factor of a MCMC sample X based on a Parzen Window -% -% INPUTS -% X: time series -% Nc: # of lags -% -% OUTPUTS -% Ifac: inefficiency factor of MCMC sample -% -% SPECIAL REQUIREMENTS -% none -% ALGORITHM: -% Inefficiency factors are computed as -% \[ -% Ifac = 1 + 2\sum\limits_{i=1}^{Nc} {\hat \rho(i)} -% \] -% where $\hat \rho(i)$ denotes the autocorrelation at lag i and the terms -% of the sum are truncated using a Parzen window. -% -% For inefficiency factors, see Section 6.1 of Paolo Giordani, Michael Pitt, and Robert Kohn (2011): -% "Bayesian Inference for Time Series State Space Models" in : John Geweke, Gary Koop, -% Herman van Dijk (editors): "The Oxford Handbook of Bayesian -% Econometrics", Oxford University Press -% -% The Parzen-Window is given by -% \[ -% k(x) = \left\{ {\begin{array}{*{20}{c}} -% {1 - 6{x^2} + 6|x|^3} \text{ for } 0 \leqslant |x| \leqslant \frac{1}{2}} \\ -% {2(1-|x|^3) \text{ for } \frac{1}{2} \leqslant |x| \leqslant 1} \\ -% {0 \text{ otherwise}} -% \end{array}} \right. -% \] -% See Donald W.K Andrews (1991): "Heteroskedasticity and autocorrelation -% consistent covariance matrix estimation", Econometrica, 59(3), p. 817-858 - - -% Copyright (C) 2015-16 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/>. - -Nc = floor(min(Nc, length(X)/2)); -if mod(Nc,2) - Nc=Nc-1; -end -AcorrXSIM = dyn_autocorr(X(:), Nc); -% -%Calculate the Parzen Weight -Parzen=zeros(Nc+1,1); -for i=1: Nc/2+1 - Parzen(i)=1 - 6*(i/Nc)^2+ 6*(i/Nc)^3; -end -for i=(Nc/2)+1: Nc+1 - Parzen(i)=2 * (1-(i/Nc))^3; -end -Parzen=Parzen'; -Ifac= 1+2*sum(Parzen(:).* AcorrXSIM); +function Ifac = mcmc_ifac(X, Nc) +% function Ifac = mcmc_ifac(X, Nc) +% Compute inefficiency factor of a MCMC sample X based on a Parzen Window +% +% INPUTS +% X: time series +% Nc: # of lags +% +% OUTPUTS +% Ifac: inefficiency factor of MCMC sample +% +% SPECIAL REQUIREMENTS +% none +% ALGORITHM: +% Inefficiency factors are computed as +% \[ +% Ifac = 1 + 2\sum\limits_{i=1}^{Nc} {\hat \rho(i)} +% \] +% where $\hat \rho(i)$ denotes the autocorrelation at lag i and the terms +% of the sum are truncated using a Parzen window. +% +% For inefficiency factors, see Section 6.1 of Paolo Giordani, Michael Pitt, and Robert Kohn (2011): +% "Bayesian Inference for Time Series State Space Models" in : John Geweke, Gary Koop, +% Herman van Dijk (editors): "The Oxford Handbook of Bayesian +% Econometrics", Oxford University Press +% +% The Parzen-Window is given by +% \[ +% k(x) = \left\{ {\begin{array}{*{20}{c}} +% {1 - 6{x^2} + 6|x|^3} \text{ for } 0 \leqslant |x| \leqslant \frac{1}{2}} \\ +% {2(1-|x|^3) \text{ for } \frac{1}{2} \leqslant |x| \leqslant 1} \\ +% {0 \text{ otherwise}} +% \end{array}} \right. +% \] +% See Donald W.K Andrews (1991): "Heteroskedasticity and autocorrelation +% consistent covariance matrix estimation", Econometrica, 59(3), p. 817-858 + + +% Copyright (C) 2015-16 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/>. + +Nc = floor(min(Nc, length(X)/2)); +if mod(Nc,2) + Nc=Nc-1; +end +AcorrXSIM = dyn_autocorr(X(:), Nc); +% +%Calculate the Parzen Weight +Parzen=zeros(Nc+1,1); +for i=1: Nc/2+1 + Parzen(i)=1 - 6*(i/Nc)^2+ 6*(i/Nc)^3; +end +for i=(Nc/2)+1: Nc+1 + Parzen(i)=2 * (1-(i/Nc))^3; +end +Parzen=Parzen'; +Ifac= 1+2*sum(Parzen(:).* AcorrXSIM); diff --git a/matlab/convergence_diagnostics/raftery_lewis.m b/matlab/convergence_diagnostics/raftery_lewis.m index 0b61ca9baa..342e36ab55 100644 --- a/matlab/convergence_diagnostics/raftery_lewis.m +++ b/matlab/convergence_diagnostics/raftery_lewis.m @@ -1,15 +1,15 @@ function [raftery_lewis] = raftery_lewis(runs,q,r,s) % function raftery_lewis = raftery_lewis(runs,q,r,s) -% Computes the convergence diagnostics of Raftery and Lewis (1992), i.e. the -% number of draws needed in MCMC to estimate the posterior cdf of the q-quantile +% Computes the convergence diagnostics of Raftery and Lewis (1992), i.e. the +% number of draws needed in MCMC to estimate the posterior cdf of the q-quantile % within an accuracy r with probability s -% +% % Inputs: -% - draws [n_draws by n_var] double matrix of draws from the sampler +% - draws [n_draws by n_var] double matrix of draws from the sampler % - q [scalar] quantile of the quantity of interest -% - r [scalar] level of desired precision +% - r [scalar] level of desired precision % - s [scalar] probability associated with r -% +% % Output: % raftery_lewis [structure] containing the fields: % - M_burn [n_draws by 1] number of draws required for burn-in @@ -21,7 +21,7 @@ function [raftery_lewis] = raftery_lewis(runs,q,r,s) % iterations due to dependence in chain % - N_min [scalar] # draws if the chain is white noise % - N_total [n_draws by 1] nburn + nprec -% +% % --------------------------------------------------------------------- % NOTES: Example values of q, r, s: @@ -30,18 +30,18 @@ function [raftery_lewis] = raftery_lewis(runs,q,r,s) % % - The result is quite sensitive to r, being proportional to the % inverse of r^2. -% - For epsilon (closeness of probabilities to equilibrium values), +% - For epsilon (closeness of probabilities to equilibrium values), % Raftery/Lewis use 0.001 and argue that the results % are quite robust to changes in this value % % --------------------------------------------------------------------- -% REFERENCES: +% REFERENCES: % Raftery, Adrien E./Lewis, Steven (1992a): "How many iterations in the Gibbs sampler?" -% in: Bernardo/Berger/Dawid/Smith (eds.): Bayesian Statistics, Vol. 4, Clarendon Press: Oxford, -% pp. 763-773. -% Raftery, Adrien E./Lewis, Steven (1992b): "Comment: One long run with diagnostics: -% Implementation strategies for Markov chain Monte Carlo." Statistical Science, -% 7(4), pp. 493-497. +% in: Bernardo/Berger/Dawid/Smith (eds.): Bayesian Statistics, Vol. 4, Clarendon Press: Oxford, +% pp. 763-773. +% Raftery, Adrien E./Lewis, Steven (1992b): "Comment: One long run with diagnostics: +% Implementation strategies for Markov chain Monte Carlo." Statistical Science, +% 7(4), pp. 493-497. % % ---------------------------------------------------- @@ -80,26 +80,26 @@ thinned_chain = zeros(n_runs,1); Phi = norminv((s+1)/2); %note the missing ^{-1} at the Phi in equation top page 5, see RL (1995) raftery_lewis.N_min = fix(Phi^2*(1-q)*q/r^2+1); -for nv = 1:n_vars % big loop over variables +for nv = 1:n_vars % big loop over variables if q > 0 && q < 1 work = (runs(:,nv) <= quantile(runs(:,nv),q)); else - error('Quantile must be between 0 and 1'); + error('Quantile must be between 0 and 1'); end - - k_thin_current_var = 1; - bic = 1; + + k_thin_current_var = 1; + bic = 1; epss = 0.001; % Find thinning factor for which first-order Markov Chain is preferred to second-order one while(bic > 0) - thinned_chain=work(1:k_thin_current_var:n_runs,1); + thinned_chain=work(1:k_thin_current_var:n_runs,1); [g2, bic] = first_vs_second_order_MC_test(thinned_chain); k_thin_current_var = k_thin_current_var+1; end - + k_thin_current_var = k_thin_current_var-1; %undo last step - - %compute transition probabilities + + %compute transition probabilities transition_matrix = zeros(2,2); for i1 = 2:size(thinned_chain,1) transition_matrix(thinned_chain(i1-1)+1,thinned_chain(i1)+1) = transition_matrix(thinned_chain(i1-1)+1,thinned_chain(i1)+1)+1; @@ -109,13 +109,13 @@ for nv = 1:n_vars % big loop over variables kmind=k_thin_current_var; [g2, bic]=independence_chain_test(thinned_chain); - + while(bic > 0) - thinned_chain=work(1:kmind:n_runs,1); + thinned_chain=work(1:kmind:n_runs,1); [g2, bic] = independence_chain_test(thinned_chain); kmind = kmind+1; end - + m_star = log((alpha + beta)*epss/max(alpha,beta))/log(abs(1 - alpha - beta)); %equation bottom page 4 raftery_lewis.M_burn(nv) = fix((m_star+1)*k_thin_current_var); n_star = (2 - (alpha + beta))*alpha*beta*(Phi^2)/((alpha + beta)^3 * r^2); %equation top page 5 @@ -131,7 +131,7 @@ end function [g2, bic] = first_vs_second_order_MC_test(d) %conducts a test of first vs. second order Markov Chain via BIC criterion n_obs=size(d,1); -g2 = 0; +g2 = 0; tran=zeros(2,2,2); for t_iter=3:n_obs % count state transitions tran(d(t_iter-2,1)+1,d(t_iter-1,1)+1,d(t_iter,1)+1)=tran(d(t_iter-2,1)+1,d(t_iter-1,1)+1,d(t_iter,1)+1)+1; @@ -142,17 +142,17 @@ for ind_1 = 1:2 for ind_3 = 1:2 if tran(ind_1,ind_2,ind_3) ~= 0 fitted = (tran(ind_1,ind_2,1) + tran(ind_1,ind_2,2))*(tran(1,ind_2,ind_3) + tran(2,ind_2,ind_3))/... - (tran(1,ind_2,1) + tran(1,ind_2,2) + tran(2,ind_2,1) + tran(2,ind_2,2)); + (tran(1,ind_2,1) + tran(1,ind_2,2) + tran(2,ind_2,1) + tran(2,ind_2,2)); focus = tran(ind_1,ind_2,ind_3); g2 = g2 + log(focus/fitted)*focus; end end % end of for i3 end % end of for i2 end % end of for i1 -g2 = g2*2; -bic = g2 - log(n_obs-2)*2; + g2 = g2*2; + bic = g2 - log(n_obs-2)*2; -end + end function [g2, bic] = independence_chain_test(d) @@ -162,18 +162,18 @@ trans = zeros(2,2); for ind_1 = 2:n_obs trans(d(ind_1-1)+1,d(ind_1)+1)=trans(d(ind_1-1)+1,d(ind_1)+1)+1; end -dcm1 = n_obs - 1; +dcm1 = n_obs - 1; g2 = 0; % Compute the log likelihood ratio statistic for second-order MC vs first-order MC. G2 statistic of Bishop, Fienberg and Holland (1975) for ind_1 = 1:2 for ind_2 = 1:2 if trans(ind_1,ind_2) ~= 0 - fitted = ((trans(ind_1,1) + trans(ind_1,2))*(trans(1,ind_2) + trans(2,ind_2)))/dcm1; + fitted = ((trans(ind_1,1) + trans(ind_1,2))*(trans(1,ind_2) + trans(2,ind_2)))/dcm1; focus = trans(ind_1,ind_2); g2 = g2 + log(focus/fitted)*focus; end end end -g2 = g2*2; +g2 = g2*2; bic = g2 - log(dcm1); end diff --git a/matlab/convert_dyn_45_to_44.m b/matlab/convert_dyn_45_to_44.m index ba3dbc671f..14859d6786 100644 --- a/matlab/convert_dyn_45_to_44.m +++ b/matlab/convert_dyn_45_to_44.m @@ -40,7 +40,7 @@ if isfield(oo_,'PointForecast') oo_.MeanForecast.(moment_names{moment_iter}).(var_names{var_iter})=... [oo_.SmoothedVariables.(moment_names{moment_iter}).(var_names{var_iter})(:,end)*ones(M_.maximum_endo_lag,1) oo_.MeanForecast.(moment_names{moment_iter}).(var_names{var_iter})]; oo_.PointForecast.(moment_names{moment_iter}).(var_names{var_iter})=... - [oo_.SmoothedVariables.(moment_names{moment_iter}).(var_names{var_iter})(:,end)*ones(M_.maximum_endo_lag,1) oo_.PointForecast.(moment_names{moment_iter}).(var_names{var_iter})]; + [oo_.SmoothedVariables.(moment_names{moment_iter}).(var_names{var_iter})(:,end)*ones(M_.maximum_endo_lag,1) oo_.PointForecast.(moment_names{moment_iter}).(var_names{var_iter})]; else oo_.MeanForecast.(moment_names{moment_iter}).(var_names{var_iter})=... [oo_.SmoothedVariables.(moment_names{moment_iter}).(var_names{var_iter})(end)*ones(M_.maximum_endo_lag,1); oo_.MeanForecast.(moment_names{moment_iter}).(var_names{var_iter})]; @@ -106,7 +106,7 @@ if isfield(oo_,'UpdatedVariables') for ii=1:length(names) %make sure Bayesian fields are not affected if ~strcmp(names{ii},'Mean') && ~strcmp(names{ii},'Median') && ~strcmp(names{ii},'deciles') ... - && ~strcmp(names{ii},'Var') && ~strcmp(names{ii},'HPDinf') && ~strcmp(names{ii},'HPDsup') + && ~strcmp(names{ii},'Var') && ~strcmp(names{ii},'HPDinf') && ~strcmp(names{ii},'HPDsup') current_var_index=find(strmatch(names{ii},deblank(M_.endo_names),'exact')); if options_.loglinear == 1 %logged steady state must be used constant_current_variable=log(oo_.dr.ys(current_var_index)); @@ -127,7 +127,7 @@ if isfield(oo_,'FilteredVariables') for ii=1:length(names) %make sure Bayesian fields are not affected if ~strcmp(names{ii},'Mean') && ~strcmp(names{ii},'Median') && ~strcmp(names{ii},'deciles') ... - && ~strcmp(names{ii},'Var') && ~strcmp(names{ii},'HPDinf') && ~strcmp(names{ii},'HPDsup') + && ~strcmp(names{ii},'Var') && ~strcmp(names{ii},'HPDinf') && ~strcmp(names{ii},'HPDsup') current_var_index=find(strmatch(names{ii},deblank(M_.endo_names),'exact')); if options_.loglinear == 1 %logged steady state must be used constant_current_variable=log(oo_.dr.ys(current_var_index)); @@ -147,11 +147,11 @@ end if ~isempty(options_.nk) && options_.nk ~= 0 && ~isempty(bayestopt_) if ~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.pshape> 0) && options_.load_mh_file)) %no Bayesian estimation positions_in_decision_order=oo_.dr.inv_order_var(bayestopt_.smoother_var_list(bayestopt_.smoother_saved_var_list)); - if options_.loglinear == 1 %logged steady state must be used - constant_all_variables=log(oo_.dr.ys(bayestopt_.smoother_var_list(bayestopt_.smoother_saved_var_list))); - elseif options_.loglinear == 0 %unlogged steady state must be used - constant_all_variables=oo_.dr.ys(bayestopt_.smoother_var_list(bayestopt_.smoother_saved_var_list)); - end + if options_.loglinear == 1 %logged steady state must be used + constant_all_variables=log(oo_.dr.ys(bayestopt_.smoother_var_list(bayestopt_.smoother_saved_var_list))); + elseif options_.loglinear == 0 %unlogged steady state must be used + constant_all_variables=oo_.dr.ys(bayestopt_.smoother_var_list(bayestopt_.smoother_saved_var_list)); + end if ~(options_.selected_variables_only && ~(options_.forecast > 0)) %happens only when selected_variables_only is not used oo_.FilteredVariablesKStepAhead(:,positions_in_decision_order,:)=oo_.FilteredVariablesKStepAhead-constant_all_variables; if ~isempty(PK) %get K-step ahead variances @@ -182,11 +182,11 @@ end %Deal with OSR if ~isempty(M_.osr.variable_weights) - evalin('base','optim_weights_=M_.osr.variable_weights') + evalin('base','optim_weights_=M_.osr.variable_weights') end if ~isempty(M_.osr.variable_indices) - evalin('base','obj_var_=M_.osr.variable_indices') + evalin('base','obj_var_=M_.osr.variable_indices') end if ~isempty(M_.osr.param_names) - evalin('base','osr_params_=char(M_.osr.param_names)') + evalin('base','osr_params_=char(M_.osr.param_names)') end diff --git a/matlab/convert_oo_.m b/matlab/convert_oo_.m index d7cdac1f88..914cc0adbe 100644 --- a/matlab/convert_oo_.m +++ b/matlab/convert_oo_.m @@ -81,5 +81,5 @@ else end eval(['oo_ = convert_dyn_' strrep(new_from_ver, '.', '') '_to_' ... - strrep(to_ver, '.', '') '(M_, options_, oo_);']); + strrep(to_ver, '.', '') '(M_, options_, oo_);']); end diff --git a/matlab/correlation_mc_analysis.m b/matlab/correlation_mc_analysis.m index 94388f2fda..5ba0ca813e 100644 --- a/matlab/correlation_mc_analysis.m +++ b/matlab/correlation_mc_analysis.m @@ -137,7 +137,7 @@ end function oo_ = fill_output_structure(var1,var2,type,oo_,moment,lag,result) switch moment - case {'Mean','Median','Variance','HPDinf','HPDsup'} + case {'Mean','Median','Variance','HPDinf','HPDsup'} oo_.([type, 'TheoreticalMoments']).dsge.correlation.(moment).(var1).(var2)(lag,1) = result; case {'deciles','density'} oo_.([type, 'TheoreticalMoments']).dsge.correlation.(moment).(var1).(var2)(lag,1) = {result}; diff --git a/matlab/cosn.m b/matlab/cosn.m index 33bba8c4e8..b64245e7b8 100644 --- a/matlab/cosn.m +++ b/matlab/cosn.m @@ -37,6 +37,3 @@ if rank(yhat) else co=0; end - - - diff --git a/matlab/covariance_mc_analysis.m b/matlab/covariance_mc_analysis.m index 60753407b4..16b46eb9a6 100644 --- a/matlab/covariance_mc_analysis.m +++ b/matlab/covariance_mc_analysis.m @@ -1,7 +1,7 @@ function oo_ = covariance_mc_analysis(NumberOfSimulations,type,dname,fname,vartan,nvar,var1,var2,mh_conf_sig,oo_,options_) % This function analyses the (posterior or prior) distribution of the % endogenous variables' covariance matrix. -% +% % INPUTS % NumberOfSimulations [integer] scalar, number of simulations. % type [string] 'prior' or 'posterior' @@ -14,7 +14,7 @@ function oo_ = covariance_mc_analysis(NumberOfSimulations,type,dname,fname,varta % mh_conf_sig [double] 2 by 1 vector with upper % and lower bound of HPD intervals % oo_ [structure] Dynare structure where the results are saved. -% options_ [structure] Dynare options structure +% options_ [structure] Dynare options structure % % OUTPUTS % oo_ [structure] Dynare structure where the results are saved. @@ -64,7 +64,7 @@ var1=deblank(var1); var2=deblank(var2); if isfield(oo_,[ TYPE 'TheoreticalMoments']) - temporary_structure = oo_.([TYPE, 'TheoreticalMoments']); + temporary_structure = oo_.([TYPE, 'TheoreticalMoments']); if isfield(temporary_structure,'dsge') temporary_structure = oo_.([TYPE, 'TheoreticalMoments']).dsge; if isfield(temporary_structure,'covariance') @@ -104,17 +104,17 @@ for file = 1:length(ListOfFiles) temp=Covariance_matrix(:,cov_pos)./(sqrt(Covariance_matrix(:,var_pos_1)).*sqrt(Covariance_matrix(:,var_pos_2))); temp(Covariance_matrix(:,cov_pos)==0)=0; %filter out 0 correlations that would result in 0/0 tmp_corr_mat(i1:i2)=temp; - end + end i1 = i2+1; end if options_.estimation.moments_posterior_density.indicator [p_mean, p_median, p_var, hpd_interval, p_deciles, density] = ... - posterior_moments(tmp,1,mh_conf_sig); + posterior_moments(tmp,1,mh_conf_sig); oo_.([TYPE, 'TheoreticalMoments']).dsge.covariance.density.(var1).(var2) = density; else [p_mean, p_median, p_var, hpd_interval, p_deciles] = ... - posterior_moments(tmp,0,mh_conf_sig); + posterior_moments(tmp,0,mh_conf_sig); end oo_.([TYPE, 'TheoreticalMoments']).dsge.covariance.Mean.(var1).(var2) = p_mean; oo_.([TYPE, 'TheoreticalMoments']).dsge.covariance.Median.(var1).(var2) = p_median; diff --git a/matlab/csolve.m b/matlab/csolve.m index b4d79229be..a0db73369f 100644 --- a/matlab/csolve.m +++ b/matlab/csolve.m @@ -12,7 +12,7 @@ function [x,rc] = csolve(FUN,x,gradfun,crit,itmax,varargin) % the equation is solved. % itmax: the solver stops when this number of iterations is reached, with rc=4 % varargin: in this position the user can place any number of additional arguments, all -% of which are passed on to FUN and gradfun (when it is non-empty) as a list of +% of which are passed on to FUN and gradfun (when it is non-empty) as a list of % arguments following x. % rc: 0 means normal solution, 1 and 3 mean no solution despite extremely fine adjustments % in step length (very likely a numerical problem, or a discontinuity). 4 means itmax @@ -60,7 +60,7 @@ if isempty(varargin) f0=feval(FUN,x); else f0=feval(FUN,x,varargin{:}); -end +end af0=sum(abs(f0)); af00=af0; itct=0; diff --git a/matlab/cubature_with_gaussian_weight.m b/matlab/cubature_with_gaussian_weight.m index 55f7d2a233..8e31d1f842 100644 --- a/matlab/cubature_with_gaussian_weight.m +++ b/matlab/cubature_with_gaussian_weight.m @@ -29,8 +29,8 @@ function [nodes, weights] = cubature_with_gaussian_weight(d,n,method) %! The routine returns nodes and associated weights to compute a multivariate integral of the form: %! %! \int_D f(x)*\exp(-<x,x>) dx -%! -%! +%! +%! %! @end deftypefn %@eod: @@ -52,7 +52,7 @@ function [nodes, weights] = cubature_with_gaussian_weight(d,n,method) % along with Dynare. If not, see <http://www.gnu.org/licenses/>. % AUTHOR(S) stephane DOT adjemian AT univ DASH lemans DOT fr - + % Set default. if nargin<3 || isempty(method) method = 'Stroud'; @@ -90,7 +90,7 @@ if strcmp(method,'Stroud') && isequal(n,5) nodes = zeros(d,m); weights = zeros(m,1); % Set the weight for the first node (0) - weights(1) = A; + weights(1) = A; skip = 1; % Set the remaining nodes and associated weights. nodes(:,skip+(1:d)) = r*eye(d); @@ -117,20 +117,20 @@ end function v = e(n,i) - v = zeros(n,1); - v(i) = 1; - +v = zeros(n,1); +v(i) = 1; + function m = ee(n,i,j) - m = zeros(n,4); - m(:,1) = e(n,i)+e(n,j); - m(:,2) = e(n,i)-e(n,j); - m(:,3) = -m(:,2); - m(:,4) = -m(:,1); - +m = zeros(n,4); +m(:,1) = e(n,i)+e(n,j); +m(:,2) = e(n,i)-e(n,j); +m(:,3) = -m(:,2); +m(:,4) = -m(:,1); + %@test:1 %$ % Set problem %$ d = 4; -%$ +%$ %$ t = zeros(5,1); %$ %$ % Call the tested routine @@ -289,7 +289,7 @@ function m = ee(n,i,j) %@test:5 %$ % Set problem %$ d = 5; -%$ +%$ %$ t = zeros(6,1); %$ %$ % Call the tested routine @@ -333,7 +333,7 @@ function m = ee(n,i,j) %@test:6 %$ % Set problem %$ d = 3; -%$ +%$ %$ t = zeros(4,1); %$ %$ % Call the tested routine diff --git a/matlab/cycle_reduction.m b/matlab/cycle_reduction.m index c1edc26c1b..be8fdb3e8f 100644 --- a/matlab/cycle_reduction.m +++ b/matlab/cycle_reduction.m @@ -76,7 +76,7 @@ id0 = 1:n; id2 = id0+n; cont = 1; -while cont +while cont tmp = ([A0; A2]/A1)*[A0 A2]; A1 = A1 - tmp(id0,id2) - tmp(id2,id0); A0 = -tmp(id0,id0); @@ -97,7 +97,7 @@ while cont info(2) = log(norm(A1,1)); end return - end + end it = it + 1; end diff --git a/matlab/datatomfile.m b/matlab/datatomfile.m index 4f6a5ff49a..76928c77fa 100644 --- a/matlab/datatomfile.m +++ b/matlab/datatomfile.m @@ -3,16 +3,16 @@ function datatomfile (s, var_list, names) % This command saves the simulation results in a text file. The name of each % variable preceeds the corresponding results. This command must follow SIMUL % or STOCH_SIMUL commands. -% -% INPUTS +% +% INPUTS % - s: data file name % - var_list: vector of selected endogenous variables % - names: vector of strings (alternative names for the endogenous variables in the data file) % -% OUTPUTS +% OUTPUTS % none % -% REMARKS +% REMARKS % Only the first argument is mandatory. If only one input argument is % provided, all the variables as defined in M_.endo_names will be saved in % the generated m file. @@ -36,7 +36,7 @@ function datatomfile (s, var_list, names) global M_ oo_ -% Open the data file. +% Open the data file. sm=[s,'.m']; fid=fopen(sm,'w') ; @@ -65,8 +65,8 @@ for i=1:n end end stack = dbstack; - fprintf(fid,'%% Dataset generated by %s.\n',stack(2).file); - fprintf(fid,['%% ' datestr(now,0) '\n']); +fprintf(fid,'%% Dataset generated by %s.\n',stack(2).file); +fprintf(fid,['%% ' datestr(now,0) '\n']); % Save the selected data. for i = 1:n fprintf(fid,[strtrim(names(i,:)), ' = ['],'\n') ; @@ -78,4 +78,3 @@ end % Close the data file. fclose(fid) ; - diff --git a/matlab/dcompare.m b/matlab/dcompare.m index 6efc5ae272..9a6ac2c7b9 100644 --- a/matlab/dcompare.m +++ b/matlab/dcompare.m @@ -52,5 +52,3 @@ z = mean(mean(abs(x(j,i)-y(j,i)))) ; disp (['The mean absolute difference between set ' s1(1,:) 'and set ' s1(2,:)]) ; disp (['is : ' num2str(z)]) ; return ; - - diff --git a/matlab/delete_mh_history_files.m b/matlab/delete_mh_history_files.m index 64b720ec9b..635bb9c94d 100644 --- a/matlab/delete_mh_history_files.m +++ b/matlab/delete_mh_history_files.m @@ -1,5 +1,5 @@ function info = delete_mh_history_files(MetropolisFolder, ModelName) - + % Copyright (C) 2013 Dynare Team % % This file is part of Dynare. diff --git a/matlab/discretionary_policy_1.m b/matlab/discretionary_policy_1.m index 931d3b596f..9657dfa023 100644 --- a/matlab/discretionary_policy_1.m +++ b/matlab/discretionary_policy_1.m @@ -39,7 +39,7 @@ if isfield(M_,'orig_model') M_.maximum_lag = orig_model.maximum_lag; M_.maximum_endo_lag = orig_model.maximum_endo_lag; else - M_.orig_model = M_; + M_.orig_model = M_; end beta = get_optimal_policy_discount_factor(M_.params,M_.param_names); @@ -53,10 +53,10 @@ if isfield(M_,'orig_model') MaxLead = orig_model.maximum_lead; MaxLag = orig_model.maximum_lag; else - endo_names = M_.endo_names; - endo_nbr = M_.endo_nbr; - MaxLag=M_.maximum_lag; - MaxLead=M_.maximum_lead; + endo_names = M_.endo_names; + endo_nbr = M_.endo_nbr; + MaxLag=M_.maximum_lag; + MaxLead=M_.maximum_lead; lead_lag_incidence = M_.lead_lag_incidence; end @@ -64,7 +64,7 @@ end if options_.steadystate_flag % explicit steady state file [junk,M_.params,info] = evaluate_steady_state_file(oo_.steady_state,[oo_.exo_steady_state; oo_.exo_det_steady_state],M_, ... - options_,0); + options_,0); end [U,Uy,W] = feval([M_.fname,'_objective_static'],zeros(endo_nbr,1),[], M_.params); if any(any(Uy~=0)) @@ -96,32 +96,32 @@ eq_nbr= size(jacobia_,1); instr_nbr=endo_nbr-eq_nbr; if instr_nbr==0 - error('discretionary_policy:: There are no available instruments, because the model has as many equations as variables.') + error('discretionary_policy:: There are no available instruments, because the model has as many equations as variables.') end if size(Instruments,1)~= instr_nbr - error('discretionary_policy:: There are more declared instruments than omitted equations.') -end + error('discretionary_policy:: There are more declared instruments than omitted equations.') +end instr_id=nan(instr_nbr,1); for j=1:instr_nbr - vj=deblank(Instruments(j,:)); - vj_id=strmatch(vj,endo_names,'exact'); - if ~isempty(vj_id) - instr_id(j)=vj_id; - else - error([mfilename,':: instrument ',vj,' not found']) - end + vj=deblank(Instruments(j,:)); + vj_id=strmatch(vj,endo_names,'exact'); + if ~isempty(vj_id) + instr_id(j)=vj_id; + else + error([mfilename,':: instrument ',vj,' not found']) + end end Indices={'lag','0','lead'}; iter=1; for j=1:numel(Indices) eval(['A',Indices{j},'=zeros(eq_nbr,endo_nbr);']) - if strcmp(Indices{j},'0')||(strcmp(Indices{j},'lag') && MaxLag)||(strcmp(Indices{j},'lead') && MaxLead) - [junk,row,col]=find(lead_lag_incidence(iter,:)); - eval(['A',Indices{j},'(:,row)=jacobia_(:,col);']) - iter=iter+1; - end + if strcmp(Indices{j},'0')||(strcmp(Indices{j},'lag') && MaxLag)||(strcmp(Indices{j},'lead') && MaxLead) + [junk,row,col]=find(lead_lag_incidence(iter,:)); + eval(['A',Indices{j},'(:,row)=jacobia_(:,col);']) + iter=iter+1; + end end B=jacobia_(:,nnz(iyv)+1:end); @@ -131,17 +131,17 @@ solve_maxit = options_.dp.maxit; discretion_tol = options_.discretionary_tol; if ~isempty(Hold) - [H,G,info]=discretionary_policy_engine(Alag,A0,Alead,B,W,instr_id,beta,solve_maxit,discretion_tol,qz_criterium,Hold); + [H,G,info]=discretionary_policy_engine(Alag,A0,Alead,B,W,instr_id,beta,solve_maxit,discretion_tol,qz_criterium,Hold); else - [H,G,info]=discretionary_policy_engine(Alag,A0,Alead,B,W,instr_id,beta,solve_maxit,discretion_tol,qz_criterium); + [H,G,info]=discretionary_policy_engine(Alag,A0,Alead,B,W,instr_id,beta,solve_maxit,discretion_tol,qz_criterium); end if info dr=[]; return else - Hold=H; %save previous solution - % Hold=[]; use this line if persistent command is not used. + Hold=H; %save previous solution + % Hold=[]; use this line if persistent command is not used. end % set the state dr=oo_.dr; @@ -159,7 +159,7 @@ dr.ys=ys; % <--- dr.ys =zeros(NewEndo_nbr,1); function ys=NondistortionarySteadyState(M_) if exist([M_.fname,'_steadystate.m'],'file') - eval(['ys=',M_.fname,'_steadystate.m;']) + eval(['ys=',M_.fname,'_steadystate.m;']) else - ys=zeros(M_.endo_nbr,1); + ys=zeros(M_.endo_nbr,1); end diff --git a/matlab/discretionary_policy_engine.m b/matlab/discretionary_policy_engine.m index f86276eecf..05c781ae4a 100644 --- a/matlab/discretionary_policy_engine.m +++ b/matlab/discretionary_policy_engine.m @@ -1,23 +1,23 @@ function [H,G,retcode]=discretionary_policy_engine(AAlag,AA0,AAlead,BB,bigw,instr_id,beta,solve_maxit,discretion_tol,qz_criterium,H00,verbose) % Solves the discretionary problem for a model of the form: -% +% % Loss=E_0 sum_{t=0}^{\infty} beta^t [y_t'*W*y+x_t'*Q*x_t] % subject to % AAlag*yy_{t-1}+AA0*yy_t+AAlead*yy_{t+1}+BB*e=0 -% +% % with W the weight on the variables in vector y_t. -% +% % The solution takes the form % y_t=H*y_{t-1}+G*e_t % where H=[H1;F1] and G=[H2;F2]. -% +% % We use the Dennis (2007, Macroeconomic Dynamics) algorithm and so we need % to re-write the model in the form % A0*y_t=A1*y_{t-1}+A2*y_{t+1}+A3*x_t+A4*x_{t+1}+A5*e_t, with W the % weight on the y_t vector and Q the weight on the x_t vector of % instruments. -% +% % Inputs: % AAlag [double] matrix of coefficients on lagged % variables @@ -28,7 +28,7 @@ function [H,G,retcode]=discretionary_policy_engine(AAlag,AA0,AAlead,BB,bigw,inst % BB [double] matrix of coefficients on % shocks % bigw [double] matrix of coefficients on variables in -% loss/objective function; stacks [W and Q] +% loss/objective function; stacks [W and Q] % instr_id [double] location vector of the instruments in the yy_t vector. % beta [scalar] planner discount factor % solve_maxit [scalar] maximum number of iterations @@ -41,12 +41,12 @@ function [H,G,retcode]=discretionary_policy_engine(AAlag,AA0,AAlead,BB,bigw,inst % H [double] (endo_nbr*endo_nbr) solution matrix for endogenous % variables, stacks [H1 and H1] % G [double] (endo_nbr*exo_nbr) solution matrix for shocks, stacks [H2 and F2] -% +% % retcode [scalar] return code % % Algorithm: % Dennis, Richard (2007): Optimal policy in rational expectations models: new solution algorithms, -% Macroeconomic Dynamics, 11, 31�55. +% Macroeconomic Dynamics, 11, 3155. % Copyright (C) 2007-2017 Dynare Team % @@ -121,10 +121,10 @@ while 1 end D=A0-A2*H1-A4*F1; %equation (20) Dinv=inv(D); - A3DPD=A3'*Dinv'*P*Dinv; + A3DPD=A3'*Dinv'*P*Dinv; F1=-(Q+A3DPD*A3)\(A3DPD*A1); %component of (26) H1=Dinv*(A1+A3*F1); %component of (27) - + [rcode,NQ]=CheckConvergence([H1;F1]-[H10;F10],iter,solve_maxit,discretion_tol); if rcode break @@ -174,7 +174,7 @@ else H(instr_id,endo_augm_id)=F1; G(endo_augm_id,:)=H2; G(instr_id,:)=F2; - + % Account for auxilliary variables H(:,instr_id(aux))=H(:,end-(AuxiliaryVariables_nbr-1:-1:0)); H=H(1:endo_nbr,1:endo_nbr); @@ -253,7 +253,7 @@ end function v = SylvesterHessenbergSchur(d,g,h) % -% DSYLHS Solves a discrete time sylvester equation using the +% DSYLHS Solves a discrete time sylvester equation using the % Hessenberg-Schur algorithm % % v = DSYLHS(g,d,h) computes the matrix v that satisfies the @@ -301,7 +301,7 @@ if i< n i = i+1; else A = [w-g*h(i,i) (-g*h(i+1,i));... - -g*h(i,i+1) w-g*h(i+1,i+1)]; + -g*h(i,i+1) w-g*h(i+1,i+1)]; C = [d(:,i); d(:,i+1)]; X = A\C; v(:,i) = X(1:m,:); @@ -320,9 +320,9 @@ while i<n i = i+1; else A = [w - g*h(i,i) (-g*h(i+1,i)); ... - -g*h(i,i+1) w - g*h(i+1,i+1)]; + -g*h(i,i+1) w - g*h(i+1,i+1)]; C = [d(:,i) + temp*h(1:b,i); ... - d(:,i+1) + temp*h(1:b,i+1)]; + d(:,i+1) + temp*h(1:b,i+1)]; X = A\C; v(:,i) = X(1:m,:); v(:,i+1) = X(m+1:2*m, :); diff --git a/matlab/disp_dr.m b/matlab/disp_dr.m index d16ba24238..f8f4e4b4cb 100644 --- a/matlab/disp_dr.m +++ b/matlab/disp_dr.m @@ -7,7 +7,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-2017 Dynare Team % % This file is part of Dynare. @@ -80,7 +80,7 @@ var_name_width=max([max(size(deblank(M_.endo_names(k1(ivar),:)),2)),max(size(deb %deal with covariances if order > 1 - var_name_width=max(2*(var_name_width+aux_var_additional_characters)+2,20); %account for covariances, separated by comma + var_name_width=max(2*(var_name_width+aux_var_additional_characters)+2,20); %account for covariances, separated by comma else var_name_width=max(var_name_width+aux_var_additional_characters,20); end @@ -90,7 +90,7 @@ label_format = sprintf('%%-%ds',var_name_width); %% start displayimg disp('POLICY AND TRANSITION FUNCTIONS') % variable names -str = char(32*ones(1,var_name_width)); +str = char(32*ones(1,var_name_width)); for i=1:nvar str = [str sprintf(header_label_format,deblank(M_.endo_names(k1(ivar(i)),:)))]; end @@ -232,7 +232,7 @@ for i = 1:length(M_.aux_vars) if M_.aux_vars(i).endo_index == aux_index switch M_.aux_vars(i).type case 0 - str = sprintf('%s(%d)',deblank(M_.endo_names(aux_index,:)),aux_lead_lag); + str = sprintf('%s(%d)',deblank(M_.endo_names(aux_index,:)),aux_lead_lag); return case 1 orig_name = deblank(M_.endo_names(M_.aux_vars(i).orig_index, :)); @@ -256,10 +256,10 @@ error(sprintf('Could not find aux var: %s', M_.endo_names(aux_index, :))) end function [str,flag]=get_print_string(str,x,value_format_zero,value_format_float,flag,options_) - if abs(x) >= options_.dr_display_tol - flag = 1; - str = [str sprintf(value_format_float,x)]; - else - str = [str sprintf(value_format_zero,0)]; - end +if abs(x) >= options_.dr_display_tol + flag = 1; + str = [str sprintf(value_format_float,x)]; +else + str = [str sprintf(value_format_zero,0)]; +end end \ No newline at end of file diff --git a/matlab/disp_identification.m b/matlab/disp_identification.m index 2bc6d8db05..b8a3421d57 100644 --- a/matlab/disp_identification.m +++ b/matlab/disp_identification.m @@ -118,7 +118,7 @@ if any(idemodel.ino) disp([' [',name{jx(1)},',',name{jy(1)},'] are PAIRWISE collinear (with tol = 1.e-10) !' ]) end end - + end skipline() for j=1:npar @@ -133,23 +133,23 @@ if any(idemodel.ino) end end end -% if npar>(j+1), -% [ipair, jpair] = find(squeeze(idemodel.Pco(j,j+1:end,:))'>(1-1.e-10)); -% else -% [ipair, jpair] = find(squeeze(idemodel.Pco(j,j+1:end,:))>(1-1.e-10)); -% end -% if ~isempty(jpair), -% for jx=j+1:npar, -% ixp = find(jx==(jpair+j)); -% if ~isempty(ixp) -% if SampleSize > 1, -% disp([' [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10) for ',num2str(length(ixp)/SampleSize*100),'% of MC runs!' ]) -% else -% disp([' [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10)!' ]) -% end -% end -% end -% end + % if npar>(j+1), + % [ipair, jpair] = find(squeeze(idemodel.Pco(j,j+1:end,:))'>(1-1.e-10)); + % else + % [ipair, jpair] = find(squeeze(idemodel.Pco(j,j+1:end,:))>(1-1.e-10)); + % end + % if ~isempty(jpair), + % for jx=j+1:npar, + % ixp = find(jx==(jpair+j)); + % if ~isempty(ixp) + % if SampleSize > 1, + % disp([' [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10) for ',num2str(length(ixp)/SampleSize*100),'% of MC runs!' ]) + % else + % disp([' [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10)!' ]) + % end + % end + % end + % end end if ~any(idemodel.ino) && ~any(any(idemodel.ind0==0)) @@ -167,10 +167,10 @@ if any(idemoments.ino) end % disp('WARNING !!!') % disp(['The rank of J (moments) is deficient for ', num2str(length(find(idemoments.ino))/SampleSize*100),'% of MC runs!' ]), -% indno=[]; -% for j=1:SampleSize, indno=[indno;idemoments.indno{j}]; end -% freqno = mean(indno)*100; -% ifreq=find(freqno); + % indno=[]; + % for j=1:SampleSize, indno=[indno;idemoments.indno{j}]; end + % freqno = mean(indno)*100; + % ifreq=find(freqno); % disp('MOMENT RANK FAILURE DUE TO COLLINEARITY OF PARAMETERS:'); skipline() for j=1:npar @@ -199,7 +199,7 @@ if any(idemoments.ino) disp([' [',name{jx(1)},',',name{jy(1)},'] are PAIRWISE collinear (with tol = 1.e-10) !' ]) end end - + end skipline() for j=1:npar @@ -214,25 +214,25 @@ if any(idemoments.ino) end end end -% if npar>(j+1), -% [ipair, jpair] = find(squeeze(idemoments.Pco(j,j+1:end,:))'>(1-1.e-10)); -% else -% [ipair, jpair] = find(squeeze(idemoments.Pco(j,j+1:end,:))>(1-1.e-10)); -% end -% if ~isempty(jpair), -% for jx=j+1:npar, -% ixp = find(jx==(jpair+j)); -% if ~isempty(ixp) -% if SampleSize > 1 -% disp([' [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10) for ',num2str(length(ixp)/SampleSize*100),'% of MC runs!' ]) -% else -% disp([' [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10) !' ]) -% end -% end -% end -% end -% end -% end + % if npar>(j+1), + % [ipair, jpair] = find(squeeze(idemoments.Pco(j,j+1:end,:))'>(1-1.e-10)); + % else + % [ipair, jpair] = find(squeeze(idemoments.Pco(j,j+1:end,:))>(1-1.e-10)); + % end + % if ~isempty(jpair), + % for jx=j+1:npar, + % ixp = find(jx==(jpair+j)); + % if ~isempty(ixp) + % if SampleSize > 1 + % disp([' [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10) for ',num2str(length(ixp)/SampleSize*100),'% of MC runs!' ]) + % else + % disp([' [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10) !' ]) + % end + % end + % end + % end + % end + % end end if ~any(idemoments.ino) && ~any(any(idemoments.ind0==0)) skipline() @@ -255,12 +255,12 @@ end % if advanced && (~options_.noprint), % for j=1:length(kokP), % dyntable([name{kokP(j)},' pairwise correlations in the model'],char(' ','min','mean','max'), ... -% char(name{jpM{j}}),[pminM{j}' pmeanM{j}' pmaxM{j}'],10,10,3); +% char(name{jpM{j}}),[pminM{j}' pmeanM{j}' pmaxM{j}'],10,10,3); % end -% +% % for j=1:length(kokPJ), % dyntable([name{kokPJ(j)},' pairwise correlations in J moments'],char(' ','min','mean','max'), ... -% char(name{jpJ{j}}),[pminJ{j}' pmeanJ{j}' pmaxJ{j}'],10,10,3); +% char(name{jpJ{j}}),[pminJ{j}' pmeanJ{j}' pmaxJ{j}'],10,10,3); % end % end % disp(' ') diff --git a/matlab/disp_model_summary.m b/matlab/disp_model_summary.m index 394bc00d9d..563efad9ff 100644 --- a/matlab/disp_model_summary.m +++ b/matlab/disp_model_summary.m @@ -4,7 +4,7 @@ function disp_model_summary(M,dr,options) % displays the model summary % % INPUTS -% M [matlab structure] Definition of the model. +% M [matlab structure] Definition of the model. % dr [matlab structure] Decision rules % options [matlab structure] Options % @@ -40,4 +40,3 @@ labels = deblank(M.exo_names); headers = char('Variables',labels); lh = size(labels,2)+2; dyntable(options,my_title,headers,labels,M.Sigma_e,lh,10,6); - diff --git a/matlab/disp_moments.m b/matlab/disp_moments.m index 9fd634c133..6e55bb5711 100644 --- a/matlab/disp_moments.m +++ b/matlab/disp_moments.m @@ -7,7 +7,7 @@ function oo_=disp_moments(y,var_list,M_,options_,oo_) % M_ [structure] Dynare's model structure % oo_ [structure] Dynare's results structure % options_ [structure] Dynare's options structure -% +% % OUTPUTS % oo_ [structure] Dynare's results structure, @@ -57,18 +57,18 @@ s2 = mean(y.*y); s = sqrt(s2); oo_.mean = transpose(m); oo_.var = y'*y/size(y,1); -oo_.skewness = (mean(y.^3)./s2.^1.5)'; +oo_.skewness = (mean(y.^3)./s2.^1.5)'; oo_.kurtosis = (mean(y.^4)./(s2.*s2)-3)'; labels = deblank(M_.endo_names(ivar,:)); labels_TeX = deblank(M_.endo_names_tex(ivar,:)); if options_.nomoments == 0 - z = [ m' s' s2' (mean(y.^3)./s2.^1.5)' (mean(y.^4)./(s2.*s2)-3)' ]; + z = [ m' s' s2' (mean(y.^3)./s2.^1.5)' (mean(y.^4)./(s2.*s2)-3)' ]; title='MOMENTS OF SIMULATED VARIABLES'; - + title=add_filter_subtitle(title,options_); - + headers=char('VARIABLE','MEAN','STD. DEV.','VARIANCE','SKEWNESS', ... 'KURTOSIS'); dyntable(options_,title,headers,labels,z,size(labels,2)+2,16,6); @@ -79,7 +79,7 @@ end if options_.nocorr == 0 corr = (y'*y/size(y,1))./(s'*s); - if options_.contemporaneous_correlation + if options_.contemporaneous_correlation oo_.contemporaneous_correlation = corr; end if options_.noprint == 0 @@ -98,7 +98,7 @@ if options_.nocorr == 0 end if options_.noprint == 0 && length(options_.conditional_variance_decomposition) - fprintf('\nSTOCH_SIMUL: conditional_variance_decomposition requires theoretical moments, i.e. periods=0.\n') + fprintf('\nSTOCH_SIMUL: conditional_variance_decomposition requires theoretical moments, i.e. periods=0.\n') end ar = options_.ar; @@ -119,7 +119,7 @@ if ar > 0 dyn_latex_table(M_,options_,title,'sim_autocorr_matrix',headers,labels_TeX,autocorr,size(labels_TeX,2)+2,8,4); end end - + end @@ -143,7 +143,7 @@ if ~options_.nodecomposition chol_S = chol(M_.Sigma_e(i_exo_var,i_exo_var)); %decompose rest shock_mat=zeros(options_.periods,M_.exo_nbr); %initialize shock_mat(:,i_exo_var)=oo_.exo_simul(:,i_exo_var)/chol_S; %invert construction of oo_.exo_simul from simult.m - + for shock_iter=1:length(i_exo_var) temp_shock_mat=zeros(size(shock_mat)); temp_shock_mat(:,i_exo_var(shock_iter))=shock_mat(:,i_exo_var(shock_iter)); @@ -156,9 +156,9 @@ if ~options_.nodecomposition if ~options_.noprint %options_.nomoments == 0 skipline() title='VARIANCE DECOMPOSITION SIMULATING ONE SHOCK AT A TIME (in percent)'; - + title=add_filter_subtitle(title,options_); - + headers = M_.exo_names; headers(M_.exo_names_orig_ord,:) = headers; headers = char(' ',headers); @@ -181,12 +181,12 @@ if ~options_.nodecomposition end end - + warning(warning_old_state); end function y=get_filtered_time_series(y,m,options_) - + if options_.hp_filter && ~options_.one_sided_hp_filter && ~options_.bandpass.indicator [hptrend,y] = sample_hp_filter(y,options_.hp_filter); elseif ~options_.hp_filter && options_.one_sided_hp_filter && ~options_.bandpass.indicator @@ -197,8 +197,8 @@ elseif ~options_.hp_filter && ~options_.one_sided_hp_filter && options_.bandpass y=data_temp.data; elseif ~options_.hp_filter && ~options_.one_sided_hp_filter && ~options_.bandpass.indicator y = bsxfun(@minus, y, m); -else +else error('disp_moments:: You cannot use more than one filter at the same time') end - + end \ No newline at end of file diff --git a/matlab/disp_steady_state.m b/matlab/disp_steady_state.m index 5424c6e3b2..81984ed685 100644 --- a/matlab/disp_steady_state.m +++ b/matlab/disp_steady_state.m @@ -1,11 +1,11 @@ function disp_steady_state(M,oo) % function disp_steady_state(M,oo) % computes and prints the steady state calculations -% +% % INPUTS % M structure of parameters % oo structure of results -% +% % OUTPUTS % none % diff --git a/matlab/disp_th_moments.m b/matlab/disp_th_moments.m index 7218ee1feb..014102f5cf 100644 --- a/matlab/disp_th_moments.m +++ b/matlab/disp_th_moments.m @@ -76,7 +76,7 @@ if size(stationary_vars, 1) > 0 if M_.exo_nbr > 1 && ~nodecomposition skipline() if options_.order == 2 - title='APPROXIMATED VARIANCE DECOMPOSITION (in percent)'; + title='APPROXIMATED VARIANCE DECOMPOSITION (in percent)'; else title='VARIANCE DECOMPOSITION (in percent)'; end @@ -86,7 +86,7 @@ if size(stationary_vars, 1) > 0 headers = char(' ',headers); lh = size(deblank(M_.endo_names(ivar(stationary_vars),:)),2)+2; dyntable(options_,title,headers,deblank(M_.endo_names(ivar(stationary_vars), ... - :)),100* ... + :)),100* ... oo_.gamma_y{options_.ar+2}(stationary_vars,:),lh,8,2); if options_.TeX headers=M_.exo_names_tex; @@ -97,7 +97,7 @@ if size(stationary_vars, 1) > 0 end end end - + conditional_variance_steps = options_.conditional_variance_decomposition; if length(conditional_variance_steps) StateSpaceModel.number_of_state_equations = M_.endo_nbr; @@ -107,10 +107,10 @@ if size(stationary_vars, 1) > 0 StateSpaceModel.state_innovations_covariance_matrix = M_.Sigma_e; StateSpaceModel.order_var = dr.order_var; oo_.conditional_variance_decomposition = conditional_variance_decomposition(StateSpaceModel,conditional_variance_steps,ivar); - + if options_.noprint == 0 display_conditional_variance_decomposition(oo_.conditional_variance_decomposition,conditional_variance_steps,... - ivar,M_,options_); + ivar,M_,options_); end end end @@ -124,13 +124,13 @@ end if options_.nocorr == 0 && size(stationary_vars, 1) > 0 corr = oo_.gamma_y{1}(i1,i1)./(sd(i1)*sd(i1)'); - if options_.contemporaneous_correlation + if options_.contemporaneous_correlation oo_.contemporaneous_correlation = corr; end if ~options_.noprint skipline() if options_.order == 2 - title='APPROXIMATED MATRIX OF CORRELATIONS'; + title='APPROXIMATED MATRIX OF CORRELATIONS'; else title='MATRIX OF CORRELATIONS'; end @@ -154,22 +154,22 @@ if options_.ar > 0 && size(stationary_vars, 1) > 0 z(:,i) = diag(oo_.gamma_y{i+1}(i1,i1)); end if ~options_.noprint - skipline() + skipline() if options_.order == 2 - title='APPROXIMATED COEFFICIENTS OF AUTOCORRELATION'; + title='APPROXIMATED COEFFICIENTS OF AUTOCORRELATION'; else title='COEFFICIENTS OF AUTOCORRELATION'; end title=add_filter_subtitle(title,options_); - labels = deblank(M_.endo_names(ivar(i1),:)); + labels = deblank(M_.endo_names(ivar(i1),:)); headers = char('Order ',int2str([1:options_.ar]')); lh = size(labels,2)+2; dyntable(options_,title,headers,labels,z,lh,8,4); if options_.TeX - labels = deblank(M_.endo_names_tex(ivar(i1),:)); + labels = deblank(M_.endo_names_tex(ivar(i1),:)); headers=char('Order ',int2str([1:options_.ar]')); lh = size(labels,2)+2; dyn_latex_table(M_,options_,title,'th_autocorr_matrix',headers,labels,z,lh,8,4); end - end + end end diff --git a/matlab/display_conditional_variance_decomposition.m b/matlab/display_conditional_variance_decomposition.m index 8aab292d00..4f5836925e 100644 --- a/matlab/display_conditional_variance_decomposition.m +++ b/matlab/display_conditional_variance_decomposition.m @@ -1,8 +1,8 @@ function display_conditional_variance_decomposition(conditional_decomposition_array,Steps,SubsetOfVariables,M_,options_) % This function displays the conditional variance decomposition of a given state space model % for a subset of endogenous variables. -% -% INPUTS +% +% INPUTS % conditional_decomposition_array [matrix] Output matrix from compute_conditional_variance_decomposition % Steps [integer] 1*h vector of dates. % SubsetOfVariables [integer] 1*q vector of indices. @@ -10,7 +10,7 @@ function display_conditional_variance_decomposition(conditional_decomposition_ar % Model description % options_ [structure] Dynare structure containing the % options -% OUTPUTS +% OUTPUTS % none % % Copyright (C) 2010-2016 Dynare Team @@ -56,10 +56,10 @@ for i=1:length(Steps) dyntable(options_,'',headers,... deblank(M_.endo_names(SubsetOfVariables,:)),... vardec_i,lh,8,2); - if options_.TeX - labels_TeX = deblank(M_.endo_names_tex(SubsetOfVariables,:)); - headers_TeX=char('',deblank(M_.exo_names_tex)); - lh = size(labels_TeX,2)+2; - dyn_latex_table(M_,options_,[title,'; Period ' int2str(Steps(i))],['th_var_decomp_cond_h',int2str(Steps(i))],headers_TeX,labels_TeX,vardec_i,lh,8,2); - end + if options_.TeX + labels_TeX = deblank(M_.endo_names_tex(SubsetOfVariables,:)); + headers_TeX=char('',deblank(M_.exo_names_tex)); + lh = size(labels_TeX,2)+2; + dyn_latex_table(M_,options_,[title,'; Period ' int2str(Steps(i))],['th_var_decomp_cond_h',int2str(Steps(i))],headers_TeX,labels_TeX,vardec_i,lh,8,2); + end end \ No newline at end of file diff --git a/matlab/display_estimation_results_table.m b/matlab/display_estimation_results_table.m index 152ea006b9..aaf23cb4fe 100644 --- a/matlab/display_estimation_results_table.m +++ b/matlab/display_estimation_results_table.m @@ -1,20 +1,20 @@ function oo_=display_estimation_results_table(xparam1,stdh,M_,options_,estim_params_,bayestopt_,oo_,pnames,table_title,field_name) %function oo_=display_results_table(xparam1,stdh,M_,estim_params_,bayestopt_,oo_,pnames,table_title,field_name) % Display estimation results on screen and write them to TeX-file -% -% INPUTS +% +% INPUTS % o xparam1 [double] (p*1) vector of estimate parameters. % o stdh [double] (p*1) vector of estimate parameters. -% o M_ Matlab's structure describing the Model (initialized by dynare, see @ref{M_}). +% o M_ Matlab's structure describing the Model (initialized by dynare, see @ref{M_}). % o estim_params_ Matlab's structure describing the estimated_parameters (initialized by dynare, see @ref{estim_params_}). % o options_ Matlab's structure describing the options (initialized by dynare, see @ref{options_}). % o bayestopt_ Matlab's structure describing the priors (initialized by dynare, see @ref{bayesopt_}). % o oo_ Matlab's structure gathering the results (initialized by dynare, see @ref{oo_}). -% o pnames [string] Character Array storing the names for prior distributions -% o table_title [string] Title of the Table +% o pnames [string] Character Array storing the names for prior distributions +% o table_title [string] Title of the Table % o field_name [string] String storing the name of the fields for oo_ where the parameters are stored -% -% OUTPUTS +% +% OUTPUTS % o oo_ Matlab's structure gathering the results % % SPECIAL REQUIREMENTS @@ -64,13 +64,13 @@ if np name = bayestopt_.name{ip}; if strcmp(field_name,'posterior') fprintf('%-*s %7.3f %8.4f %7.4f %4s %6.4f \n', ... - header_width,name, ... - bayestopt_.p1(ip),xparam1(ip),stdh(ip), ... - pnames(bayestopt_.pshape(ip)+1,:), ... - bayestopt_.p2(ip)); + header_width,name, ... + bayestopt_.p1(ip),xparam1(ip),stdh(ip), ... + pnames(bayestopt_.pshape(ip)+1,:), ... + bayestopt_.p2(ip)); else fprintf('%-*s %8.4f %7.4f %7.4f \n', ... - header_width,name,xparam1(ip),stdh(ip),tstath(ip)); + header_width,name,xparam1(ip),stdh(ip),tstath(ip)); end eval(['oo_.' field_name '_mode.parameters.' name ' = xparam1(ip);']); eval(['oo_.' field_name '_std_at_mode.parameters.' name ' = stdh(ip);']); @@ -87,9 +87,9 @@ if nvx name = deblank(M_.exo_names(k,:)); if strcmp(field_name,'posterior') fprintf('%-*s %7.3f %8.4f %7.4f %4s %6.4f \n', ... - header_width,name,bayestopt_.p1(ip),xparam1(ip), ... - stdh(ip),pnames(bayestopt_.pshape(ip)+1,:), ... - bayestopt_.p2(ip)); + header_width,name,bayestopt_.p1(ip),xparam1(ip), ... + stdh(ip),pnames(bayestopt_.pshape(ip)+1,:), ... + bayestopt_.p2(ip)); else fprintf('%-*s %8.4f %7.4f %7.4f \n',header_width,name,xparam1(ip),stdh(ip),tstath(ip)); end @@ -99,28 +99,28 @@ if nvx ip = ip+1; end skipline() - end - if nvn +end +if nvn disp('standard deviation of measurement errors') disp(tit1) ip = nvx+1; for i=1:nvn name = options_.varobs{estim_params_.nvn_observable_correspondence(i,1)}; - if strcmp(field_name,'posterior') + if strcmp(field_name,'posterior') fprintf('%-*s %7.3f %8.4f %7.4f %4s %6.4f \n', ... - header_width,name,bayestopt_.p1(ip), ... - xparam1(ip),stdh(ip), ... - pnames(bayestopt_.pshape(ip)+1,:), ... - bayestopt_.p2(ip)); + header_width,name,bayestopt_.p1(ip), ... + xparam1(ip),stdh(ip), ... + pnames(bayestopt_.pshape(ip)+1,:), ... + bayestopt_.p2(ip)); else - fprintf('%-*s %8.4f %7.4f %7.4f \n',header_width,name,xparam1(ip),stdh(ip),tstath(ip)) + fprintf('%-*s %8.4f %7.4f %7.4f \n',header_width,name,xparam1(ip),stdh(ip),tstath(ip)) end eval(['oo_.' field_name '_mode.measurement_errors_std.' name ' = xparam1(ip);']); eval(['oo_.' field_name '_std_at_mode.measurement_errors_std.' name ' = stdh(ip);']); ip = ip+1; end skipline() - end +end if ncx disp('correlation of shocks') @@ -131,12 +131,12 @@ if ncx 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,:))]; - if strcmp(field_name,'posterior') + if strcmp(field_name,'posterior') fprintf('%-*s %7.3f %8.4f %7.4f %4s %6.4f \n', ... - header_width,name,bayestopt_.p1(ip),xparam1(ip),stdh(ip), ... - pnames(bayestopt_.pshape(ip)+1,:), bayestopt_.p2(ip)); + header_width,name,bayestopt_.p1(ip),xparam1(ip),stdh(ip), ... + pnames(bayestopt_.pshape(ip)+1,:), bayestopt_.p2(ip)); else - fprintf('%-*s %8.4f %7.4f %7.4f \n', header_width,name,xparam1(ip),stdh(ip),tstath(ip)); + fprintf('%-*s %8.4f %7.4f %7.4f \n', header_width,name,xparam1(ip),stdh(ip),tstath(ip)); end 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); @@ -156,12 +156,12 @@ if ncn 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,:))]; - if strcmp(field_name,'posterior') + if strcmp(field_name,'posterior') fprintf('%-*s %7.3f %8.4f %7.4f %4s %6.4f \n', ... - header_width,name,bayestopt_.p1(ip),xparam1(ip),stdh(ip), ... - pnames(bayestopt_.pshape(ip)+1,:), bayestopt_.p2(ip)); + header_width,name,bayestopt_.p1(ip),xparam1(ip),stdh(ip), ... + pnames(bayestopt_.pshape(ip)+1,:), bayestopt_.p2(ip)); else - fprintf('%-*s %8.4f %7.4f %7.4f \n',header_width,name,xparam1(ip),stdh(ip),tstath(ip)); + fprintf('%-*s %8.4f %7.4f %7.4f \n',header_width,name,xparam1(ip),stdh(ip),tstath(ip)); end eval(['oo_.' field_name '_mode.measurement_errors_corr.' NAME ' = xparam1(ip);']); eval(['oo_.' field_name '_std_at_mode.measurement_errors_corr.' NAME ' = stdh(ip);']); @@ -268,17 +268,17 @@ if any(bayestopt_.pshape > 0) && options_.TeX %% Bayesian estimation (posterior TeXEnd(fidTeX) end elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output - if np + if np filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_1.tex']; fidTeX = fopen(filename,'w'); - TeXBegin_ML(fidTeX,1,'parameters',table_title,LaTeXtitle) + TeXBegin_ML(fidTeX,1,'parameters',table_title,LaTeXtitle) ip = nvx+nvn+ncx+ncn+1; for i=1:np fprintf(fidTeX,'$%s$ & %8.4f & %7.4f & %7.4f\\\\ \n',... M_.param_names_tex(estim_params_.param_vals(i,1),:),... xparam1(ip),... stdh(ip),... - tstath(ip)); + tstath(ip)); ip = ip + 1; end TeXEnd(fidTeX) @@ -286,7 +286,7 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output if nvx filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_2.tex']; fidTeX = fopen(filename,'w'); - TeXBegin_ML(fidTeX,2,'standard deviation of structural shocks',table_title,LaTeXtitle) + TeXBegin_ML(fidTeX,2,'standard deviation of structural shocks',table_title,LaTeXtitle) ip = 1; for i=1:nvx k = estim_params_.var_exo(i,1); @@ -302,11 +302,11 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output if nvn filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_3.tex']; fidTeX = fopen(filename,'w'); - TeXBegin_ML(fidTeX,3,'standard deviation of measurement errors',table_title,LaTeXtitle) + TeXBegin_ML(fidTeX,3,'standard deviation of measurement errors',table_title,LaTeXtitle) ip = nvx+1; for i=1:nvn - idx = strmatch(options_.varobs{estim_params_.nvn_observable_correspondence(i,1)},M_.endo_names); - fprintf(fidTeX,'$%s$ & %8.4f & %7.4f & %7.4f \\\\ \n',... + idx = strmatch(options_.varobs{estim_params_.nvn_observable_correspondence(i,1)},M_.endo_names); + fprintf(fidTeX,'$%s$ & %8.4f & %7.4f & %7.4f \\\\ \n',... deblank(M_.endo_names_tex(idx,:)), ... xparam1(ip),... stdh(ip),... @@ -318,7 +318,7 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output if ncx filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_4.tex']; fidTeX = fopen(filename,'w'); - TeXBegin_ML(fidTeX,4,'correlation of structural shocks',table_title,LaTeXtitle) + TeXBegin_ML(fidTeX,4,'correlation of structural shocks',table_title,LaTeXtitle) ip = nvx+nvn+1; for i=1:ncx k1 = estim_params_.corrx(i,1); @@ -335,7 +335,7 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output if ncn filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_5.tex']; fidTeX = fopen(filename,'w'); - TeXBegin_ML(fidTeX,5,'correlation of measurement errors',table_title,LaTeXtitle) + TeXBegin_ML(fidTeX,5,'correlation of measurement errors',table_title,LaTeXtitle) ip = nvx+nvn+ncx+1; for i=1:ncn k1 = estim_params_.corrn(i,1); @@ -347,7 +347,7 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output tstath(ip)); ip = ip+1; end - TeXEnd(fidTeX) + TeXEnd(fidTeX) end end @@ -356,51 +356,51 @@ end %% subfunctions: % function TeXBegin_Bayesian(fid,fnum,title) - fprintf(fid,'%% TeX-table generated by dynare_estimation (Dynare).\n'); - fprintf(fid,['%% RESULTS FROM POSTERIOR MAXIMIZATION (' title ')\n']); - fprintf(fid,['%% ' datestr(now,0)]); - fprintf(fid,' \n'); - fprintf(fid,' \n'); - fprintf(fid,'\\begin{center}\n'); - fprintf(fid,'\\begin{longtable}{llcccc} \n'); - fprintf(fid,['\\caption{Results from posterior maximization (' title ')}\\\\\n ']); - fprintf(fid,['\\label{Table:Posterior:' int2str(fnum) '}\\\\\n']); - fprintf(fid,'\\toprule \n'); - fprintf(fid,' & \\multicolumn{3}{c}{Prior} & \\multicolumn{2}{c}{Posterior} \\\\\n'); - fprintf(fid,' \\cmidrule(r{.75em}){2-4} \\cmidrule(r{.75em}){5-6}\n'); - fprintf(fid,' & Dist. & Mean & Stdev & Mode & Stdev \\\\ \n'); - fprintf(fid,'\\midrule \\endfirsthead \n'); - fprintf(fid,'\\caption{(continued)}\\\\\n '); - fprintf(fid,'\\bottomrule \n'); - fprintf(fid,' & \\multicolumn{3}{c}{Prior} & \\multicolumn{2}{c}{Posterior} \\\\\n'); - fprintf(fid,' \\cmidrule(r{.75em}){2-4} \\cmidrule(r{.75em}){5-6}\n'); - fprintf(fid,' & Dist. & Mean & Stdev & Mode & Stdev \\\\ \n'); - fprintf(fid,'\\midrule \\endhead \n'); - fprintf(fid,'\\bottomrule \\multicolumn{6}{r}{(Continued on next page)}\\endfoot \n'); - fprintf(fid,'\\bottomrule\\endlastfoot \n'); +fprintf(fid,'%% TeX-table generated by dynare_estimation (Dynare).\n'); +fprintf(fid,['%% RESULTS FROM POSTERIOR MAXIMIZATION (' title ')\n']); +fprintf(fid,['%% ' datestr(now,0)]); +fprintf(fid,' \n'); +fprintf(fid,' \n'); +fprintf(fid,'\\begin{center}\n'); +fprintf(fid,'\\begin{longtable}{llcccc} \n'); +fprintf(fid,['\\caption{Results from posterior maximization (' title ')}\\\\\n ']); +fprintf(fid,['\\label{Table:Posterior:' int2str(fnum) '}\\\\\n']); +fprintf(fid,'\\toprule \n'); +fprintf(fid,' & \\multicolumn{3}{c}{Prior} & \\multicolumn{2}{c}{Posterior} \\\\\n'); +fprintf(fid,' \\cmidrule(r{.75em}){2-4} \\cmidrule(r{.75em}){5-6}\n'); +fprintf(fid,' & Dist. & Mean & Stdev & Mode & Stdev \\\\ \n'); +fprintf(fid,'\\midrule \\endfirsthead \n'); +fprintf(fid,'\\caption{(continued)}\\\\\n '); +fprintf(fid,'\\bottomrule \n'); +fprintf(fid,' & \\multicolumn{3}{c}{Prior} & \\multicolumn{2}{c}{Posterior} \\\\\n'); +fprintf(fid,' \\cmidrule(r{.75em}){2-4} \\cmidrule(r{.75em}){5-6}\n'); +fprintf(fid,' & Dist. & Mean & Stdev & Mode & Stdev \\\\ \n'); +fprintf(fid,'\\midrule \\endhead \n'); +fprintf(fid,'\\bottomrule \\multicolumn{6}{r}{(Continued on next page)}\\endfoot \n'); +fprintf(fid,'\\bottomrule\\endlastfoot \n'); + +function TeXBegin_ML(fid,fnum,title,table_title,LaTeXtitle) +fprintf(fid,'%% TeX-table generated by dynare_estimation (Dynare).\n'); +fprintf(fid,['%% RESULTS FROM ' table_title ' MAXIMIZATION (' title ')\n']); +fprintf(fid,['%% ' datestr(now,0)]); +fprintf(fid,' \n'); +fprintf(fid,' \n'); +fprintf(fid,'\\begin{center}\n'); +fprintf(fid,'\\begin{longtable}{llcc} \n'); +fprintf(fid,['\\caption{Results from ' table_title ' maximization (' title ')}\\\\\n ']); +fprintf(fid,['\\label{Table:' LaTeXtitle ':' int2str(fnum) '}\\\\\n']); +fprintf(fid,'\\toprule \n'); +fprintf(fid,' & Mode & s.d. & t-stat\\\\ \n'); +fprintf(fid,'\\midrule \\endfirsthead \n'); +fprintf(fid,'\\caption{(continued)}\\\\\n '); +fprintf(fid,'\\toprule \n'); +fprintf(fid,' & Mode & s.d. & t-stat\\\\ \n'); +fprintf(fid,'\\midrule \\endhead \n'); +fprintf(fid,'\\bottomrule \\multicolumn{4}{r}{(Continued on next page)} \\endfoot \n'); +fprintf(fid,'\\bottomrule \\endlastfoot \n'); - function TeXBegin_ML(fid,fnum,title,table_title,LaTeXtitle) - fprintf(fid,'%% TeX-table generated by dynare_estimation (Dynare).\n'); - fprintf(fid,['%% RESULTS FROM ' table_title ' MAXIMIZATION (' title ')\n']); - fprintf(fid,['%% ' datestr(now,0)]); - fprintf(fid,' \n'); - fprintf(fid,' \n'); - fprintf(fid,'\\begin{center}\n'); - fprintf(fid,'\\begin{longtable}{llcc} \n'); - fprintf(fid,['\\caption{Results from ' table_title ' maximization (' title ')}\\\\\n ']); - fprintf(fid,['\\label{Table:' LaTeXtitle ':' int2str(fnum) '}\\\\\n']); - fprintf(fid,'\\toprule \n'); - fprintf(fid,' & Mode & s.d. & t-stat\\\\ \n'); - fprintf(fid,'\\midrule \\endfirsthead \n'); - fprintf(fid,'\\caption{(continued)}\\\\\n '); - fprintf(fid,'\\toprule \n'); - fprintf(fid,' & Mode & s.d. & t-stat\\\\ \n'); - fprintf(fid,'\\midrule \\endhead \n'); - fprintf(fid,'\\bottomrule \\multicolumn{4}{r}{(Continued on next page)} \\endfoot \n'); - fprintf(fid,'\\bottomrule \\endlastfoot \n'); - function TeXEnd(fid) -fprintf(fid,'\\end{longtable}\n '); +fprintf(fid,'\\end{longtable}\n '); fprintf(fid,'\\end{center}\n'); fprintf(fid,'%% End of TeX file.\n'); fclose(fid); \ No newline at end of file diff --git a/matlab/display_problematic_vars_Jacobian.m b/matlab/display_problematic_vars_Jacobian.m index c302df2137..c1bb0429ee 100644 --- a/matlab/display_problematic_vars_Jacobian.m +++ b/matlab/display_problematic_vars_Jacobian.m @@ -1,20 +1,20 @@ function []=display_problematic_vars_Jacobian(problemrow,problemcol,M_,x,type,caller_string) % []=display_problematic_vars_Jacobian(problemrow,problemcol,M_,ys,caller_string) -% print the equation numbers and variables associated with problematic entries -% of the Jacobian +% print the equation numbers and variables associated with problematic entries +% of the Jacobian % % INPUTS % problemrow [vector] rows associated with problematic entries % problemcol [vector] columns associated with problematic entries -% M_ [matlab structure] Definition of the model. +% M_ [matlab structure] Definition of the model. % x [vector] point at which the Jacobian was evaluated % type [string] 'static' or 'dynamic' depending on the type of % Jacobian -% caller_string [string] contains name of calling function for printing -% +% caller_string [string] contains name of calling function for printing +% % OUTPUTS % none. -% +% % Copyright (C) 2014-16 Dynare Team % @@ -62,25 +62,25 @@ if strcmp(type,'dynamic') fprintf('Derivative of Equation %d with respect to %s Variable %s (initial value of %s: %g) \n',eq_nbr,type_string,deblank(M_.endo_names(var_index,:)),deblank(M_.endo_names(var_index,:)),x(var_index)) end elseif problemcol(ii)<=max(max(M_.lead_lag_incidence)) && var_index>M_.orig_endo_nbr %auxiliary vars - if M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).type ==6 %Ramsey Lagrange Multiplier - if problemrow(ii)<=aux_eq_nbr - eq_nbr=problemrow(ii); - fprintf('Derivative of Auxiliary Equation %d with respect to %s of Langrange multiplier of equation %s (initial value: %g) \n',eq_nbr,type_string,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii))) - else - eq_nbr=problemrow(ii)-aux_eq_nbr; - fprintf('Derivative of Equation %d with respect to %s of Langrange multiplier of equation %s (initial value: %g) \n',eq_nbr,type_string,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii))) - end + if M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).type ==6 %Ramsey Lagrange Multiplier + if problemrow(ii)<=aux_eq_nbr + eq_nbr=problemrow(ii); + fprintf('Derivative of Auxiliary Equation %d with respect to %s of Langrange multiplier of equation %s (initial value: %g) \n',eq_nbr,type_string,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii))) else - if problemrow(ii)<=aux_eq_nbr - eq_nbr=problemrow(ii); - orig_var_index=M_.aux_vars(1,var_index-M_.orig_endo_nbr).orig_index; - fprintf('Derivative of Auxiliary Equation %d with respect to %s Variable %s (initial value of %s: %g) \n',eq_nbr,type_string,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(orig_var_index)) - else - eq_nbr=problemrow(ii)-aux_eq_nbr; - orig_var_index=M_.aux_vars(1,var_index-M_.orig_endo_nbr).orig_index; - fprintf('Derivative of Equation %d with respect to %s Variable %s (initial value of %s: %g) \n',eq_nbr,type_string,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(orig_var_index)) - end + eq_nbr=problemrow(ii)-aux_eq_nbr; + fprintf('Derivative of Equation %d with respect to %s of Langrange multiplier of equation %s (initial value: %g) \n',eq_nbr,type_string,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii))) end + else + if problemrow(ii)<=aux_eq_nbr + eq_nbr=problemrow(ii); + orig_var_index=M_.aux_vars(1,var_index-M_.orig_endo_nbr).orig_index; + fprintf('Derivative of Auxiliary Equation %d with respect to %s Variable %s (initial value of %s: %g) \n',eq_nbr,type_string,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(orig_var_index)) + else + eq_nbr=problemrow(ii)-aux_eq_nbr; + orig_var_index=M_.aux_vars(1,var_index-M_.orig_endo_nbr).orig_index; + fprintf('Derivative of Equation %d with respect to %s Variable %s (initial value of %s: %g) \n',eq_nbr,type_string,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(orig_var_index)) + end + end elseif problemcol(ii)>max(max(M_.lead_lag_incidence)) && var_index<=M_.exo_nbr if problemrow(ii)<=aux_eq_nbr eq_nbr=problemrow(ii); @@ -88,7 +88,7 @@ if strcmp(type,'dynamic') else eq_nbr=problemrow(ii)-aux_eq_nbr; fprintf('Derivative of Equation %d with respect to %s shock %s \n',eq_nbr,type_string,deblank(M_.exo_names(var_index,:))); - end + end else error('display_problematic_vars_Jacobian:: The error should not happen. Please contact the developers') end @@ -108,24 +108,24 @@ elseif strcmp(type,'static') fprintf('Derivative of Equation %d with respect to Variable %s (initial value of %s: %g) \n',eq_nbr,deblank(M_.endo_names(problemcol(ii),:)),deblank(M_.endo_names(problemcol(ii),:)),x(problemcol(ii))) end else %auxiliary vars - if M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).type ==6 %Ramsey Lagrange Multiplier + if M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).type ==6 %Ramsey Lagrange Multiplier if problemrow(ii)<=aux_eq_nbr eq_nbr=problemrow(ii); - fprintf('Derivative of Auxiliary Equation %d with respect to Lagrange multiplier of equation %d (initial value: %g) \n',eq_nbr,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii))) + fprintf('Derivative of Auxiliary Equation %d with respect to Lagrange multiplier of equation %d (initial value: %g) \n',eq_nbr,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii))) else eq_nbr=problemrow(ii)-aux_eq_nbr; - fprintf('Derivative of Equation %d with respect to Lagrange multiplier of equation %d (initial value: %g) \n',eq_nbr,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii))) + fprintf('Derivative of Equation %d with respect to Lagrange multiplier of equation %d (initial value: %g) \n',eq_nbr,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii))) end else - if problemrow(ii)<=aux_eq_nbr - eq_nbr=problemrow(ii); - orig_var_index=M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).orig_index; - fprintf('Derivative of Auxiliary Equation %d with respect to Variable %s (initial value of %s: %g) \n',eq_nbr,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(problemcol(ii))) - else - eq_nbr=problemrow(ii)-aux_eq_nbr; - orig_var_index=M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).orig_index; - fprintf('Derivative of Equation %d with respect to Variable %s (initial value of %s: %g) \n',eq_nbr,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(problemcol(ii))) - end + if problemrow(ii)<=aux_eq_nbr + eq_nbr=problemrow(ii); + orig_var_index=M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).orig_index; + fprintf('Derivative of Auxiliary Equation %d with respect to Variable %s (initial value of %s: %g) \n',eq_nbr,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(problemcol(ii))) + else + eq_nbr=problemrow(ii)-aux_eq_nbr; + orig_var_index=M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).orig_index; + fprintf('Derivative of Equation %d with respect to Variable %s (initial value of %s: %g) \n',eq_nbr,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(problemcol(ii))) + end end end end @@ -134,5 +134,5 @@ elseif strcmp(type,'static') fprintf('%s and evaluating it at the steady state then results in a division by 0.\n',caller_string) fprintf('%s If you are using model-local variables (# operator), check their values as well.\n',caller_string) else - error('Unknown Type') + error('Unknown Type') end \ No newline at end of file diff --git a/matlab/distributions/beta_specification.m b/matlab/distributions/beta_specification.m index 33a38085d3..9d84f04da8 100644 --- a/matlab/distributions/beta_specification.m +++ b/matlab/distributions/beta_specification.m @@ -2,13 +2,13 @@ function [a, b] = beta_specification(mu, sigma2, lb, ub, name) % --*-- Unitary % Returns the hyperparameters of the beta distribution given the expectation and variance. % -% INPUTS +% INPUTS % - mu [double] Expectation of the Gamma random variable. % - sigma2 [double] Variance of the Gamma random variable. % - lb [double] Lower bound of the domain (default is zero). % - ub [double] Upper bound of the domain (default is one). % -% OUTPUTS +% OUTPUTS % - a [double] First hyperparameter of the Beta density. % - b [double] Second hyperparameter of the Beta density. @@ -63,7 +63,7 @@ if sigma2>(1-mu)*mu error('Beta prior%s. Given the declared prior expectation, prior lower and upper bounds, the prior std. has to be smaller than %f.',name2,sqrt((1-mu)*mu)) end -a = (1-mu)*mu*mu/sigma2-mu; +a = (1-mu)*mu*mu/sigma2-mu; b = a*(1/mu-1); %@test:1 diff --git a/matlab/distributions/compute_prior_mode.m b/matlab/distributions/compute_prior_mode.m index 3286c08eab..57a0d10358 100644 --- a/matlab/distributions/compute_prior_mode.m +++ b/matlab/distributions/compute_prior_mode.m @@ -1,8 +1,8 @@ function m = compute_prior_mode(hyperparameters,shape) % --*-- Unitary tests --*-- % This function computes the mode of the prior distribution given the (two, three or four) hyperparameters % of the prior distribution. -% -% INPUTS +% +% INPUTS % hyperparameters [double] 1*n vector of hyper parameters. % shape [integer] scalar specifying the prior shape: % shape=1 => Beta distribution, @@ -12,14 +12,14 @@ function m = compute_prior_mode(hyperparameters,shape) % --*-- Unitary tests --* % shape=5 => Uniform distribution, % shape=6 => Inverse Gamma (type 2) distribution, % shape=8 => Weibull distribution. -% -% OUTPUTS +% +% OUTPUTS % m [double] scalar or 2*1 vector, the prior mode. % -% REMARKS -% [1] The size of the vector of hyperparameters is 3 when the Gamma or Inverse Gamma is shifted and 4 when -% the support of the Beta distribution is not [0,1]. -% [2] The hyperparameters of the uniform distribution are the lower and upper bounds. +% REMARKS +% [1] The size of the vector of hyperparameters is 3 when the Gamma or Inverse Gamma is shifted and 4 when +% the support of the Beta distribution is not [0,1]. +% [2] The hyperparameters of the uniform distribution are the lower and upper bounds. % [3] The uniform distribution has an infinity of modes. In this case the function returns the prior mean. % [4] For the beta distribution we can have 1, 2 or an infinity of modes. diff --git a/matlab/distributions/gamma_specification.m b/matlab/distributions/gamma_specification.m index 0f73011932..279c0702b8 100644 --- a/matlab/distributions/gamma_specification.m +++ b/matlab/distributions/gamma_specification.m @@ -2,13 +2,13 @@ function [a, b] = gamma_specification(mu, sigma2, lb, name) % --*-- Unitary te % Returns the hyperparameters of the gamma distribution given the expectation and variance. % -% INPUTS +% INPUTS % - mu [double] Expectation of the Gamma random variable. % - sigma2 [double] Variance of the Gamma random variable. % - lb [double] Lower bound of the domain (default is zero). % - name [string] Name of the parameter (or random variable). % -% OUTPUTS +% OUTPUTS % - a [double] First hyperparameter of the Gamma density (shape). % - b [double] Second hyperparameter of the Gamma density (scale). diff --git a/matlab/distributions/inverse_gamma_specification.m b/matlab/distributions/inverse_gamma_specification.m index 3018921c96..410d4e52b2 100644 --- a/matlab/distributions/inverse_gamma_specification.m +++ b/matlab/distributions/inverse_gamma_specification.m @@ -2,7 +2,7 @@ function [s,nu] = inverse_gamma_specification(mu, sigma2, lb, type, use_fzero_fl % Computes the inverse Gamma hyperparameters from the prior mean and standard deviation. % -% INPUTS +% INPUTS % - mu [double] scalar, prior mean. % - sigma2 [double] positive scalar, prior variance. % - type [integer] scalar equal to 1 or 2, type of the inverse gamma distribution @@ -10,11 +10,11 @@ function [s,nu] = inverse_gamma_specification(mu, sigma2, lb, type, use_fzero_fl % dynare's implementation of the secant method otherwise. % - name [string] name of the parameter or random variable. % -% OUTPUS +% OUTPUS % - s [double] scalar, first hyperparameter. % - nu [double] scalar, second hyperparameter. % -% REMARK +% REMARK % The call to the matlab's implementation of the secant method is here for testing purpose and should not be used. This routine fails % more often in finding an interval for nu containing a signe change because it expands the interval on both sides and eventually % violates the condition nu>2. diff --git a/matlab/distributions/lpdfgweibull.m b/matlab/distributions/lpdfgweibull.m index 7aa1d718af..708a5b4d44 100644 --- a/matlab/distributions/lpdfgweibull.m +++ b/matlab/distributions/lpdfgweibull.m @@ -1,14 +1,14 @@ function [ldens,Dldens,D2ldens] = lpdfgweibull(x,a,b,c) % --*-- Unitary tests --*-- -% Evaluates the logged Weibull PDF at x. +% Evaluates the logged Weibull PDF at x. % -% INPUTS +% INPUTS % - x [double] m*n matrix of points where the (logged) density will be evaluated, % - a [double] m*n matrix of First Weibull distribution parameters (shape parameter, k), % - b [double] m*n matrix of Second Weibull distribution parameters (scale parameter, λ), % - c [double] m*n matrix of Third Weibull distribution parameters (location parameter, default is 0). % -% OUTPUTS +% OUTPUTS % - ldens [double] m*n matrix of logged (generalized) Weibull densities. % - Dldens [double] m*n matrix (first order derivatives w.r.t. x) % - D2ldens [double] m*n matrix (second order derivatives w.r.t. x) @@ -54,11 +54,11 @@ end if ~isscalar(x) if isscalar(a) a = repmat(a, size(x)); - end + end if isscalar(b) b = repmat(b, size(x)); end - if isscalar(c) + if isscalar(c) c = repmat(c, size(x)); end end @@ -77,7 +77,7 @@ if isempty(idx), return, end jdx = find( abs(a-1)<1e-12 & x>=c & (x-c)<1e-12) ; ldens(jdx) = 1.0; - + if ~isempty(idx) x0 = x(idx)-c(idx); x1 = x0./b(idx); @@ -136,7 +136,7 @@ end %$ catch %$ t(1) = false; %$ end -%$ +%$ %$ if t(1) %$ t(2) = isinf(a); %$ end @@ -179,7 +179,7 @@ end %$ scale = 1; %$ shape = 2; %$ mode = scale*((shape-1)/shape)^(1/shape); -%$ +%$ %$ try %$ [a, b, c] = lpdfgweibull(mode, shape, scale); %$ p = rand(1000,1)*4; @@ -203,7 +203,7 @@ end %$ scale = 1; %$ shape = 2; %$ density = @(x) exp(lpdfgweibull(x,shape,scale)); -%$ +%$ %$ try %$ if isoctave %$ s = quadv(density, .0000000001, 100000,1e-10); @@ -226,7 +226,7 @@ end %$ scale = 1; %$ shape = 1; %$ density = @(x) exp(lpdfgweibull(x,shape,scale)); -%$ +%$ %$ try %$ if isoctave %$ s = quadv(density, .0000000001, 100000,1e-10); @@ -249,7 +249,7 @@ end %$ scale = 1; %$ shape = .5; %$ density = @(x) exp(lpdfgweibull(x,shape,scale)); -%$ +%$ %$ try %$ if isoctave %$ s = quadv(density, .0000000001, 100000,1e-10) @@ -276,7 +276,7 @@ end %$ scale = 1; %$ shape = 2; %$ xdens = @(x) x.*exp(lpdfgweibull(x,shape,scale)); -%$ +%$ %$ try %$ if isoctave %$ s = quadv(xdens, .0000000001, 20,1e-10) @@ -299,7 +299,7 @@ end %$ scale = 1; %$ shape = 1; %$ xdens = @(x) x.*exp(lpdfgweibull(x,shape,scale)); -%$ +%$ %$ try %$ if isoctave %$ s = quadv(xdens, .0000000001, 100000,1e-10) @@ -322,7 +322,7 @@ end %$ scale = 1; %$ shape = .5; %$ xdens = @(x) x.*exp(lpdfgweibull(x,shape,scale)); -%$ +%$ %$ try %$ if isoctave %$ s = quadv(xdens, .0000000001, 100000,1e-10) diff --git a/matlab/distributions/mode_and_variance_to_mean.m b/matlab/distributions/mode_and_variance_to_mean.m index a69f0cdbe2..6035721fa0 100644 --- a/matlab/distributions/mode_and_variance_to_mean.m +++ b/matlab/distributions/mode_and_variance_to_mean.m @@ -1,21 +1,21 @@ function [mu, parameters] = mode_and_variance_to_mean(m,s2,distribution,lower_bound,upper_bound) % This function computes the mean of a distribution given the mode and variance of this distribution. % -% INPUTS +% INPUTS % m [double] scalar, mode of the distribution. % s2 [double] scalar, variance of the distribution. -% distribution [integer] scalar for the distribution shape +% distribution [integer] scalar for the distribution shape % 1 gamma % 2 inv-gamma-2 % 3 inv-gamma-1 -% 4 beta +% 4 beta % lower_bound [double] scalar, lower bound of the random variable support (optional). % upper_bound [double] scalar, upper bound of the random variable support (optional). -% -% OUTPUT +% +% OUTPUT % mu [double] scalar, mean of the distribution. % parameters [double] 2*1 vector, parameters of the distribution. -% +% % Copyright (C) 2009 Dynare Team % @@ -34,7 +34,7 @@ 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. +% Check input aruments. if ~(nargin==3 || nargin==5 || nargin==4 ) error('mode_and_variance_to mean:: 3 or 5 input arguments are needed!') end @@ -80,7 +80,7 @@ if (distribution==1)% Gamma distribution end if (m-lower_bound)<1e-12 error('The gamma distribution should be specified with the mean and variance.') - end + end m = m - lower_bound ; beta = -.5*m*(1-sqrt(1+4*s2/(m*m))) ; alpha = (m+beta)/beta ; diff --git a/matlab/distributions/multivariate_normal_pdf.m b/matlab/distributions/multivariate_normal_pdf.m index e65858404e..55bae7283a 100644 --- a/matlab/distributions/multivariate_normal_pdf.m +++ b/matlab/distributions/multivariate_normal_pdf.m @@ -1,18 +1,18 @@ function density = multivariate_normal_pdf(X,Mean,Sigma_upper_chol,n) % Evaluates the density of a multivariate gaussian, with expectation Mean % and variance Sigma_upper_chol'*Sigma_upper_chol, at X. -% % -% INPUTS % -% X [double] 1*n vector +% INPUTS +% +% X [double] 1*n vector % Mean [double] 1*n vector, expectation of the multivariate random variable. % Sigma_upper_chol [double] n*n matrix, upper triangular Cholesky decomposition of Sigma (the covariance matrix). % n [integer] dimension. -% -% OUTPUTS -% density [double] density -% +% +% OUTPUTS +% density [double] density +% % SPECIAL REQUIREMENTS % Copyright (C) 2003-2017 Dynare Team @@ -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) * ... +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 bb3ee1ef2e..1465d44024 100644 --- a/matlab/distributions/multivariate_student_pdf.m +++ b/matlab/distributions/multivariate_student_pdf.m @@ -2,16 +2,16 @@ function density = multivariate_student_pdf(X,Mean,Sigma_upper_chol,df) % Evaluates the density of a multivariate student, with expectation Mean, % variance Sigma_upper_chol'*Sigma_upper_chol and degrees of freedom df, at X. % -% INPUTS +% INPUTS % -% X [double] 1*n vector +% X [double] 1*n vector % Mean [double] 1*n vector, expectation of the multivariate random variable. % Sigma_upper_chol [double] n*n matrix, upper triangular Cholesky decomposition of Sigma (the "covariance matrix"). % df [integer] degrees of freedom. -% -% OUTPUTS -% density [double] density. -% +% +% OUTPUTS +% density [double] density. +% % SPECIAL REQUIREMENTS % Copyright (C) 2003-2017 Dynare Team diff --git a/matlab/distributions/rand_inverse_wishart.m b/matlab/distributions/rand_inverse_wishart.m index c561fb7f46..3c65c18670 100644 --- a/matlab/distributions/rand_inverse_wishart.m +++ b/matlab/distributions/rand_inverse_wishart.m @@ -17,12 +17,12 @@ function G = rand_inverse_wishart(m, v, H_inv_upper_chol) % OUTPUTS: % G: G ~ IW(m, v, H) where H = inv(H_inv_upper_chol'*H_inv_upper_chol) % or, equivalently, using the correspondence between Wishart and -% inverse-Wishart: inv(G) ~ W(m, v, S) where +% inverse-Wishart: inv(G) ~ W(m, v, S) where % S = H_inv_upper_chol'*H_inv_upper_chol = inv(H) -% +% % SPECIAL REQUIREMENT % none -% +% % Copyright (C) 2003-2009 Dynare Team % @@ -41,7 +41,7 @@ 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; +X = randn(v, m) * H_inv_upper_chol; % At this point, X'*X is Wishart distributed diff --git a/matlab/distributions/rand_matrix_normal.m b/matlab/distributions/rand_matrix_normal.m index ff595cca87..04c6273f43 100644 --- a/matlab/distributions/rand_matrix_normal.m +++ b/matlab/distributions/rand_matrix_normal.m @@ -2,7 +2,7 @@ function B = rand_matrix_normal(n, p, M, Omega_lower_chol, Sigma_lower_chol) % function B = rand_matrix_normal(n, p, M, Omega_lower_chol, Sigma_lower_chol) % Pseudo random matrices drawn from a matrix-normal distribution -% B ~ MN_n*p(M, Omega, Sigma) +% B ~ MN_n*p(M, Omega, Sigma) % Equivalent to vec(B) ~ N(vec(Mu), kron(Omega, Sigma)) % % INPUTS @@ -13,10 +13,10 @@ function B = rand_matrix_normal(n, p, M, Omega_lower_chol, Sigma_lower_chol) % (Omega_lower_chol = chol(Omega, 'lower')) % Sigma_lower_chol: (n*n), lower Cholesky decomposition of Sigma, % (Sigma_lower_chol = chol(Sigma, 'lower')) -% +% % OUTPUTS % B: (n*p) matrix drawn from a Matrix-normal distribution -% +% % SPECIAL REQUIREMENTS % Same notations than: http://en.wikipedia.org/wiki/Matrix_normal_distribution diff --git a/matlab/distributions/rand_multivariate_normal.m b/matlab/distributions/rand_multivariate_normal.m index 174c3706cc..992f9c9e3d 100644 --- a/matlab/distributions/rand_multivariate_normal.m +++ b/matlab/distributions/rand_multivariate_normal.m @@ -2,16 +2,16 @@ function draw = rand_multivariate_normal(Mean,Sigma_upper_chol,n) % Pseudo random draws from a multivariate normal distribution, % \mathcal N_n(Mean,Sigma), with expectation Mean and variance Sigma. % -% INPUTS +% INPUTS % % Mean [double] 1*n vector, expectation of the multivariate random variable. % Sigma_upper_chol [double] n*n matrix, upper triangular Cholesky decomposition of Sigma (the covariance matrix). % n [integer] dimension. -% -% OUTPUTS +% +% OUTPUTS % draw [double] 1*n vector drawn from a multivariate normal distribution with expectation Mean and -% covariance Sigma -% +% covariance Sigma +% % SPECIAL REQUIREMENTS % Copyright (C) 2003-2009 Dynare Team diff --git a/matlab/distributions/rand_multivariate_student.m b/matlab/distributions/rand_multivariate_student.m index 37e2419f8d..cdf06b2f12 100644 --- a/matlab/distributions/rand_multivariate_student.m +++ b/matlab/distributions/rand_multivariate_student.m @@ -3,22 +3,22 @@ function draw = rand_multivariate_student(Mean,Sigma_upper_chol,df) % Pseudo random draws from a multivariate student distribution, % with expectation Mean, variance Sigma*df/(df-2) and degrees of freedom df>0. % -% INPUTS +% INPUTS % % Mean [double] 1*n vector, expectation of the multivariate random variable. -% Sigma_upper_chol [double] n*n matrix, upper triangular Cholesky decomposition of Sigma +% Sigma_upper_chol [double] n*n matrix, upper triangular Cholesky decomposition of Sigma % (the covariance matrix up to a factor df/(df-2)). % df [integer] degrees of freedom. -% -% OUTPUTS +% +% OUTPUTS % draw [double] 1*n vector drawn from a multivariate normal distribution with expectation Mean and % covariance Sigma. -% % -% NOTE See Zellner (appendix B.2, 1971) for a definition. -% Computes the t-distributed random numbers from +% +% NOTE See Zellner (appendix B.2, 1971) for a definition. +% Computes the t-distributed random numbers from % X = \mu + Y\sqrt{\frac{\nu}{U}} -% where +% where % Y~N(0,Sigma) with Sigma=Sigma_upper_chol'*Sigma_upper_chol % U~\Chi^2_{\nu} % The latter is constructed as the sum of \nu standard normals. diff --git a/matlab/distributions/weibull_specification.m b/matlab/distributions/weibull_specification.m index 8036dcb8df..064924cf48 100644 --- a/matlab/distributions/weibull_specification.m +++ b/matlab/distributions/weibull_specification.m @@ -2,12 +2,12 @@ function [shape, scale] = weibull_specification(mu, sigma2, lb, name) % --*-- % Returns the hyperparameters of the Weibull distribution given the expectation and variance. % -% INPUTS +% INPUTS % % -% OUTPUTS +% OUTPUTS +% % -% % Copyright (C) 2015-2016 Dynare Team % @@ -49,8 +49,8 @@ end scale = NaN; shape = NaN; -mu = mu-lb; -mu2 = mu*mu; +mu = mu-lb; +mu2 = mu*mu; eqn = @(k) gammaln(1+2./k) - 2*gammaln(1+1./k) - log(1+sigma2/mu2); eqn2 = @(k) eqn(k).*eqn(k); @@ -140,4 +140,3 @@ scale = mu/gamma(1+1/shape); %$ end %$ T = all(t); %@eof:1 - diff --git a/matlab/do_parameter_initialization.m b/matlab/do_parameter_initialization.m index 1f18c3f566..161c14641f 100644 --- a/matlab/do_parameter_initialization.m +++ b/matlab/do_parameter_initialization.m @@ -6,20 +6,20 @@ function [xparam1,estim_params_,xparam1_explicitly_initialized,xparam1_properly_ % o estim_params_ [structure] characterizing parameters to be estimated. % o xparam1_calib [double] vector of parameters to be estimated, with parameters % initialized from calibration using get_all_parameters -% +% % o xparam1_NaN_set_to_prior_mean [double] vector of parameters to be estimated, with parameters % initialized using dynare_estimation_init; not explicitly initialized % parameters are at prior mean % OUTPUTS % o xparam1 [double] vector of initialized parameters; uses the hierarchy: 1) explicitly initialized parameters, % 2) calibrated parameters, 3) prior mean -% o estim_params_ [structure] characterizing parameters to be estimated; it is +% o estim_params_ [structure] characterizing parameters to be estimated; it is % updated here to reflect calibrated parameters % o xparam1_explicitly_initialized [double] vector of parameters to be estimated that -% were explicitly initialized +% were explicitly initialized % o xparam1_properly_calibrated [double] vector of parameters to be estimated that -% were properly calibrated -% +% were properly calibrated +% % SPECIAL REQUIREMENTS % None @@ -59,7 +59,7 @@ offset=0; if nvx initialized_par_index=find(~isnan(estim_params_.var_exo(:,2))); calibrated_par_index=find(isnan(estim_params_.var_exo(:,2)) & ~isnan(xparam1_calib(offset+1:offset+nvx,1))); - uninitialized_par_index=find(isnan(estim_params_.var_exo(:,2)) & isnan(xparam1_calib(offset+1:offset+nvx,1))); + uninitialized_par_index=find(isnan(estim_params_.var_exo(:,2)) & isnan(xparam1_calib(offset+1:offset+nvx,1))); xparam1_explicitly_initialized(offset+initialized_par_index,1) = estim_params_.var_exo(initialized_par_index,2); %update estim_params_ with calibrated starting values estim_params_.var_exo(calibrated_par_index,2)=xparam1_calib(offset+calibrated_par_index,1); @@ -67,13 +67,13 @@ if nvx xparam1_properly_calibrated(offset+calibrated_par_index,1) = xparam1_calib(offset+calibrated_par_index,1); inv_gamma_violation=find(estim_params_.var_exo(calibrated_par_index,2)==0 & estim_params_.var_exo(calibrated_par_index,5)==4); if inv_gamma_violation - estim_params_.var_exo(calibrated_par_index(inv_gamma_violation),2)=NaN; - xparam1_properly_calibrated(offset+calibrated_par_index(inv_gamma_violation),1)=NaN; - fprintf('PARAMETER INITIALIZATION: Some standard deviations of shocks of the calibrated model are 0 and\n') - fprintf('PARAMETER INITIALIZATION: violate the inverse gamma prior. They will instead be initialized with the prior mean.\n') + estim_params_.var_exo(calibrated_par_index(inv_gamma_violation),2)=NaN; + xparam1_properly_calibrated(offset+calibrated_par_index(inv_gamma_violation),1)=NaN; + fprintf('PARAMETER INITIALIZATION: Some standard deviations of shocks of the calibrated model are 0 and\n') + fprintf('PARAMETER INITIALIZATION: violate the inverse gamma prior. They will instead be initialized with the prior mean.\n') end if uninitialized_par_index - fprintf('PARAMETER INITIALIZATION: Warning, some estimated standard deviations of shocks are not\n') + fprintf('PARAMETER INITIALIZATION: Warning, some estimated standard deviations of shocks are not\n') fprintf('PARAMETER INITIALIZATION: initialized. They will be initialized with the prior mean.\n') end end @@ -88,10 +88,10 @@ if nvn xparam1_properly_calibrated(offset+calibrated_par_index,1) = xparam1_calib(offset+calibrated_par_index,1); inv_gamma_violation=find(estim_params_.var_endo(calibrated_par_index,2)==0 & estim_params_.var_endo(calibrated_par_index,5)==4); if inv_gamma_violation - estim_params_.var_endo(calibrated_par_index(inv_gamma_violation),2)=NaN; - xparam1_properly_calibrated(offset+calibrated_par_index(inv_gamma_violation),1)=NaN; + estim_params_.var_endo(calibrated_par_index(inv_gamma_violation),2)=NaN; + xparam1_properly_calibrated(offset+calibrated_par_index(inv_gamma_violation),1)=NaN; fprintf('PARAMETER INITIALIZATION: Some measurement errors of the calibrated model are 0 and violate the\n') - fprintf('PARAMETER INITIALIZATION: inverse gamma prior. They will instead be initialized with the prior mean.\n') + fprintf('PARAMETER INITIALIZATION: inverse gamma prior. They will instead be initialized with the prior mean.\n') end if uninitialized_par_index fprintf('PARAMETER INITIALIZATION: Warning, some measurement errors are not initialized. They will be initialized\n') @@ -140,4 +140,3 @@ end xparam1=xparam1_explicitly_initialized; xparam1(isnan(xparam1))=xparam1_properly_calibrated(isnan(xparam1)); %set not explicitly initialized parameters that do not obviously violate prior distribution to calibrated parameter values xparam1(isnan(xparam1))=xparam1_NaN_set_to_prior_mean(isnan(xparam1)); %set not yet initialized parameters to prior mean coming from dynare_estimation_init - diff --git a/matlab/dr_block.m b/matlab/dr_block.m index 67e9a4f466..61826d390f 100644 --- a/matlab/dr_block.m +++ b/matlab/dr_block.m @@ -1,38 +1,38 @@ function [dr,info,M_,options_,oo_] = dr_block(dr,task,M_,options_,oo_,varargin) % function [dr,info,M_,options_,oo_] = dr_block(dr,task,M_,options_,oo_,varargin) % computes the reduced form solution of a rational expectations model -% (first order approximation of the stochastic model around the deterministic steady state). +% (first order approximation of the stochastic model around the deterministic steady state). % % INPUTS % dr [matlab structure] Decision rules for stochastic simulations. % task [integer] if task = 0 then dr_block computes decision rules. % if task = 1 then dr_block computes eigenvalues. -% M_ [matlab structure] Definition of the model. +% M_ [matlab structure] Definition of the model. % options_ [matlab structure] Global options. -% oo_ [matlab structure] Results +% oo_ [matlab structure] Results % oo_ [matlab cell] Other input arguments -% +% % OUTPUTS % dr [matlab structure] Decision rules for stochastic simulations. % info [integer] info=1: the model doesn't define current variables uniquely -% info=2: problem in mjdgges.dll info(2) contains error code. +% info=2: problem in mjdgges.dll info(2) contains error code. % info=3: BK order condition not satisfied info(2) contains "distance" % absence of stable trajectory. % info=4: BK order condition not satisfied info(2) contains "distance" % indeterminacy. % info=5: BK rank condition not satisfied. -% info=6: The jacobian matrix evaluated at the steady state is complex. -% M_ [matlab structure] +% info=6: The jacobian matrix evaluated at the steady state is complex. +% M_ [matlab structure] % options_ [matlab structure] % oo_ [matlab structure] -% +% % ALGORITHM % first order block relaxation method applied to the model % E[A Yt-1 + B Yt + C Yt+1 + ut] = 0 -% +% % SPECIAL REQUIREMENTS % none. -% +% % Copyright (C) 2010-2017 Dynare Team % @@ -54,7 +54,7 @@ function [dr,info,M_,options_,oo_] = dr_block(dr,task,M_,options_,oo_,varargin) info = 0; verbose = 0; if nargin > 5 - verbose = varargin{1}; + verbose = varargin{1}; end %verbose = options_.verbosity; if options_.order > 1 @@ -122,19 +122,19 @@ for i = 1:Size maximum_lag = data(i).maximum_endo_lag; maximum_lead = data(i).maximum_endo_lead; n = n_dynamic + n_static; - + block_type = M_.block_structure.block(i).Simulation_Type; if task ~= 1 - if block_type == 2 || block_type == 4 || block_type == 7 + if block_type == 2 || block_type == 4 || block_type == 7 block_type = 8; end end - if maximum_lag > 0 && (n_pred > 0 || n_both > 0) && block_type ~= 1 + if maximum_lag > 0 && (n_pred > 0 || n_both > 0) && block_type ~= 1 indexi_0 = min(lead_lag_incidence(2,:)); end switch block_type case 1 - %% ------------------------------------------------------------------ + %% ------------------------------------------------------------------ %Evaluate Forward if maximum_lag > 0 && n_pred > 0 indx_r = find(M_.block_structure.block(i).lead_lag_incidence(1,:)); @@ -175,11 +175,11 @@ for i = 1:Size l_x_sv = dr.ghx(dr.state_var, 1:n_sv); selector_tm1 = M_.block_structure.block(i).tm1; - + ghx_other = - B \ (fx_t * l_x + (fx_tp1 * l_x * l_x_sv) + fx_tm1 * selector_tm1); dr.ghx(endo, :) = dr.ghx(endo, :) + ghx_other; end - + if exo_nbr fu = data(i).g1_x; exo = dr.exo_var; @@ -198,17 +198,17 @@ for i = 1:Size else exo = dr.exo_var; if other_endo_nbr > 0 - l_u_sv = dr.ghu(dr.state_var,:); - l_x = dr.ghx(data(i).other_endogenous,:); - l_u = dr.ghu(data(i).other_endogenous,:); - ghu = -B \ (fx_tp1 * l_x * l_u_sv + (fx_t) * l_u ); + l_u_sv = dr.ghu(dr.state_var,:); + l_x = dr.ghx(data(i).other_endogenous,:); + l_u = dr.ghu(data(i).other_endogenous,:); + ghu = -B \ (fx_tp1 * l_x * l_u_sv + (fx_t) * l_u ); else ghu = []; end end end case 2 - %% ------------------------------------------------------------------ + %% ------------------------------------------------------------------ %Evaluate Backward if maximum_lead > 0 && n_fwrd > 0 indx_r = find(M_.block_structure.block(i).lead_lag_incidence(3,:)); @@ -233,7 +233,7 @@ for i = 1:Size ghu = - inv(jacob(indx_r, indx_c)) * data(i).g1_x; end case 3 - %% ------------------------------------------------------------------ + %% ------------------------------------------------------------------ %Solve Forward single equation if maximum_lag > 0 && n_pred > 0 data(i).eigval = - jacob(1 , 1 : n_pred) / jacob(1 , n_pred + n_static + 1 : n_pred + n_static + n_pred + n_both); @@ -246,9 +246,9 @@ for i = 1:Size %First order approximation if task ~= 1 if (maximum_lag > 0) - ghx = - jacob(1 , 1 : n_pred) / jacob(1 , n_pred + n_static + 1 : n_pred + n_static + n_pred + n_both); + ghx = - jacob(1 , 1 : n_pred) / jacob(1 , n_pred + n_static + 1 : n_pred + n_static + n_pred + n_both); else - ghx = 0; + ghx = 0; end if other_endo_nbr fx = data(i).g1_o; @@ -269,7 +269,7 @@ for i = 1:Size l_x = dr.ghx(data(i).other_endogenous,:); l_x_sv = dr.ghx(dr.state_var, 1:n_sv); - + selector_tm1 = M_.block_structure.block(i).tm1; ghx_other = - (fx_t * l_x + (fx_tp1 * l_x * l_x_sv) + fx_tm1 * selector_tm1) / jacob(1 , n_pred + 1 : n_pred + n_static + n_pred + n_both); dr.ghx(endo, :) = dr.ghx(endo, :) + ghx_other; @@ -289,19 +289,19 @@ for i = 1:Size ghu = - fu / jacob(1 , n_pred + 1 : n_pred + n_static + n_pred + n_both); end else - if other_endo_nbr > 0 - l_u_sv = dr.ghu(dr.state_var,:); - l_x = dr.ghx(data(i).other_endogenous,:); - l_u = dr.ghu(data(i).other_endogenous,:); - ghu = -(fx_tp1 * l_x * l_u_sv + (fx_t) * l_u ) / jacob(1 , n_pred + 1 : n_pred + n_static + n_pred + n_both); - exo = dr.exo_var; - else - ghu = []; - end + if other_endo_nbr > 0 + l_u_sv = dr.ghu(dr.state_var,:); + l_x = dr.ghx(data(i).other_endogenous,:); + l_u = dr.ghu(data(i).other_endogenous,:); + ghu = -(fx_tp1 * l_x * l_u_sv + (fx_t) * l_u ) / jacob(1 , n_pred + 1 : n_pred + n_static + n_pred + n_both); + exo = dr.exo_var; + else + ghu = []; + end end end case 4 - %% ------------------------------------------------------------------ + %% ------------------------------------------------------------------ %Solve Backward single equation if maximum_lead > 0 && n_fwrd > 0 data(i).eigval = - jacob(1 , n_pred + n - n_fwrd + 1 : n_pred + n) / jacob(1 , n_pred + n + 1 : n_pred + n + n_fwrd) ; @@ -315,11 +315,11 @@ for i = 1:Size dr.full_rank = dr.full_rank && full_rank; dr.eigval = [dr.eigval ; data(i).eigval]; case 6 - %% ------------------------------------------------------------------ - %Solve Forward complete + %% ------------------------------------------------------------------ + %Solve Forward complete if (maximum_lag > 0) ghx = - jacob(: , n_pred + 1 : n_pred + n_static ... - + n_pred + n_both) \ jacob(: , 1 : n_pred); + + n_pred + n_both) \ jacob(: , 1 : n_pred); else ghx = 0; end @@ -354,7 +354,7 @@ for i = 1:Size l_x = dr.ghx(data(i).other_endogenous,:); l_x_sv = dr.ghx(dr.state_var, 1:n_sv); - + selector_tm1 = M_.block_structure.block(i).tm1; ghx_other = - (fx_t * l_x + (fx_tp1 * l_x * l_x_sv) + fx_tm1 * selector_tm1) / jacob(: , n_pred + 1 : n_pred + n_static + n_pred + n_both); dr.ghx(endo, :) = dr.ghx(endo, :) + ghx_other; @@ -373,19 +373,19 @@ for i = 1:Size ghu = - fu / jacob(: , n_pred + 1 : n_pred + n_static + n_pred + n_both); end else - if other_endo_nbr > 0 - l_u_sv = dr.ghu(dr.state_var,:); - l_x = dr.ghx(data(i).other_endogenous,:); - l_u = dr.ghu(data(i).other_endogenous,:); - ghu = -(fx_tp1 * l_x * l_u_sv + (fx_t) * l_u ) / jacob(1 , n_pred + 1 : n_pred + n_static + n_pred + n_both); - exo = dr.exo_var; - else - ghu = []; - end + if other_endo_nbr > 0 + l_u_sv = dr.ghu(dr.state_var,:); + l_x = dr.ghx(data(i).other_endogenous,:); + l_u = dr.ghu(data(i).other_endogenous,:); + ghu = -(fx_tp1 * l_x * l_u_sv + (fx_t) * l_u ) / jacob(1 , n_pred + 1 : n_pred + n_static + n_pred + n_both); + exo = dr.exo_var; + else + ghu = []; + end end end case 7 - %% ------------------------------------------------------------------ + %% ------------------------------------------------------------------ %Solve Backward complete if maximum_lead > 0 && n_fwrd > 0 data(i).eigval = eig(- jacob(: , n_pred + n - n_fwrd + 1: n_pred + n))/ ... @@ -401,10 +401,10 @@ for i = 1:Size dr.full_rank = dr.full_rank && full_rank; dr.eigval = [dr.eigval ; data(i).eigval]; case {5,8} - %% ------------------------------------------------------------------ + %% ------------------------------------------------------------------ %The lead_lag_incidence contains columns in the following order: % static variables, backward variable, mixed variables and forward variables - % + % %Proceeds to a QR decomposition on the jacobian matrix in order to reduce the problem size index_c = lead_lag_incidence(2,:); % Index of all endogenous variables present at time=t index_s = lead_lag_incidence(2,1:n_static); % Index of all static endogenous variables present at time=t @@ -435,7 +435,7 @@ for i = 1:Size hx = ghx(1:n_pred+n_both,:); gx = ghx(1+n_pred:end,:); end - + if (task ~= 1 && ((options_.dr_cycle_reduction == 1 && info ==1) || options_.dr_cycle_reduction == 0)) || task == 1 D = [[aa(row_indx,index_0m) zeros(n_dynamic,n_both) aa(row_indx,index_p)] ; [zeros(n_both, n_pred) eye(n_both) zeros(n_both, n_both + n_fwrd)]]; E = [-aa(row_indx,[index_m index_0p]) ; [zeros(n_both, n_both + n_pred) eye(n_both, n_both + n_fwrd) ] ]; @@ -483,7 +483,7 @@ for i = 1:Size nba = nyf; end else - sorted_roots = sort(abs(data(i).eigval)); + sorted_roots = sort(abs(data(i).eigval)); if nba > nyf temp = sorted_roots(nd-nba+1:nd-nyf)-1-options_.qz_criterium; info(1) = 3; @@ -497,8 +497,8 @@ for i = 1:Size end indx_stable_root = 1: (nd - nyf); %=> index of stable roots indx_explosive_root = n_pred + n_both + 1:nd; %=> index of explosive roots - % derivatives with respect to dynamic state variables - % forward variables + % derivatives with respect to dynamic state variables + % forward variables Z = w'; Z11t = Z(indx_stable_root, indx_stable_root)'; Z21 = Z(indx_explosive_root, indx_stable_root); @@ -522,13 +522,13 @@ for i = 1:Size ghx = [hx(k1,:); gx(k2(n_both+1:end),:)]; end end - - if task~= 1 + + if task~= 1 %lead variables actually present in the model j4 = n_static+n_pred+1:n_static+n_pred+n_both+n_fwrd; % Index on the forward and both variables j3 = nonzeros(lead_lag_incidence(2,j4)) - n_static - 2 * n_pred - n_both; % Index on the non-zeros forward and both variables - j4 = find(lead_lag_incidence(2,j4)); - + j4 = find(lead_lag_incidence(2,j4)); + if n_static > 0 B_static = B(:,1:n_static); % submatrix containing the derivatives w.r. to static variables else @@ -550,12 +550,12 @@ for i = 1:Size ghx = [temp; ghx]; temp = []; end - + A_ = real([B_static C(:,j3)*gx+B_pred B_fyd]); % The state_variable of the block are located at [B_pred B_both] - + if other_endo_nbr if n_static > 0 - fx = Q' * data(i).g1_o; + fx = Q' * data(i).g1_o; else fx = data(i).g1_o; end @@ -575,10 +575,10 @@ for i = 1:Size fx_tp1(:,c) = fx(:,lead); l_x = dr.ghx(data(i).other_endogenous,:); - + l_x_sv = dr.ghx(dr.state_var, :); - - selector_tm1 = M_.block_structure.block(i).tm1; + + selector_tm1 = M_.block_structure.block(i).tm1; B_ = [zeros(size(B_static)) zeros(n,n_pred) C(:,j3) ]; C_ = l_x_sv; @@ -590,14 +590,14 @@ for i = 1:Size ghx_other = reshape(vghx_other, size(D_,1), size(D_,2)); elseif options_.sylvester_fp == 1 ghx_other = gensylv_fp(A_, B_, C_, D_, i, options_.sylvester_fixed_point_tol); - else + else [err, ghx_other] = gensylv(1, A_, B_, C_, -D_); end if options_.aim_solver ~= 1 && options_.use_qzdiv - % Necessary when using Sims' routines for QZ - ghx_other = real(ghx_other); + % Necessary when using Sims' routines for QZ + ghx_other = real(ghx_other); end - + dr.ghx(endo, :) = dr.ghx(endo, :) + ghx_other; end @@ -616,7 +616,7 @@ for i = 1:Size fu_complet(:,data(i).exogenous) = fu; % Solve the equation in ghu: % A_ * ghu + (fu_complet + fx_tp1 * l_x * l_u_sv + (fx_t + B_ * ghx_other) * l_u ) = 0 - + ghu = -A_\ (fu_complet + fx_tp1 * l_x * l_u_sv + fx_t * l_u + B_ * ghx_other * l_u_sv ); exo = dr.exo_var; else @@ -637,16 +637,16 @@ for i = 1:Size end - + if options_.loglinear error('The loglinear option is not yet supported in first order approximation for a block decomposed model'); -% k = find(dr.kstate(:,2) <= M_.maximum_endo_lag+1); -% klag = dr.kstate(k,[1 2]); -% k1 = dr.order_var; -% -% ghx = repmat(1./dr.ys(k1),1,size(ghx,2)).*ghx.* ... -% repmat(dr.ys(k1(klag(:,1)))',size(ghx,1),1); -% ghu = repmat(1./dr.ys(k1),1,size(ghu,2)).*ghu; + % k = find(dr.kstate(:,2) <= M_.maximum_endo_lag+1); + % klag = dr.kstate(k,[1 2]); + % k1 = dr.order_var; + % + % ghx = repmat(1./dr.ys(k1),1,size(ghx,2)).*ghx.* ... + % repmat(dr.ys(k1(klag(:,1)))',size(ghx,1),1); + % ghu = repmat(1./dr.ys(k1),1,size(ghu,2)).*ghu; end @@ -659,16 +659,16 @@ for i = 1:Size %exogenous deterministic variables if exo_det_nbr > 0 error('Deterministic exogenous variables are not yet implemented in first order approximation for a block decomposed model'); -% 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 = data(i).g1_xd; -% M1 = inv(f0+[zeros(n,n_static) f1*gx zeros(n,nyf-n_both)]); -% 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 + % 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 = data(i).g1_xd; + % M1 = inv(f0+[zeros(n,n_static) f1*gx zeros(n,nyf-n_both)]); + % 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 end end @@ -685,22 +685,22 @@ for i = 1:Size dr.ghu(endo, exo) = ghu; data(i).pol.i_ghu = exo; end - - if (verbose) + + if (verbose) disp('dr.ghx'); dr.ghx disp('dr.ghu'); dr.ghu - end - + end + end M_.block_structure.block = data ; if (verbose) - disp('dr.ghx'); - disp(real(dr.ghx)); - disp('dr.ghu'); - disp(real(dr.ghu)); -end + disp('dr.ghx'); + disp(real(dr.ghx)); + disp('dr.ghu'); + disp(real(dr.ghu)); +end if (task == 1) return end diff --git a/matlab/draw_prior_density.m b/matlab/draw_prior_density.m index 22b43518ca..94f32ac881 100644 --- a/matlab/draw_prior_density.m +++ b/matlab/draw_prior_density.m @@ -4,11 +4,11 @@ function [x,f,abscissa,dens,binf,bsup] = draw_prior_density(indx,bayestopt_) % INPUTS % indx [integer] Parameter number. % bayestopt_ [structure] Describes the prior beliefs. -% +% % OUTPUTS % x [double] Row vector, subset of 'abscissa' such as the density is less than 10 % f [double] Row vector, subset of 'dens' such as the density is less than 10 -% abscissa [double] Row vector, abscissa +% abscissa [double] Row vector, abscissa % dens [double] Row vector, density % binf: [double] Scalar, first element of x % bsup: [double] Scalar, last element of x @@ -63,10 +63,10 @@ switch pshape(indx) abscissa = linspace(infbound,supbound,steps); dens = density(abscissa,p6(indx),p7(indx),p3(indx)); case 3% Gaussian prior - infbound = norminv(truncprior,p6(indx),p7(indx)); + infbound = norminv(truncprior,p6(indx),p7(indx)); supbound = norminv(1-truncprior,p6(indx),p7(indx)); abscissa = linspace(infbound,supbound,steps); - dens = normpdf(abscissa,p6(indx),p7(indx)); + dens = normpdf(abscissa,p6(indx),p7(indx)); case 4% Inverse-gamma of type 1 prior try infbound = 1/sqrt(gaminv(1-10*truncprior, p7(indx)/2, 2/p6(indx)))+p3(indx); @@ -80,7 +80,7 @@ switch pshape(indx) end end abscissa = linspace(infbound,supbound,steps); - dens = exp(lpdfig1(abscissa-p3(indx),p6(indx),p7(indx))); + dens = exp(lpdfig1(abscissa-p3(indx),p6(indx),p7(indx))); case 5% Uniform prior infbound = p6(indx); supbound = p7(indx); @@ -108,9 +108,9 @@ switch pshape(indx) dens = density(abscissa,p6(indx),p7(indx),p3(indx)); otherwise error(sprintf('draw_prior_density: unknown distribution shape (index %d, type %d)', indx, pshape(indx))); -end +end -if pshape(indx) ~= 5 +if pshape(indx) ~= 5 [junk,k1] = max(dens); if k1 == 1 || k1 == length(dens) k = find(dens > 10); diff --git a/matlab/dsample.m b/matlab/dsample.m index 2e7251ac18..761f3290fb 100644 --- a/matlab/dsample.m +++ b/matlab/dsample.m @@ -1,17 +1,17 @@ function dsample(s1,s2) % function dsample(s1,s2) % This optional command permits to reduce the number of periods considered in following output commands. -% If only one argument is provided, output is from period 1 to the period specified in the DSAMPLE command. +% If only one argument is provided, output is from period 1 to the period specified in the DSAMPLE command. % If two arguments are present output is done for the interval between the two periods. % DSAMPLE without arguments reset the sample to the one specified by PERIODS % % INPUTS % s1: first period % s2: last period -% +% % OUTPUTS % none -% +% % SPECIAL REQUIREMENTS % none diff --git a/matlab/dsge_likelihood.m b/matlab/dsge_likelihood.m index 2e869d4c8a..0b62e51675 100644 --- a/matlab/dsge_likelihood.m +++ b/matlab/dsge_likelihood.m @@ -149,7 +149,7 @@ xparam1 = xparam1(:); if DynareOptions.estimation_dll [fval,exit_flag,SteadyState,trend_coeff,info,params,H,Q] ... = logposterior(xparam1,DynareDataset, DynareOptions,Model, ... - EstimatedParameters,BayesInfo,DynareResults); + EstimatedParameters,BayesInfo,DynareResults); mexErrCheck('logposterior', exit_flag); Model.params = params; if ~isequal(Model.H,0) @@ -268,8 +268,8 @@ end % Return, with endogenous penalty when possible, if dynare_resolve issues an error code (defined in resol). if info(1) if info(1) == 3 || info(1) == 4 || info(1) == 5 || info(1)==6 ||info(1) == 19 ||... - info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ... - info(1) == 81 || info(1) == 84 || info(1) == 85 || info(1) == 86 + info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ... + info(1) == 81 || info(1) == 84 || info(1) == 85 || info(1) == 86 %meaningful second entry of output that can be used fval = Inf; info(4) = info(2); @@ -320,8 +320,8 @@ if BayesInfo.with_trend [trend_addition, trend_coeff]=compute_trend_coefficients(Model,DynareOptions,DynareDataset.vobs,DynareDataset.nobs); trend = repmat(constant,1,DynareDataset.nobs)+trend_addition; else - trend_coeff = zeros(DynareDataset.vobs,1); - trend = repmat(constant,1,DynareDataset.nobs); + trend_coeff = zeros(DynareDataset.vobs,1); + trend = repmat(constant,1,DynareDataset.nobs); end % Get needed informations for kalman filter routines. @@ -369,8 +369,8 @@ switch DynareOptions.lik_init if kalman_algo == 0 kalman_algo = 3; elseif ~((kalman_algo == 3) || (kalman_algo == 4)) - error(['The model requires Diffuse filter, but you specified a different Kalman filter. You must set options_.kalman_algo ' ... - 'to 0 (default), 3 or 4']) + error(['The model requires Diffuse filter, but you specified a different Kalman filter. You must set options_.kalman_algo ' ... + 'to 0 (default), 3 or 4']) end [Pstar,Pinf] = compute_Pinf_Pstar(Z,T,R,Q,DynareOptions.qz_criterium,[1:length(T)]); Z =zeros(length(BayesInfo.mf),size(T,1)); @@ -384,9 +384,9 @@ switch DynareOptions.lik_init Pstar0 = Pstar; % store Pstar if no_missing_data_flag [dLIK,dlik,a,Pstar] = kalman_filter_d(Y, 1, size(Y,2), ... - zeros(mm,1), Pinf, Pstar, ... - kalman_tol, diffuse_kalman_tol, riccati_tol, DynareOptions.presample, ... - T,R,Q,H,Z,mm,pp,rr); + zeros(mm,1), Pinf, Pstar, ... + kalman_tol, diffuse_kalman_tol, riccati_tol, DynareOptions.presample, ... + T,R,Q,H,Z,mm,pp,rr); else [dLIK,dlik,a,Pstar] = missing_observations_kalman_filter_d(DatasetInfo.missing.aindex,DatasetInfo.missing.number_of_observations,DatasetInfo.missing.no_more_missing_observations, ... Y, 1, size(Y,2), ... @@ -430,17 +430,17 @@ switch DynareOptions.lik_init Pinf = blkdiag(Pinf,zeros(pp)); H1 = zeros(pp,1); mmm = mm+pp; - + end end [dLIK,dlik,a,Pstar] = univariate_kalman_filter_d(DatasetInfo.missing.aindex,... - DatasetInfo.missing.number_of_observations,... - DatasetInfo.missing.no_more_missing_observations, ... - Y, 1, size(Y,2), ... - zeros(mmm,1), Pinf, Pstar, ... - kalman_tol, diffuse_kalman_tol, riccati_tol, DynareOptions.presample, ... - T,R,Q,H1,Z,mmm,pp,rr); + DatasetInfo.missing.number_of_observations,... + DatasetInfo.missing.no_more_missing_observations, ... + Y, 1, size(Y,2), ... + zeros(mmm,1), Pinf, Pstar, ... + kalman_tol, diffuse_kalman_tol, riccati_tol, DynareOptions.presample, ... + T,R,Q,H1,Z,mmm,pp,rr); diffuse_periods = size(dlik,1); end if isnan(dLIK) @@ -450,7 +450,7 @@ switch DynareOptions.lik_init exit_flag = 0; return end - + case 4% Start from the solution of the Riccati equation. if kalman_algo ~= 2 kalman_algo = 1; @@ -536,9 +536,9 @@ if analytic_derivation full_Hess = derivatives_info.full_Hess; end if full_Hess - D2T = derivatives_info.D2T; - D2Om = derivatives_info.D2Om; - D2Yss = derivatives_info.D2Yss; + D2T = derivatives_info.D2T; + D2Om = derivatives_info.D2Om; + D2Yss = derivatives_info.D2Yss; end if isfield(derivatives_info,'no_DLIK') no_DLIK = derivatives_info.no_DLIK; @@ -551,7 +551,7 @@ if analytic_derivation DP=zeros([size(T),length(xparam1)]); if full_Hess for j=1:size(D2Yss,1) - tmp(j,:,:) = blkdiag(zeros(offset,offset), squeeze(D2Yss(j,:,:))); + tmp(j,:,:) = blkdiag(zeros(offset,offset), squeeze(D2Yss(j,:,:))); end D2Yss = tmp; D2H=sparse(size(D2Om,1),size(D2Om,2)); %zeros([size(H),length(xparam1),length(xparam1)]); @@ -559,58 +559,58 @@ if analytic_derivation jcount=0; end if DynareOptions.lik_init==1 - for i=1:EstimatedParameters.nvx - k =EstimatedParameters.var_exo(i,1); - DQ(k,k,i) = 2*sqrt(Q(k,k)); - dum = lyapunov_symm(T,DOm(:,:,i),DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold,[],DynareOptions.debug); -% kk = find(abs(dum) < 1e-12); -% dum(kk) = 0; - DP(:,:,i)=dum; - if full_Hess - for j=1:i - jcount=jcount+1; - dum = lyapunov_symm(T,dyn_unvech(D2Om(:,jcount)),DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold,[],DynareOptions.debug); -% kk = (abs(dum) < 1e-12); -% dum(kk) = 0; - D2P(:,jcount)=dyn_vech(dum); -% D2P(:,:,j,i)=dum; - end + for i=1:EstimatedParameters.nvx + k =EstimatedParameters.var_exo(i,1); + DQ(k,k,i) = 2*sqrt(Q(k,k)); + dum = lyapunov_symm(T,DOm(:,:,i),DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold,[],DynareOptions.debug); + % kk = find(abs(dum) < 1e-12); + % dum(kk) = 0; + DP(:,:,i)=dum; + if full_Hess + for j=1:i + jcount=jcount+1; + dum = lyapunov_symm(T,dyn_unvech(D2Om(:,jcount)),DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold,[],DynareOptions.debug); + % kk = (abs(dum) < 1e-12); + % dum(kk) = 0; + D2P(:,jcount)=dyn_vech(dum); + % D2P(:,:,j,i)=dum; + end + end end end - end offset = EstimatedParameters.nvx; for i=1:EstimatedParameters.nvn k = EstimatedParameters.var_endo(i,1); DH(k,k,i+offset) = 2*sqrt(H(k,k)); if full_Hess - D2H(k,k,i+offset,i+offset) = 2; + D2H(k,k,i+offset,i+offset) = 2; end end offset = offset + EstimatedParameters.nvn; if DynareOptions.lik_init==1 - for j=1:EstimatedParameters.np - dum = lyapunov_symm(T,DT(:,:,j+offset)*Pstar*T'+T*Pstar*DT(:,:,j+offset)'+DOm(:,:,j+offset),DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold,[],DynareOptions.debug); -% kk = find(abs(dum) < 1e-12); -% dum(kk) = 0; - DP(:,:,j+offset)=dum; - if full_Hess - DTj = DT(:,:,j+offset); - DPj = dum; - for i=1:j+offset - jcount=jcount+1; - DTi = DT(:,:,i); - DPi = DP(:,:,i); - D2Tij = reshape(D2T(:,jcount),size(T)); - D2Omij = dyn_unvech(D2Om(:,jcount)); - tmp = D2Tij*Pstar*T' + T*Pstar*D2Tij' + DTi*DPj*T' + DTj*DPi*T' + T*DPj*DTi' + T*DPi*DTj' + DTi*Pstar*DTj' + DTj*Pstar*DTi' + D2Omij; - dum = lyapunov_symm(T,tmp,DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold,[],DynareOptions.debug); -% dum(abs(dum)<1.e-12) = 0; - D2P(:,jcount) = dyn_vech(dum); -% D2P(:,:,j+offset,i) = dum; - end + for j=1:EstimatedParameters.np + dum = lyapunov_symm(T,DT(:,:,j+offset)*Pstar*T'+T*Pstar*DT(:,:,j+offset)'+DOm(:,:,j+offset),DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold,[],DynareOptions.debug); + % kk = find(abs(dum) < 1e-12); + % dum(kk) = 0; + DP(:,:,j+offset)=dum; + if full_Hess + DTj = DT(:,:,j+offset); + DPj = dum; + for i=1:j+offset + jcount=jcount+1; + DTi = DT(:,:,i); + DPi = DP(:,:,i); + D2Tij = reshape(D2T(:,jcount),size(T)); + D2Omij = dyn_unvech(D2Om(:,jcount)); + tmp = D2Tij*Pstar*T' + T*Pstar*D2Tij' + DTi*DPj*T' + DTj*DPi*T' + T*DPj*DTi' + T*DPi*DTj' + DTi*Pstar*DTj' + DTj*Pstar*DTi' + D2Omij; + dum = lyapunov_symm(T,tmp,DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold,[],DynareOptions.debug); + % dum(abs(dum)<1.e-12) = 0; + D2P(:,jcount) = dyn_vech(dum); + % D2P(:,:,j+offset,i) = dum; + end + end end end - end if analytic_derivation==1 analytic_deriv_info={analytic_derivation,DT,DYss,DOm,DH,DP,asy_Hess}; else @@ -640,7 +640,7 @@ if ((kalman_algo==1) || (kalman_algo==3))% Multivariate Kalman Filter fval = Inf; info(1) = 55; info(4) = 0.1; - exit_flag = 0; + exit_flag = 0; return end [LIK,lik] = kalman_filter_fast(Y,diffuse_periods+1,size(Y,2), ... @@ -746,7 +746,7 @@ if (kalman_algo==2) || (kalman_algo==4) if singularity_has_been_detected a = zeros(mmm,1); elseif ~expanded_state_vector_for_univariate_filter - a = [a; zeros(pp,1)]; + a = [a; zeros(pp,1)]; end end end @@ -841,14 +841,14 @@ else end if DynareOptions.endogenous_prior==1 - if DynareOptions.lik_init==2 || DynareOptions.lik_init==3 - error('Endogenous prior not supported with non-stationary models') - else - [lnpriormom] = endogenous_prior(Y,Pstar,BayesInfo,H); - fval = (likelihood-lnprior-lnpriormom); - end + if DynareOptions.lik_init==2 || DynareOptions.lik_init==3 + error('Endogenous prior not supported with non-stationary models') + else + [lnpriormom] = endogenous_prior(Y,Pstar,BayesInfo,H); + fval = (likelihood-lnprior-lnpriormom); + end else - fval = (likelihood-lnprior); + fval = (likelihood-lnprior); end if DynareOptions.prior_restrictions.status diff --git a/matlab/dsge_simulated_theoretical_correlation.m b/matlab/dsge_simulated_theoretical_correlation.m index b468defe30..ae141905b3 100644 --- a/matlab/dsge_simulated_theoretical_correlation.m +++ b/matlab/dsge_simulated_theoretical_correlation.m @@ -16,7 +16,7 @@ function [nvar,vartan,CorrFileNumber] = dsge_simulated_theoretical_correlation(S % nvar [integer] nvar is the number of stationary variables. % vartan [char] array of characters (with nvar rows). % CorrFileNumber [integer] scalar, number of prior or posterior data files (for correlation). - + % Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. diff --git a/matlab/dsge_simulated_theoretical_variance_decomposition.m b/matlab/dsge_simulated_theoretical_variance_decomposition.m index a6ce7313fb..9eb9851741 100644 --- a/matlab/dsge_simulated_theoretical_variance_decomposition.m +++ b/matlab/dsge_simulated_theoretical_variance_decomposition.m @@ -119,17 +119,17 @@ for file = 1:NumberOfDrawsFiles if file==1 && linee==1 [tmp, stationary_vars] = th_autocovariances(dr,ivar,M_,options_,nodecomposition); if isempty(stationary_vars) - fprintf('\ndsge_simulated_theoretical_variance_decomposition:: All requested endogenous variables have a unit root and thus infinite variance.\n') - fprintf('dsge_simulated_theoretical_variance_decomposition:: No decomposition is performed.\n') - only_non_stationary_vars=1; + fprintf('\ndsge_simulated_theoretical_variance_decomposition:: All requested endogenous variables have a unit root and thus infinite variance.\n') + fprintf('dsge_simulated_theoretical_variance_decomposition:: No decomposition is performed.\n') + only_non_stationary_vars=1; end end if only_non_stationary_vars - for i=1:nvar + for i=1:nvar for j=1:nexo Decomposition_array(linea,(i-1)*nexo+j) = NaN; end - end + end else tmp = th_autocovariances(dr,ivar,M_,options_,nodecomposition); for i=1:nvar diff --git a/matlab/dsge_var_likelihood.m b/matlab/dsge_var_likelihood.m index d67dcfb84d..9878d19c97 100644 --- a/matlab/dsge_var_likelihood.m +++ b/matlab/dsge_var_likelihood.m @@ -9,15 +9,15 @@ function [fval,info,exit_flag,grad,hess,SteadyState,trend_coeff,PHI_tilde,SIGMA_ % o fval [double] Value of the posterior kernel at xparam1. % o info [integer] Vector of informations about the penalty. % o exit_flag [integer] Zero if the function returns a penalty, one otherwise. -% o grad [double] place holder for gradient of the likelihood +% o grad [double] place holder for gradient of the likelihood % currently not supported by dsge_var -% o hess [double] place holder for hessian matrix of the likelihood +% o hess [double] place holder for hessian matrix of the likelihood % currently not supported by dsge_var % o SteadyState [double] Steady state vector possibly recomputed % by call to dynare_resolve() % o trend_coeff [double] place holder for trend coefficients, % currently not supported by dsge_var -% o PHI_tilde [double] Stacked BVAR-DSGE autoregressive matrices (at the mode associated to xparam1); +% o PHI_tilde [double] Stacked BVAR-DSGE autoregressive matrices (at the mode associated to xparam1); % formula (28), DS (2004) % o SIGMA_u_tilde [double] Covariance matrix of the BVAR-DSGE (at the mode associated to xparam1), % formula (29), DS (2004) @@ -32,8 +32,8 @@ function [fval,info,exit_flag,grad,hess,SteadyState,trend_coeff,PHI_tilde,SIGMA_ % ALGORITHMS % Follows the computations outlined in Del Negro/Schorfheide (2004): % Priors from general equilibrium models for VARs, International Economic -% Review, 45(2), pp. 643-673 -% +% Review, 45(2), pp. 643-673 +% % SPECIAL REQUIREMENTS % None. @@ -158,8 +158,8 @@ end % Return, with endogenous penalty when possible, if dynare_resolve issues an error code (defined in resol). if info(1) if info(1) == 3 || info(1) == 4 || info(1) == 5 || info(1)==6 ||info(1) == 19 ||... - info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ... - info(1) == 81 || info(1) == 84 || info(1) == 85 + info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ... + info(1) == 81 || info(1) == 84 || info(1) == 85 %meaningful second entry of output that can be used fval = Inf; info(4) = info(2); @@ -246,7 +246,7 @@ if ~isinf(dsge_prior_weight)% Evaluation of the likelihood of the dsge-var model tmp0 = dsge_prior_weight*NumberOfObservations*TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1) + mYY ; %first term of square bracket in formula (29), DS (2004) tmp1 = dsge_prior_weight*NumberOfObservations*GYX + mYX; %first element of second term of square bracket in formula (29), DS (2004) tmp2 = inv(dsge_prior_weight*NumberOfObservations*GXX+mXX); %middle element of second term of square bracket in formula (29), DS (2004) - SIGMA_u_tilde = tmp0 - tmp1*tmp2*tmp1'; %square bracket term in formula (29), DS (2004) + SIGMA_u_tilde = tmp0 - tmp1*tmp2*tmp1'; %square bracket term in formula (29), DS (2004) clear('tmp0'); [SIGMAu_is_positive_definite, penalty] = ispd(SIGMA_u_tilde); if ~SIGMAu_is_positive_definite @@ -265,7 +265,7 @@ if ~isinf(dsge_prior_weight)% Evaluation of the likelihood of the dsge-var model prodlng2 = sum(gammaln(.5*(dsge_prior_weight*NumberOfObservations- ... NumberOfParameters ... +1-(1:NumberOfObservedVariables)'))); %last term in denominator of third line of (A.2), DS (2004) - %Compute minus log likelihood according to (A.2), DS (2004) + %Compute minus log likelihood according to (A.2), DS (2004) lik = .5*NumberOfObservedVariables*log(det(dsge_prior_weight*NumberOfObservations*GXX+mXX)) ... %first term in numerator of second line of (A.2), DS (2004) + .5*((dsge_prior_weight+1)*NumberOfObservations-NumberOfParameters)*log(det((dsge_prior_weight+1)*NumberOfObservations*SIGMA_u_tilde)) ... %second term in numerator of second line of (A.2), DS (2004) - .5*NumberOfObservedVariables*log(det(dsge_prior_weight*NumberOfObservations*GXX)) ... %first term in denominator of second line of (A.2), DS (2004) @@ -278,7 +278,7 @@ else% Evaluation of the likelihood of the dsge-var model when the dsge prior wei PHI_star = iGXX*transpose(GYX); %Compute minus log likelihood according to (33), DS (2004) (where the last term in the trace operator has been multiplied out) lik = NumberOfObservations * ( log(det(SIGMA_u_star)) + NumberOfObservedVariables*log(2*pi) + ... - trace(inv(SIGMA_u_star)*(mYY - transpose(mYX*PHI_star) - mYX*PHI_star + transpose(PHI_star)*mXX*PHI_star)/NumberOfObservations)); + trace(inv(SIGMA_u_star)*(mYY - transpose(mYX*PHI_star) - mYX*PHI_star + transpose(PHI_star)*mXX*PHI_star)/NumberOfObservations)); lik = .5*lik;% Minus likelihood SIGMA_u_tilde=SIGMA_u_star; PHI_tilde=PHI_star; @@ -337,8 +337,8 @@ if (nargout >= 10) end if (nargout==11) - prior.SIGMA_u_star = SIGMA_u_star; - prior.PHI_star = PHI_star; + prior.SIGMA_u_star = SIGMA_u_star; + prior.PHI_star = PHI_star; prior.ArtificialSampleSize = fix(dsge_prior_weight*NumberOfObservations); prior.DF = prior.ArtificialSampleSize - NumberOfParameters - NumberOfObservedVariables; prior.iGXX_star = iGXX; diff --git a/matlab/dy_date.m b/matlab/dy_date.m index 7ce72e836a..980e838977 100644 --- a/matlab/dy_date.m +++ b/matlab/dy_date.m @@ -20,4 +20,3 @@ function y=dy_date(year,period) 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 a944dc1883..2690275542 100644 --- a/matlab/dyn2vec.m +++ b/matlab/dyn2vec.m @@ -12,7 +12,7 @@ function [z,zss]=dyn2vec(s1,s2) % % SPECIAL REQUIREMENTS % none -% +% % Copyright (C) 2001-2009 Dynare Team % @@ -50,7 +50,7 @@ if nargin == 0 end return else - j = strmatch(s1,M_.endo_names,'exact'); + j = strmatch(s1,M_.endo_names,'exact'); if ~ isempty(j) z = oo_.endo_simul(j,k)'; else @@ -83,6 +83,3 @@ end % 08/24/01 MJ replaced globlize by internal assignin % 08/24/01 MJ added 'exact' to strmatch (thanks to David Vavra) % 01/31/03 MJ added provision for alternative name of variable - - - diff --git a/matlab/dyn_diag_vech.m b/matlab/dyn_diag_vech.m index 5d5d946648..4491038086 100644 --- a/matlab/dyn_diag_vech.m +++ b/matlab/dyn_diag_vech.m @@ -1,11 +1,11 @@ function d = dyn_diag_vech(Vector) % This function returns the diagonal elements of a symmetric matrix % stored in vech form -% -% INPUTS +% +% INPUTS % Vector [double] a m*1 vector. -% -% OUTPUTS +% +% OUTPUTS % d [double] a n*1 vector, where n solves n*(n+1)/2=m. % Copyright (C) 2010 Dynare Team diff --git a/matlab/dyn_first_order_solver.m b/matlab/dyn_first_order_solver.m index 63d79cbe27..a09aa1645e 100644 --- a/matlab/dyn_first_order_solver.m +++ b/matlab/dyn_first_order_solver.m @@ -66,8 +66,8 @@ function [dr,info] = dyn_first_order_solver(jacobia,DynareModel,dr,DynareOptions persistent reorder_jacobian_columns innovations_idx index_s index_m index_c persistent index_p row_indx index_0m index_0p k1 k2 state_var -persistent ndynamic nstatic nfwrd npred nboth nd nsfwrd n_current index_d -persistent index_e index_d1 index_d2 index_e1 index_e2 row_indx_de_1 +persistent ndynamic nstatic nfwrd npred nboth nd nsfwrd n_current index_d +persistent index_e index_d1 index_d2 index_e1 index_e2 row_indx_de_1 persistent row_indx_de_2 cols_b @@ -82,7 +82,7 @@ end exo_nbr = DynareModel.exo_nbr; if isempty(reorder_jacobian_columns) - + maximum_lag = DynareModel.maximum_endo_lag; kstate = dr.kstate; nfwrd = DynareModel.nfwrd; @@ -149,7 +149,7 @@ if isempty(reorder_jacobian_columns) index_e1 = [1:npred+nboth, npred+nboth+find(llx(maximum_lag+1,nstatic+npred+(1: ... nsfwrd)))]; index_e2 = npred+nboth+(1:nboth); - + [junk,cols_b] = find(lead_lag_incidence(maximum_lag+1, order_var)); reorder_jacobian_columns = [nonzeros(lead_lag_incidence(:,order_var)'); ... @@ -179,12 +179,12 @@ if task ~= 1 && (DynareOptions.dr_cycle_reduction || DynareOptions.dr_logarithmi if n_current < DynareModel.endo_nbr if DynareOptions.dr_cycle_reduction error(['The cycle reduction algorithme can''t be used when the ' ... - 'coefficient matrix for current variables isn''t invertible']) + 'coefficient matrix for current variables isn''t invertible']) elseif DynareOptions.dr_logarithmic_reduction error(['The logarithmic reduction algorithme can''t be used when the ' ... 'coefficient matrix for current variables isn''t invertible']) end - end + end if DynareOptions.gpu gpuArray(A1); gpuArray(B1); @@ -212,7 +212,7 @@ else D(row_indx_de_2,index_d2) = eye(nboth); E(row_indx_de_1,index_e1) = -aa(row_indx,index_e); E(row_indx_de_2,index_e2) = eye(nboth); - + [err, ss, tt, w, sdim, dr.eigval, info1] = mjdgges(E, D, DynareOptions.qz_criterium, DynareOptions.qz_zero_threshold); mexErrCheck('mjdgges', err); @@ -235,7 +235,7 @@ else dr.full_rank = 0; else dr.full_rank = 1; - end + end return end diff --git a/matlab/dyn_forecast.m b/matlab/dyn_forecast.m index edb1e4ef13..a58b126a18 100644 --- a/matlab/dyn_forecast.m +++ b/matlab/dyn_forecast.m @@ -1,7 +1,7 @@ function [forecast,info] = dyn_forecast(var_list,M,options,oo,task,dataset_info) % function dyn_forecast(var_list,M,options,oo,task,dataset_info) % computes mean forecast for a given value of the parameters -% compues also confidence band for the forecast +% compues also confidence band for the forecast % % INPUTS % var_list: list of variables (character matrix) @@ -43,7 +43,7 @@ if nargin<6 && options.prefilter elseif nargin==6 mean_varobs=dataset_info.descriptive.mean'; end - + info = 0; oo=make_ex_(M,options,oo); @@ -92,7 +92,7 @@ switch task for i = 1:M.endo_nbr v_name = deblank(M.endo_names(i,:)); y0(i,:) = y_smoothed.(v_name)(end-maximum_lag+1:end); %includes steady state or mean, but simult_ will subtract only steady state - % 2. Subtract mean/steady state and add steady state; takes care of prefiltering + % 2. Subtract mean/steady state and add steady state; takes care of prefiltering if isfield(oo.Smoother,'Constant') && isfield(oo.Smoother.Constant,v_name) y0(i,:)=y0(i,:)-oo.Smoother.Constant.(v_name)(end-maximum_lag+1:end); %subtract mean or steady state if options.loglinear @@ -100,7 +100,7 @@ switch task else y0(i,:)=y0(i,:)+oo.dr.ys(strmatch(v_name,deblank(M.endo_names),'exact')); end - end + end % 2. Subtract trend if isfield(oo.Smoother,'Trend') && isfield(oo.Smoother.Trend,v_name) y0(i,:)=y0(i,:)-oo.Smoother.Trend.(v_name)(end-maximum_lag+1:end); %subtract trend, which is not subtracted by simult_ @@ -121,8 +121,8 @@ switch task trend_coeffs = [trend_coeffs; oo.Smoother.TrendCoeffs(trend_var_index)]; end end - if ~isempty(trend_coeffs) - trend = trend_coeffs*(options.first_obs+gend-1+(1-M.maximum_lag:horizon)); + if ~isempty(trend_coeffs) + trend = trend_coeffs*(options.first_obs+gend-1+(1-M.maximum_lag:horizon)); if options.prefilter trend = trend - repmat(mean(trend_coeffs*[options.first_obs:options.first_obs+gend-1],2),1,horizon+1); %subtract mean trend end @@ -132,13 +132,13 @@ switch task end otherwise error('Wrong flag value') -end +end if M.exo_det_nbr == 0 if isequal(M.H,0) [yf,int_width] = forcst(oo.dr,y0,horizon,var_list,M,oo,options); else - [yf,int_width,int_width_ME] = forcst(oo.dr,y0,horizon,var_list,M,oo,options); + [yf,int_width,int_width_ME] = forcst(oo.dr,y0,horizon,var_list,M,oo,options); end else exo_det_length = size(oo.exo_det_simul,1)-M.maximum_lag; @@ -146,17 +146,17 @@ else ex = zeros(horizon,M.exo_nbr); oo.exo_det_simul = [ oo.exo_det_simul;... repmat(oo.exo_det_steady_state',... - horizon- ... + horizon- ... exo_det_length,1)]; - elseif horizon <= exo_det_length - ex = zeros(exo_det_length,M.exo_nbr); + elseif horizon <= exo_det_length + ex = zeros(exo_det_length,M.exo_nbr); end if isequal(M.H,0) [yf,int_width] = simultxdet(y0,ex,oo.exo_det_simul,... - options.order,var_list,M,oo,options); + options.order,var_list,M,oo,options); else [yf,int_width,int_width_ME] = simultxdet(y0,ex,oo.exo_det_simul,... - options.order,var_list,M,oo,options); + options.order,var_list,M,oo,options); end end @@ -171,7 +171,7 @@ if options.loglinear == 1 else if options.prefilter == 1 %subtract steady state and add mean for observables yf(i_var_obs,:)=yf(i_var_obs,:)-repmat(oo.dr.ys(i_var_obs),1,horizon+M.maximum_lag)+ repmat(mean_varobs,1,horizon+M.maximum_lag); - end + end end for i=1:n_var diff --git a/matlab/dyn_latex_table.m b/matlab/dyn_latex_table.m index 63fb6095f6..ca14e351f5 100644 --- a/matlab/dyn_latex_table.m +++ b/matlab/dyn_latex_table.m @@ -27,7 +27,7 @@ OutputDirectoryName = CheckPath('Output',M_.dname); %% get width of label column if ~isempty(label_width) label_width = max(size(deblank(char(headers(1,:),labels)),2)+2, ... - label_width); + label_width); else %use default length label_width = max(size(deblank(char(headers(1,:),labels)),2))+2; end diff --git a/matlab/dyn_ramsey_static.m b/matlab/dyn_ramsey_static.m index e87b59b4d8..25b5301e63 100644 --- a/matlab/dyn_ramsey_static.m +++ b/matlab/dyn_ramsey_static.m @@ -8,7 +8,7 @@ function [steady_state,params,check] = dyn_ramsey_static(ys_init,M,options_,oo) % M: Dynare model structure % options: Dynare options structure % oo: Dynare results structure -% +% % OUTPUTS % steady_state: steady state value % params: parameters at steady state, potentially updated by @@ -39,7 +39,7 @@ function [steady_state,params,check] = dyn_ramsey_static(ys_init,M,options_,oo) params = M.params; check = 0; options_.steadystate.nocheck = 1; %locally disable checking because Lagrange multipliers are not accounted for in evaluate_steady_state_file -% dyn_ramsey_static_1 is a subfunction + % dyn_ramsey_static_1 is a subfunction nl_func = @(x) dyn_ramsey_static_1(x,M,options_,oo); % check_static_model is a subfunction @@ -61,7 +61,7 @@ elseif options_.steadystate_flag end if info1==4 check=87; - end + end else %solve for instrument, using multivariate solver, starting at %initial value for instrument @@ -102,7 +102,7 @@ endo_nbr = M.endo_nbr; endo_names = M.endo_names; orig_endo_nbr = M.orig_endo_nbr; aux_vars_type = [M.aux_vars.type]; -orig_endo_aux_nbr = orig_endo_nbr + min(find(aux_vars_type == 6)) - 1; +orig_endo_aux_nbr = orig_endo_nbr + min(find(aux_vars_type == 6)) - 1; orig_eq_nbr = M.orig_eq_nbr; inst_nbr = orig_endo_aux_nbr - orig_eq_nbr; % indices of Lagrange multipliers @@ -120,7 +120,7 @@ if options_.steadystate_flag ys_init(k_inst) = x; %set instrument, the only value required for steady state computation, to current value [x,params,check] = evaluate_steady_state_file(ys_init,... %returned x now has size endo_nbr as opposed to input size of n_instruments [oo.exo_steady_state; ... - oo.exo_det_steady_state], ... + oo.exo_det_steady_state], ... M,options_,~options_.steadystate.nocheck); if any(imag(x(1:M.orig_endo_nbr))) %return with penalty resids=1+sum(abs(imag(x(1:M.orig_endo_nbr)))); %return with penalty @@ -137,7 +137,7 @@ xx(1:M.orig_endo_nbr) = x(1:M.orig_endo_nbr); %set values of original endogenous if any([M.aux_vars.type] ~= 6) %auxiliary variables other than multipliers needs_set_auxiliary_variables = 1; fh = str2func([M.fname '_set_auxiliary_variables']); - s_a_v_func = @(z) fh(z,... + s_a_v_func = @(z) fh(z,... [oo.exo_steady_state,... oo.exo_det_steady_state],... params); @@ -154,12 +154,12 @@ Uyy = reshape(Uyy,endo_nbr,endo_nbr); % set multipliers and auxiliary variables that % depends on multipliers to 0 to compute residuals if (options_.bytecode) - [chck, res, junk] = bytecode('static',xx,[oo.exo_steady_state oo.exo_det_steady_state], ... - params, 'evaluate'); - fJ = junk.g1; + [chck, res, junk] = bytecode('static',xx,[oo.exo_steady_state oo.exo_det_steady_state], ... + params, 'evaluate'); + fJ = junk.g1; else - [res,fJ] = feval([fname '_static'],xx,[oo.exo_steady_state oo.exo_det_steady_state], ... - params); + [res,fJ] = feval([fname '_static'],xx,[oo.exo_steady_state oo.exo_det_steady_state], ... + params); end % index of multipliers and corresponding equations % the auxiliary variables before the Lagrange multipliers are treated @@ -193,7 +193,7 @@ function result = check_static_model(ys,M,options_,oo) result = false; if (options_.bytecode) [chck, res, junk] = bytecode('static',ys,[oo.exo_steady_state oo.exo_det_steady_state], ... - M.params, 'evaluate'); + M.params, 'evaluate'); else res = feval([M.fname '_static'],ys,[oo.exo_steady_state oo.exo_det_steady_state], ... M.params); @@ -201,4 +201,3 @@ end if norm(res) < options_.solve_tolf result = true; end - diff --git a/matlab/dyn_risky_steadystate_solver.m b/matlab/dyn_risky_steadystate_solver.m index c198ef25ec..3ea116df9e 100644 --- a/matlab/dyn_risky_steadystate_solver.m +++ b/matlab/dyn_risky_steadystate_solver.m @@ -1,550 +1,550 @@ function [dr,info] = dyn_risky_steadystate_solver(ys0,M, ... dr,options,oo) - %@info: - %! @deftypefn {Function File} {[@var{dr},@var{info}] =} dyn_risky_steadystate_solver (@var{ys0},@var{M},@var{dr},@var{options},@var{oo}) - %! @anchor{dyn_risky_steadystate_solver} - %! @sp 1 - %! Computes the second order risky steady state and first and second order reduced form of the DSGE model. - %! @sp 2 - %! @strong{Inputs} - %! @sp 1 - %! @table @ @var - %! @item ys0 - %! Vector containing a guess value for the risky steady state - %! @item M - %! Matlab's structure describing the model (initialized by @code{dynare}). - %! @item dr - %! Matlab's structure describing the reduced form solution of the model. - %! @item options - %! Matlab's structure describing the options (initialized by @code{dynare}). - %! @item oo - %! Matlab's structure gathering the results (initialized by @code{dynare}). - %! @end table - %! @sp 2 - %! @strong{Outputs} - %! @sp 1 - %! @table @ @var - %! @item dr - %! Matlab's structure describing the reduced form solution of the model. - %! @item info - %! Integer scalar, error code. - %! @sp 1 - %! @table @ @code - %! @item info==0 - %! No error. - %! @item info==1 - %! The model doesn't determine the current variables uniquely. - %! @item info==2 - %! MJDGGES returned an error code. - %! @item info==3 - %! Blanchard & Kahn conditions are not satisfied: no stable equilibrium. - %! @item info==4 - %! Blanchard & Kahn conditions are not satisfied: indeterminacy. - %! @item info==5 - %! Blanchard & Kahn conditions are not satisfied: indeterminacy due to rank failure. - %! @item info==6 - %! The jacobian evaluated at the deterministic steady state is complex. - %! @item info==19 - %! The steadystate routine thrown an exception (inconsistent deep parameters). - %! @item info==20 - %! Cannot find the steady state, info(2) contains the sum of square residuals (of the static equations). - %! @item info==21 - %! The steady state is complex, info(2) contains the sum of square of imaginary parts of the steady state. - %! @item info==22 - %! The steady has NaNs. - %! @item info==23 - %! M_.params has been updated in the steadystate routine and has complex valued scalars. - %! @item info==24 - %! M_.params has been updated in the steadystate routine and has some NaNs. - %! @end table - %! @end table - %! @end deftypefn - %@eod: - - % Copyright (C) 2001-2014 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/>. - - - info = 0; - lead_lag_incidence = M.lead_lag_incidence; - order_var = dr.order_var; - endo_nbr = M.endo_nbr; - exo_nbr = M.exo_nbr; - - M.var_order_endo_names = M.endo_names(dr.order_var,:); - - [junk,dr.i_fwrd_g,i_fwrd_f] = find(lead_lag_incidence(3,order_var)); - dr.i_fwrd_f = i_fwrd_f; - nd = nnz(lead_lag_incidence) + M.exo_nbr; - dr.nd = nd; - kk = reshape(1:nd^2,nd,nd); - kkk = reshape(1:nd^3,nd^2,nd); - dr.i_fwrd2_f = kk(i_fwrd_f,i_fwrd_f); - dr.i_fwrd2a_f = kk(i_fwrd_f,:); - dr.i_fwrd3_f = kkk(dr.i_fwrd2_f,:); - dr.i_uu = kk(end-exo_nbr+1:end,end-exo_nbr+1:end); - if options.k_order_solver - func = @risky_residuals_k_order; - else - func = @risky_residuals; - end - - if isfield(options,'portfolio') && options.portfolio == 1 - pm = portfolio_model_structure(M,options); - - x0 = ys0(pm.v_p); - n = length(x0); - [x, info] = solve1(@risky_residuals_ds,x0,1:n,1:n,0,options.gstep, ... - options.solve_tolf,options.solve_tolx, ... - options.steady.maxit,options.debug,pm,M,dr, ... - options,oo); - if info - error('DS approach can''t be computed') - end - %[x, info] = csolve(@risky_residuals_ds,x0,[],1e-10,100,M,dr,options,oo); - % ys0(l_var) = x; - [resids,dr1] = risky_residuals_ds(x,pm,M,dr,options,oo); - ys1 = dr1.ys; - else - pm = model_structure(M,options); - end - - [ys, info] = solve1(func,ys0,1:endo_nbr,1:endo_nbr,0,options.gstep, ... - options.solve_tolf,options.solve_tolx, ... - options.steady.maxit,options.debug,pm,M,dr,options,oo); - % [ys, info] = csolve(func,ys0,[],1e-10,100,M,dr,options,oo); - if info - error('RSS approach can''t be computed') - end - dr.ys = ys; +%@info: +%! @deftypefn {Function File} {[@var{dr},@var{info}] =} dyn_risky_steadystate_solver (@var{ys0},@var{M},@var{dr},@var{options},@var{oo}) +%! @anchor{dyn_risky_steadystate_solver} +%! @sp 1 +%! Computes the second order risky steady state and first and second order reduced form of the DSGE model. +%! @sp 2 +%! @strong{Inputs} +%! @sp 1 +%! @table @ @var +%! @item ys0 +%! Vector containing a guess value for the risky steady state +%! @item M +%! Matlab's structure describing the model (initialized by @code{dynare}). +%! @item dr +%! Matlab's structure describing the reduced form solution of the model. +%! @item options +%! Matlab's structure describing the options (initialized by @code{dynare}). +%! @item oo +%! Matlab's structure gathering the results (initialized by @code{dynare}). +%! @end table +%! @sp 2 +%! @strong{Outputs} +%! @sp 1 +%! @table @ @var +%! @item dr +%! Matlab's structure describing the reduced form solution of the model. +%! @item info +%! Integer scalar, error code. +%! @sp 1 +%! @table @ @code +%! @item info==0 +%! No error. +%! @item info==1 +%! The model doesn't determine the current variables uniquely. +%! @item info==2 +%! MJDGGES returned an error code. +%! @item info==3 +%! Blanchard & Kahn conditions are not satisfied: no stable equilibrium. +%! @item info==4 +%! Blanchard & Kahn conditions are not satisfied: indeterminacy. +%! @item info==5 +%! Blanchard & Kahn conditions are not satisfied: indeterminacy due to rank failure. +%! @item info==6 +%! The jacobian evaluated at the deterministic steady state is complex. +%! @item info==19 +%! The steadystate routine thrown an exception (inconsistent deep parameters). +%! @item info==20 +%! Cannot find the steady state, info(2) contains the sum of square residuals (of the static equations). +%! @item info==21 +%! The steady state is complex, info(2) contains the sum of square of imaginary parts of the steady state. +%! @item info==22 +%! The steady has NaNs. +%! @item info==23 +%! M_.params has been updated in the steadystate routine and has complex valued scalars. +%! @item info==24 +%! M_.params has been updated in the steadystate routine and has some NaNs. +%! @end table +%! @end table +%! @end deftypefn +%@eod: + +% Copyright (C) 2001-2014 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/>. + + +info = 0; +lead_lag_incidence = M.lead_lag_incidence; +order_var = dr.order_var; +endo_nbr = M.endo_nbr; +exo_nbr = M.exo_nbr; + +M.var_order_endo_names = M.endo_names(dr.order_var,:); + +[junk,dr.i_fwrd_g,i_fwrd_f] = find(lead_lag_incidence(3,order_var)); +dr.i_fwrd_f = i_fwrd_f; +nd = nnz(lead_lag_incidence) + M.exo_nbr; +dr.nd = nd; +kk = reshape(1:nd^2,nd,nd); +kkk = reshape(1:nd^3,nd^2,nd); +dr.i_fwrd2_f = kk(i_fwrd_f,i_fwrd_f); +dr.i_fwrd2a_f = kk(i_fwrd_f,:); +dr.i_fwrd3_f = kkk(dr.i_fwrd2_f,:); +dr.i_uu = kk(end-exo_nbr+1:end,end-exo_nbr+1:end); +if options.k_order_solver + func = @risky_residuals_k_order; +else + func = @risky_residuals; +end - [resid,dr] = func(ys,pm,M,dr,options,oo); - dr.ghs2 = zeros(M.endo_nbr,1); - - for i=1:M.endo_nbr - if isfield(options,'portfolio') && options.portfolio == 1 - disp(sprintf('%16s %12.6f %12.6f',M.endo_names(i,:),ys1(i), ... - ys(i))) - else - disp(sprintf('%16s %12.6f %12.6f',M.endo_names(i,:),ys(i))) - end +if isfield(options,'portfolio') && options.portfolio == 1 + pm = portfolio_model_structure(M,options); + + x0 = ys0(pm.v_p); + n = length(x0); + [x, info] = solve1(@risky_residuals_ds,x0,1:n,1:n,0,options.gstep, ... + options.solve_tolf,options.solve_tolx, ... + options.steady.maxit,options.debug,pm,M,dr, ... + options,oo); + if info + error('DS approach can''t be computed') end + %[x, info] = csolve(@risky_residuals_ds,x0,[],1e-10,100,M,dr,options,oo); + % ys0(l_var) = x; + [resids,dr1] = risky_residuals_ds(x,pm,M,dr,options,oo); + ys1 = dr1.ys; +else + pm = model_structure(M,options); +end +[ys, info] = solve1(func,ys0,1:endo_nbr,1:endo_nbr,0,options.gstep, ... + options.solve_tolf,options.solve_tolx, ... + options.steady.maxit,options.debug,pm,M,dr,options,oo); +% [ys, info] = csolve(func,ys0,[],1e-10,100,M,dr,options,oo); +if info + error('RSS approach can''t be computed') end +dr.ys = ys; -function [resid,dr] = risky_residuals(ys,pm,M,dr,options,oo) - - lead_lag_incidence = M.lead_lag_incidence; - iyv = lead_lag_incidence'; - iyv = iyv(:); - iyr0 = find(iyv) ; - - if M.exo_nbr == 0 - oo.exo_steady_state = [] ; - end - - z = repmat(ys,1,3); - z = z(iyr0) ; - [resid1,d1,d2] = feval([M.fname '_dynamic'],z,... - [oo.exo_simul ... - oo.exo_det_simul], M.params, dr.ys, 2); - if ~isreal(d1) || ~isreal(d2) - pause - end - - if options.use_dll - % In USE_DLL mode, the hessian is in the 3-column sparse representation - d2 = sparse(d2(:,1), d2(:,2), d2(:,3), ... - size(d1, 1), size(d1, 2)*size(d1, 2)); - end +[resid,dr] = func(ys,pm,M,dr,options,oo); +dr.ghs2 = zeros(M.endo_nbr,1); +for i=1:M.endo_nbr if isfield(options,'portfolio') && options.portfolio == 1 - pm = portfolio_model_structure(M,options); - x = ys(pm.v_p); - dr = first_step_ds(x,pm,M,dr,options,oo); - dr.ys = ys; + disp(sprintf('%16s %12.6f %12.6f',M.endo_names(i,:),ys1(i), ... + ys(i))) else - pm = model_structure(M,options); - [dr,info] = dyn_first_order_solver(d1,M,dr,options,0); - if info - print_info(info,options.noprint,options); - end - dr = dyn_second_order_solver(d1,d2,dr,M,... - options.threads.kronecker.A_times_B_kronecker_C,... - options.threads.kronecker.sparse_hessian_times_B_kronecker_C); + disp(sprintf('%16s %12.6f %12.6f',M.endo_names(i,:),ys(i))) end - - gu1 = dr.ghu(pm.i_fwrd_g,:); +end - resid = resid1+0.5*(d1(:,pm.i_fwrd_f1)*dr.ghuu(pm.i_fwrd_g,:)+ ... - d2(:,pm.i_fwrd_f2)*kron(gu1,gu1))*vec(M.Sigma_e); end -function [resid,dr] = risky_residuals_ds(x,pm,M,dr,options,oo) - - v_p = pm.v_p; - v_np = pm.v_np; - - % computing steady state of non-portfolio variables consistent with - % assumed portfolio - dr.ys(v_p) = x; - ys0 = dr.ys(v_np); - f_h =str2func([M.fname '_static']); - [dr.ys(v_np),info] = csolve(@ds_static_model,ys0,[],1e-10,100,f_h,x,pm.eq_np,v_np,v_p, ... - M.endo_nbr,M.exo_nbr,M.params); +function [resid,dr] = risky_residuals(ys,pm,M,dr,options,oo) + +lead_lag_incidence = M.lead_lag_incidence; +iyv = lead_lag_incidence'; +iyv = iyv(:); +iyr0 = find(iyv) ; + +if M.exo_nbr == 0 + oo.exo_steady_state = [] ; +end + +z = repmat(ys,1,3); +z = z(iyr0) ; +[resid1,d1,d2] = feval([M.fname '_dynamic'],z,... + [oo.exo_simul ... + oo.exo_det_simul], M.params, dr.ys, 2); +if ~isreal(d1) || ~isreal(d2) + pause +end + +if options.use_dll + % In USE_DLL mode, the hessian is in the 3-column sparse representation + d2 = sparse(d2(:,1), d2(:,2), d2(:,3), ... + size(d1, 1), size(d1, 2)*size(d1, 2)); +end + +if isfield(options,'portfolio') && options.portfolio == 1 + pm = portfolio_model_structure(M,options); + x = ys(pm.v_p); + dr = first_step_ds(x,pm,M,dr,options,oo); + dr.ys = ys; +else + pm = model_structure(M,options); + [dr,info] = dyn_first_order_solver(d1,M,dr,options,0); if info - error('can''t compute non-portfolio steady state') - end - - dr_np = first_step_ds(x,pm,M,dr,options,oo); - - lead_lag_incidence = M.lead_lag_incidence; - iyv = lead_lag_incidence'; - iyv = iyv(:); - iyr0 = find(iyv) ; - - z = repmat(dr.ys,1,3); - z = z(iyr0) ; - [resid1,d1,d2] = feval([M.fname '_dynamic'],z,... - [oo.exo_simul ... - oo.exo_det_simul], M.params, dr.ys, 2); - if ~isreal(d1) || ~isreal(d2) - pause - end - - if options.use_dll - % In USE_DLL mode, the hessian is in the 3-column sparse representation - d2 = sparse(d2(:,1), d2(:,2), d2(:,3), ... - size(d1, 1), size(d1, 2)*size(d1, 2)); + print_info(info,options.noprint,options); end + dr = dyn_second_order_solver(d1,d2,dr,M,... + options.threads.kronecker.A_times_B_kronecker_C,... + options.threads.kronecker.sparse_hessian_times_B_kronecker_C); +end + +gu1 = dr.ghu(pm.i_fwrd_g,:); + +resid = resid1+0.5*(d1(:,pm.i_fwrd_f1)*dr.ghuu(pm.i_fwrd_g,:)+ ... + d2(:,pm.i_fwrd_f2)*kron(gu1,gu1))*vec(M.Sigma_e); +end + +function [resid,dr] = risky_residuals_ds(x,pm,M,dr,options,oo) + +v_p = pm.v_p; +v_np = pm.v_np; + +% computing steady state of non-portfolio variables consistent with +% assumed portfolio +dr.ys(v_p) = x; +ys0 = dr.ys(v_np); +f_h =str2func([M.fname '_static']); +[dr.ys(v_np),info] = csolve(@ds_static_model,ys0,[],1e-10,100,f_h,x,pm.eq_np,v_np,v_p, ... + M.endo_nbr,M.exo_nbr,M.params); +if info + error('can''t compute non-portfolio steady state') +end + +dr_np = first_step_ds(x,pm,M,dr,options,oo); + +lead_lag_incidence = M.lead_lag_incidence; +iyv = lead_lag_incidence'; +iyv = iyv(:); +iyr0 = find(iyv) ; + +z = repmat(dr.ys,1,3); +z = z(iyr0) ; +[resid1,d1,d2] = feval([M.fname '_dynamic'],z,... + [oo.exo_simul ... + oo.exo_det_simul], M.params, dr.ys, 2); +if ~isreal(d1) || ~isreal(d2) + pause +end + +if options.use_dll + % In USE_DLL mode, the hessian is in the 3-column sparse representation + d2 = sparse(d2(:,1), d2(:,2), d2(:,3), ... + size(d1, 1), size(d1, 2)*size(d1, 2)); +end + - - gu1 = dr_np.ghu(pm.i_fwrd_g,:); +gu1 = dr_np.ghu(pm.i_fwrd_g,:); - resid = resid1+0.5*(d2(:,pm.i_fwrd_f2)*kron(gu1,gu1))*vec(M.Sigma_e); +resid = resid1+0.5*(d2(:,pm.i_fwrd_f2)*kron(gu1,gu1))*vec(M.Sigma_e); - resid = resid(pm.eq_p) +resid = resid(pm.eq_p) end function dr_np = first_step_ds(x,pm,M,dr,options,oo) - lead_lag_incidence = M.lead_lag_incidence; - iyv = lead_lag_incidence'; - iyv = iyv(:); - iyr0 = find(iyv) ; - - ys = dr.ys; - ys(pm.v_p) = x; - - z = repmat(ys,1,3); - z = z(iyr0) ; - [resid1,d1,d2] = feval([M.fname '_dynamic'],z,... - [oo.exo_simul ... - oo.exo_det_simul], M.params, dr.ys, 2); - if ~isreal(d1) || ~isreal(d2) - pause - end - - if options.use_dll - % In USE_DLL mode, the hessian is in the 3-column sparse representation - d2 = sparse(d2(:,1), d2(:,2), d2(:,3), ... - size(d1, 1), size(d1, 2)*size(d1, 2)); - end +lead_lag_incidence = M.lead_lag_incidence; +iyv = lead_lag_incidence'; +iyv = iyv(:); +iyr0 = find(iyv) ; + +ys = dr.ys; +ys(pm.v_p) = x; + +z = repmat(ys,1,3); +z = z(iyr0) ; +[resid1,d1,d2] = feval([M.fname '_dynamic'],z,... + [oo.exo_simul ... + oo.exo_det_simul], M.params, dr.ys, 2); +if ~isreal(d1) || ~isreal(d2) + pause +end + +if options.use_dll + % In USE_DLL mode, the hessian is in the 3-column sparse representation + d2 = sparse(d2(:,1), d2(:,2), d2(:,3), ... + size(d1, 1), size(d1, 2)*size(d1, 2)); +end + +d1_np = d1(pm.eq_np,pm.i_d1_np); +d2_np = d2(pm.eq_np,pm.i_d2_np); + +[dr_np,info] = dyn_first_order_solver(d1_np,pm.M_np,pm.dr_np,options,0); +if info + print_info(info, 0, options); + return +end + +dr_np = dyn_second_order_solver(d1_np,d2_np,dr_np,pm.M_np,... + options.threads.kronecker.A_times_B_kronecker_C,... + options.threads.kronecker.sparse_hessian_times_B_kronecker_C); +end + +function [resid,dr] = risky_residuals_k_order(ys,pm,M,dr,options,oo) +exo_nbr = M.exo_nbr; +endo_nbr = M.endo_nbr; + +iyv = M.lead_lag_incidence'; +iyv = iyv(:); +iyr0 = find(iyv) ; + +if exo_nbr == 0 + oo.exo_steady_state = [] ; +end + +z = repmat(ys,1,3); +z = z(iyr0) ; +[resid1,d1,d2] = feval([M.fname '_dynamic'],z,... + [oo.exo_simul ... + oo.exo_det_simul], M.params, dr.ys, 2); + +if isfield(options,'portfolio') && options.portfolio == 1 + eq_np = pm.eq_np; + + d1_np = d1(eq_np,pm.i_d1_np); + d2_np = d2(eq_np,pm.i_d2_np); + + M_np = pm.M_np; + dr_np = pm.dr_np; - d1_np = d1(pm.eq_np,pm.i_d1_np); - d2_np = d2(pm.eq_np,pm.i_d2_np); - [dr_np,info] = dyn_first_order_solver(d1_np,pm.M_np,pm.dr_np,options,0); if info print_info(info, 0, options); return end - + dr_np = dyn_second_order_solver(d1_np,d2_np,dr_np,pm.M_np,... options.threads.kronecker.A_times_B_kronecker_C,... options.threads.kronecker.sparse_hessian_times_B_kronecker_C); end -function [resid,dr] = risky_residuals_k_order(ys,pm,M,dr,options,oo) - exo_nbr = M.exo_nbr; - endo_nbr = M.endo_nbr; - - iyv = M.lead_lag_incidence'; - iyv = iyv(:); - iyr0 = find(iyv) ; - - if exo_nbr == 0 - oo.exo_steady_state = [] ; - end - - z = repmat(ys,1,3); - z = z(iyr0) ; - [resid1,d1,d2] = feval([M.fname '_dynamic'],z,... +i_fwrd_f1 = pm.i_fwrd_f1; +i_fwrd_f2 = pm.i_fwrd_f2; +i_fwrd_f3 = pm.i_fwrd_f3; +i_fwrd_g = pm.i_fwrd_g; +gu1 = dr_np.ghu(i_fwrd_g,:); +ghuu = dr_np.ghuu; + +resid = resid1+0.5*(d1(:,i_fwrd_f1)*ghuu(i_fwrd_g,:)+d2(:,i_fwrd_f2)* ... + kron(gu1,gu1))*vec(M.Sigma_e); + +if nargout > 1 + [resid1,d1,d2,d3] = feval([M.fname '_dynamic'],z,... [oo.exo_simul ... oo.exo_det_simul], M.params, dr.ys, 2); - - if isfield(options,'portfolio') && options.portfolio == 1 - eq_np = pm.eq_np; - - d1_np = d1(eq_np,pm.i_d1_np); - d2_np = d2(eq_np,pm.i_d2_np); - - M_np = pm.M_np; - dr_np = pm.dr_np; - - [dr_np,info] = dyn_first_order_solver(d1_np,pm.M_np,pm.dr_np,options,0); - if info - print_info(info, 0, options); - return - end - - dr_np = dyn_second_order_solver(d1_np,d2_np,dr_np,pm.M_np,... - options.threads.kronecker.A_times_B_kronecker_C,... - options.threads.kronecker.sparse_hessian_times_B_kronecker_C); - end - - i_fwrd_f1 = pm.i_fwrd_f1; - i_fwrd_f2 = pm.i_fwrd_f2; - i_fwrd_f3 = pm.i_fwrd_f3; - i_fwrd_g = pm.i_fwrd_g; - gu1 = dr_np.ghu(i_fwrd_g,:); - ghuu = dr_np.ghuu; - - resid = resid1+0.5*(d1(:,i_fwrd_f1)*ghuu(i_fwrd_g,:)+d2(:,i_fwrd_f2)* ... - kron(gu1,gu1))*vec(M.Sigma_e); - - if nargout > 1 - [resid1,d1,d2,d3] = feval([M.fname '_dynamic'],z,... - [oo.exo_simul ... - oo.exo_det_simul], M.params, dr.ys, 2); - - - [a,b,c] = find(d2(eq_np,pm.i_d2_np)); - d2_np = [a b c]; - - [a,b,c] = find(d3(eq_np,pm.i_d3_np)); - d3_np = [a b c]; - - options.order = 3; - % space holder, unused by k_order_pertrubation - dr_np.ys = dr.ys(pm.v_np); - nu2 = exo_nbr*(exo_nbr+1)/2; - nu3 = exo_nbr*(exo_nbr+1)*(exo_nbr+2)/3; - M_np.NZZDerivatives = [nnz(d1_np); nnz(d2_np); nnz(d3_np)]; - [err,g_0, g_1, g_2, g_3] = k_order_perturbation(dr_np,M_np,options,d1_np,d2_np,d3_np); - mexErrCheck('k_order_perturbation', err); - - gu1 = g_1(i_fwrd_g,end-exo_nbr+1:end); - ghuu = unfold2(g_2(:,end-nu2+1:end),exo_nbr); - ghsuu = get_ghsuu(g_3,size(g_1,2),exo_nbr); - - i_fwrd1_f2 = pm.i_fwrd1_f2; - i_fwrd1_f3 = pm.i_fwrd1_f3; - n = size(d1,2); - d1b = d1 + 0.5*( ... - d1(:,i_fwrd_f1)*... - d2(:,i_fwrd1_f2)*kron(eye(n),dr_np.ghuu(i_fwrd_g,:)*vec(M.Sigma_e))... - + 0.5*d3(:,i_fwrd1_f3)*kron(eye(n),kron(gu1,gu1)*vec(M.Sigma_e))); - format short - kk1 = [nonzeros(M.lead_lag_incidence(:,1:6)'); ... - nnz(M.lead_lag_incidence)+[1; 2]] - kk2 = [nonzeros(M.lead_lag_incidence(:,1:6)'); ... - nnz(M.lead_lag_incidence)+[3; 4]] - format short - gu1 - kron(gu1,gu1)*vec(M.Sigma_e) - disp(d1(:,:)) - disp(d1b(:,:)) - aa2=d2(:,i_fwrd1_f2)*kron(eye(n),dr_np.ghuu(i_fwrd_g,:)*vec(M.Sigma_e)); - aa3=d3(:,i_fwrd1_f3)*kron(eye(n),kron(gu1,gu1)*vec(M.Sigma_e)); - disp(d3(4,7+6*n+6*n*n)) - disp(d3(4,8+16*n+17*n*n)) %8,17,18 - disp(d3(4,8+17*n+16*n*n)) %8,17,18 - disp(d3(4,7*n+17+17*n*n)) %8,17,18 - disp(d3(4,7*n+18+16*n*n)) %8,17,18 - disp(d3(4,7*n*n+16*n+18)) %8,17,18 - disp(d3(4,7*n*n+17+17*n)) %8,17,18 - pause - disp(aa2(:,kk1)) - disp(aa2(:,kk2)) - disp(aa3(:,kk1)) - disp(aa3(:,kk2)) - [dr,info] = dyn_first_order_solver(d1b,M,dr,options,0); - if info - print_info(info, 0, options); - return - end - - disp_dr(dr,dr.order_var,[]); - + + + [a,b,c] = find(d2(eq_np,pm.i_d2_np)); + d2_np = [a b c]; + + [a,b,c] = find(d3(eq_np,pm.i_d3_np)); + d3_np = [a b c]; + + options.order = 3; + % space holder, unused by k_order_pertrubation + dr_np.ys = dr.ys(pm.v_np); + nu2 = exo_nbr*(exo_nbr+1)/2; + nu3 = exo_nbr*(exo_nbr+1)*(exo_nbr+2)/3; + M_np.NZZDerivatives = [nnz(d1_np); nnz(d2_np); nnz(d3_np)]; + [err,g_0, g_1, g_2, g_3] = k_order_perturbation(dr_np,M_np,options,d1_np,d2_np,d3_np); + mexErrCheck('k_order_perturbation', err); + + gu1 = g_1(i_fwrd_g,end-exo_nbr+1:end); + ghuu = unfold2(g_2(:,end-nu2+1:end),exo_nbr); + ghsuu = get_ghsuu(g_3,size(g_1,2),exo_nbr); + + i_fwrd1_f2 = pm.i_fwrd1_f2; + i_fwrd1_f3 = pm.i_fwrd1_f3; + n = size(d1,2); + d1b = d1 + 0.5*( ... + d1(:,i_fwrd_f1)*... + d2(:,i_fwrd1_f2)*kron(eye(n),dr_np.ghuu(i_fwrd_g,:)*vec(M.Sigma_e))... + + 0.5*d3(:,i_fwrd1_f3)*kron(eye(n),kron(gu1,gu1)*vec(M.Sigma_e))); + format short + kk1 = [nonzeros(M.lead_lag_incidence(:,1:6)'); ... + nnz(M.lead_lag_incidence)+[1; 2]] + kk2 = [nonzeros(M.lead_lag_incidence(:,1:6)'); ... + nnz(M.lead_lag_incidence)+[3; 4]] + format short + gu1 + kron(gu1,gu1)*vec(M.Sigma_e) + disp(d1(:,:)) + disp(d1b(:,:)) + aa2=d2(:,i_fwrd1_f2)*kron(eye(n),dr_np.ghuu(i_fwrd_g,:)*vec(M.Sigma_e)); + aa3=d3(:,i_fwrd1_f3)*kron(eye(n),kron(gu1,gu1)*vec(M.Sigma_e)); + disp(d3(4,7+6*n+6*n*n)) + disp(d3(4,8+16*n+17*n*n)) %8,17,18 + disp(d3(4,8+17*n+16*n*n)) %8,17,18 + disp(d3(4,7*n+17+17*n*n)) %8,17,18 + disp(d3(4,7*n+18+16*n*n)) %8,17,18 + disp(d3(4,7*n*n+16*n+18)) %8,17,18 + disp(d3(4,7*n*n+17+17*n)) %8,17,18 + pause + disp(aa2(:,kk1)) + disp(aa2(:,kk2)) + disp(aa3(:,kk1)) + disp(aa3(:,kk2)) + [dr,info] = dyn_first_order_solver(d1b,M,dr,options,0); + if info + print_info(info, 0, options); + return end + + disp_dr(dr,dr.order_var,[]); + +end end function y=unfold2(x,n) - y = zeros(size(x,1),n*n); - k = 1; - for i=1:n - for j=i:n - y(:,(i-1)*n+j) = x(:,k); - if i ~= j - y(:,(j-1)*n+i) = x(:,k); - end - k = k+1; +y = zeros(size(x,1),n*n); +k = 1; +for i=1:n + for j=i:n + y(:,(i-1)*n+j) = x(:,k); + if i ~= j + y(:,(j-1)*n+i) = x(:,k); end + k = k+1; end end +end function y=unfold3(x,n) - y = zeros(size(x,1),n*n*n); - k = 1; - for i=1:n - for j=i:n - for m=j:n - y(:,(i-1)*n*n+(j-1)*n+m) = x(:,k); - y(:,(i-1)*n*n+(m-1)*n+j) = x(:,k); - y(:,(j-1)*n*n+(i-1)*n+m) = x(:,k); - y(:,(j-1)*n*n+(m-1)*n+i) = x(:,k); - y(:,(m-1)*n*n+(i-1)*n+j) = x(:,k); - y(:,(m-1)*n*n+(j-1)*n+i) = x(:,k); - - k = k+1; - end +y = zeros(size(x,1),n*n*n); +k = 1; +for i=1:n + for j=i:n + for m=j:n + y(:,(i-1)*n*n+(j-1)*n+m) = x(:,k); + y(:,(i-1)*n*n+(m-1)*n+j) = x(:,k); + y(:,(j-1)*n*n+(i-1)*n+m) = x(:,k); + y(:,(j-1)*n*n+(m-1)*n+i) = x(:,k); + y(:,(m-1)*n*n+(i-1)*n+j) = x(:,k); + y(:,(m-1)*n*n+(j-1)*n+i) = x(:,k); + + k = k+1; end end end +end function pm = model_structure(M,options) - lead_index = M.maximum_endo_lag+2; - lead_lag_incidence = M.lead_lag_incidence; - dr = struct(); - dr = set_state_space(dr,M,options); - pm.i_fwrd_g = find(lead_lag_incidence(lead_index,dr.order_var)'); - - i_fwrd_f1 = nonzeros(lead_lag_incidence(lead_index,dr.order_var)); - pm.i_fwrd_f1 = i_fwrd_f1; - n = nnz(lead_lag_incidence)+M.exo_nbr; - ih = reshape(1:n*n,n,n); - i_fwrd_f2 = ih(i_fwrd_f1,i_fwrd_f1); - pm.i_fwrd_f2 = i_fwrd_f2(:); - i_fwrd1_f2 = ih(i_fwrd_f1,:); - pm.i_fwrd1_f2 = i_fwrd1_f2(:); - - ih = reshape(1:n*n*n,n,n,n); - i_fwrd_f3 = ih(i_fwrd_f1,i_fwrd_f1,i_fwrd_f1); - pm.i_fwrd_f3 = i_fwrd_f3(:); - i_fwrd1_f3 = ih(i_fwrd_f1,i_fwrd_f1,:); - pm.i_fwrd1_f3 = i_fwrd1_f3(:); +lead_index = M.maximum_endo_lag+2; +lead_lag_incidence = M.lead_lag_incidence; +dr = struct(); +dr = set_state_space(dr,M,options); +pm.i_fwrd_g = find(lead_lag_incidence(lead_index,dr.order_var)'); + +i_fwrd_f1 = nonzeros(lead_lag_incidence(lead_index,dr.order_var)); +pm.i_fwrd_f1 = i_fwrd_f1; +n = nnz(lead_lag_incidence)+M.exo_nbr; +ih = reshape(1:n*n,n,n); +i_fwrd_f2 = ih(i_fwrd_f1,i_fwrd_f1); +pm.i_fwrd_f2 = i_fwrd_f2(:); +i_fwrd1_f2 = ih(i_fwrd_f1,:); +pm.i_fwrd1_f2 = i_fwrd1_f2(:); + +ih = reshape(1:n*n*n,n,n,n); +i_fwrd_f3 = ih(i_fwrd_f1,i_fwrd_f1,i_fwrd_f1); +pm.i_fwrd_f3 = i_fwrd_f3(:); +i_fwrd1_f3 = ih(i_fwrd_f1,i_fwrd_f1,:); +pm.i_fwrd1_f3 = i_fwrd1_f3(:); end function pm = portfolio_model_structure(M,options) - i_d3_np = []; - i_d3_p = []; - - lead_index = M.maximum_endo_lag+2; - lead_lag_incidence = M.lead_lag_incidence; - eq_tags = M.equations_tags; - n_tags = size(eq_tags,1); - eq_p = cell2mat(eq_tags(strcmp(eq_tags(:,2), ... - 'portfolio'),1)); - pm.eq_p = eq_p; - pm.eq_np = setdiff(1:M.endo_nbr,eq_p); - v_p = zeros(n_tags,1); - for i=1:n_tags - v_p(i) = find(strncmp(eq_tags(i,3),M.endo_names, ... - length(cell2mat(eq_tags(i,3))))); - end - if any(lead_lag_incidence(lead_index,v_p)) - error(['portfolio variables appear in the model as forward ' ... - 'variable']) - end - pm.v_p = v_p; - v_np = setdiff(1:M.endo_nbr,v_p); - pm.v_np = v_np; - lli_np = lead_lag_incidence(:,v_np)'; - k = find(lli_np); - lead_lag_incidence_np = lli_np; - lead_lag_incidence_np(k) = 1:nnz(lli_np); - lead_lag_incidence_np = lead_lag_incidence_np'; - pm.lead_lag_incidence_np = lead_lag_incidence_np; - i_d1_np = [nonzeros(lli_np); nnz(lead_lag_incidence)+(1:M.exo_nbr)']; - pm.i_d1_np = i_d1_np; - - n = nnz(lead_lag_incidence)+M.exo_nbr; - ih = reshape(1:n*n,n,n); - i_d2_np = ih(i_d1_np,i_d1_np); - pm.i_d2_np = i_d2_np(:); - - ih = reshape(1:n*n*n,n,n,n); - i_d3_np = ih(i_d1_np,i_d1_np,i_d1_np); - pm.i_d3_np = i_d3_np(:); - - M_np = M; - M_np.lead_lag_incidence = lead_lag_incidence_np; - M_np.lead_lag_incidence = lead_lag_incidence_np; - M_np.endo_nbr = length(v_np); - M_np.endo_names = M.endo_names(v_np,:); - dr_np = struct(); - dr_np = set_state_space(dr_np,M_np,options); - pm.dr_np = dr_np; - M_np.var_order_endo_names = M_np.endo_names(dr_np.order_var,:); - pm.M_np = M_np; - pm.i_fwrd_g = find(lead_lag_incidence_np(lead_index,dr_np.order_var)'); - - i_fwrd_f1 = nonzeros(lead_lag_incidence(lead_index,:)); - pm.i_fwrd_f1 = i_fwrd_f1; - n = nnz(lead_lag_incidence)+M.exo_nbr; - ih = reshape(1:n*n,n,n); - i_fwrd_f2 = ih(i_fwrd_f1,i_fwrd_f1); - pm.i_fwrd_f2 = i_fwrd_f2(:); - i_fwrd1_f2 = ih(i_fwrd_f1,:); - pm.i_fwrd1_f2 = i_fwrd1_f2(:); - - ih = reshape(1:n*n*n,n,n,n); - i_fwrd_f3 = ih(i_fwrd_f1,i_fwrd_f1,i_fwrd_f1); - pm.i_fwrd_f3 = i_fwrd_f3(:); - i_fwrd1_f3 = ih(i_fwrd_f1,i_fwrd_f1,:); - pm.i_fwrd1_f3 = i_fwrd1_f3(:); +i_d3_np = []; +i_d3_p = []; + +lead_index = M.maximum_endo_lag+2; +lead_lag_incidence = M.lead_lag_incidence; +eq_tags = M.equations_tags; +n_tags = size(eq_tags,1); +eq_p = cell2mat(eq_tags(strcmp(eq_tags(:,2), ... + 'portfolio'),1)); +pm.eq_p = eq_p; +pm.eq_np = setdiff(1:M.endo_nbr,eq_p); +v_p = zeros(n_tags,1); +for i=1:n_tags + v_p(i) = find(strncmp(eq_tags(i,3),M.endo_names, ... + length(cell2mat(eq_tags(i,3))))); +end +if any(lead_lag_incidence(lead_index,v_p)) + error(['portfolio variables appear in the model as forward ' ... + 'variable']) +end +pm.v_p = v_p; +v_np = setdiff(1:M.endo_nbr,v_p); +pm.v_np = v_np; +lli_np = lead_lag_incidence(:,v_np)'; +k = find(lli_np); +lead_lag_incidence_np = lli_np; +lead_lag_incidence_np(k) = 1:nnz(lli_np); +lead_lag_incidence_np = lead_lag_incidence_np'; +pm.lead_lag_incidence_np = lead_lag_incidence_np; +i_d1_np = [nonzeros(lli_np); nnz(lead_lag_incidence)+(1:M.exo_nbr)']; +pm.i_d1_np = i_d1_np; + +n = nnz(lead_lag_incidence)+M.exo_nbr; +ih = reshape(1:n*n,n,n); +i_d2_np = ih(i_d1_np,i_d1_np); +pm.i_d2_np = i_d2_np(:); + +ih = reshape(1:n*n*n,n,n,n); +i_d3_np = ih(i_d1_np,i_d1_np,i_d1_np); +pm.i_d3_np = i_d3_np(:); + +M_np = M; +M_np.lead_lag_incidence = lead_lag_incidence_np; +M_np.lead_lag_incidence = lead_lag_incidence_np; +M_np.endo_nbr = length(v_np); +M_np.endo_names = M.endo_names(v_np,:); +dr_np = struct(); +dr_np = set_state_space(dr_np,M_np,options); +pm.dr_np = dr_np; +M_np.var_order_endo_names = M_np.endo_names(dr_np.order_var,:); +pm.M_np = M_np; +pm.i_fwrd_g = find(lead_lag_incidence_np(lead_index,dr_np.order_var)'); + +i_fwrd_f1 = nonzeros(lead_lag_incidence(lead_index,:)); +pm.i_fwrd_f1 = i_fwrd_f1; +n = nnz(lead_lag_incidence)+M.exo_nbr; +ih = reshape(1:n*n,n,n); +i_fwrd_f2 = ih(i_fwrd_f1,i_fwrd_f1); +pm.i_fwrd_f2 = i_fwrd_f2(:); +i_fwrd1_f2 = ih(i_fwrd_f1,:); +pm.i_fwrd1_f2 = i_fwrd1_f2(:); + +ih = reshape(1:n*n*n,n,n,n); +i_fwrd_f3 = ih(i_fwrd_f1,i_fwrd_f1,i_fwrd_f1); +pm.i_fwrd_f3 = i_fwrd_f3(:); +i_fwrd1_f3 = ih(i_fwrd_f1,i_fwrd_f1,:); +pm.i_fwrd1_f3 = i_fwrd1_f3(:); end function r=ds_static_model(y0,f_h,p0,eq_np,v_np,v_p,endo_nbr,exo_nbr,params) - ys = zeros(endo_nbr,1); - ys(v_p) = p0; - ys(v_np) = y0; - r = f_h(ys,zeros(exo_nbr,1),params); - r = r(eq_np); +ys = zeros(endo_nbr,1); +ys(v_p) = p0; +ys(v_np) = y0; +r = f_h(ys,zeros(exo_nbr,1),params); +r = r(eq_np); end function ghsuu = get_ghsuu(g,ns,nx) - nxx = nx*(nx+1)/2; - m1 = 0; - m2 = ns*(ns+1)/2; - kk = 1:(nx*nx); - ghsuu = zeros(size(g,1),(ns*nx*nx)); - - for i=1:n - j = m1+(1:m2); - k = j(end-nxx+1:end); - ghsuu(:,kk) = unfold2(g(:,k),nx); - m1 = m1+m2; - m2 = m2 - (n-i+1); - kk = kk + nx*nx; - end +nxx = nx*(nx+1)/2; +m1 = 0; +m2 = ns*(ns+1)/2; +kk = 1:(nx*nx); +ghsuu = zeros(size(g,1),(ns*nx*nx)); + +for i=1:n + j = m1+(1:m2); + k = j(end-nxx+1:end); + ghsuu(:,kk) = unfold2(g(:,k),nx); + m1 = m1+m2; + m2 = m2 - (n-i+1); + kk = kk + nx*nx; +end end \ No newline at end of file diff --git a/matlab/dyn_saveas.m b/matlab/dyn_saveas.m index a31c724b2e..009a49d5e8 100644 --- a/matlab/dyn_saveas.m +++ b/matlab/dyn_saveas.m @@ -39,13 +39,13 @@ if any(strcmp('eps',cellstr(graph_format))) set(h, 'Visible','on'); end end - print(h,'-depsc2',[fname,'.eps']) + print(h,'-depsc2',[fname,'.eps']) end if any(strcmp('pdf',cellstr(graph_format))) if isoctave error('Octave cannot create pdf files!') else - print(h,'-dpdf',[fname,'.pdf']) + print(h,'-dpdf',[fname,'.pdf']) end end if any(strcmp('fig',cellstr(graph_format))) @@ -53,19 +53,19 @@ if any(strcmp('fig',cellstr(graph_format))) error('Octave cannot create fig files!') else if nodisplay -% THE FOLLOWING LINES COULD BE USED IF BUGS/PROBLEMS ARE REPORTED USING LINE 60 -% set(h,'Units','Normalized') -% mypos=get(h,'Position'); -% set(h,'Position',[-1 -1 mypos(3:4)]) -% set(h, 'Visible','on'); + % THE FOLLOWING LINES COULD BE USED IF BUGS/PROBLEMS ARE REPORTED USING LINE 60 + % set(h,'Units','Normalized') + % mypos=get(h,'Position'); + % set(h,'Position',[-1 -1 mypos(3:4)]) + % set(h, 'Visible','on'); set(h,'CreateFcn','set(gcf, ''Visible'',''on'')') ; end saveas(h,[fname '.fig']); end end if any(strcmp('none',cellstr(graph_format))) -% don't save -% check here as a reminder that none is an option to graph_format + % don't save + % check here as a reminder that none is an option to graph_format end if nodisplay close(h); diff --git a/matlab/dyn_second_order_solver.m b/matlab/dyn_second_order_solver.m index 76fe1baa3d..11de2659b7 100644 --- a/matlab/dyn_second_order_solver.m +++ b/matlab/dyn_second_order_solver.m @@ -48,135 +48,135 @@ function dr = dyn_second_order_solver(jacobia,hessian_mat,dr,M_,threads_ABC,thre % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - dr.ghxx = []; - dr.ghuu = []; - dr.ghxu = []; - dr.ghs2 = []; - Gy = dr.Gy; - - kstate = dr.kstate; - nstatic = M_.nstatic; - nfwrd = M_.nfwrd; - nspred = M_.nspred; - nboth = M_.nboth; - nsfwrd = M_.nsfwrd; - order_var = dr.order_var; - nd = size(kstate,1); - lead_lag_incidence = M_.lead_lag_incidence; - - np = nd - nsfwrd; - - k1 = nonzeros(lead_lag_incidence(:,order_var)'); - kk = [k1; length(k1)+(1:M_.exo_nbr+M_.exo_det_nbr)']; - nk = size(kk,1); - kk1 = reshape([1:nk^2],nk,nk); - kk1 = kk1(kk,kk); - % reordering second order derivatives - hessian_mat = hessian_mat(:,kk1(:)); - - zx = zeros(np,np); - zu=zeros(np,M_.exo_nbr); - zx(1:np,:)=eye(np); - k0 = [1:M_.endo_nbr]; - gx1 = dr.ghx; - hu = dr.ghu(nstatic+[1:nspred],:); - k0 = find(lead_lag_incidence(M_.maximum_endo_lag+1,order_var)'); - zx = [zx; gx1(k0,:)]; - zu = [zu; dr.ghu(k0,:)]; - k1 = find(lead_lag_incidence(M_.maximum_endo_lag+2,order_var)'); - zu = [zu; gx1(k1,:)*hu]; - zx = [zx; gx1(k1,:)*Gy]; - 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, err] = sparse_hessian_times_B_kronecker_C(hessian_mat,zx,threads_BC); - mexErrCheck('sparse_hessian_times_B_kronecker_C', err); - rhs = -rhs; - - %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(M_.endo_nbr,M_.endo_nbr); - B = zeros(M_.endo_nbr,M_.endo_nbr); - A(:,k0) = jacobia(:,nonzeros(lead_lag_incidence(M_.maximum_endo_lag+1,order_var))); - % variables with the highest lead - k1 = find(kstate(:,2) == M_.maximum_endo_lag+2); - % Jacobian with respect to the variables with the highest lead - fyp = jacobia(:,kstate(k1,3)+nnz(M_.lead_lag_incidence(M_.maximum_endo_lag+1,:))); - B(:,nstatic+M_.npred+1:end) = fyp; - [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+nspred)=... - A(1:M_.endo_nbr,nstatic+[1:nspred])+fyp*gx1(k1,1:nspred); - C = Gy; - D = [rhs; zeros(n-M_.endo_nbr,size(rhs,2))]; - - - [err, dr.ghxx] = gensylv(2,A,B,C,D); - mexErrCheck('gensylv', err); - - %ghxu - %rhs - hu = dr.ghu(nstatic+1:nstatic+nspred,:); - [rhs, err] = sparse_hessian_times_B_kronecker_C(hessian_mat,zx,zu,threads_BC); - mexErrCheck('sparse_hessian_times_B_kronecker_C', err); - - hu1 = [hu;zeros(np-nspred,M_.exo_nbr)]; - [nrhx,nchx] = size(Gy); - [nrhu1,nchu1] = size(hu1); - - [abcOut,err] = A_times_B_kronecker_C(dr.ghxx,Gy,hu1,threads_ABC); - mexErrCheck('A_times_B_kronecker_C', err); - B1 = B*abcOut; - rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1; - - - %lhs - dr.ghxu = A\rhs; - - %ghuu - %rhs - [rhs, err] = sparse_hessian_times_B_kronecker_C(hessian_mat,zu,threads_BC); - mexErrCheck('sparse_hessian_times_B_kronecker_C', err); - - [B1, err] = A_times_B_kronecker_C(B*dr.ghxx,hu1,threads_ABC); - mexErrCheck('A_times_B_kronecker_C', err); - rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1; - - %lhs - dr.ghuu = A\rhs; - - % 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-nspred); - LHS = zeros(M_.endo_nbr,M_.endo_nbr); - LHS(:,k0) = jacobia(:,nonzeros(lead_lag_incidence(M_.maximum_endo_lag+1,order_var))); - RHS = zeros(M_.endo_nbr,M_.exo_nbr^2); - gu = dr.ghu; - guu = dr.ghuu; - E = eye(M_.endo_nbr); - kh = reshape([1:nk^2],nk,nk); - kp = sum(kstate(:,2) <= M_.maximum_endo_lag+1); - E1 = [eye(nspred); zeros(kp-nspred,nspred)]; - H = E1; - hxx = dr.ghxx(nstatic+[1:nspred],:); - [junk,k2a,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+2,order_var)); - k3 = nnz(M_.lead_lag_incidence(1:M_.maximum_endo_lag+1,:))+(1:M_.nsfwrd)'; - [B1, err] = sparse_hessian_times_B_kronecker_C(hessian_mat(:,kh(k3,k3)),gu(k2a,:),threads_BC); - mexErrCheck('sparse_hessian_times_B_kronecker_C', err); - RHS = RHS + jacobia(:,k2)*guu(k2a,:)+B1; - - % LHS - LHS = LHS + jacobia(:,k2)*(E(k2a,:)+[O1(k2a,:) dr.ghx(k2a,:)*H O2(k2a,:)]); - - 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 - end + +dr.ghxx = []; +dr.ghuu = []; +dr.ghxu = []; +dr.ghs2 = []; +Gy = dr.Gy; + +kstate = dr.kstate; +nstatic = M_.nstatic; +nfwrd = M_.nfwrd; +nspred = M_.nspred; +nboth = M_.nboth; +nsfwrd = M_.nsfwrd; +order_var = dr.order_var; +nd = size(kstate,1); +lead_lag_incidence = M_.lead_lag_incidence; + +np = nd - nsfwrd; + +k1 = nonzeros(lead_lag_incidence(:,order_var)'); +kk = [k1; length(k1)+(1:M_.exo_nbr+M_.exo_det_nbr)']; +nk = size(kk,1); +kk1 = reshape([1:nk^2],nk,nk); +kk1 = kk1(kk,kk); +% reordering second order derivatives +hessian_mat = hessian_mat(:,kk1(:)); + +zx = zeros(np,np); +zu=zeros(np,M_.exo_nbr); +zx(1:np,:)=eye(np); +k0 = [1:M_.endo_nbr]; +gx1 = dr.ghx; +hu = dr.ghu(nstatic+[1:nspred],:); +k0 = find(lead_lag_incidence(M_.maximum_endo_lag+1,order_var)'); +zx = [zx; gx1(k0,:)]; +zu = [zu; dr.ghu(k0,:)]; +k1 = find(lead_lag_incidence(M_.maximum_endo_lag+2,order_var)'); +zu = [zu; gx1(k1,:)*hu]; +zx = [zx; gx1(k1,:)*Gy]; +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, err] = sparse_hessian_times_B_kronecker_C(hessian_mat,zx,threads_BC); +mexErrCheck('sparse_hessian_times_B_kronecker_C', err); +rhs = -rhs; + +%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(M_.endo_nbr,M_.endo_nbr); +B = zeros(M_.endo_nbr,M_.endo_nbr); +A(:,k0) = jacobia(:,nonzeros(lead_lag_incidence(M_.maximum_endo_lag+1,order_var))); +% variables with the highest lead +k1 = find(kstate(:,2) == M_.maximum_endo_lag+2); +% Jacobian with respect to the variables with the highest lead +fyp = jacobia(:,kstate(k1,3)+nnz(M_.lead_lag_incidence(M_.maximum_endo_lag+1,:))); +B(:,nstatic+M_.npred+1:end) = fyp; +[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+nspred)=... + A(1:M_.endo_nbr,nstatic+[1:nspred])+fyp*gx1(k1,1:nspred); +C = Gy; +D = [rhs; zeros(n-M_.endo_nbr,size(rhs,2))]; + + +[err, dr.ghxx] = gensylv(2,A,B,C,D); +mexErrCheck('gensylv', err); + +%ghxu +%rhs +hu = dr.ghu(nstatic+1:nstatic+nspred,:); +[rhs, err] = sparse_hessian_times_B_kronecker_C(hessian_mat,zx,zu,threads_BC); +mexErrCheck('sparse_hessian_times_B_kronecker_C', err); + +hu1 = [hu;zeros(np-nspred,M_.exo_nbr)]; +[nrhx,nchx] = size(Gy); +[nrhu1,nchu1] = size(hu1); + +[abcOut,err] = A_times_B_kronecker_C(dr.ghxx,Gy,hu1,threads_ABC); +mexErrCheck('A_times_B_kronecker_C', err); +B1 = B*abcOut; +rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1; + + +%lhs +dr.ghxu = A\rhs; + +%ghuu +%rhs +[rhs, err] = sparse_hessian_times_B_kronecker_C(hessian_mat,zu,threads_BC); +mexErrCheck('sparse_hessian_times_B_kronecker_C', err); + +[B1, err] = A_times_B_kronecker_C(B*dr.ghxx,hu1,threads_ABC); +mexErrCheck('A_times_B_kronecker_C', err); +rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1; + +%lhs +dr.ghuu = A\rhs; + +% 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-nspred); +LHS = zeros(M_.endo_nbr,M_.endo_nbr); +LHS(:,k0) = jacobia(:,nonzeros(lead_lag_incidence(M_.maximum_endo_lag+1,order_var))); +RHS = zeros(M_.endo_nbr,M_.exo_nbr^2); +gu = dr.ghu; +guu = dr.ghuu; +E = eye(M_.endo_nbr); +kh = reshape([1:nk^2],nk,nk); +kp = sum(kstate(:,2) <= M_.maximum_endo_lag+1); +E1 = [eye(nspred); zeros(kp-nspred,nspred)]; +H = E1; +hxx = dr.ghxx(nstatic+[1:nspred],:); +[junk,k2a,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+2,order_var)); +k3 = nnz(M_.lead_lag_incidence(1:M_.maximum_endo_lag+1,:))+(1:M_.nsfwrd)'; +[B1, err] = sparse_hessian_times_B_kronecker_C(hessian_mat(:,kh(k3,k3)),gu(k2a,:),threads_BC); +mexErrCheck('sparse_hessian_times_B_kronecker_C', err); +RHS = RHS + jacobia(:,k2)*guu(k2a,:)+B1; + +% LHS +LHS = LHS + jacobia(:,k2)*(E(k2a,:)+[O1(k2a,:) dr.ghx(k2a,:)*H O2(k2a,:)]); + +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 +end diff --git a/matlab/dyn_unvech.m b/matlab/dyn_unvech.m index f70670a986..6ed9c40f9a 100644 --- a/matlab/dyn_unvech.m +++ b/matlab/dyn_unvech.m @@ -1,10 +1,10 @@ function Matrix = dyn_unvech(Vector) % This function implements the unvech operator. -% -% INPUTS +% +% INPUTS % Vector [double] a m*1 vector. -% -% OUTPUTS +% +% OUTPUTS % Matrix [double] a n*n symetric matrix, where n solves n*(n+1)/2=m. % Copyright (C) 2010 Dynare Team diff --git a/matlab/dyn_vech.m b/matlab/dyn_vech.m index 6e54c40502..fef8d134de 100644 --- a/matlab/dyn_vech.m +++ b/matlab/dyn_vech.m @@ -1,10 +1,10 @@ function Vector = dyn_vech(Matrix) % This function implements the vech operator. -% -% INPUTS +% +% INPUTS % Matrix [double] a squared n*n symetric matrix. -% -% OUTPUTS +% +% OUTPUTS % Vector [double] a n*(n+1)/2 vector. % Copyright (C) 2010 Dynare Team diff --git a/matlab/dyn_waitbar.m b/matlab/dyn_waitbar.m index f8bc2aa785..43567dcd34 100644 --- a/matlab/dyn_waitbar.m +++ b/matlab/dyn_waitbar.m @@ -43,7 +43,7 @@ if nargout end if ~whoiam - if isoctave || options_.console_mode + if isoctave || options_.console_mode if init diary off; running_text = varargin{1}; @@ -58,7 +58,7 @@ if ~whoiam s0=repmat('\b',1,length(newString)); newString=sprintf([running_text,' %3.f%% done'], prctdone*100); fprintf([s0,'%s'],newString); - end + end else if nargout h = waitbar(prctdone,varargin{:}); @@ -79,4 +79,3 @@ else end fMessageStatus(prctdone,whoiam,running_text, waitbarTitle, Parallel); end - diff --git a/matlab/dyn_waitbar_close.m b/matlab/dyn_waitbar_close.m index da7d17bbf6..c2864a9b6a 100644 --- a/matlab/dyn_waitbar_close.m +++ b/matlab/dyn_waitbar_close.m @@ -1,6 +1,6 @@ function dyn_waitbar_close(h) % h = dyn_waitbar_close(h) -% adaptive close waitbar, compatible with +% adaptive close waitbar, compatible with % octave and when console_mode=1 % @@ -31,5 +31,3 @@ else end clear dyn_waitbar; - - diff --git a/matlab/dynare.m b/matlab/dynare.m index a1fd768885..472888be9d 100644 --- a/matlab/dynare.m +++ b/matlab/dynare.m @@ -1,7 +1,7 @@ function dynare(fname, varargin) % This command runs dynare with specified model file in argument % Filename. -% The name of model file begins with an alphabetic character, +% The name of model file begins with an alphabetic character, % and has a filename extension of .mod or .dyn. % When extension is omitted, a model file with .mod extension % is processed. @@ -9,10 +9,10 @@ function dynare(fname, varargin) % INPUTS % fname: file name % varargin: list of arguments following fname -% +% % OUTPUTS % none -% +% % SPECIAL REQUIREMENTS % none @@ -64,7 +64,7 @@ dynareroot = dynare_config; warning_config() -if isoctave +if isoctave if octave_ver_less_than('3.6.0') warning('This version of Dynare has only been tested on Octave 3.6.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 @@ -111,7 +111,7 @@ if isempty(strfind(fname,'.')) % Checking file extension else if dot_location~=length(fname)-3 ... %if the file name has fewer than 4 characters and there is a period - || ~strcmp(upper(fname(size(fname,2)-3:size(fname,2))),'.MOD') ... + || ~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 and must not include any other periods') end @@ -176,11 +176,11 @@ else end if isempty(strfind(arch, '64')) - arch_ext = '32'; - disp('Using 32-bit preprocessor'); + arch_ext = '32'; + disp('Using 32-bit preprocessor'); else - arch_ext = '64'; - disp('Using 64-bit preprocessor'); + arch_ext = '64'; + disp('Using 64-bit preprocessor'); end command = ['"' dynareroot 'preprocessor' arch_ext filesep 'dynare_m" ' fname] ; diff --git a/matlab/dynare_config.m b/matlab/dynare_config.m index baa8503084..65a363999e 100644 --- a/matlab/dynare_config.m +++ b/matlab/dynare_config.m @@ -58,7 +58,7 @@ p = {'/distributions/' ; ... '/particles/src' ; ... '/gsa/' ; ... '/ep/' ; ... - '/convergence_diagnostics/' ; ... + '/convergence_diagnostics/' ; ... '/cli/' ; ... '/lmmcp/' ; ... '/optimization/' ; ... @@ -114,7 +114,7 @@ end % nanmean is in Octave Forge Statistics package and in MATLAB Statistics % toolbox if (isoctave && ~user_has_octave_forge_package('statistics')) ... - || (~isoctave && ~user_has_matlab_license('statistics_toolbox')) + || (~isoctave && ~user_has_matlab_license('statistics_toolbox')) p{end+1} = '/missing/nanmean'; end diff --git a/matlab/dynare_estimation.m b/matlab/dynare_estimation.m index cca524d64e..98ad16c32d 100644 --- a/matlab/dynare_estimation.m +++ b/matlab/dynare_estimation.m @@ -33,7 +33,7 @@ global options_ oo_ M_ dataset_ dataset_info oo_recursive_={}; mode_file0 = options_.mode_file; % store mode_file set by the user -% Test if the order of approximation is nonzero (the preprocessor tests if order is non negative). + % Test if the order of approximation is nonzero (the preprocessor tests if order is non negative). if isequal(options_.order,0) error('Estimation:: The order of the Taylor approximation cannot be 0!') end @@ -46,8 +46,8 @@ end var_list = check_list_of_variables(options_, M_, var_list); options_.varlist = var_list; -nobs = sort(options_.nobs); -first_obs = sort(options_.first_obs); +nobs = sort(options_.nobs); +first_obs = sort(options_.first_obs); nnobs = length(nobs); nfirstobs = length(first_obs); @@ -55,7 +55,7 @@ nfirstobs = length(first_obs); if nnobs~=1 && nfirstobs~=1 error('You cannot simultaneously do rolling window and recursive estimation') end - + horizon = options_.forecast; if nargin<2 || ~exist('dname','var') || isempty(dname) @@ -83,7 +83,7 @@ if nnobs>1 || nfirstobs > 1 options_.nobs = nobs(i); M_.dname = [dname '_' int2str(nobs(i))]; elseif nfirstobs>1 - options_.first_obs=first_obs(i); + options_.first_obs=first_obs(i); M_.dname = [dname '_' int2str(first_obs(i))]; end dynare_estimation_1(var_list,M_.dname); @@ -138,11 +138,11 @@ if nnobs > 1 && horizon > 0 IdObs(j,1) = iobs; end end - + gend = dataset_.nobs; time_offset=min(3,gend-1); %for observables, plot 3 previous periods unless data is shorter k = time_offset+min(nobs(end)-nobs(1)+horizon, ... - size(dataset_.data,1)-nobs(1)); + size(dataset_.data,1)-nobs(1)); data2 = dataset_info.rawdata(end-k+1:end,:); [nbplt,nr,nc,lr,lc,nstar] = pltorg(nvar); m = 1; @@ -167,23 +167,23 @@ if nnobs > 1 && horizon > 0 for j=1:nnobs if mh_replic > 0 oo_.RecursiveForecast.Mean.(vname)(j,:) = ... - oo_recursive_{nobs(j)}.MeanForecast.Mean.(vname); + oo_recursive_{nobs(j)}.MeanForecast.Mean.(vname); oo_.RecursiveForecast.HPDinf.(vname)(j,:) = ... - oo_recursive_{nobs(j)}.MeanForecast.HPDinf.(vname); + oo_recursive_{nobs(j)}.MeanForecast.HPDinf.(vname); oo_.RecursiveForecast.HPDsup.(vname)(j,:) = ... - oo_recursive_{nobs(j)}.MeanForecast.HPDsup.(vname); + oo_recursive_{nobs(j)}.MeanForecast.HPDsup.(vname); oo_.RecursiveForecast.HPDTotalinf.(vname)(j,:) = ... - oo_recursive_{nobs(j)}.PointForecast.HPDinf.(vname); + oo_recursive_{nobs(j)}.PointForecast.HPDinf.(vname); oo_.RecursiveForecast.HPDTotalsup.(vname)(j,:) = ... - oo_recursive_{nobs(j)}.PointForecast.HPDsup.(vname); + oo_recursive_{nobs(j)}.PointForecast.HPDsup.(vname); else oo_.RecursiveForecast.Mean.(vname)(j,:) =... - oo_recursive_{nobs(j)}.forecast.Mean.(vname); + oo_recursive_{nobs(j)}.forecast.Mean.(vname); oo_.RecursiveForecast.HPDinf.(vname)(j,:) =... - oo_recursive_{nobs(j)}.forecast.HPDinf.(vname); + oo_recursive_{nobs(j)}.forecast.HPDinf.(vname); oo_.RecursiveForecast.HPDsup.(vname)(j,:) =... - oo_recursive_{nobs(j)}.forecast.HPDsup.(vname); - end + oo_recursive_{nobs(j)}.forecast.HPDsup.(vname); + end x = nobs(1)+nobs(j)-nobs(1)+(1:horizon); y = oo_.RecursiveForecast.Mean.(vname)(j,:); @@ -212,5 +212,5 @@ if nnobs > 1 && horizon > 0 end end end -options_.mode_file = mode_file0; +options_.mode_file = mode_file0; %reset stored mode-file to user defined one (and in case it was only set by the recursive estimation) diff --git a/matlab/dynare_estimation_1.m b/matlab/dynare_estimation_1.m index cd0e28c9bd..a4b4166145 100644 --- a/matlab/dynare_estimation_1.m +++ b/matlab/dynare_estimation_1.m @@ -52,12 +52,12 @@ end % Set particle filter flag. if options_.order > 1 - if options_.particle.status && options_.order==2 + if options_.particle.status && options_.order==2 skipline() disp('Estimation using a non linear filter!') skipline() if ~options_.nointeractive && ismember(options_.mode_compute,[1,3,4]) && ~strcmpi(options_.particle.filter_algorithm,'gf')% Known gradient-based optimizers - disp('You are using a gradient-based mode-finder. Particle filtering introduces discontinuities in the') + disp('You are using a gradient-based mode-finder. Particle filtering introduces discontinuities in the') disp('objective function w.r.t the parameters. Thus, should use a non-gradient based optimizer.') fprintf('\nPlease choose a mode-finder:\n') fprintf('\t 0 - Continue using gradient-based method (it is most likely that you will no get any sensible result).\n') @@ -170,7 +170,7 @@ catch % if check fails, provide info on using calibration if present fprintf('ESTIMATION_CHECKS: There was an error in computing the likelihood for initial parameter values.\n') fprintf('ESTIMATION_CHECKS: If this is not a problem with the setting of options (check the error message below),\n') fprintf('ESTIMATION_CHECKS: you should try using the calibrated version of the model as starting values. To do\n') - fprintf('ESTIMATION_CHECKS: this, add an empty estimated_params_init-block with use_calibration option immediately before the estimation\n') + fprintf('ESTIMATION_CHECKS: this, add an empty estimated_params_init-block with use_calibration option immediately before the estimation\n') fprintf('ESTIMATION_CHECKS: command (and after the estimated_params-block so that it does not get overwritten):\n'); skipline(2); end @@ -210,30 +210,30 @@ if ~isequal(options_.mode_compute,0) && ~options_.mh_posterior_mode_estimation else %use default newratflag=0; %exclude DYNARE numerical hessian end - elseif ~options_.analytic_derivation - if isempty(newratflag) - newratflag=options_.newrat.hess; %use default numerical dynare hessian + elseif ~options_.analytic_derivation + if isempty(newratflag) + newratflag=options_.newrat.hess; %use default numerical dynare hessian end end end - + [xparam1, fval, exitflag, hh, options_, Scale, new_rat_hess_info] = dynare_minimize_objective(objective_function,xparam1,options_.mode_compute,options_,[bounds.lb bounds.ub],bayestopt_.name,bayestopt_,hh,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_); fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval); if isnumeric(options_.mode_compute) && options_.mode_compute==5 && options_.analytic_derivation==-1 %reset options changed by newrat - options_.analytic_derivation = options_analytic_derivation_old; %reset + options_.analytic_derivation = options_analytic_derivation_old; %reset elseif isnumeric(options_.mode_compute) && options_.mode_compute==6 %save scaling factor save([M_.fname '_optimal_mh_scale_parameter.mat'],'Scale'); options_.mh_jscale = Scale; bayestopt_.jscale = ones(length(xparam1),1)*Scale; - end + end if ~isnumeric(options_.mode_compute) || ~isequal(options_.mode_compute,6) %always already computes covariance matrix if options_.cova_compute == 1 %user did not request covariance not to be computed if options_.analytic_derivation && strcmp(func2str(objective_function),'dsge_likelihood') ana_deriv_old = options_.analytic_derivation; options_.analytic_derivation = 2; [junk1, junk2,junk3, junk4, hh] = feval(objective_function,xparam1, ... - dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_); + dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_); options_.analytic_derivation = ana_deriv_old; elseif ~isnumeric(options_.mode_compute) || ~(isequal(options_.mode_compute,5) && newratflag~=1) % with flag==0, we force to use the hessian from outer product gradient of optimizer 5 @@ -264,7 +264,7 @@ if ~isequal(options_.mode_compute,0) && ~options_.mh_posterior_mode_estimation options_.kalman_algo=4; end elseif newratflag==0 % hh already contains outer product gradient with univariate filter - compute_hessian = 0; + compute_hessian = 0; end if compute_hessian crit = options_.newrat.tolerance.f; @@ -296,7 +296,7 @@ if ~options_.mh_posterior_mode_estimation && options_.cova_compute params_at_bound=find(abs(xparam1-bounds.ub)<1.e-10 | abs(xparam1-bounds.lb)<1.e-10); if ~isempty(params_at_bound) for ii=1:length(params_at_bound) - params_at_bound_name{ii,1}=get_the_name(params_at_bound(ii),0,M_,estim_params_,options_); + params_at_bound_name{ii,1}=get_the_name(params_at_bound(ii),0,M_,estim_params_,options_); end disp_string=[params_at_bound_name{1,:}]; for ii=2:size(params_at_bound_name,1) @@ -385,36 +385,36 @@ if np > 0 end switch options_.MCMC_jumping_covariance - case 'hessian' %Baseline - %do nothing and use hessian from mode_compute - case 'prior_variance' %Use prior variance - if any(isinf(bayestopt_.p2)) - error('Infinite prior variances detected. You cannot use the prior variances as the proposal density, if some variances are Inf.') - else - hh = diag(1./(bayestopt_.p2.^2)); - end + case 'hessian' %Baseline + %do nothing and use hessian from mode_compute + case 'prior_variance' %Use prior variance + if any(isinf(bayestopt_.p2)) + error('Infinite prior variances detected. You cannot use the prior variances as the proposal density, if some variances are Inf.') + else + hh = diag(1./(bayestopt_.p2.^2)); + end + hsd = sqrt(diag(hh)); + invhess = inv(hh./(hsd*hsd'))./(hsd*hsd'); + case 'identity_matrix' %Use identity + invhess = eye(nx); + otherwise %user specified matrix in file + try + load(options_.MCMC_jumping_covariance,'jumping_covariance') + hh=jumping_covariance; + catch + error(['No matrix named ''jumping_covariance'' could be found in ',options_.MCMC_jumping_covariance,'.mat']) + end + [nrow, ncol]=size(hh); + if ~isequal(nrow,ncol) && ~isequal(nrow,nx) %check if square and right size + error(['jumping_covariance matrix must be square and have ',num2str(nx),' rows and columns']) + end + try %check for positive definiteness + chol(hh); hsd = sqrt(diag(hh)); invhess = inv(hh./(hsd*hsd'))./(hsd*hsd'); - case 'identity_matrix' %Use identity - invhess = eye(nx); - otherwise %user specified matrix in file - try - load(options_.MCMC_jumping_covariance,'jumping_covariance') - hh=jumping_covariance; - catch - error(['No matrix named ''jumping_covariance'' could be found in ',options_.MCMC_jumping_covariance,'.mat']) - end - [nrow, ncol]=size(hh); - if ~isequal(nrow,ncol) && ~isequal(nrow,nx) %check if square and right size - error(['jumping_covariance matrix must be square and have ',num2str(nx),' rows and columns']) - end - try %check for positive definiteness - chol(hh); - hsd = sqrt(diag(hh)); - invhess = inv(hh./(hsd*hsd'))./(hsd*hsd'); - catch - error(['Specified jumping_covariance is not positive definite']) - end + catch + error(['Specified jumping_covariance is not positive definite']) + end end if (any(bayestopt_.pshape >0 ) && options_.mh_replic) || ... @@ -457,9 +457,9 @@ if (any(bayestopt_.pshape >0 ) && options_.mh_replic) || ... else %get stored results if required if options_.load_mh_file && options_.load_results_after_load_mh - oo_load_mh=load([M_.fname '_results'],'oo_'); + oo_load_mh=load([M_.fname '_results'],'oo_'); end - if ~options_.nodiagnostic + if ~options_.nodiagnostic if (options_.mh_replic>0 || (options_.load_mh_file && ~options_.load_results_after_load_mh)) oo_= McMCDiagnostics(options_, estim_params_, M_,oo_); elseif options_.load_mh_file && options_.load_results_after_load_mh @@ -481,20 +481,20 @@ if (any(bayestopt_.pshape >0 ) && options_.mh_replic) || ... [oo_.posterior.metropolis.mean,oo_.posterior.metropolis.Variance] ... = GetPosteriorMeanVariance(M_,options_.mh_drop); elseif options_.load_mh_file && options_.load_results_after_load_mh - %% load fields from previous MCMC run stored in results-file + %% load fields from previous MCMC run stored in results-file field_names={'posterior_mode','posterior_std_at_mode',...% fields set by marginal_density - 'posterior_mean','posterior_hpdinf','posterior_hpdsup','posterior_median','posterior_variance','posterior_std','posterior_deciles','posterior_density',...% fields set by GetPosteriorParametersStatistics - 'prior_density',...%fields set by PlotPosteriorDistributions - }; + 'posterior_mean','posterior_hpdinf','posterior_hpdsup','posterior_median','posterior_variance','posterior_std','posterior_deciles','posterior_density',...% fields set by GetPosteriorParametersStatistics + 'prior_density',...%fields set by PlotPosteriorDistributions + }; for field_iter=1:size(field_names,2) if isfield(oo_load_mh.oo_,field_names{1,field_iter}) oo_.(field_names{1,field_iter})=oo_load_mh.oo_.(field_names{1,field_iter}); end - end + end % field set by marginal_density if isfield(oo_load_mh.oo_,'MarginalDensity') && isfield(oo_load_mh.oo_.MarginalDensity,'ModifiedHarmonicMean') oo_.MarginalDensity.ModifiedHarmonicMean=oo_load_mh.oo_.MarginalDensity.ModifiedHarmonicMean; - end + end % field set by GetPosteriorMeanVariance if isfield(oo_load_mh.oo_,'posterior') && isfield(oo_load_mh.oo_.posterior,'metropolis') oo_.posterior.metropolis=oo_load_mh.oo_.posterior.metropolis; @@ -691,76 +691,76 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha %% Historical and smoothed variabes %% if ~options_.nograph - [nbplt,nr,nc,lr,lc,nstar] = pltorg(n_varobs); - if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) - fidTeX = fopen([M_.fname '_HistoricalAndSmoothedVariables.tex'],'w'); - fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation_1.m (Dynare).\n'); - fprintf(fidTeX,['%% ' datestr(now,0) '\n']); - fprintf(fidTeX,' \n'); - end - for plt = 1:nbplt - fh = dyn_figure(options_.nodisplay,'Name','Historical and smoothed variables'); - NAMES = []; - if options_.TeX, TeXNAMES = []; end - nstar0=min(nstar,n_varobs-(plt-1)*nstar); - if gend==1 - marker_string{1,1}='-ro'; - marker_string{2,1}='--ko'; - else - marker_string{1,1}='-r'; - marker_string{2,1}='--k'; + [nbplt,nr,nc,lr,lc,nstar] = pltorg(n_varobs); + if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) + fidTeX = fopen([M_.fname '_HistoricalAndSmoothedVariables.tex'],'w'); + fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation_1.m (Dynare).\n'); + fprintf(fidTeX,['%% ' datestr(now,0) '\n']); + fprintf(fidTeX,' \n'); end - for i=1:nstar0 - k = (plt-1)*nstar+i; - subplot(nr,nc,i); - plot(1:gend,yf(k,:),marker_string{1,1},'linewidth',1) - hold on - plot(1:gend,rawdata(:,k),marker_string{2,1},'linewidth',1) - hold off - name = options_.varobs{k}; - if isempty(NAMES) - NAMES = name; + for plt = 1:nbplt + fh = dyn_figure(options_.nodisplay,'Name','Historical and smoothed variables'); + NAMES = []; + if options_.TeX, TeXNAMES = []; end + nstar0=min(nstar,n_varobs-(plt-1)*nstar); + if gend==1 + marker_string{1,1}='-ro'; + marker_string{2,1}='--ko'; else - NAMES = char(NAMES,name); - end - if ~isempty(options_.XTick) - set(gca,'XTick',options_.XTick) - set(gca,'XTickLabel',options_.XTickLabel) - end - if gend>1 - xlim([1 gend]) + marker_string{1,1}='-r'; + marker_string{2,1}='--k'; end - if options_.TeX - idx = strmatch(options_.varobs{k},M_.endo_names,'exact'); - texname = M_.endo_names_tex(idx,:); - if isempty(TeXNAMES) - TeXNAMES = ['$ ' deblank(texname) ' $']; + for i=1:nstar0 + k = (plt-1)*nstar+i; + subplot(nr,nc,i); + plot(1:gend,yf(k,:),marker_string{1,1},'linewidth',1) + hold on + plot(1:gend,rawdata(:,k),marker_string{2,1},'linewidth',1) + hold off + name = options_.varobs{k}; + if isempty(NAMES) + NAMES = name; else - TeXNAMES = char(TeXNAMES,['$ ' deblank(texname) ' $']); + NAMES = char(NAMES,name); + end + if ~isempty(options_.XTick) + set(gca,'XTick',options_.XTick) + set(gca,'XTickLabel',options_.XTickLabel) + end + if gend>1 + xlim([1 gend]) + end + if options_.TeX + idx = strmatch(options_.varobs{k},M_.endo_names,'exact'); + texname = M_.endo_names_tex(idx,:); + if isempty(TeXNAMES) + TeXNAMES = ['$ ' deblank(texname) ' $']; + else + TeXNAMES = char(TeXNAMES,['$ ' deblank(texname) ' $']); + end end + title(name,'Interpreter','none') + end + dyn_saveas(fh,[M_.fname '_HistoricalAndSmoothedVariables' int2str(plt)],options_.nodisplay,options_.graph_format); + if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) + fprintf(fidTeX,'\\begin{figure}[H]\n'); + for jj = 1:nstar0 + fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); + end + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_HistoricalAndSmoothedVariables%s}\n',options_.figures.textwidth*min(i/nc,1),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 - title(name,'Interpreter','none') end - dyn_saveas(fh,[M_.fname '_HistoricalAndSmoothedVariables' int2str(plt)],options_.nodisplay,options_.graph_format); if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) - fprintf(fidTeX,'\\begin{figure}[H]\n'); - for jj = 1:nstar0 - fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:))); - end - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_HistoricalAndSmoothedVariables%s}\n',options_.figures.textwidth*min(i/nc,1),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'); + fprintf(fidTeX,'%% End of TeX file.\n'); + fclose(fidTeX); end end - if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) - 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 diff --git a/matlab/dynare_estimation_init.m b/matlab/dynare_estimation_init.m index d3e8f5b600..5ee9a9fa71 100644 --- a/matlab/dynare_estimation_init.m +++ b/matlab/dynare_estimation_init.m @@ -14,7 +14,7 @@ function [dataset_, dataset_info, xparam1, hh, M_, options_, oo_, estim_params_, % estim_params_: structure storing information about estimated % parameters % bayestopt_: structure storing information about priors - + % OUTPUTS % dataset_: the dataset after required transformation % dataset_info: Various informations about the dataset (descriptive statistics and missing observations). @@ -28,7 +28,7 @@ function [dataset_, dataset_info, xparam1, hh, M_, options_, oo_, estim_params_, % parameters % bayestopt_: structure storing information about priors % bounds: structure containing prior bounds -% +% % SPECIAL REQUIREMENTS % none @@ -104,13 +104,13 @@ if options_.analytic_derivation && options_.fast_kalman_filter end % fast kalman filter is only available with kalman_algo == 0,1,3 -if options_.fast_kalman_filter +if options_.fast_kalman_filter if ~ismember(options_.kalman_algo, [0,1,3]) error(['estimation option conflict: fast_kalman_filter is only available ' ... - 'with kalman_algo = 0, 1 or 3']) + 'with kalman_algo = 0, 1 or 3']) elseif options_.block error(['estimation option conflict: fast_kalman_filter is not available ' ... - 'with block']) + 'with block']) end end @@ -189,7 +189,7 @@ if ~isempty(estim_params_) && ~(isfield(estim_params_,'nvx') && sum(estim_params % The posterior mode is not estimated. error('Please change the mode_file option, the list of estimated parameters or set mode_compute>0.') else - % The posterior mode is estimated, the Hessian evaluated at the mode is not needed so we set values for the parameters missing in the mode file using the prior mean. + % The posterior mode is estimated, the Hessian evaluated at the mode is not needed so we set values for the parameters missing in the mode file using the prior mean. if ~isempty(xd) xparam1(xd) = mode_file.xparam1(md); else @@ -229,7 +229,7 @@ if ~isempty(estim_params_) && ~(isfield(estim_params_,'nvx') && sum(estim_params error('Please change the mode_file option, the list of estimated parameters or set mode_compute>0.') end else - % The posterior mode is estimated, the Hessian evaluated at the mode is not needed so we set values for the parameters missing in the mode file using the prior mean. + % The posterior mode is estimated, the Hessian evaluated at the mode is not needed so we set values for the parameters missing in the mode file using the prior mean. if ~isempty(xd) xparam1(xd) = mode_file.xparam1(md); else @@ -238,7 +238,7 @@ if ~isempty(estim_params_) && ~(isfield(estim_params_,'nvx') && sum(estim_params end end else - % The number of declared estimated parameters match the number of parameters in the mode file. + % The number of declared estimated parameters match the number of parameters in the mode file. % Check that the parameters in the mode file and according to the current mod file are identical. if ~isfield(mode_file,'parameter_names') disp(['The posterior mode file ' options_.mode_file ' has been generated using an older version of Dynare. It cannot be verified if it matches the present model. Proceed at your own risk.']) @@ -275,7 +275,7 @@ if ~isempty(estim_params_) && ~(isfield(estim_params_,'nvx') && sum(estim_params error('Please change the mode_file option, the list of estimated parameters or set mode_compute>0.') end else - % The posterior mode is estimated, the Hessian evaluated at the mode is not needed so we set values for the parameters missing in the mode file using the prior mean. + % The posterior mode is estimated, the Hessian evaluated at the mode is not needed so we set values for the parameters missing in the mode file using the prior mean. if ~isempty(xd) xparam1(xd) = mode_file.xparam1(md); if isfield(mode_file,'hh') @@ -322,8 +322,8 @@ if ~isempty(estim_params_) && ~(all(strcmp(fieldnames(estim_params_),'full_calib bounds.lb = max(bounds.lb,lb); bounds.ub = min(bounds.ub,ub); else % estimated parameters but no declared priors - % No priors are declared so Dynare will estimate the model by - % maximum likelihood with inequality constraints for the parameters. + % 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.lb = lb; bounds.ub = ub; @@ -339,7 +339,7 @@ if ~isempty(estim_params_) && ~(all(strcmp(fieldnames(estim_params_),'full_calib end else check_prior_bounds(xparam1,bounds,M_,estim_params_,options_,bayestopt_) - end + end end if isempty(estim_params_) || all(strcmp(fieldnames(estim_params_),'full_calibration_detected')) || (isfield(estim_params_,'nvx') && sum(estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+estim_params_.ncn+estim_params_.np)==0) % If estim_params_ is empty (e.g. when running the smoother on a calibrated model) @@ -423,7 +423,7 @@ if options_.selected_variables_only if options_.forecast > 0 && options_.mh_replic == 0 && ~options_.load_mh_file fprintf('\nEstimation: The selected_variables_only option is incompatible with classical forecasts. It will be ignored.\n') k3 = (1:M_.endo_nbr)'; - k3p = (1:M_.endo_nbr)'; + k3p = (1:M_.endo_nbr)'; else for i=1:size(var_list_,1) k3 = [k3; strmatch(var_list_(i,:),M_.endo_names(dr.order_var,:), 'exact')]; @@ -551,7 +551,7 @@ ncx = estim_params_.ncx; nvn = estim_params_.nvn; ncn = estim_params_.ncn; if estim_params_.np - M.params(estim_params_.param_vals(:,1)) = xparam1(nvx+ncx+nvn+ncn+1:end); + M.params(estim_params_.param_vals(:,1)) = xparam1(nvx+ncx+nvn+ncn+1:end); end [oo_.steady_state, params,info] = evaluate_steady_state(oo_.steady_state,M,options_,oo_,steadystate_check_flag); diff --git a/matlab/dynare_gradient.m b/matlab/dynare_gradient.m index 91b4140c15..fc15ba633b 100644 --- a/matlab/dynare_gradient.m +++ b/matlab/dynare_gradient.m @@ -4,14 +4,14 @@ function [F,G] = dynare_gradient(fcn,x,epsilon,varargin) % INPUTS: % fcn [string] name of the matlab's function. % x [double] m*1 vector (where the gradient is evaluated). -% epsilon [double] scalar or m*1 vector of steps. +% epsilon [double] scalar or m*1 vector of steps. % -% OUTPUTS: +% OUTPUTS: % F [double] n*1 vector, evaluation of the function at x. % G [double] n*m matrix, evaluation of the gradient at x. % % OUTPUTS -% +% % Copyright (C) 2010-2012 Dynare Team % % This file is part of Dynare. @@ -51,7 +51,7 @@ for i=1:m h = H(i,:); else h = H(:,i); - end + end [Fh,junk1,junk2,flag] = feval(fcn, x+transpose(h), varargin{:}); if flag G(:,i) = (Fh-F)/epsilon; diff --git a/matlab/dynare_graph.m b/matlab/dynare_graph.m index 9400f624ee..3717efa45f 100644 --- a/matlab/dynare_graph.m +++ b/matlab/dynare_graph.m @@ -1,5 +1,5 @@ function dyn_graph=dynare_graph(dyn_graph,y,tit,x) -% function dynare_graph(y,tit,x) +% function dynare_graph(y,tit,x) % graphs % % INPUT @@ -32,7 +32,7 @@ function dyn_graph=dynare_graph(dyn_graph,y,tit,x) if nargin < 4 x = (1:size(y,1))'; end -nplot = dyn_graph.plot_nbr + 1; +nplot = dyn_graph.plot_nbr + 1; if nplot > dyn_graph.max_nplot figure('Name',dyn_graph.figure_name); nplot = 1; @@ -46,7 +46,7 @@ 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 diff --git a/matlab/dynare_graph_close.m b/matlab/dynare_graph_close.m index ed4371034c..a91d9f63e9 100644 --- a/matlab/dynare_graph_close.m +++ b/matlab/dynare_graph_close.m @@ -1,5 +1,5 @@ function dynare_graph_close() -% function dynare_graph_close() +% function dynare_graph_close() % close a figure % % INPUT @@ -27,4 +27,3 @@ function dynare_graph_close() % % 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 0783a4029a..b97c2b5f84 100644 --- a/matlab/dynare_graph_init.m +++ b/matlab/dynare_graph_init.m @@ -1,5 +1,5 @@ function dyn_graph=dynare_graph_init(figure_name,nplot,line_types,line_width) -% function dynare_graph_init(figure_name,colors) +% function dynare_graph_init(figure_name,colors) % initializes set of graphs % % INPUTS: diff --git a/matlab/dynare_identification.m b/matlab/dynare_identification.m index e568909131..7b5c1e5569 100644 --- a/matlab/dynare_identification.m +++ b/matlab/dynare_identification.m @@ -3,8 +3,8 @@ function [pdraws, TAU, GAM, LRE, gp, H, JJ] = dynare_identification(options_iden % % INPUTS % o options_ident [structure] identification options -% o pdraws0 [matrix] optional: matrix of MC sample of model params. -% +% o pdraws0 [matrix] optional: matrix of MC sample of model params. +% % OUTPUTS % o pdraws [matrix] matrix of MC sample of model params used % o TAU, [matrix] MC sample of entries in the model solution (stacked vertically) @@ -13,11 +13,11 @@ function [pdraws, TAU, GAM, LRE, gp, H, JJ] = dynare_identification(options_iden % o gp, [matrix] derivatives of the Jacobian (LRE model) % o H, [matrix] derivatives of the model solution % o JJ [matrix] derivatives of the moments -% +% % SPECIAL REQUIREMENTS % None -% main +% main % % Copyright (C) 2010-2017 Dynare Team % @@ -67,7 +67,7 @@ else if options_.diffuse_filter==1 %warning if estimation with diffuse filter was done, but not passed warning('IDENTIFICATION:: Previously the diffuse_filter option was used, but it was not passed to the identification command. This may result in problems if your model contains unit roots.') end - if isfield(options_ident,'lik_init') + if isfield(options_ident,'lik_init') options_.lik_init=options_ident.lik_init; %make options_ inherit lik_init if options_ident.lik_init==3 %user specified diffuse filter using the lik_init option options_ident.analytic_derivation=0; %diffuse filter not compatible with analytic derivation @@ -195,7 +195,7 @@ if prior_exist end name=cell(nparam,1); name_tex=cell(nparam,1); - for jj=1:nparam + for jj=1:nparam if options_.TeX [param_name_temp, param_name_tex_temp]= get_the_name(jj,options_.TeX,M_,estim_params_,options_); name_tex{jj,1} = strrep(param_name_tex_temp,'$',''); @@ -245,18 +245,18 @@ store_options_ident = options_ident; if iload <=0 [I,J]=find(M_.lead_lag_incidence'); if prior_exist -% if exist([fname_,'_mean.mat'],'file'), -% % disp('Testing posterior mean') -% load([fname_,'_mean'],'xparam1') -% pmean = xparam1'; -% clear xparam1 -% end -% if exist([fname_,'_mode.mat'],'file'), -% % disp('Testing posterior mode') -% load([fname_,'_mode'],'xparam1') -% pmode = xparam1'; -% clear xparam1 -% end + % if exist([fname_,'_mean.mat'],'file'), + % % disp('Testing posterior mean') + % load([fname_,'_mean'],'xparam1') + % pmean = xparam1'; + % clear xparam1 + % end + % if exist([fname_,'_mode.mat'],'file'), + % % disp('Testing posterior mode') + % load([fname_,'_mode'],'xparam1') + % pmode = xparam1'; + % clear xparam1 + % end params = set_prior(estim_params_,M_,options_)'; if all(bayestopt_.pshape == 0) parameters = 'ML_Starting_value'; @@ -264,38 +264,38 @@ if iload <=0 disp('Testing ML Starting value') else switch parameters - case 'calibration' - parameters_TeX = 'Calibration'; - disp('Testing calibration') - params(1,:) = get_all_parameters(estim_params_,M_); - case 'posterior_mode' - parameters_TeX = 'Posterior mode'; - disp('Testing posterior mode') - params(1,:) = get_posterior_parameters('mode'); - case 'posterior_mean' - parameters_TeX = 'Posterior mean'; - disp('Testing posterior mean') - params(1,:) = get_posterior_parameters('mean'); - case 'posterior_median' - parameters_TeX = 'Posterior median'; - disp('Testing posterior median') - params(1,:) = get_posterior_parameters('median'); - case 'prior_mode' - parameters_TeX = 'Prior mode'; - disp('Testing prior mode') - params(1,:) = bayestopt_.p5(:); - case 'prior_mean' - parameters_TeX = 'Prior mean'; - disp('Testing prior mean') - params(1,:) = bayestopt_.p1; - otherwise - disp('The option parameter_set has to be equal to:') - disp(' ''posterior_mode'', ') - disp(' ''posterior_mean'', ') - disp(' ''posterior_median'', ') - disp(' ''prior_mode'' or') - disp(' ''prior_mean''.') - error; + case 'calibration' + parameters_TeX = 'Calibration'; + disp('Testing calibration') + params(1,:) = get_all_parameters(estim_params_,M_); + case 'posterior_mode' + parameters_TeX = 'Posterior mode'; + disp('Testing posterior mode') + params(1,:) = get_posterior_parameters('mode'); + case 'posterior_mean' + parameters_TeX = 'Posterior mean'; + disp('Testing posterior mean') + params(1,:) = get_posterior_parameters('mean'); + case 'posterior_median' + parameters_TeX = 'Posterior median'; + disp('Testing posterior median') + params(1,:) = get_posterior_parameters('median'); + case 'prior_mode' + parameters_TeX = 'Prior mode'; + disp('Testing prior mode') + params(1,:) = bayestopt_.p5(:); + case 'prior_mean' + parameters_TeX = 'Prior mean'; + disp('Testing prior mean') + params(1,:) = bayestopt_.p1; + otherwise + disp('The option parameter_set has to be equal to:') + disp(' ''posterior_mode'', ') + disp(' ''posterior_mean'', ') + disp(' ''posterior_median'', ') + disp(' ''prior_mode'' or') + disp(' ''prior_mean''.') + error; end end else @@ -313,31 +313,31 @@ if iload <=0 disp(['The model does not solve for ', parameters, ' with error code info = ', int2str(info(1))]), skipline() if info(1)==1 - disp('info==1 %! The model doesn''t determine the current variables uniquely.') + disp('info==1 %! The model doesn''t determine the current variables uniquely.') elseif info(1)==2 - disp('info==2 %! MJDGGES returned an error code.') + disp('info==2 %! MJDGGES returned an error code.') elseif info(1)==3 - disp('info==3 %! Blanchard & Kahn conditions are not satisfied: no stable equilibrium. ') + disp('info==3 %! Blanchard & Kahn conditions are not satisfied: no stable equilibrium. ') elseif info(1)==4 - disp('info==4 %! Blanchard & Kahn conditions are not satisfied: indeterminacy. ') + disp('info==4 %! Blanchard & Kahn conditions are not satisfied: indeterminacy. ') elseif info(1)==5 - disp('info==5 %! Blanchard & Kahn conditions are not satisfied: indeterminacy due to rank failure. ') + disp('info==5 %! Blanchard & Kahn conditions are not satisfied: indeterminacy due to rank failure. ') elseif info(1)==6 - disp('info==6 %! The jacobian evaluated at the deterministic steady state is complex.') + disp('info==6 %! The jacobian evaluated at the deterministic steady state is complex.') elseif info(1)==19 - disp('info==19 %! The steadystate routine thrown an exception (inconsistent deep parameters). ') + disp('info==19 %! The steadystate routine thrown an exception (inconsistent deep parameters). ') elseif info(1)==20 - disp('info==20 %! Cannot find the steady state, info(2) contains the sum of square residuals (of the static equations). ') + disp('info==20 %! Cannot find the steady state, info(2) contains the sum of square residuals (of the static equations). ') elseif info(1)==21 - disp('info==21 %! The steady state is complex, info(2) contains the sum of square of imaginary parts of the steady state.') + disp('info==21 %! The steady state is complex, info(2) contains the sum of square of imaginary parts of the steady state.') elseif info(1)==22 - disp('info==22 %! The steady has NaNs. ') + disp('info==22 %! The steady has NaNs. ') elseif info(1)==23 - disp('info==23 %! M_.params has been updated in the steadystate routine and has complex valued scalars. ') + disp('info==23 %! M_.params has been updated in the steadystate routine and has complex valued scalars. ') elseif info(1)==24 - disp('info==24 %! M_.params has been updated in the steadystate routine and has some NaNs. ') + disp('info==24 %! M_.params has been updated in the steadystate routine and has some NaNs. ') elseif info(1)==30 - disp('info==30 %! Ergodic variance can''t be computed. ') + disp('info==30 %! Ergodic variance can''t be computed. ') end disp('----------- ') skipline() @@ -367,12 +367,12 @@ if iload <=0 end end idehess_point.params=params; -% siH = idemodel_point.siH; -% siJ = idemoments_point.siJ; -% siLRE = idelre_point.siLRE; -% normH = max(abs(siH)')'; -% normJ = max(abs(siJ)')'; -% normLRE = max(abs(siLRE)')'; + % siH = idemodel_point.siH; + % siJ = idemoments_point.siJ; + % siLRE = idelre_point.siLRE; + % normH = max(abs(siH)')'; + % normJ = max(abs(siJ)')'; + % normLRE = max(abs(siLRE)')'; save([IdentifDirectoryName '/' M_.fname '_identif.mat'], 'idehess_point', 'idemoments_point','idemodel_point', 'idelre_point','store_options_ident') save([IdentifDirectoryName '/' M_.fname '_' parameters '_identif.mat'], 'idehess_point', 'idemoments_point','idemodel_point', 'idelre_point','store_options_ident') disp_identification(params, idemodel_point, idemoments_point, name, advanced); @@ -476,21 +476,21 @@ if iload <=0 stoH = zeros(size(stoH)); stoJJ = zeros(size(stoJJ)); stoLRE = zeros(size(stoLRE)); - + end - + if SampleSize > 1 -% if isoctave || options_.console_mode, -% console_waitbar(0,iteration/SampleSize); -% else - dyn_waitbar(iteration/SampleSize,h,['MC identification checks ',int2str(iteration),'/',int2str(SampleSize)]) -% end + % if isoctave || options_.console_mode, + % console_waitbar(0,iteration/SampleSize); + % else + dyn_waitbar(iteration/SampleSize,h,['MC identification checks ',int2str(iteration),'/',int2str(SampleSize)]) + % end end end - + end - - + + if SampleSize > 1 if isoctave || options_.console_mode fprintf('\n'); @@ -511,28 +511,28 @@ if iload <=0 siHnorm(iter,:) = vnorm(stoH(:,:,irun)./repmat(normTAU,1,nparam)).*normaliz1; siLREnorm(iter,:) = vnorm(stoLRE(:,:,irun)./repmat(normLRE,1,nparam-offset)).*normaliz1(offset+1:end); end - + end idemoments.siJnorm = siJnorm; idemodel.siHnorm = siHnorm; idelre.siLREnorm = siLREnorm; save([IdentifDirectoryName '/' M_.fname '_identif.mat'], 'pdraws', 'idemodel', 'idemoments', 'idelre', ... %'indJJ', 'indH', 'indLRE', ... - 'TAU', 'GAM', 'LRE','-append') + 'TAU', 'GAM', 'LRE','-append') else siJnorm = idemoments_point.siJnorm; siHnorm = idemodel_point.siHnorm; siLREnorm = idelre_point.siLREnorm; end - + else load([IdentifDirectoryName '/' M_.fname '_identif']) -% identFiles = dir([IdentifDirectoryName '/' M_.fname '_identif_*']); + % identFiles = dir([IdentifDirectoryName '/' M_.fname '_identif_*']); parameters = store_options_ident.parameter_set; options_ident.parameter_set = parameters; options_ident.prior_mc=size(pdraws,1); SampleSize = options_ident.prior_mc; options_.options_ident = options_ident; -end +end if nargout>3 && iload filnam = dir([IdentifDirectoryName '/' M_.fname '_identif_*.mat']); @@ -544,7 +544,7 @@ if nargout>3 && iload H = cat(3,H, stoH(:,abs(iload),:)); JJ = cat(3,JJ, stoJJ(:,abs(iload),:)); gp = cat(3,gp, stoLRE(:,abs(iload),:)); - + end end diff --git a/matlab/dynare_sensitivity.m b/matlab/dynare_sensitivity.m index cb1f332f10..acb0f12b54 100644 --- a/matlab/dynare_sensitivity.m +++ b/matlab/dynare_sensitivity.m @@ -24,7 +24,7 @@ function x0=dynare_sensitivity(options_gsa) global M_ options_ oo_ bayestopt_ estim_params_ if options_.dsge_var - error('Identification does not support DSGE-VARs at the current stage') + error('Identification does not support DSGE-VARs at the current stage') end fname_ = M_.fname; @@ -43,7 +43,7 @@ end if isfield(options_gsa,'morris') && options_gsa.morris==1 if isfield(options_gsa,'identification') && options_gsa.identification==0 -% options_gsa.redform=1; + % options_gsa.redform=1; end if isfield(options_gsa,'ppost') && options_gsa.ppost error('sensitivity:: Morris is incompatible with posterior sampling') @@ -144,7 +144,7 @@ if options_gsa.identification if isfield(options_,'options_ident') options_.options_ident.load_ident_files = options_gsa.load_ident_files; options_.options_ident.useautocorr = options_gsa.useautocorr; - options_.options_ident.ar = options_gsa.ar; + options_.options_ident.ar = options_gsa.ar; options_ident=options_.options_ident; else options_ident=[]; @@ -213,7 +213,7 @@ if options_gsa.morris>2 disp('the option is reset at morris = 1 .') options_gsa.morris=1; end - + if options_gsa.morris==1 if ~options_gsa.identification options_gsa.redform=1; @@ -231,12 +231,12 @@ if options_gsa.morris==1 options_gsa.alpha2_stab=1; options_gsa.pvalue_ks=0; options_gsa.pvalue_corr=0; -% if options_gsa.morris==3, -% options_gsa = set_default_option(options_gsa,'Nsam',256); -% OutputDirectoryName = CheckPath('gsa/identif',M_.dname); -% else - OutputDirectoryName = CheckPath('gsa/screen',M_.dname); -% end + % if options_gsa.morris==3, + % options_gsa = set_default_option(options_gsa,'Nsam',256); + % OutputDirectoryName = CheckPath('gsa/identif',M_.dname); + % else + OutputDirectoryName = CheckPath('gsa/screen',M_.dname); + % end else OutputDirectoryName = CheckPath('gsa',M_.dname); end @@ -252,8 +252,8 @@ if (options_gsa.load_stab || options_gsa.load_rmse || options_gsa.load_redform) 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 + 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) || ... @@ -305,7 +305,7 @@ if options_gsa.redform && ~isempty(options_gsa.namendo) nshock = nshock + estim_params_.nvn; nshock = nshock + estim_params_.ncx; nshock = nshock + estim_params_.ncn; - + lpmat0=lpmat(:,1:nshock); lpmat=lpmat(:,nshock+1:end); istable=(1:size(lpmat,1)); @@ -314,7 +314,7 @@ if options_gsa.redform && ~isempty(options_gsa.namendo) iindeterm=[]; save([OutputDirectoryName filesep M_.fname '_mc.mat'],'lpmat','lpmat0','istable','iunstable','iwrong','iindeterm') options_gsa.load_stab=1; - + x0 = stab_map_(OutputDirectoryName,options_gsa); end if strmatch(':',options_gsa.namendo,'exact') @@ -326,7 +326,7 @@ if options_gsa.redform && ~isempty(options_gsa.namendo) if strmatch(':',options_gsa.namlagendo,'exact') options_gsa.namlagendo=M_.endo_names(1:M_.orig_endo_nbr,:); end -% options_.opt_gsa = options_gsa; + % options_.opt_gsa = options_gsa; if options_gsa.morris==1 redform_screen(OutputDirectoryName,options_gsa); else @@ -365,54 +365,54 @@ if options_gsa.rmse end end if isempty(a) - if options_gsa.lik_only - options_.smoother=0; - options_.filter_step_ahead=[]; - options_.forecast=0; - options_.filtered_vars=0; - end -% dynare_MC([],OutputDirectoryName,data,rawdata,data_info); - if options_gsa.pprior - TmpDirectoryName = ([M_.dname filesep 'gsa' filesep 'prior']); - else - TmpDirectoryName = ([M_.dname filesep 'gsa' filesep 'mc']); - end - if exist(TmpDirectoryName,'dir') - mydelete([M_.fname '_filter_step_ahead*.mat'],[TmpDirectoryName filesep]); - mydelete([M_.fname '_inno*.mat'],[TmpDirectoryName filesep]); - mydelete([M_.fname '_smooth*.mat'],[TmpDirectoryName filesep]); - mydelete([M_.fname '_update*.mat'],[TmpDirectoryName filesep]); - filparam = dir([TmpDirectoryName filesep M_.fname '_param*.mat']); - for j=1:length(filparam) - if isempty(strmatch([M_.fname '_param_irf'],filparam(j).name)) - delete([TmpDirectoryName filesep filparam(j).name]); + if options_gsa.lik_only + options_.smoother=0; + options_.filter_step_ahead=[]; + options_.forecast=0; + options_.filtered_vars=0; + end + % dynare_MC([],OutputDirectoryName,data,rawdata,data_info); + if options_gsa.pprior + TmpDirectoryName = ([M_.dname filesep 'gsa' filesep 'prior']); + else + TmpDirectoryName = ([M_.dname filesep 'gsa' filesep 'mc']); + end + if exist(TmpDirectoryName,'dir') + mydelete([M_.fname '_filter_step_ahead*.mat'],[TmpDirectoryName filesep]); + mydelete([M_.fname '_inno*.mat'],[TmpDirectoryName filesep]); + mydelete([M_.fname '_smooth*.mat'],[TmpDirectoryName filesep]); + mydelete([M_.fname '_update*.mat'],[TmpDirectoryName filesep]); + filparam = dir([TmpDirectoryName filesep M_.fname '_param*.mat']); + for j=1:length(filparam) + if isempty(strmatch([M_.fname '_param_irf'],filparam(j).name)) + delete([TmpDirectoryName filesep filparam(j).name]); + end end + end - - end - prior_posterior_statistics('gsa',dataset_, dataset_info); - if options_.bayesian_irf - PosteriorIRF('gsa'); - end - 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 - + prior_posterior_statistics('gsa',dataset_, dataset_info); + if options_.bayesian_irf + PosteriorIRF('gsa'); + end + 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,data_info); + % filt_mc_(OutputDirectoryName,data_info); filt_mc_(OutputDirectoryName,options_gsa,dataset_,dataset_info); end options_.opt_gsa = options_gsa; @@ -448,14 +448,14 @@ if options_gsa.glue else data = transpose(rawdata); end - + Obs.data = data; Obs.time = [1:gend]; Obs.num = gend; for j=1:length(options_.varobs) Obs.name{j} = options_.varobs{j}; vj = options_.varobs{j}; - + jxj = strmatch(vj,lgy_(dr_.order_var,:),'exact'); js = strmatch(vj,lgy_,'exact'); if ~options_gsa.ppost @@ -477,7 +477,7 @@ if options_gsa.glue 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)); @@ -490,14 +490,14 @@ if options_gsa.glue Out1=Out; end ismoo(j)=jxj; - + end jsmoo = length(options_.varobs); 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 + 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)]; @@ -514,7 +514,7 @@ if options_gsa.glue end tit(M_.exo_names_orig_ord,:) = M_.exo_names; for j=1:M_.exo_nbr - Exo(j).name = deblank(tit(j,:)); + Exo(j).name = deblank(tit(j,:)); end if ~options_gsa.ppost Lik(length(options_.varobs)+1).name = 'logpo'; @@ -525,10 +525,10 @@ if options_gsa.glue 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; @@ -539,7 +539,7 @@ if options_gsa.glue Info.TypeofSample='post'; save([OutputDirectoryName,'/',fname_,'_glue_post.mat'], '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'; @@ -555,5 +555,5 @@ if options_gsa.glue % 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 4e1c614e1e..b2b9781989 100644 --- a/matlab/dynare_solve.m +++ b/matlab/dynare_solve.m @@ -141,19 +141,19 @@ if options.solve_algo == 0 if max(abs(fvec)) >= tolf info = 1; else - info = 0; + info = 0; end else info = 1; end elseif options.solve_algo == 1 - [x,info]=solve1(func,x,1:nn,1:nn,jacobian_flag,options.gstep, ... + [x,info]=solve1(func,x,1:nn,1:nn,jacobian_flag,options.gstep, ... tolf,options.solve_tolx, ... maxit,options.debug,varargin{:}); elseif options.solve_algo == 9 - [x,info]=trust_region(func,x,1:nn,1:nn,jacobian_flag,options.gstep, ... - tolf,options.solve_tolx, ... - maxit,options.debug,varargin{:}); + [x,info]=trust_region(func,x,1:nn,1:nn,jacobian_flag,options.gstep, ... + tolf,options.solve_tolx, ... + maxit,options.debug,varargin{:}); elseif options.solve_algo == 2 || options.solve_algo == 4 if options.solve_algo == 2 @@ -233,4 +233,3 @@ elseif options.solve_algo == 11 else error('DYNARE_SOLVE: option solve_algo must be one of [0,1,2,3,4,9,10,11]') end - diff --git a/matlab/dynare_solve_block_or_bytecode.m b/matlab/dynare_solve_block_or_bytecode.m index 6b3192f186..2a1f547b9b 100644 --- a/matlab/dynare_solve_block_or_bytecode.m +++ b/matlab/dynare_solve_block_or_bytecode.m @@ -22,7 +22,7 @@ if options.block && ~options.bytecode for b = 1:length(M.block_structure_stat.block) ss = x; if M.block_structure_stat.block(b).Simulation_Type ~= 1 && ... - M.block_structure_stat.block(b).Simulation_Type ~= 2 + M.block_structure_stat.block(b).Simulation_Type ~= 2 if options.solve_algo <= 4 [y, check] = dynare_solve('block_mfs_steadystate', ... ss(M.block_structure_stat.block(b).variable), ... @@ -60,7 +60,7 @@ elseif options.bytecode elseif options.block for b = 1:length(M.block_structure_stat.block) if M.block_structure_stat.block(b).Simulation_Type ~= 1 && ... - M.block_structure_stat.block(b).Simulation_Type ~= 2 + M.block_structure_stat.block(b).Simulation_Type ~= 2 [y, check] = dynare_solve('block_bytecode_mfs_steadystate', ... x(M.block_structure_stat ... .block(b).variable), ... diff --git a/matlab/dynare_squeeze.m b/matlab/dynare_squeeze.m index 50fbec3562..85e66f332e 100644 --- a/matlab/dynare_squeeze.m +++ b/matlab/dynare_squeeze.m @@ -18,7 +18,7 @@ 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); +sizA = size(A); dimA = length(sizA); switch dimA case 1 diff --git a/matlab/dynatype.m b/matlab/dynatype.m index 35276028f4..a65b2961b3 100644 --- a/matlab/dynatype.m +++ b/matlab/dynatype.m @@ -1,12 +1,12 @@ function dynatype (s,var_list) % function dynatype (s,var_list) -% This optional command saves the simulation results in a text file. The name of each +% 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: filename % var_list: vector of selected endogenous variables -% +% % OUTPUTS % none % diff --git a/matlab/dyntable.m b/matlab/dyntable.m index 86d92fc2b8..b7a2262642 100644 --- a/matlab/dyntable.m +++ b/matlab/dyntable.m @@ -7,10 +7,10 @@ function dyntable(options_,title,headers,labels,values,label_width,val_width,val % labels [n by nchar] character array of labels for label column % values [matrix] matrix of values to display % label_width [scalar] Width of the label -% val_width [scalar] Width of value column +% val_width [scalar] Width of value column % val_precis [integer] precision of displayed values -% -% +% +% % Copyright (C) 2002-2016 Dynare Team % % This file is part of Dynare. @@ -33,9 +33,9 @@ if options_.noprint end %% get width of label column -if ~isempty(label_width) +if ~isempty(label_width) label_width = max(size(deblank(char(headers(1,:),labels)),2)+2, ... - label_width); + label_width); else %use default length label_width = max(size(deblank(char(headers(1,:),labels)),2))+2; end @@ -51,7 +51,7 @@ if any(values) < 0 %add one character for minus sign values_length = values_length+1; end -%% get width of header strings +%% get width of header strings headers_length = max(size(deblank(headers(2:end,:)),2)); if ~isempty(val_width) val_width = max(max(headers_length,values_length)+2,val_width); diff --git a/matlab/endogenous_prior.m b/matlab/endogenous_prior.m index c2930abad8..0c2fda36dc 100644 --- a/matlab/endogenous_prior.m +++ b/matlab/endogenous_prior.m @@ -2,17 +2,17 @@ function [lnpriormom] = endogenous_prior(data,Pstar,BayesInfo,H) % Computes the endogenous log prior addition to the initial prior % % INPUTS -% data [double] n*T vector of data observations +% data [double] n*T vector of data observations % Pstar [double] k*k matrix of -% BayesInfo [structure] +% BayesInfo [structure] % % OUTPUTS % lnpriormom [double] scalar of log endogenous prior value % Code to implement notes on endogenous priors by Lawrence Christiano, % specified in the appendix of: -% �Introducing Financial Frictions and Unemployment into a Small Open Economy Model� -% by Lawrence J. Christiano, Mathias Trabandt and Karl Walentin (2011), Journal of Economic Dynamics and Control +% Introducing Financial Frictions and Unemployment into a Small Open Economy Model +% by Lawrence J. Christiano, Mathias Trabandt and Karl Walentin (2011), Journal of Economic Dynamics and Control % this is the 'mother' of the priors on the model parameters. % the priors include a metric across some choosen moments of the (supposedly % pre-sample) data. @@ -23,7 +23,7 @@ function [lnpriormom] = endogenous_prior(data,Pstar,BayesInfo,H) % appropriate adjustment to the following code. -% Copyright (C) 2011 Lawrence J. Christiano, Mathias Trabandt and Karl Walentin +% Copyright (C) 2011 Lawrence J. Christiano, Mathias Trabandt and Karl Walentin % Copyright (C) 2013 Dynare Team % % This file is part of Dynare. @@ -75,7 +75,7 @@ end % Finally, we have the sampling uncertainty measure Shat: Shat=C0 +(1-1/(2+1))*(C1+C1')... - +(1-2/(2+1))*(C2+C2'); + +(1-2/(2+1))*(C2+C2'); % Model variances below: mf=BayesInfo.mf1; @@ -86,4 +86,3 @@ Ftheta=diag(Z*Pstar(:,mf)+H); % below commented out line is for Del Negro Schorfheide style priors: % lnpriormom=-.5*n*TT*log(2*pi)-.5*TT*log(det(sigma))-.5*TT*trace(inv(sigma)*(gamyy-2*phi'*gamxy+phi'*gamxx*phi)); lnpriormom=.5*n*log(Tsamp/(2*pi))-.5*log(det(Shat))-.5*Tsamp*(Fhat-Ftheta)'/Shat*(Fhat-Ftheta); - diff --git a/matlab/endogenous_prior_restrictions.m b/matlab/endogenous_prior_restrictions.m index df38fd5468..ef734acd12 100644 --- a/matlab/endogenous_prior_restrictions.m +++ b/matlab/endogenous_prior_restrictions.m @@ -1,173 +1,173 @@ -function [info, info_irf, info_moment, data_irf, data_moment] = endogenous_prior_restrictions(T,R,Model,DynareOptions,DynareResults) -% Check for prior (sign) restrictions on irf's and theoretical moments -% -% INPUTS -% T [double] n*n state space matrix -% R [double] n*k matrix of shocks -% Model [structure] -% DynareOptions [structure] -% DynareResults [structure] - -% OUTPUTS -% info [double] check if prior restrictions are matched by the -% model and related info -% info_irf [double] array of test checks for all individual irf restrictions -% info_moment [double] array of test checks for all individual moment restrictions -% - -% Copyright (C) 2013-2017 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/>. - -info=[0 0]; -info_irf=[]; -info_moment=[]; -data_irf=[]; -data_moment=[]; - -endo_prior_restrictions.irf= DynareOptions.endogenous_prior_restrictions.irf; -endo_prior_restrictions.moment= DynareOptions.endogenous_prior_restrictions.moment; - -if ~isempty(endo_prior_restrictions.irf) - data_irf=cell(size(endo_prior_restrictions.irf,1),1); - if DynareOptions.order>1 - error('The algorithm for prior (sign) restrictions on irf''s is currently restricted to first-order decision rules') - return - end - varlist=Model.endo_names(DynareResults.dr.order_var,:); - if isempty(T) - [T,R,SteadyState,infox,Model,DynareOptions,DynareResults] = dynare_resolve(Model,DynareOptions,DynareResults); - else % check if T and R are given in the restricted form!!! - if size(T,1)<size(varlist,1) - varlist=varlist(DynareResults.dr.restrict_var_list,:); - end - % check if endo_prior_restrictions.irf{:,1} variables are in varlist - varlistok=1; - for j=1:size(endo_prior_restrictions.irf,1) - if isempty(strmatch(endo_prior_restrictions.irf{j,1},varlist,'exact')) - varlistok=0; - end - end - if ~varlistok - varlist=Model.endo_names(DynareResults.dr.order_var,:); - [T,R,SteadyState,infox,Model,DynareOptions,DynareResults] = dynare_resolve(Model,DynareOptions,DynareResults); - end - end - NT=1; - for j=1:size(endo_prior_restrictions.irf,1) - NT=max(NT,max(endo_prior_restrictions.irf{j,3})); - end - info_irf=ones(size(endo_prior_restrictions.irf,1),2); - for t=1:NT - if ~DynareOptions.relative_irf - RR = T^(t-1)*R*diag(sqrt(diag(Model.Sigma_e))); - else - RR = T^(t-1)*R*100; - end - for j=1:size(endo_prior_restrictions.irf,1) - if endo_prior_restrictions.irf{j,3}~=t - continue - end - iendo=strmatch(endo_prior_restrictions.irf{j,1},varlist,'exact'); - iexo=strmatch(endo_prior_restrictions.irf{j,2},Model.exo_names,'exact'); - data_irf{j}=[data_irf{j}; [t RR(iendo,iexo)]]; - if (RR(iendo,iexo)>endo_prior_restrictions.irf{j,4}(1)) && (RR(iendo,iexo)<endo_prior_restrictions.irf{j,4}(2)) - info_irf(j,:)=info_irf(j,:).*[0, 0]; - else - if RR(iendo,iexo)<endo_prior_restrictions.irf{j,4}(1) - delt = (RR(iendo,iexo)-endo_prior_restrictions.irf{j,4}(1))^2; - else - delt = (RR(iendo,iexo)-endo_prior_restrictions.irf{j,4}(2))^2; - end - info_irf(j,:)=info_irf(j,:).*[49, delt]; - end - end - end - if any(info_irf) - info=[49,sum(info_irf(:,2))]; - end - -end - -if ~isempty(endo_prior_restrictions.moment) - if DynareOptions.order>1 - error('The algorithm for prior (sign) restrictions on moments is currently restricted to first-order decision rules') - return - end - data_moment=cell(size(endo_prior_restrictions.moment,1),1); - var_list_=endo_prior_restrictions.moment{1,1}; - for j=1:size(endo_prior_restrictions.moment,1) - tmp=endo_prior_restrictions.moment{j,1}; - if ~ismember(tmp,cellstr(var_list_)) - var_list_ = char(var_list_, tmp); - end - tmp=endo_prior_restrictions.moment{j,2}; - if ~ismember(tmp,cellstr(var_list_)) - var_list_ = char(var_list_, tmp); - end - end - NTmax=0; - NTmin=0; - for j=1:size(endo_prior_restrictions.moment,1) - NTmax=max(NTmax,max(endo_prior_restrictions.moment{j,3})); - NTmin=min(NTmin,min(endo_prior_restrictions.moment{j,3})); - end - info_moment=ones(size(endo_prior_restrictions.moment,1),2); - nvar = size(var_list_,1); - ivar=zeros(nvar,1); - for i=1:nvar - i_tmp = strmatch(var_list_(i,:),Model.endo_names,'exact'); - if isempty(i_tmp) - error (['One of the variable specified does not exist']) - else - ivar(i) = i_tmp; - end - end - DynareOptions.ar = max(abs(NTmin),NTmax); - [gamma_y,stationary_vars] = th_autocovariances(DynareResults.dr, ivar, Model, DynareOptions,1); - for t=NTmin:NTmax - RR = gamma_y{abs(t)+1}; - if t==0 - RR = RR./(sqrt(diag(RR))*sqrt(diag(RR))')-eye(nvar)+diag(diag(gamma_y{t+1})); % becomes correlation - end - for j=1:size(endo_prior_restrictions.moment,1) - if endo_prior_restrictions.moment{j,3}~=t - continue - end - iendo1 = strmatch(endo_prior_restrictions.moment{j,1},var_list_,'exact'); - iendo2 = strmatch(endo_prior_restrictions.moment{j,2},var_list_,'exact'); - if t>0 - tmp0 = iendo1; - iendo1=iendo2; - iendo2=tmp0; - end - data_moment{j}=[data_moment{j}; [t RR(iendo1,iendo2)]]; - if (RR(iendo1,iendo2)>endo_prior_restrictions.moment{j,4}(1)) && (RR(iendo1,iendo2)<endo_prior_restrictions.moment{j,4}(2)) - info_moment(j,:)=info_moment(j,:).*[0, 0]; - else - if RR(iendo1,iendo2)<endo_prior_restrictions.moment{j,4}(1) - delt = (RR(iendo1,iendo2)-endo_prior_restrictions.moment{j,4}(1))^2; - else - delt = (RR(iendo1,iendo2)-endo_prior_restrictions.moment{j,4}(2))^2; - end - info_moment(j,:)=info_moment(j,:).*[49, delt]; - end - end - end - if any(info_moment) - info=[49, info(2) + sum(info_moment(:,2))]; - end +function [info, info_irf, info_moment, data_irf, data_moment] = endogenous_prior_restrictions(T,R,Model,DynareOptions,DynareResults) +% Check for prior (sign) restrictions on irf's and theoretical moments +% +% INPUTS +% T [double] n*n state space matrix +% R [double] n*k matrix of shocks +% Model [structure] +% DynareOptions [structure] +% DynareResults [structure] + +% OUTPUTS +% info [double] check if prior restrictions are matched by the +% model and related info +% info_irf [double] array of test checks for all individual irf restrictions +% info_moment [double] array of test checks for all individual moment restrictions +% + +% Copyright (C) 2013-2017 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/>. + +info=[0 0]; +info_irf=[]; +info_moment=[]; +data_irf=[]; +data_moment=[]; + +endo_prior_restrictions.irf= DynareOptions.endogenous_prior_restrictions.irf; +endo_prior_restrictions.moment= DynareOptions.endogenous_prior_restrictions.moment; + +if ~isempty(endo_prior_restrictions.irf) + data_irf=cell(size(endo_prior_restrictions.irf,1),1); + if DynareOptions.order>1 + error('The algorithm for prior (sign) restrictions on irf''s is currently restricted to first-order decision rules') + return + end + varlist=Model.endo_names(DynareResults.dr.order_var,:); + if isempty(T) + [T,R,SteadyState,infox,Model,DynareOptions,DynareResults] = dynare_resolve(Model,DynareOptions,DynareResults); + else % check if T and R are given in the restricted form!!! + if size(T,1)<size(varlist,1) + varlist=varlist(DynareResults.dr.restrict_var_list,:); + end + % check if endo_prior_restrictions.irf{:,1} variables are in varlist + varlistok=1; + for j=1:size(endo_prior_restrictions.irf,1) + if isempty(strmatch(endo_prior_restrictions.irf{j,1},varlist,'exact')) + varlistok=0; + end + end + if ~varlistok + varlist=Model.endo_names(DynareResults.dr.order_var,:); + [T,R,SteadyState,infox,Model,DynareOptions,DynareResults] = dynare_resolve(Model,DynareOptions,DynareResults); + end + end + NT=1; + for j=1:size(endo_prior_restrictions.irf,1) + NT=max(NT,max(endo_prior_restrictions.irf{j,3})); + end + info_irf=ones(size(endo_prior_restrictions.irf,1),2); + for t=1:NT + if ~DynareOptions.relative_irf + RR = T^(t-1)*R*diag(sqrt(diag(Model.Sigma_e))); + else + RR = T^(t-1)*R*100; + end + for j=1:size(endo_prior_restrictions.irf,1) + if endo_prior_restrictions.irf{j,3}~=t + continue + end + iendo=strmatch(endo_prior_restrictions.irf{j,1},varlist,'exact'); + iexo=strmatch(endo_prior_restrictions.irf{j,2},Model.exo_names,'exact'); + data_irf{j}=[data_irf{j}; [t RR(iendo,iexo)]]; + if (RR(iendo,iexo)>endo_prior_restrictions.irf{j,4}(1)) && (RR(iendo,iexo)<endo_prior_restrictions.irf{j,4}(2)) + info_irf(j,:)=info_irf(j,:).*[0, 0]; + else + if RR(iendo,iexo)<endo_prior_restrictions.irf{j,4}(1) + delt = (RR(iendo,iexo)-endo_prior_restrictions.irf{j,4}(1))^2; + else + delt = (RR(iendo,iexo)-endo_prior_restrictions.irf{j,4}(2))^2; + end + info_irf(j,:)=info_irf(j,:).*[49, delt]; + end + end + end + if any(info_irf) + info=[49,sum(info_irf(:,2))]; + end + +end + +if ~isempty(endo_prior_restrictions.moment) + if DynareOptions.order>1 + error('The algorithm for prior (sign) restrictions on moments is currently restricted to first-order decision rules') + return + end + data_moment=cell(size(endo_prior_restrictions.moment,1),1); + var_list_=endo_prior_restrictions.moment{1,1}; + for j=1:size(endo_prior_restrictions.moment,1) + tmp=endo_prior_restrictions.moment{j,1}; + if ~ismember(tmp,cellstr(var_list_)) + var_list_ = char(var_list_, tmp); + end + tmp=endo_prior_restrictions.moment{j,2}; + if ~ismember(tmp,cellstr(var_list_)) + var_list_ = char(var_list_, tmp); + end + end + NTmax=0; + NTmin=0; + for j=1:size(endo_prior_restrictions.moment,1) + NTmax=max(NTmax,max(endo_prior_restrictions.moment{j,3})); + NTmin=min(NTmin,min(endo_prior_restrictions.moment{j,3})); + end + info_moment=ones(size(endo_prior_restrictions.moment,1),2); + nvar = size(var_list_,1); + ivar=zeros(nvar,1); + for i=1:nvar + i_tmp = strmatch(var_list_(i,:),Model.endo_names,'exact'); + if isempty(i_tmp) + error (['One of the variable specified does not exist']) + else + ivar(i) = i_tmp; + end + end + DynareOptions.ar = max(abs(NTmin),NTmax); + [gamma_y,stationary_vars] = th_autocovariances(DynareResults.dr, ivar, Model, DynareOptions,1); + for t=NTmin:NTmax + RR = gamma_y{abs(t)+1}; + if t==0 + RR = RR./(sqrt(diag(RR))*sqrt(diag(RR))')-eye(nvar)+diag(diag(gamma_y{t+1})); % becomes correlation + end + for j=1:size(endo_prior_restrictions.moment,1) + if endo_prior_restrictions.moment{j,3}~=t + continue + end + iendo1 = strmatch(endo_prior_restrictions.moment{j,1},var_list_,'exact'); + iendo2 = strmatch(endo_prior_restrictions.moment{j,2},var_list_,'exact'); + if t>0 + tmp0 = iendo1; + iendo1=iendo2; + iendo2=tmp0; + end + data_moment{j}=[data_moment{j}; [t RR(iendo1,iendo2)]]; + if (RR(iendo1,iendo2)>endo_prior_restrictions.moment{j,4}(1)) && (RR(iendo1,iendo2)<endo_prior_restrictions.moment{j,4}(2)) + info_moment(j,:)=info_moment(j,:).*[0, 0]; + else + if RR(iendo1,iendo2)<endo_prior_restrictions.moment{j,4}(1) + delt = (RR(iendo1,iendo2)-endo_prior_restrictions.moment{j,4}(1))^2; + else + delt = (RR(iendo1,iendo2)-endo_prior_restrictions.moment{j,4}(2))^2; + end + info_moment(j,:)=info_moment(j,:).*[49, delt]; + end + end + end + if any(info_moment) + info=[49, info(2) + sum(info_moment(:,2))]; + end end \ No newline at end of file diff --git a/matlab/ep/ep_problem_2.m b/matlab/ep/ep_problem_2.m index d31f0e7aa1..9168631bfe 100644 --- a/matlab/ep/ep_problem_2.m +++ b/matlab/ep/ep_problem_2.m @@ -78,7 +78,7 @@ for i = 1:order+1 else k1 = (nnodes-1)*(i-1)+k; end - if hybrid_order == 2 && (k > 1 || i == order) + if hybrid_order == 2 && (k > 1 || i == order) z = [Y(i_cols_p,1); Y(i_cols_s,1); Y(i_cols_f,k1)+h_correction(i_hc)]; @@ -93,10 +93,10 @@ for i = 1:order+1 % in first period we don't keep track of % predetermined variables i_cols_A = [i_cols_As - ny; i_cols_Af]; - A1(i_rows,i_cols_A) = A1(i_rows,i_cols_A) + weights(k)*jacobian(eq_index,i_cols_1); + A1(i_rows,i_cols_A) = A1(i_rows,i_cols_A) + weights(k)*jacobian(eq_index,i_cols_1); else i_cols_A = [i_cols_Ap; i_cols_As; i_cols_Af]; - A1(i_rows,i_cols_A) = A1(i_rows,i_cols_A) + weights(k)*jacobian(eq_index,i_cols_j); + A1(i_rows,i_cols_A) = A1(i_rows,i_cols_A) + weights(k)*jacobian(eq_index,i_cols_j); end else d1 = dynamic_model(z,innovation,params,steady_state,i+1); @@ -180,7 +180,7 @@ for j=1:world_nbr nzA{i,j} = [offset_r+ir,offset_c+icA(ic), v]'; else d1 = dynamic_model(Y(i_rows_y,j),x,params, ... - steady_state,i+1); + steady_state,i+1); end res(:,i,j) = d1(eq_index); i_rows_y = i_rows_y + ny; diff --git a/matlab/ep/euler_equation_error.m b/matlab/ep/euler_equation_error.m index 16de7a4b16..758f8785e3 100644 --- a/matlab/ep/euler_equation_error.m +++ b/matlab/ep/euler_equation_error.m @@ -18,7 +18,7 @@ i_fwrd = find(M.lead_lag_incidence(3,:)); x1 = [x(2:end,:); zeros(1,M.exo_nbr)]; for i=1:length(nodes) x2 = x1; - x2(2,:) = x2(2,:) + nodes(i,:); + x2(2,:) = x2(2,:) + nodes(i,:); [y2, info_convergence, endogenousvariablespaths] = ... extended_path_core(ep.periods, M.endo_nbr, M.exo_nbr, ... innovations.positive_var_indx, x2, ep.init, ... @@ -26,7 +26,7 @@ for i=1:length(nodes) ep.stochastic.order, M, pfm, ep.stochastic.algo, ... ep.solve_algo, ep.stack_solve_algo, options.lmmcp, ... options, oo, []); - + z = [y0(i_pred); y1; y2(i_fwrd)]; res(:,i) = dynamic_model(z,x,M.params,oo.steady_state,2); end diff --git a/matlab/ep/extended_path.m b/matlab/ep/extended_path.m index 03a7e4ed70..92f6be0819 100644 --- a/matlab/ep/extended_path.m +++ b/matlab/ep/extended_path.m @@ -3,7 +3,7 @@ function [ts, DynareResults] = extended_path(initialconditions, samplesize, exog % 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 +% INPUTS % o initialconditions [double] m*1 array, where m is the number of endogenous variables in the model. % o samplesize [integer] scalar, size of the sample to be simulated. % o exogenousvariables [double] T*n array, values for the structural innovations. @@ -11,7 +11,7 @@ function [ts, DynareResults] = extended_path(initialconditions, samplesize, exog % o DynareModel [struct] M_ % o DynareResults [struct] oo_ % -% OUTPUTS +% OUTPUTS % o ts [dseries] m*samplesize array, the simulations. % o results [cell] % @@ -96,7 +96,7 @@ end if any(isnan(endogenous_variables_paths(:))) sl = find(~isnan(endogenous_variables_paths)); nn = size(endogenous_variables_paths, 1); - endogenous_variables_paths = reshape(endogenous_variables_paths(sl), nn, length(sl)/nn); + endogenous_variables_paths = reshape(endogenous_variables_paths(sl), nn, length(sl)/nn); end ts = dseries(transpose(endogenous_variables_paths), initial_period, cellstr(DynareModel.endo_names)); diff --git a/matlab/ep/extended_path_core.m b/matlab/ep/extended_path_core.m index 33c42b619c..851a822022 100644 --- a/matlab/ep/extended_path_core.m +++ b/matlab/ep/extended_path_core.m @@ -1,8 +1,8 @@ function [y, info_convergence, endogenousvariablespaths] = extended_path_core(periods,endo_nbr,exo_nbr,positive_var_indx, ... - exo_simul,init,initial_conditions,... - steady_state, ... - debug,bytecode_flag,order,M,pfm,algo,solve_algo,stack_solve_algo,... - olmmcp,options,oo,initialguess) + exo_simul,init,initial_conditions,... + steady_state, ... + debug,bytecode_flag,order,M,pfm,algo,solve_algo,stack_solve_algo,... + olmmcp,options,oo,initialguess) % Copyright (C) 2016 Dynare Team % @@ -58,7 +58,7 @@ if flag options.solve_algo = solve_algo; options.stack_solve_algo = stack_solve_algo; tmp = perfect_foresight_solver_core(M, options, oo); - if ~tmp.deterministic_simulation.status + if ~tmp.deterministic_simulation.status info_convergence = false; else info_convergence = true; diff --git a/matlab/ep/extended_path_homotopy.m b/matlab/ep/extended_path_homotopy.m index 463003d2bf..47259765c0 100644 --- a/matlab/ep/extended_path_homotopy.m +++ b/matlab/ep/extended_path_homotopy.m @@ -17,7 +17,7 @@ function [info_convergence, endo_simul] = extended_path_homotopy(endo_simul, exo % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - + endo_simul0 = endo_simul; if ismember(method, [1, 2]) noconvergence = true; diff --git a/matlab/ep/extended_path_initialization.m b/matlab/ep/extended_path_initialization.m index 1a9e6d22ec..fb8581bc68 100644 --- a/matlab/ep/extended_path_initialization.m +++ b/matlab/ep/extended_path_initialization.m @@ -2,15 +2,15 @@ function [initial_conditions, innovations, pfm, ep, verbosity, DynareOptions, Dy % Initialization of the extended path routines. % -% INPUTS +% INPUTS % o initial_conditions [double] m*1 array, where m is the number of endogenous variables in the model. % o sample_size [integer] scalar, size of the sample to be simulated. % o exogenousvariables [double] T*n array, values for the structural innovations. -% o DynareOptions [struct] options_ +% o DynareOptions [struct] options_ % o DynareModel [struct] M_ % o DynareResults [struct] oo_ % -% OUTPUTS +% OUTPUTS % % ALGORITHM % @@ -118,7 +118,7 @@ pfm.nnzA = DynareModel.NNZDerivatives(1); if ep.stochastic.order > 0 [nodes,weights,nnodes] = setup_integration_nodes(DynareOptions.ep,pfm); pfm.nodes = nodes; - pfm.weights = weights; + pfm.weights = weights; pfm.nnodes = nnodes; % compute number of blocks [block_nbr,pfm.world_nbr] = get_block_world_nbr(ep.stochastic.algo,nnodes,ep.stochastic.order,ep.periods); @@ -136,4 +136,3 @@ elseif DynareOptions.ep.solve_algo == 11 DynareOptions.mcppath.ub = repmat(ub,block_nbr,1); end pfm.block_nbr = block_nbr; - diff --git a/matlab/ep/extended_path_mc.m b/matlab/ep/extended_path_mc.m index f03bca8aed..72d3a55f47 100644 --- a/matlab/ep/extended_path_mc.m +++ b/matlab/ep/extended_path_mc.m @@ -3,7 +3,7 @@ function Simulations = extended_path_mc(initialconditions, samplesize, replic, e % 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 +% INPUTS % o initialconditions [double] m*1 array, where m is the number of endogenous variables in the model. % o samplesize [integer] scalar, size of the sample to be simulated. % o exogenousvariables [double] T*n array, values for the structural innovations. @@ -11,7 +11,7 @@ function Simulations = extended_path_mc(initialconditions, samplesize, replic, e % o DynareModel [struct] M_ % o DynareResults [struct] oo_ % -% OUTPUTS +% OUTPUTS % o ts [dseries] m*samplesize array, the simulations. % o results [cell] % @@ -65,7 +65,7 @@ vexo = NaN(innovations.effective_number_of_shocks, samplesize+1, replic); info = NaN(replic, 1); if ep.parallel - % Use the Parallel toolbox. + % Use the Parallel toolbox. parfor i=1:replic innovations_ = innovations; DynareResults_ = DynareResults; diff --git a/matlab/ep/setup_integration_nodes.m b/matlab/ep/setup_integration_nodes.m index 85d1be960c..5a6d206c1b 100644 --- a/matlab/ep/setup_integration_nodes.m +++ b/matlab/ep/setup_integration_nodes.m @@ -1,39 +1,39 @@ function [nodes,weights,nnodes] = setup_integration_nodes(EpOptions,pfm) - if EpOptions.stochastic.order - % Compute weights and nodes for the stochastic version of the extended path. - switch EpOptions.IntegrationAlgorithm - case 'Tensor-Gaussian-Quadrature' - % Get the nodes and weights from a univariate Gauss-Hermite quadrature. - [nodes0,weights0] = gauss_hermite_weights_and_nodes(EpOptions.stochastic.quadrature.nodes); - % Replicate the univariate nodes for each innovation and dates, and, if needed, correlate them. - nodes0 = repmat(nodes0,1,pfm.number_of_shocks*pfm.stochastic_order)*kron(eye(pfm.stochastic_order),pfm.Omega); - % Put the nodes and weights in cells - for i=1:pfm.number_of_shocks - rr(i) = {nodes0(:,i)}; - ww(i) = {weights0}; - end - % Build the tensorial grid - nodes = cartesian_product_of_sets(rr{:}); - weights = prod(cartesian_product_of_sets(ww{:}),2); - nnodes = length(weights); - case 'Stroud-Cubature-3' - [nodes,weights] = cubature_with_gaussian_weight(pfm.number_of_shocks*pfm.stochastic_order,3,'Stroud') - nodes = kron(eye(pfm.stochastic_order),transpose(pfm.Omega))*nodes; - weights = weights; - nnodes = length(weights); - case 'Stroud-Cubature-5' - [nodes,weights] = cubature_with_gaussian_weight(pfm.number_of_shocks*pfm.stochastic_order,5,'Stroud') - nodes = kron(eye(pfm.stochastic_order),transpose(pfm.Omega))*nodes; - weights = weights; - nnodes = length(weights); - case 'Unscented' - p = pfm.number_of_shocks; - k = EpOptions.ut.k; - C = sqrt(pfm.number_of_shocks + k)*pfm.Omega'; - nodes = [zeros(1,p); -C; C]; - weights = [k/(p+k); (1/(2*(p+k)))*ones(2*p,1)]; - nnodes = 2*p+1; - otherwise - error('Stochastic extended path:: Unknown integration algorithm!') +if EpOptions.stochastic.order + % Compute weights and nodes for the stochastic version of the extended path. + switch EpOptions.IntegrationAlgorithm + case 'Tensor-Gaussian-Quadrature' + % Get the nodes and weights from a univariate Gauss-Hermite quadrature. + [nodes0,weights0] = gauss_hermite_weights_and_nodes(EpOptions.stochastic.quadrature.nodes); + % Replicate the univariate nodes for each innovation and dates, and, if needed, correlate them. + nodes0 = repmat(nodes0,1,pfm.number_of_shocks*pfm.stochastic_order)*kron(eye(pfm.stochastic_order),pfm.Omega); + % Put the nodes and weights in cells + for i=1:pfm.number_of_shocks + rr(i) = {nodes0(:,i)}; + ww(i) = {weights0}; end + % Build the tensorial grid + nodes = cartesian_product_of_sets(rr{:}); + weights = prod(cartesian_product_of_sets(ww{:}),2); + nnodes = length(weights); + case 'Stroud-Cubature-3' + [nodes,weights] = cubature_with_gaussian_weight(pfm.number_of_shocks*pfm.stochastic_order,3,'Stroud') + nodes = kron(eye(pfm.stochastic_order),transpose(pfm.Omega))*nodes; + weights = weights; + nnodes = length(weights); + case 'Stroud-Cubature-5' + [nodes,weights] = cubature_with_gaussian_weight(pfm.number_of_shocks*pfm.stochastic_order,5,'Stroud') + nodes = kron(eye(pfm.stochastic_order),transpose(pfm.Omega))*nodes; + weights = weights; + nnodes = length(weights); + case 'Unscented' + p = pfm.number_of_shocks; + k = EpOptions.ut.k; + C = sqrt(pfm.number_of_shocks + k)*pfm.Omega'; + nodes = [zeros(1,p); -C; C]; + weights = [k/(p+k); (1/(2*(p+k)))*ones(2*p,1)]; + nnodes = 2*p+1; + otherwise + error('Stochastic extended path:: Unknown integration algorithm!') end +end diff --git a/matlab/ep/setup_stochastic_perfect_foresight_model_solver.m b/matlab/ep/setup_stochastic_perfect_foresight_model_solver.m index 2bf6829eeb..0ddf453609 100644 --- a/matlab/ep/setup_stochastic_perfect_foresight_model_solver.m +++ b/matlab/ep/setup_stochastic_perfect_foresight_model_solver.m @@ -16,7 +16,7 @@ function pfm = setup_stochastic_perfect_foresight_model_solver(DynareModel,Dynar % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - + pfm.lead_lag_incidence = DynareModel.lead_lag_incidence; pfm.ny = DynareModel.endo_nbr; pfm.Sigma = DynareModel.Sigma_e; @@ -71,4 +71,3 @@ pfm.verbose = DynareOptions.ep.verbosity; pfm.maxit_ = DynareOptions.simul.maxit; pfm.tolerance = DynareOptions.dynatol.f; pfm.use_bytecode = DynareOptions.ep.use_bytecode ; - diff --git a/matlab/ep/solve_stochastic_perfect_foresight_model.m b/matlab/ep/solve_stochastic_perfect_foresight_model.m index ab13e3043a..12373d15d9 100644 --- a/matlab/ep/solve_stochastic_perfect_foresight_model.m +++ b/matlab/ep/solve_stochastic_perfect_foresight_model.m @@ -17,219 +17,219 @@ function [flag,endo_simul,err] = solve_stochastic_perfect_foresight_model(endo_s % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - flag = 0; - err = 0; - stop = 0; +flag = 0; +err = 0; +stop = 0; - params = pfm.params; - steady_state = pfm.steady_state; - ny = pfm.ny; - periods = pfm.periods; - dynamic_model = pfm.dynamic_model; - lead_lag_incidence = pfm.lead_lag_incidence; - nyp = pfm.nyp; - nyf = pfm.nyf; - i_cols_1 = pfm.i_cols_1; - i_cols_A1 = pfm.i_cols_A1; - i_cols_j = pfm.i_cols_j; - i_cols_T = nonzeros(lead_lag_incidence(1:2,:)'); +params = pfm.params; +steady_state = pfm.steady_state; +ny = pfm.ny; +periods = pfm.periods; +dynamic_model = pfm.dynamic_model; +lead_lag_incidence = pfm.lead_lag_incidence; +nyp = pfm.nyp; +nyf = pfm.nyf; +i_cols_1 = pfm.i_cols_1; +i_cols_A1 = pfm.i_cols_A1; +i_cols_j = pfm.i_cols_j; +i_cols_T = nonzeros(lead_lag_incidence(1:2,:)'); - maxit = pfm.maxit_; - tolerance = pfm.tolerance; - verbose = pfm.verbose; +maxit = pfm.maxit_; +tolerance = pfm.tolerance; +verbose = pfm.verbose; - number_of_shocks = size(exo_simul,2); +number_of_shocks = size(exo_simul,2); - [nodes,weights] = gauss_hermite_weights_and_nodes(nnodes); +[nodes,weights] = gauss_hermite_weights_and_nodes(nnodes); - if number_of_shocks>1 - nodes = repmat(nodes,1,number_of_shocks)*chol(pfm.Sigma); - % to be fixed for Sigma ~= I - for i=1:number_of_shocks - rr(i) = {nodes(:,i)}; - ww(i) = {weights}; - end - nodes = cartesian_product_of_sets(rr{:}); - weights = prod(cartesian_product_of_sets(ww{:}),2); - nnodes = nnodes^number_of_shocks; - else - nodes = nodes*sqrt(pfm.Sigma); +if number_of_shocks>1 + nodes = repmat(nodes,1,number_of_shocks)*chol(pfm.Sigma); + % to be fixed for Sigma ~= I + for i=1:number_of_shocks + rr(i) = {nodes(:,i)}; + ww(i) = {weights}; end + nodes = cartesian_product_of_sets(rr{:}); + weights = prod(cartesian_product_of_sets(ww{:}),2); + nnodes = nnodes^number_of_shocks; +else + nodes = nodes*sqrt(pfm.Sigma); +end - innovations = zeros(periods+2,number_of_shocks); +innovations = zeros(periods+2,number_of_shocks); - if verbose - disp ([' -----------------------------------------------------']); - disp (['MODEL SIMULATION :']); - fprintf('\n'); - end +if verbose + disp ([' -----------------------------------------------------']); + disp (['MODEL SIMULATION :']); + fprintf('\n'); +end - z = endo_simul(find(lead_lag_incidence')); - [d1,jacobian] = dynamic_model(z,exo_simul,params,steady_state,2); +z = endo_simul(find(lead_lag_incidence')); +[d1,jacobian] = dynamic_model(z,exo_simul,params,steady_state,2); - % Each column of Y represents a different world - % The upper right cells are unused - % The first row block is ny x 1 - % The second row block is ny x nnodes - % The third row block is ny x nnodes^2 - % and so on until size ny x nnodes^order - world_nbr = nnodes^order; - Y = repmat(endo_simul(:),1,world_nbr); +% Each column of Y represents a different world +% The upper right cells are unused +% The first row block is ny x 1 +% The second row block is ny x nnodes +% The third row block is ny x nnodes^2 +% and so on until size ny x nnodes^order +world_nbr = nnodes^order; +Y = repmat(endo_simul(:),1,world_nbr); - % The columns of A map the elements of Y such that - % each block of Y with ny rows are unfolded column wise - dimension = ny*(sum(nnodes.^(0:order-1),2)+(periods-order)*world_nbr); - if order == 0 - i_upd_r = (1:ny*periods); - i_upd_y = i_upd_r + ny; - else - i_upd_r = zeros(dimension,1); - i_upd_y = i_upd_r; - i_upd_r(1:ny) = (1:ny); - i_upd_y(1:ny) = ny+(1:ny); - i1 = ny+1; - i2 = 2*ny; - n1 = ny+1; - n2 = 2*ny; - for i=2:periods - k = n1:n2; - for j=1:nnodes^min(i-1,order) - i_upd_r(i1:i2) = (n1:n2)+(j-1)*ny*periods; - i_upd_y(i1:i2) = (n1:n2)+ny+(j-1)*ny*(periods+2); - i1 = i2+1; - i2 = i2+ny; - end - n1 = n2+1; - n2 = n2+ny; +% The columns of A map the elements of Y such that +% each block of Y with ny rows are unfolded column wise +dimension = ny*(sum(nnodes.^(0:order-1),2)+(periods-order)*world_nbr); +if order == 0 + i_upd_r = (1:ny*periods); + i_upd_y = i_upd_r + ny; +else + i_upd_r = zeros(dimension,1); + i_upd_y = i_upd_r; + i_upd_r(1:ny) = (1:ny); + i_upd_y(1:ny) = ny+(1:ny); + i1 = ny+1; + i2 = 2*ny; + n1 = ny+1; + n2 = 2*ny; + for i=2:periods + k = n1:n2; + for j=1:nnodes^min(i-1,order) + i_upd_r(i1:i2) = (n1:n2)+(j-1)*ny*periods; + i_upd_y(i1:i2) = (n1:n2)+ny+(j-1)*ny*(periods+2); + i1 = i2+1; + i2 = i2+ny; end + n1 = n2+1; + n2 = n2+ny; end - icA = [find(lead_lag_incidence(1,:)) find(lead_lag_incidence(2,:))+world_nbr*ny ... - find(lead_lag_incidence(3,:))+2*world_nbr*ny]'; - h1 = clock; - for iter = 1:maxit - h2 = clock; - A1 = sparse([],[],[],ny*(sum(nnodes.^(0:order-1),2)+1),dimension,(order+1)*world_nbr*nnz(jacobian)); - res = zeros(ny,periods,world_nbr); - i_rows = 1:ny; - i_cols = find(lead_lag_incidence'); - i_cols_p = i_cols(1:nyp); - i_cols_s = i_cols(nyp+(1:ny)); - i_cols_f = i_cols(nyp+ny+(1:nyf)); - i_cols_A = i_cols; - i_cols_Ap = i_cols_p; - i_cols_As = i_cols_s; - i_cols_Af = i_cols_f - ny; - for i = 1:order+1 - i_w_p = 1; - for j = 1:nnodes^(i-1) - innovation = exo_simul; - if i > 1 - innovation(i+1,:) = nodes(mod(j-1,nnodes)+1,:); - end - if i <= order - for k=1:nnodes - y = [Y(i_cols_p,i_w_p); - Y(i_cols_s,j); - Y(i_cols_f,(j-1)*nnodes+k)]; - [d1,jacobian] = dynamic_model(y,innovation,params,steady_state,i+1); - if i == 1 - % in first period we don't keep track of - % predetermined variables - i_cols_A = [i_cols_As - ny; i_cols_Af]; - A1(i_rows,i_cols_A) = A1(i_rows,i_cols_A) + weights(k)*jacobian(:,i_cols_1); - else - i_cols_A = [i_cols_Ap; i_cols_As; i_cols_Af]; - A1(i_rows,i_cols_A) = A1(i_rows,i_cols_A) + weights(k)*jacobian(:,i_cols_j); - end - res(:,i,j) = res(:,i,j)+weights(k)*d1; - i_cols_Af = i_cols_Af + ny; - end - else +end +icA = [find(lead_lag_incidence(1,:)) find(lead_lag_incidence(2,:))+world_nbr*ny ... + find(lead_lag_incidence(3,:))+2*world_nbr*ny]'; +h1 = clock; +for iter = 1:maxit + h2 = clock; + A1 = sparse([],[],[],ny*(sum(nnodes.^(0:order-1),2)+1),dimension,(order+1)*world_nbr*nnz(jacobian)); + res = zeros(ny,periods,world_nbr); + i_rows = 1:ny; + i_cols = find(lead_lag_incidence'); + i_cols_p = i_cols(1:nyp); + i_cols_s = i_cols(nyp+(1:ny)); + i_cols_f = i_cols(nyp+ny+(1:nyf)); + i_cols_A = i_cols; + i_cols_Ap = i_cols_p; + i_cols_As = i_cols_s; + i_cols_Af = i_cols_f - ny; + for i = 1:order+1 + i_w_p = 1; + for j = 1:nnodes^(i-1) + innovation = exo_simul; + if i > 1 + innovation(i+1,:) = nodes(mod(j-1,nnodes)+1,:); + end + if i <= order + for k=1:nnodes y = [Y(i_cols_p,i_w_p); Y(i_cols_s,j); - Y(i_cols_f,j)]; + Y(i_cols_f,(j-1)*nnodes+k)]; [d1,jacobian] = dynamic_model(y,innovation,params,steady_state,i+1); if i == 1 % in first period we don't keep track of % predetermined variables i_cols_A = [i_cols_As - ny; i_cols_Af]; - A1(i_rows,i_cols_A) = jacobian(:,i_cols_1); + A1(i_rows,i_cols_A) = A1(i_rows,i_cols_A) + weights(k)*jacobian(:,i_cols_1); else i_cols_A = [i_cols_Ap; i_cols_As; i_cols_Af]; - A1(i_rows,i_cols_A) = jacobian(:,i_cols_j); + A1(i_rows,i_cols_A) = A1(i_rows,i_cols_A) + weights(k)*jacobian(:,i_cols_j); end - res(:,i,j) = d1; + res(:,i,j) = res(:,i,j)+weights(k)*d1; i_cols_Af = i_cols_Af + ny; end - i_rows = i_rows + ny; - if mod(j,nnodes) == 0 - i_w_p = i_w_p + 1; - end - if i > 1 - if mod(j,nnodes) == 0 - i_cols_Ap = i_cols_Ap + ny; - end - i_cols_As = i_cols_As + ny; - end - end - i_cols_p = i_cols_p + ny; - i_cols_s = i_cols_s + ny; - i_cols_f = i_cols_f + ny; - end - nzA = cell(periods,world_nbr); - for j=1:world_nbr - i_rows_y = find(lead_lag_incidence')+(order+1)*ny; - offset_c = ny*(sum(nnodes.^(0:order-1),2)+j-1); - offset_r = (j-1)*ny; - for i=order+2:periods - [d1,jacobian] = dynamic_model(Y(i_rows_y,j), ... - exo_simul,params, ... - steady_state,i+1); - if i == periods - [ir,ic,v] = find(jacobian(:,i_cols_T)); + else + y = [Y(i_cols_p,i_w_p); + Y(i_cols_s,j); + Y(i_cols_f,j)]; + [d1,jacobian] = dynamic_model(y,innovation,params,steady_state,i+1); + if i == 1 + % in first period we don't keep track of + % predetermined variables + i_cols_A = [i_cols_As - ny; i_cols_Af]; + A1(i_rows,i_cols_A) = jacobian(:,i_cols_1); else - [ir,ic,v] = find(jacobian(:,i_cols_j)); + i_cols_A = [i_cols_Ap; i_cols_As; i_cols_Af]; + A1(i_rows,i_cols_A) = jacobian(:,i_cols_j); end - nzA{i,j} = [offset_r+ir,offset_c+icA(ic), v]'; res(:,i,j) = d1; - i_rows_y = i_rows_y + ny; - offset_c = offset_c + world_nbr*ny; - offset_r = offset_r + world_nbr*ny; + i_cols_Af = i_cols_Af + ny; + end + i_rows = i_rows + ny; + if mod(j,nnodes) == 0 + i_w_p = i_w_p + 1; + end + if i > 1 + if mod(j,nnodes) == 0 + i_cols_Ap = i_cols_Ap + ny; + end + i_cols_As = i_cols_As + ny; end end - err = max(abs(res(i_upd_r))); - if err < tolerance - stop = 1; - if verbose - fprintf('\n') ; - disp([' Total time of simulation :' num2str(etime(clock,h1))]) ; - fprintf('\n') ; - disp([' Convergency obtained.']) ; - fprintf('\n') ; + i_cols_p = i_cols_p + ny; + i_cols_s = i_cols_s + ny; + i_cols_f = i_cols_f + ny; + end + nzA = cell(periods,world_nbr); + for j=1:world_nbr + i_rows_y = find(lead_lag_incidence')+(order+1)*ny; + offset_c = ny*(sum(nnodes.^(0:order-1),2)+j-1); + offset_r = (j-1)*ny; + for i=order+2:periods + [d1,jacobian] = dynamic_model(Y(i_rows_y,j), ... + exo_simul,params, ... + steady_state,i+1); + if i == periods + [ir,ic,v] = find(jacobian(:,i_cols_T)); + else + [ir,ic,v] = find(jacobian(:,i_cols_j)); end - flag = 0;% Convergency obtained. - endo_simul = reshape(Y(:,1),ny,periods+2);%Y(ny+(1:ny),1); - % figure;plot(Y(16:ny:(periods+2)*ny,:)) - % pause - break + nzA{i,j} = [offset_r+ir,offset_c+icA(ic), v]'; + res(:,i,j) = d1; + i_rows_y = i_rows_y + ny; + offset_c = offset_c + world_nbr*ny; + offset_r = offset_r + world_nbr*ny; end - A2 = [nzA{:}]'; - A = [A1; sparse(A2(:,1),A2(:,2),A2(:,3),ny*(periods-order-1)*world_nbr,dimension)]; - dy = -A\res(i_upd_r); - Y(i_upd_y) = Y(i_upd_y) + dy; end - - if ~stop + err = max(abs(res(i_upd_r))); + if err < tolerance + stop = 1; if verbose fprintf('\n') ; - disp([' Total time of simulation :' num2str(etime(clock,h1))]) ; + disp([' Total time of simulation :' num2str(etime(clock,h1))]) ; fprintf('\n') ; - disp(['WARNING : maximum number of iterations is reached (modify options_.simul.maxit).']) ; + disp([' Convergency obtained.']) ; fprintf('\n') ; end - flag = 1;% more iterations are needed. - endo_simul = 1; + flag = 0;% Convergency obtained. + endo_simul = reshape(Y(:,1),ny,periods+2);%Y(ny+(1:ny),1); + % figure;plot(Y(16:ny:(periods+2)*ny,:)) + % pause + break end + A2 = [nzA{:}]'; + A = [A1; sparse(A2(:,1),A2(:,2),A2(:,3),ny*(periods-order-1)*world_nbr,dimension)]; + dy = -A\res(i_upd_r); + Y(i_upd_y) = Y(i_upd_y) + dy; +end + +if ~stop if verbose - disp (['-----------------------------------------------------']) ; + fprintf('\n') ; + disp([' Total time of simulation :' num2str(etime(clock,h1))]) ; + fprintf('\n') ; + disp(['WARNING : maximum number of iterations is reached (modify options_.simul.maxit).']) ; + fprintf('\n') ; end + flag = 1;% more iterations are needed. + endo_simul = 1; +end +if verbose + disp (['-----------------------------------------------------']) ; +end diff --git a/matlab/ep/solve_stochastic_perfect_foresight_model_1.m b/matlab/ep/solve_stochastic_perfect_foresight_model_1.m index e884f155e0..25a0e16736 100644 --- a/matlab/ep/solve_stochastic_perfect_foresight_model_1.m +++ b/matlab/ep/solve_stochastic_perfect_foresight_model_1.m @@ -83,7 +83,7 @@ end % and so on until size ny x nnodes^order world_nbr = pfm.world_nbr; Y = endo_simul(:,2:end-1); -Y = repmat(Y,1,world_nbr); +Y = repmat(Y,1,world_nbr); pfm.y0 = endo_simul(:,1); % The columns of A map the elements of Y such that diff --git a/matlab/ep/stroud_judd_7.5.8.m b/matlab/ep/stroud_judd_7.5.8.m index 40c9bc08db..57d3f8d62f 100644 --- a/matlab/ep/stroud_judd_7.5.8.m +++ b/matlab/ep/stroud_judd_7.5.8.m @@ -1,9 +1,9 @@ -function [X,w]=stroud_judd_7.5.8(d) - - E = eye(d); - X = cell(2*d,1); - m = 1; - for i=1:d - X{m} = E(:,i); - m = m+1; - X{m} = -E(:,i); +function [X,w]=stroud_judd_7.5.8.5.8(d) + +E = eye(d); +X = cell(2*d,1); +m = 1; +for i=1:d + X{m} = E(:,i); + m = m+1; + X{m} = -E(:,i); diff --git a/matlab/ep_residuals.m b/matlab/ep_residuals.m index b2acd72942..2d3780cd32 100644 --- a/matlab/ep_residuals.m +++ b/matlab/ep_residuals.m @@ -1,20 +1,20 @@ function r = ep_residuals(x, y, ix, iy, steadystate, dr, maximum_lag, endo_nbr) % Inversion of the extended path simulation approach. This routine computes the innovations needed to -% reproduce the time path of a subset of endogenous variables. -% +% reproduce the time path of a subset of endogenous variables. +% % INPUTS -% o x [double] n*1 vector, time t innovations. +% o x [double] n*1 vector, time t innovations. % o y [double] n*1 vector, time t restricted endogenous variables. % o ix [integer] index of control innovations in the full vector of innovations. -% o iy [integer] index of controlled variables in the full vector of endogenous variables. -% o s [double] m*1 vector, endogenous variables at time t-1. -% -% +% o iy [integer] index of controlled variables in the full vector of endogenous variables. +% o s [double] m*1 vector, endogenous variables at time t-1. +% +% % OUTPUTS % o r [double] n*1 vector of residuals. -% +% % ALGORITHM -% +% % SPECIAL REQUIREMENTS % Copyright (C) 2010-2014 Dynare Team. diff --git a/matlab/evaluate_max_dynamic_residual.m b/matlab/evaluate_max_dynamic_residual.m index 41aa4ec249..ac4dbb32a0 100644 --- a/matlab/evaluate_max_dynamic_residual.m +++ b/matlab/evaluate_max_dynamic_residual.m @@ -16,7 +16,7 @@ function err = evaluate_max_dynamic_residual(model_dynamic, Y, exogenous_variabl % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - + i_rows = 1:ny; i_cols = find(lead_lag_incidence'); diff --git a/matlab/evaluate_planner_objective.m b/matlab/evaluate_planner_objective.m index 40f1865903..d547be57ed 100644 --- a/matlab/evaluate_planner_objective.m +++ b/matlab/evaluate_planner_objective.m @@ -1,13 +1,13 @@ function planner_objective_value = evaluate_planner_objective(M,options,oo) %function oo1 = evaluate_planner_objective(dr,M,oo,options) -% computes value of planner objective function -% +% computes value of planner objective function +% % INPUTS % M: (structure) model description % options: (structure) options % oo: (structure) output results -% +% % SPECIAL REQUIREMENTS % none @@ -40,7 +40,7 @@ if nspred > 180 return end beta = get_optimal_policy_discount_factor(M.params,M.param_names); - + Gy = dr.ghx(nstatic+(1:nspred),:); Gu = dr.ghu(nstatic+(1:nspred),:); gy(dr.order_var,:) = dr.ghx; @@ -113,7 +113,7 @@ if ~options.noprint disp('Approximated value of planner objective function') if options.ramsey_policy disp([' - with initial Lagrange multipliers set to 0: ' ... - num2str(planner_objective_value(2)) ]) + num2str(planner_objective_value(2)) ]) disp([' - with initial Lagrange multipliers set to steady state: ' ... num2str(planner_objective_value(1)) ]) elseif options.discretionary_policy diff --git a/matlab/evaluate_posterior_kernel.m b/matlab/evaluate_posterior_kernel.m index 96ccac8d5d..ce4fd1a43f 100644 --- a/matlab/evaluate_posterior_kernel.m +++ b/matlab/evaluate_posterior_kernel.m @@ -2,20 +2,20 @@ function lpkern = evaluate_posterior_kernel(parameters,llik) % Evaluate the prior density at parameters. % % INPUTS -% o parameters a string ('posterior mode','posterior mean','posterior median','prior mode','prior mean') or a vector of values for +% o parameters a string ('posterior mode','posterior mean','posterior median','prior mode','prior mean') or a vector of values for % the (estimated) parameters of the model. -% -% +% +% % OUTPUTS % o lpkern [double] value of the logged posterior kernel. -% +% % SPECIAL REQUIREMENTS % None % % REMARKS % [1] This function cannot evaluate the prior density 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. +% [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 % diff --git a/matlab/evaluate_prior.m b/matlab/evaluate_prior.m index b8b2f7b0ba..32288062fc 100644 --- a/matlab/evaluate_prior.m +++ b/matlab/evaluate_prior.m @@ -2,14 +2,14 @@ function [ldens,parameters] = evaluate_prior(parameters) % Evaluate the prior density at parameters. % % INPUTS -% o parameters a string ('posterior mode','posterior mean','posterior median','prior mode','prior mean') or a vector of values for +% o parameters a string ('posterior mode','posterior mean','posterior median','prior mode','prior mean') or a vector of values for % the (estimated) parameters of the model. -% -% +% +% % OUTPUTS % o ldens [double] value of the logged prior density. % o parameters [double] vector of values for the estimated parameters. -% +% % SPECIAL REQUIREMENTS % None % diff --git a/matlab/evaluate_smoother.m b/matlab/evaluate_smoother.m index fb3eaad7ad..9ab94654b1 100644 --- a/matlab/evaluate_smoother.m +++ b/matlab/evaluate_smoother.m @@ -23,7 +23,7 @@ function [oo_,M_,options_,bayestopt_,Smoothed_variables_declaration_order_deviat % - FilteredVariablesKStepAheadVariances % o M_ [structure] Definition of the model % o options_ [structure] Options; returns options_.first_obs -% o bayestopt_ [structure] describing the priors; returns fields like bayestopt_.smoother_var_list from the smoother +% o bayestopt_ [structure] describing the priors; returns fields like bayestopt_.smoother_var_list from the smoother % o Smoothed_variables_declaration_order_deviation_form % Smoothed variables from the Kalman smoother in % order of declaration of variables (M_.endo_names) @@ -106,7 +106,7 @@ end [oo_]=store_smoother_results(M_,oo_,options_,bayestopt_,dataset_,dataset_info,atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,P,PK,decomp,Trend,state_uncertainty); if nargout>4 - Smoothed_variables_declaration_order_deviation_form=atT(oo_.dr.inv_order_var(bayestopt_.smoother_var_list),:); + Smoothed_variables_declaration_order_deviation_form=atT(oo_.dr.inv_order_var(bayestopt_.smoother_var_list),:); end %reset qz_criterium diff --git a/matlab/evaluate_static_model.m b/matlab/evaluate_static_model.m index 9225179642..2328f2b4ce 100644 --- a/matlab/evaluate_static_model.m +++ b/matlab/evaluate_static_model.m @@ -2,7 +2,7 @@ function [residuals,check1,jacob] = evaluate_static_model(ys,exo_ss,params,M,opt % function [residuals,check1,jacob] = evaluate_static_model(ys,exo_ss,params,M,options) % Evaluates the static model -% +% % INPUTS % ys vector initial values used to compute the steady % state @@ -10,7 +10,7 @@ function [residuals,check1,jacob] = evaluate_static_model(ys,exo_ss,params,M,opt % params vector parameters % M struct model structure % options struct options -% +% % OUTPUTS % residuals vector residuals when ys is not % the steady state @@ -37,29 +37,29 @@ function [residuals,check1,jacob] = evaluate_static_model(ys,exo_ss,params,M,opt % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - check1 = 0; - if options.bytecode - [check1, residuals] = bytecode('evaluate','static',ys,... - exo_ss, params, ys, 1); - mexErrCheck('bytecode', check1); - else - fh_static = str2func([M.fname '_static']); - if options.block - residuals = zeros(M.endo_nbr,1); - for b = 1:length(M.block_structure_stat.block) - mfsb = M.block_structure_stat.block(b).variable; - % blocks that can be directly evaluated (mfsb is empty) - % have zero residuals by construction - if M.block_structure_stat.block(b).Simulation_Type ~= 1 && ... - M.block_structure_stat.block(b).Simulation_Type ~= 2 - residuals(mfsb) = feval(fh_static,b,ys,exo_ss,params); - else - %need to evaluate the recursive blocks to compute the - %temporary terms - feval(fh_static,b,ys,exo_ss,params); - end +check1 = 0; +if options.bytecode + [check1, residuals] = bytecode('evaluate','static',ys,... + exo_ss, params, ys, 1); + mexErrCheck('bytecode', check1); +else + fh_static = str2func([M.fname '_static']); + if options.block + residuals = zeros(M.endo_nbr,1); + for b = 1:length(M.block_structure_stat.block) + mfsb = M.block_structure_stat.block(b).variable; + % blocks that can be directly evaluated (mfsb is empty) + % have zero residuals by construction + if M.block_structure_stat.block(b).Simulation_Type ~= 1 && ... + M.block_structure_stat.block(b).Simulation_Type ~= 2 + residuals(mfsb) = feval(fh_static,b,ys,exo_ss,params); + else + %need to evaluate the recursive blocks to compute the + %temporary terms + feval(fh_static,b,ys,exo_ss,params); end - else - residuals = feval(fh_static,ys,exo_ss,params); end + else + residuals = feval(fh_static,ys,exo_ss,params); end +end diff --git a/matlab/evaluate_steady_state.m b/matlab/evaluate_steady_state.m index e2bd1b86de..afd8bb4c59 100644 --- a/matlab/evaluate_steady_state.m +++ b/matlab/evaluate_steady_state.m @@ -39,120 +39,36 @@ function [ys,params,info] = evaluate_steady_state(ys_init,M,options,oo,steadysta % 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; - check = 0; +info = 0; +check = 0; - steadystate_flag = options.steadystate_flag; - params = M.params; - exo_ss = [oo.exo_steady_state; oo.exo_det_steady_state]; +steadystate_flag = options.steadystate_flag; +params = M.params; +exo_ss = [oo.exo_steady_state; oo.exo_det_steady_state]; - if length(M.aux_vars) > 0 - h_set_auxiliary_variables = str2func([M.fname '_set_auxiliary_variables']); - if ~steadystate_flag - ys_init = h_set_auxiliary_variables(ys_init,exo_ss,M.params); - end +if length(M.aux_vars) > 0 + h_set_auxiliary_variables = str2func([M.fname '_set_auxiliary_variables']); + if ~steadystate_flag + ys_init = h_set_auxiliary_variables(ys_init,exo_ss,M.params); end +end - if options.ramsey_policy - if steadystate_flag - % explicit steady state file - [ys,params,info] = evaluate_steady_state_file(ys_init,exo_ss,M, ... - options,steadystate_check_flag); - %test whether it solves model conditional on the instruments - resids = evaluate_static_model(ys,exo_ss,params,M,options); - n_multipliers=M.ramsey_eq_nbr; - nan_indices=find(isnan(resids(n_multipliers+1:end))); - - if ~isempty(nan_indices) - if options.debug - fprintf('\nevaluate_steady_state: The steady state file computation for the Ramsey problem resulted in NaNs.\n') - fprintf('evaluate_steady_state: The steady state was computed conditional on the following initial instrument values: \n') - for ii = 1:size(options.instruments,1) - fprintf('\t %s \t %f \n',options.instruments(ii,:),ys_init(strmatch(options.instruments(ii,:),M.endo_names,'exact'))) - end - fprintf('evaluate_steady_state: The problem occured in the following equations: \n') - fprintf('\t Equation(s): ') - for ii=1:length(nan_indices) - fprintf('%d, ',nan_indices(ii)); - end - skipline() - fprintf('evaluate_steady_state: If those initial values are not admissable, change them using an initval-block.\n') - skipline(2) - end - info(1) = 84; - info(2) = resids'*resids; - return - end - - if any(imag(ys(n_multipliers+1:end))) - if options.debug - fprintf('\nevaluate_steady_state: The steady state file computation for the Ramsey problem resulted in complex numbers.\n') - fprintf('evaluate_steady_state: The steady state was computed conditional on the following initial instrument values: \n') - for ii = 1:size(options.instruments,1) - fprintf('\t %s \t %f \n',options.instruments(ii,:),ys_init(strmatch(options.instruments(ii,:),M.endo_names,'exact'))) - end - fprintf('evaluate_steady_state: If those initial values are not admissable, change them using an initval-block.\n') - skipline(2) - end - info(1) = 86; - info(2) = resids'*resids; - return - end - - if max(abs(resids(n_multipliers+1:end))) > options.solve_tolf %does it solve for all variables except for the Lagrange multipliers - if options.debug - fprintf('\nevaluate_steady_state: The steady state file does not solve the steady state for the Ramsey problem.\n') - fprintf('evaluate_steady_state: Conditional on the following instrument values: \n') - for ii = 1:size(options.instruments,1) - fprintf('\t %s \t %f \n',options.instruments(ii,:),ys_init(strmatch(options.instruments(ii,:),M.endo_names,'exact'))) - end - fprintf('evaluate_steady_state: the following equations have non-zero residuals: \n') - for ii=n_multipliers+1:M.endo_nbr - if abs(resids(ii)) > options.solve_tolf - fprintf('\t Equation number %d: %f\n',ii-n_multipliers, resids(ii)) - end - end - skipline(2) - end - info(1) = 85; - info(2) = resids'*resids; - return - end - end - if options.debug - infrow=find(isinf(ys_init)); - if ~isempty(infrow) - fprintf('\nevaluate_steady_state: The initial values for the steady state of the following variables are Inf:\n'); - for iter=1:length(infrow) - fprintf('%s\n',M.endo_names(infrow(iter),:)); - end - end - nanrow=find(isnan(ys_init)); - if ~isempty(nanrow) - fprintf('\nevaluate_steady_state: The initial values for the steady state of the following variables are NaN:\n'); - for iter=1:length(nanrow) - fprintf('%s\n',M.endo_names(nanrow(iter),:)); - end - end - end - %either if no steady state file or steady state file without problems - [ys,params,info] = dyn_ramsey_static(ys_init,M,options,oo); - if info - return - end - %check whether steady state really solves the model +if options.ramsey_policy + if steadystate_flag + % explicit steady state file + [ys,params,info] = evaluate_steady_state_file(ys_init,exo_ss,M, ... + options,steadystate_check_flag); + %test whether it solves model conditional on the instruments resids = evaluate_static_model(ys,exo_ss,params,M,options); - n_multipliers=M.ramsey_eq_nbr; - nan_indices_multiplier=find(isnan(resids(1:n_multipliers))); nan_indices=find(isnan(resids(n_multipliers+1:end))); if ~isempty(nan_indices) if options.debug - fprintf('\nevaluate_steady_state: The steady state computation for the Ramsey problem resulted in NaNs.\n') - fprintf('evaluate_steady_state: The steady state computation resulted in the following instrument values: \n') - for i = 1:size(options.instruments,1) - fprintf('\t %s \t %f \n',options.instruments(i,:),ys(strmatch(options.instruments(i,:),M.endo_names,'exact'))) + fprintf('\nevaluate_steady_state: The steady state file computation for the Ramsey problem resulted in NaNs.\n') + fprintf('evaluate_steady_state: The steady state was computed conditional on the following initial instrument values: \n') + for ii = 1:size(options.instruments,1) + fprintf('\t %s \t %f \n',options.instruments(ii,:),ys_init(strmatch(options.instruments(ii,:),M.endo_names,'exact'))) end fprintf('evaluate_steady_state: The problem occured in the following equations: \n') fprintf('\t Equation(s): ') @@ -160,184 +76,268 @@ function [ys,params,info] = evaluate_steady_state(ys_init,M,options,oo,steadysta fprintf('%d, ',nan_indices(ii)); end skipline() + fprintf('evaluate_steady_state: If those initial values are not admissable, change them using an initval-block.\n') + skipline(2) end - info(1) = 82; + info(1) = 84; + info(2) = resids'*resids; return end - if ~isempty(nan_indices_multiplier) + if any(imag(ys(n_multipliers+1:end))) if options.debug - fprintf('\nevaluate_steady_state: The steady state computation for the Ramsey problem resulted in NaNs in the auxiliary equations.\n') - fprintf('evaluate_steady_state: The steady state computation resulted in the following instrument values: \n') - for i = 1:size(options.instruments,1) - fprintf('\t %s \t %f \n',options.instruments(i,:),ys(strmatch(options.instruments(i,:),M.endo_names,'exact'))) + fprintf('\nevaluate_steady_state: The steady state file computation for the Ramsey problem resulted in complex numbers.\n') + fprintf('evaluate_steady_state: The steady state was computed conditional on the following initial instrument values: \n') + for ii = 1:size(options.instruments,1) + fprintf('\t %s \t %f \n',options.instruments(ii,:),ys_init(strmatch(options.instruments(ii,:),M.endo_names,'exact'))) end - fprintf('evaluate_steady_state: The problem occured in the following equations: \n') - fprintf('\t Auxiliary equation(s): ') - for ii=1:length(nan_indices_multiplier) - fprintf('%d, ',nan_indices_multiplier(ii)); - end - skipline() + fprintf('evaluate_steady_state: If those initial values are not admissable, change them using an initval-block.\n') + skipline(2) end - info(1) = 83; + info(1) = 86; + info(2) = resids'*resids; return end - if max(abs(resids)) > options.solve_tolf %does it solve for all variables including the auxiliary ones + if max(abs(resids(n_multipliers+1:end))) > options.solve_tolf %does it solve for all variables except for the Lagrange multipliers if options.debug - fprintf('\nevaluate_steady_state: The steady state for the Ramsey problem could not be computed.\n') - fprintf('evaluate_steady_state: The steady state computation stopped with the following instrument values:: \n') - for i = 1:size(options.instruments,1) - fprintf('\t %s \t %f \n',options.instruments(i,:),ys(strmatch(options.instruments(i,:),M.endo_names,'exact'))) - end - fprintf('evaluate_steady_state: The following equations have non-zero residuals: \n') - for ii=1:n_multipliers - if abs(resids(ii)) > options.solve_tolf/100 - fprintf('\t Auxiliary Ramsey equation number %d: %f\n',ii, resids(ii)) - end + fprintf('\nevaluate_steady_state: The steady state file does not solve the steady state for the Ramsey problem.\n') + fprintf('evaluate_steady_state: Conditional on the following instrument values: \n') + for ii = 1:size(options.instruments,1) + fprintf('\t %s \t %f \n',options.instruments(ii,:),ys_init(strmatch(options.instruments(ii,:),M.endo_names,'exact'))) end + fprintf('evaluate_steady_state: the following equations have non-zero residuals: \n') for ii=n_multipliers+1:M.endo_nbr - if abs(resids(ii)) > options.solve_tolf/100 + if abs(resids(ii)) > options.solve_tolf fprintf('\t Equation number %d: %f\n',ii-n_multipliers, resids(ii)) end end skipline(2) end - info(1) = 81; + info(1) = 85; info(2) = resids'*resids; return end - elseif steadystate_flag - % explicit steady state file - [ys,params,info] = evaluate_steady_state_file(ys_init,exo_ss,M, options,steadystate_check_flag); - if size(ys,2)>size(ys,1) - error('STEADY: steady_state-file must return a column vector, not a row vector.') - end - if info(1) - return + end + if options.debug + infrow=find(isinf(ys_init)); + if ~isempty(infrow) + fprintf('\nevaluate_steady_state: The initial values for the steady state of the following variables are Inf:\n'); + for iter=1:length(infrow) + fprintf('%s\n',M.endo_names(infrow(iter),:)); + end end - elseif (options.bytecode == 0 && options.block == 0) - if options.linear == 0 - % non linear model - static_model = str2func([M.fname '_static']); - [ys,check] = dynare_solve(@static_problem,... - ys_init,... - options, exo_ss, params,... - M.endo_nbr,... - static_model); - if check && options.debug - [ys,check,fvec,fjac] = dynare_solve(@static_problem,... - ys_init,... - options, exo_ss, params,... - M.endo_nbr,... - static_model); - [infrow,infcol]=find(isinf(fjac) | isnan(fjac)); - if ~isempty(infrow) - fprintf('\nSTEADY: The Jacobian at the initial values contains Inf or NaN. The problem arises from: \n') - display_problematic_vars_Jacobian(infrow,infcol,M,ys_init,'static','STEADY: ') - end - problematic_equation = find(~isfinite(fvec)); - if ~isempty(problematic_equation) - fprintf('\nSTEADY: numerical initial values or parameters incompatible with the following equations\n') - disp(problematic_equation') - fprintf('Please check for example\n') - fprintf(' i) if all parameters occurring in these equations are defined\n') - fprintf(' ii) that no division by an endogenous variable initialized to 0 occurs\n') - end + nanrow=find(isnan(ys_init)); + if ~isempty(nanrow) + fprintf('\nevaluate_steady_state: The initial values for the steady state of the following variables are NaN:\n'); + for iter=1:length(nanrow) + fprintf('%s\n',M.endo_names(nanrow(iter),:)); end - else - % linear model - fh_static = str2func([M.fname '_static']); - [fvec,jacob] = fh_static(ys_init,exo_ss, ... - params); + end + end + %either if no steady state file or steady state file without problems + [ys,params,info] = dyn_ramsey_static(ys_init,M,options,oo); + if info + return + end + %check whether steady state really solves the model + resids = evaluate_static_model(ys,exo_ss,params,M,options); - ii = find(~isfinite(fvec)); - if ~isempty(ii) - ys=fvec; - check=1; - disp(['STEADY: numerical initial values or parameters incompatible with the following' ... - ' equations']) - disp(ii') - disp('Check whether your model is truly linear. Put "resid(1);" before "steady;" to see the problematic equations.\n') - elseif isempty(ii) && max(abs(fvec)) > 1e-12 - ys = ys_init-jacob\fvec; - resid = evaluate_static_model(ys,exo_ss,params,M,options); - if max(abs(resid)) > 1e-6 - check=1; - fprintf('STEADY: No steady state for your model could be found\n') - fprintf('STEADY: Check whether your model is truly linear. Put "resid(1);" before "steady;" to see the problematic equations.\n') - end - else - ys = ys_init; + n_multipliers=M.ramsey_eq_nbr; + nan_indices_multiplier=find(isnan(resids(1:n_multipliers))); + nan_indices=find(isnan(resids(n_multipliers+1:end))); + + if ~isempty(nan_indices) + if options.debug + fprintf('\nevaluate_steady_state: The steady state computation for the Ramsey problem resulted in NaNs.\n') + fprintf('evaluate_steady_state: The steady state computation resulted in the following instrument values: \n') + for i = 1:size(options.instruments,1) + fprintf('\t %s \t %f \n',options.instruments(i,:),ys(strmatch(options.instruments(i,:),M.endo_names,'exact'))) end - if options.debug - if any(any(isinf(jacob) | isnan(jacob))) - [infrow,infcol]=find(isinf(jacob) | isnan(jacob)); - fprintf('\nSTEADY: The Jacobian contains Inf or NaN. The problem arises from: \n\n') - for ii=1:length(infrow) - fprintf('STEADY: Derivative of Equation %d with respect to Variable %s (initial value of %s: %g) \n',infrow(ii),deblank(M.endo_names(infcol(ii),:)),deblank(M.endo_names(infcol(ii),:)),ys_init(infcol(ii))) - end - fprintf('Check whether your model is truly linear. Put "resid(1);" before "steady;" to see the problematic equations.\n') - end + fprintf('evaluate_steady_state: The problem occured in the following equations: \n') + fprintf('\t Equation(s): ') + for ii=1:length(nan_indices) + fprintf('%d, ',nan_indices(ii)); end + skipline() end - else - % block or bytecode - [ys,check] = dynare_solve_block_or_bytecode(ys_init,exo_ss, params, options, M); + info(1) = 82; + return end - if check - info(1)= 20; - %make sure ys contains auxiliary variables in case of problem with dynare_solve - if length(M.aux_vars) > 0 && ~steadystate_flag - ys = h_set_auxiliary_variables(ys,exo_ss,M.params); + if ~isempty(nan_indices_multiplier) + if options.debug + fprintf('\nevaluate_steady_state: The steady state computation for the Ramsey problem resulted in NaNs in the auxiliary equations.\n') + fprintf('evaluate_steady_state: The steady state computation resulted in the following instrument values: \n') + for i = 1:size(options.instruments,1) + fprintf('\t %s \t %f \n',options.instruments(i,:),ys(strmatch(options.instruments(i,:),M.endo_names,'exact'))) + end + fprintf('evaluate_steady_state: The problem occured in the following equations: \n') + fprintf('\t Auxiliary equation(s): ') + for ii=1:length(nan_indices_multiplier) + fprintf('%d, ',nan_indices_multiplier(ii)); + end + skipline() end - resid = evaluate_static_model(ys,exo_ss,params,M,options); - info(2) = resid'*resid ; - if isnan(info(2)) - info(1)=22; + info(1) = 83; + return + end + + if max(abs(resids)) > options.solve_tolf %does it solve for all variables including the auxiliary ones + if options.debug + fprintf('\nevaluate_steady_state: The steady state for the Ramsey problem could not be computed.\n') + fprintf('evaluate_steady_state: The steady state computation stopped with the following instrument values:: \n') + for i = 1:size(options.instruments,1) + fprintf('\t %s \t %f \n',options.instruments(i,:),ys(strmatch(options.instruments(i,:),M.endo_names,'exact'))) + end + fprintf('evaluate_steady_state: The following equations have non-zero residuals: \n') + for ii=1:n_multipliers + if abs(resids(ii)) > options.solve_tolf/100 + fprintf('\t Auxiliary Ramsey equation number %d: %f\n',ii, resids(ii)) + end + end + for ii=n_multipliers+1:M.endo_nbr + if abs(resids(ii)) > options.solve_tolf/100 + fprintf('\t Equation number %d: %f\n',ii-n_multipliers, resids(ii)) + end + end + skipline(2) end + info(1) = 81; + info(2) = resids'*resids; + return + end +elseif steadystate_flag + % explicit steady state file + [ys,params,info] = evaluate_steady_state_file(ys_init,exo_ss,M, options,steadystate_check_flag); + if size(ys,2)>size(ys,1) + error('STEADY: steady_state-file must return a column vector, not a row vector.') + end + if info(1) return end +elseif (options.bytecode == 0 && options.block == 0) + if options.linear == 0 + % non linear model + static_model = str2func([M.fname '_static']); + [ys,check] = dynare_solve(@static_problem,... + ys_init,... + options, exo_ss, params,... + M.endo_nbr,... + static_model); + if check && options.debug + [ys,check,fvec,fjac] = dynare_solve(@static_problem,... + ys_init,... + options, exo_ss, params,... + M.endo_nbr,... + static_model); + [infrow,infcol]=find(isinf(fjac) | isnan(fjac)); + if ~isempty(infrow) + fprintf('\nSTEADY: The Jacobian at the initial values contains Inf or NaN. The problem arises from: \n') + display_problematic_vars_Jacobian(infrow,infcol,M,ys_init,'static','STEADY: ') + end + problematic_equation = find(~isfinite(fvec)); + if ~isempty(problematic_equation) + fprintf('\nSTEADY: numerical initial values or parameters incompatible with the following equations\n') + disp(problematic_equation') + fprintf('Please check for example\n') + fprintf(' i) if all parameters occurring in these equations are defined\n') + fprintf(' ii) that no division by an endogenous variable initialized to 0 occurs\n') + end + end + else + % linear model + fh_static = str2func([M.fname '_static']); + [fvec,jacob] = fh_static(ys_init,exo_ss, ... + params); - % If some equations are tagged [static] or [dynamic], verify consistency - if M.static_and_dynamic_models_differ - % Evaluate residual of *dynamic* model using the steady state - % computed on the *static* one - z = repmat(ys,1,M.maximum_lead + M.maximum_lag + 1); - zx = repmat([exo_ss'], M.maximum_lead + M.maximum_lag + 1, 1); - if options.bytecode - [chck, r, junk]= bytecode('dynamic','evaluate', z, zx, M.params, ys, 1); - mexErrCheck('bytecode', chck); - elseif options.block - [r, oo.dr] = feval([M.fname '_dynamic'], z', zx, M.params, ys, M.maximum_lag+1, oo.dr); + ii = find(~isfinite(fvec)); + if ~isempty(ii) + ys=fvec; + check=1; + disp(['STEADY: numerical initial values or parameters incompatible with the following' ... + ' equations']) + disp(ii') + disp('Check whether your model is truly linear. Put "resid(1);" before "steady;" to see the problematic equations.\n') + elseif isempty(ii) && max(abs(fvec)) > 1e-12 + ys = ys_init-jacob\fvec; + resid = evaluate_static_model(ys,exo_ss,params,M,options); + if max(abs(resid)) > 1e-6 + check=1; + fprintf('STEADY: No steady state for your model could be found\n') + fprintf('STEADY: Check whether your model is truly linear. Put "resid(1);" before "steady;" to see the problematic equations.\n') + end else - iyv = M.lead_lag_incidence'; - iyr0 = find(iyv(:)); - xys = z(iyr0); - r = feval([M.fname '_dynamic'], z(iyr0), zx, M.params, ys, M.maximum_lag + 1); + ys = ys_init; end - % Fail if residual greater than tolerance - if max(abs(r)) > options.solve_tolf - info(1) = 25; - return + if options.debug + if any(any(isinf(jacob) | isnan(jacob))) + [infrow,infcol]=find(isinf(jacob) | isnan(jacob)); + fprintf('\nSTEADY: The Jacobian contains Inf or NaN. The problem arises from: \n\n') + for ii=1:length(infrow) + fprintf('STEADY: Derivative of Equation %d with respect to Variable %s (initial value of %s: %g) \n',infrow(ii),deblank(M.endo_names(infcol(ii),:)),deblank(M.endo_names(infcol(ii),:)),ys_init(infcol(ii))) + end + fprintf('Check whether your model is truly linear. Put "resid(1);" before "steady;" to see the problematic equations.\n') + end end end +else + % block or bytecode + [ys,check] = dynare_solve_block_or_bytecode(ys_init,exo_ss, params, options, M); +end - if ~isreal(ys) - info(1) = 21; - info(2) = sum(imag(ys).^2); - ys = real(ys); - return +if check + info(1)= 20; + %make sure ys contains auxiliary variables in case of problem with dynare_solve + if length(M.aux_vars) > 0 && ~steadystate_flag + ys = h_set_auxiliary_variables(ys,exo_ss,M.params); end + resid = evaluate_static_model(ys,exo_ss,params,M,options); + info(2) = resid'*resid ; + if isnan(info(2)) + info(1)=22; + end + return +end - if ~isempty(find(isnan(ys))) - info(1) = 22; - info(2) = NaN; +% If some equations are tagged [static] or [dynamic], verify consistency +if M.static_and_dynamic_models_differ + % Evaluate residual of *dynamic* model using the steady state + % computed on the *static* one + z = repmat(ys,1,M.maximum_lead + M.maximum_lag + 1); + zx = repmat([exo_ss'], M.maximum_lead + M.maximum_lag + 1, 1); + if options.bytecode + [chck, r, junk]= bytecode('dynamic','evaluate', z, zx, M.params, ys, 1); + mexErrCheck('bytecode', chck); + elseif options.block + [r, oo.dr] = feval([M.fname '_dynamic'], z', zx, M.params, ys, M.maximum_lag+1, oo.dr); + else + iyv = M.lead_lag_incidence'; + iyr0 = find(iyv(:)); + xys = z(iyr0); + r = feval([M.fname '_dynamic'], z(iyr0), zx, M.params, ys, M.maximum_lag + 1); + end + % Fail if residual greater than tolerance + if max(abs(r)) > options.solve_tolf + info(1) = 25; return end +end + +if ~isreal(ys) + info(1) = 21; + info(2) = sum(imag(ys).^2); + ys = real(ys); + return +end + +if ~isempty(find(isnan(ys))) + info(1) = 22; + info(2) = NaN; + return +end function [resids,jac] = static_problem(y,x,params,nvar,fh_static_model) - [r,j] = fh_static_model(y,x,params); - resids = r(1:nvar); - jac = j(1:nvar,1:nvar); +[r,j] = fh_static_model(y,x,params); +resids = r(1:nvar); +jac = j(1:nvar,1:nvar); diff --git a/matlab/evaluate_steady_state_file.m b/matlab/evaluate_steady_state_file.m index 1bb2c018b9..67a3b0c4df 100644 --- a/matlab/evaluate_steady_state_file.m +++ b/matlab/evaluate_steady_state_file.m @@ -1,14 +1,14 @@ function [ys,params,info] = evaluate_steady_state_file(ys_init,exo_ss,M,options,steady_state_checkflag) % function [ys,params1,info] = evaluate_steady_state_file(ys_init,exo_ss,M,options,steady_state_checkflag) -% Evaluates steady state files -% +% Evaluates steady state files +% % INPUTS % ys_init vector initial values used to compute the steady % state % exo_ss vector exogenous steady state % M struct model parameters % options struct options -% steady_state_checkflag boolean indicator whether to check steady state returned +% steady_state_checkflag boolean indicator whether to check steady state returned % OUTPUTS % ys vector steady state % params1 vector model parameters possibly @@ -36,125 +36,123 @@ function [ys,params,info] = evaluate_steady_state_file(ys_init,exo_ss,M,options, % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - debug = false; +debug = false; - ys = []; - params = M.params; - info = 0; +ys = []; +params = M.params; +info = 0; - fname = M.fname; +fname = M.fname; - if options.steadystate_flag == 1 - % old format - assignin('base','tmp_00_',params); - evalin('base','M_.params=tmp_00_; clear(''tmp_00_'')'); - h_steadystate = str2func([fname '_steadystate']); - [ys,check] = h_steadystate(ys_init, exo_ss); - params1 = evalin('base','M_.params'); - else % steadystate_flag == 2 - % new format - h_steadystate = str2func([fname '_steadystate2']); - [ys,params1,check] = h_steadystate(ys_init, exo_ss, params); - end - - if check - info(1) = 19; - info(2) = NaN; - return - end - - if M.param_nbr > 0 - updated_params_flag = max(abs(params1-params)) > 1e-12 ... - || ~isequal(isnan(params1),isnan(params)); %checks whether numbers or NaN changed - else - updated_params_flag = 0; - end +if options.steadystate_flag == 1 + % old format + assignin('base','tmp_00_',params); + evalin('base','M_.params=tmp_00_; clear(''tmp_00_'')'); + h_steadystate = str2func([fname '_steadystate']); + [ys,check] = h_steadystate(ys_init, exo_ss); + params1 = evalin('base','M_.params'); +else % steadystate_flag == 2 + % new format + h_steadystate = str2func([fname '_steadystate2']); + [ys,params1,check] = h_steadystate(ys_init, exo_ss, params); +end - h_set_auxiliary_variables = str2func([M.fname '_set_auxiliary_variables']); - if isnan(updated_params_flag) || (updated_params_flag && any(isnan(params(~isnan(params))-params1(~isnan(params))))) %checks if new NaNs were added - info(1) = 24; - info(2) = NaN; - ys = h_set_auxiliary_variables(ys,exo_ss,params); - return - end +if check + info(1) = 19; + info(2) = NaN; + return +end - if updated_params_flag && ~isreal(params1) - info(1) = 23; - info(2) = sum(imag(params).^2); - ys = h_set_auxiliary_variables(ys,exo_ss,params); - return +if M.param_nbr > 0 + updated_params_flag = max(abs(params1-params)) > 1e-12 ... + || ~isequal(isnan(params1),isnan(params)); %checks whether numbers or NaN changed +else + updated_params_flag = 0; +end + +h_set_auxiliary_variables = str2func([M.fname '_set_auxiliary_variables']); +if isnan(updated_params_flag) || (updated_params_flag && any(isnan(params(~isnan(params))-params1(~isnan(params))))) %checks if new NaNs were added + info(1) = 24; + info(2) = NaN; + ys = h_set_auxiliary_variables(ys,exo_ss,params); + return +end + +if updated_params_flag && ~isreal(params1) + info(1) = 23; + info(2) = sum(imag(params).^2); + ys = h_set_auxiliary_variables(ys,exo_ss,params); + return +end + +if updated_params_flag + params = params1; +end + +% adding values for auxiliary variables +if length(M.aux_vars) > 0 && ~options.ramsey_policy + if debug + ys0 = ys; end - - if updated_params_flag - params = params1; + ys = h_set_auxiliary_variables(ys,exo_ss,params); + if debug + ys1 = ys; end - - % adding values for auxiliary variables - if length(M.aux_vars) > 0 && ~options.ramsey_policy - if debug - ys0 = ys; - end + ys = h_set_auxiliary_variables(ys,exo_ss,params); + if debug + ys2 = ys; + end + if debug ys = h_set_auxiliary_variables(ys,exo_ss,params); - if debug - ys1 = ys; + ys3 = ys; + idx = find(abs(ys0-ys1)>0); + if ~isempty(idx) + M.endo_names(idx,:) + else + disp('1-invariant') end - ys = h_set_auxiliary_variables(ys,exo_ss,params); - if debug - ys2 = ys; + idx = find(abs(ys2-ys1)>0); + if ~isempty(idx) + M.endo_names(idx,:) + else + disp('2-invariant') end - if debug - ys = h_set_auxiliary_variables(ys,exo_ss,params); - ys3 = ys; - idx = find(abs(ys0-ys1)>0); - if ~isempty(idx) - M.endo_names(idx,:) - else - disp('1-invariant') - end - idx = find(abs(ys2-ys1)>0); - if ~isempty(idx) - M.endo_names(idx,:) - else - disp('2-invariant') - end - idx = find(abs(ys3-ys3)>0); - if ~isempty(idx) - M.endo_names(idx,:) - else - disp('3-invariant') - end - pause + idx = find(abs(ys3-ys3)>0); + if ~isempty(idx) + M.endo_names(idx,:) + else + disp('3-invariant') end + pause end +end - check1 = 0; - if steady_state_checkflag - % Check whether the steady state obtained from the _steadystate file is a steady state. - [residuals, check] = evaluate_static_model(ys, exo_ss, params, M, options); - if check - info(1) = 19; - info(2) = check; % to be improved - return - end - if max(abs(residuals)) > options.dynatol.f - info(1) = 19; - info(2) = residuals'*residuals; - return - end - if any(isnan(residuals)) - info(1) = 22; - return - end - elseif ~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 - [ys,check] = dynare_solve('restricted_steadystate',... - ys(indv),... - options, exo_ss,indv); +check1 = 0; +if steady_state_checkflag + % Check whether the steady state obtained from the _steadystate file is a steady state. + [residuals, check] = evaluate_static_model(ys, exo_ss, params, M, options); + if check + info(1) = 19; + info(2) = check; % to be improved + return end - - + if max(abs(residuals)) > options.dynatol.f + info(1) = 19; + info(2) = residuals'*residuals; + return + end + if any(isnan(residuals)) + info(1) = 22; + return + end +elseif ~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 + [ys,check] = dynare_solve('restricted_steadystate',... + ys(indv),... + options, exo_ss,indv); +end diff --git a/matlab/expand_group.m b/matlab/expand_group.m index 7681ffeea9..c20d38c37c 100644 --- a/matlab/expand_group.m +++ b/matlab/expand_group.m @@ -42,10 +42,8 @@ options.use_shock_groups = strrep(label,' ','_'); %[use_shock_groups_old int2str for j=1:length(shocks) M.shock_groups.(options.use_shock_groups).(['group' int2str(j)]).label=shocks{j}; M.shock_groups.(options.use_shock_groups).(['group' int2str(j)]).shocks=shocks(j); -end +end options.shock_decomp.interactive=0; options.shock_decomp.expand=1; plot_shock_decomposition(M,oo,options,var_list_); - - diff --git a/matlab/fastgensylv.m b/matlab/fastgensylv.m index 332e46f282..0f7340cd12 100644 --- a/matlab/fastgensylv.m +++ b/matlab/fastgensylv.m @@ -95,19 +95,19 @@ end % B % C % D -% block : block number (for storage purpose) +% block : block number (for storage purpose) % tol : convergence criteria % OUTPUTS % X solution -% +% % ALGORITHM % fixed point method % MARLLINY MONSALVE (2008): "Block linear method for large scale -% Sylvester equations", Computational & Applied Mathematics, Vol 27, n�1, +% Sylvester equations", Computational & Applied Mathematics, Vol 27, n°1, % p47-59 % ||A^-1||.||B||.||C|| < 1 is a suffisant condition: % - to get a unique solution for the Sylvester equation % - to get a convergent fixed-point algorithm % % SPECIAL REQUIREMENTS -% none. +% none. diff --git a/matlab/ff1_.m b/matlab/ff1_.m index 4b6b666cef..6037809f03 100644 --- a/matlab/ff1_.m +++ b/matlab/ff1_.m @@ -5,10 +5,10 @@ function y=ff1_(x) % % INPUTS % x: argument splitted between endogenous and exogenous -% +% % OUTPUTS % y: 'static' function residuals -% +% % SPECIAL REQUIREMENTS % none @@ -35,6 +35,3 @@ n1 = size(x,1) - M_.exo_nbr; oo_.exo_simul(it_+M_.maximum_lag-M_.maximum_lag,:) = x(n1+1:end)'; fh = str2func([M_.fname '_static']); y=feval(fh,x(1:n1),oo_.exo_simul, M_.params); - - - diff --git a/matlab/ffill.m b/matlab/ffill.m index fc72c9f9f7..3449ee2920 100644 --- a/matlab/ffill.m +++ b/matlab/ffill.m @@ -7,11 +7,11 @@ function [a,b] = ffill(x,ixc,y) % x: matrix % ixc: vector of indices % y: matrix -% +% % OUTPUTS % a: concatenation results % b: vector -% +% % SPECIAL REQUIREMENTS % none diff --git a/matlab/flip_plan.m b/matlab/flip_plan.m index 098e259499..5daf19fc7d 100644 --- a/matlab/flip_plan.m +++ b/matlab/flip_plan.m @@ -31,71 +31,71 @@ function plan = flip_plan(plan, exogenous, endogenous, expectation_type, date, 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 ~ischar(expectation_type) || size(expectation_type,1) ~= 1 - error(['in flip_plan the fourth argument should be a string containing the simulation type (''perfect_foresight'' or ''surprise'')']); - end - exogenous = strtrim(exogenous); - ix = find(strcmp(exogenous, plan.endo_names)); - if isempty(ix) - error(['in flip_plan the second argument ' exogenous ' is not an endogenous variable']); - end - endogenous = strtrim(endogenous); - iy = find(strcmp(endogenous, plan.exo_names)); - if isempty(iy) - error(['in flip_plan the third argument ' endogenous ' is not an exogenous variable']); - end - sdate = length(date); - if sdate > 1 - if date(1) < plan.date(1) || date(end) > plan.date(end) - error(['in flip_plan the fifth argument (date=' date ') must lay inside the plan.date ' plan.date]); - end - else - if date < plan.date(1) || date > plan.date(end) - error(['in flip_plan the fifth argument (date=' date ') must lay iside the plan.date ' plan.date]); - end - end - if ~isempty(plan.shock_vars_) - common_var = find(iy == plan.shock_vars_); - if ~isempty(common_var) - common_date = intersect(date, plan.shock_date_{common_var}); - if ~isempty(common_date) - if common_date.length > 1 - the_dates = [cell2mat(strings(common_date(1))) ':' cell2mat(strings(common_date(end)))]; - else - the_dates = cell2mat(strings(common_date)); - end - error(['Impossible case: ' plan.exo_names{plan.shock_vars_(common_var)} ' is used both as a shock and as an endogenous variable to control the path of ' plan.endo_names{ix} ' at the dates ' the_dates]); - end - end - end - i_ix = find(ix == plan.constrained_vars_); - if isempty(i_ix) +if ~ischar(expectation_type) || size(expectation_type,1) ~= 1 + error(['in flip_plan the fourth argument should be a string containing the simulation type (''perfect_foresight'' or ''surprise'')']); +end +exogenous = strtrim(exogenous); +ix = find(strcmp(exogenous, plan.endo_names)); +if isempty(ix) + error(['in flip_plan the second argument ' exogenous ' is not an endogenous variable']); +end +endogenous = strtrim(endogenous); +iy = find(strcmp(endogenous, plan.exo_names)); +if isempty(iy) + error(['in flip_plan the third argument ' endogenous ' is not an exogenous variable']); +end +sdate = length(date); +if sdate > 1 + if date(1) < plan.date(1) || date(end) > plan.date(end) + error(['in flip_plan the fifth argument (date=' date ') must lay inside the plan.date ' plan.date]); + end +else + if date < plan.date(1) || date > plan.date(end) + error(['in flip_plan the fifth argument (date=' date ') must lay iside the plan.date ' plan.date]); + end +end +if ~isempty(plan.shock_vars_) + common_var = find(iy == plan.shock_vars_); + if ~isempty(common_var) + common_date = intersect(date, plan.shock_date_{common_var}); + if ~isempty(common_date) + if common_date.length > 1 + the_dates = [cell2mat(strings(common_date(1))) ':' cell2mat(strings(common_date(end)))]; + else + the_dates = cell2mat(strings(common_date)); + end + error(['Impossible case: ' plan.exo_names{plan.shock_vars_(common_var)} ' is used both as a shock and as an endogenous variable to control the path of ' plan.endo_names{ix} ' at the dates ' the_dates]); + end + end +end +i_ix = find(ix == plan.constrained_vars_); +if isempty(i_ix) if isempty(plan.constrained_vars_) - plan.constrained_vars_ = ix; - plan.options_cond_fcst_.controlled_varexo = iy; - if strcmp(expectation_type, 'perfect_foresight') - plan.constrained_perfect_foresight_ = 1; - else - plan.constrained_perfect_foresight_ = 0; - end + plan.constrained_vars_ = ix; + plan.options_cond_fcst_.controlled_varexo = iy; + if strcmp(expectation_type, 'perfect_foresight') + plan.constrained_perfect_foresight_ = 1; + else + plan.constrained_perfect_foresight_ = 0; + end else - plan.constrained_vars_ = [plan.constrained_vars_ ; ix]; - plan.options_cond_fcst_.controlled_varexo = [plan.options_cond_fcst_.controlled_varexo ; iy]; - if strcmp(expectation_type, 'perfect_foresight') - plan.constrained_perfect_foresight_ = [plan.constrained_perfect_foresight_ ; 1]; - else - plan.constrained_perfect_foresight_ = [plan.constrained_perfect_foresight_ ; 0]; - end + plan.constrained_vars_ = [plan.constrained_vars_ ; ix]; + plan.options_cond_fcst_.controlled_varexo = [plan.options_cond_fcst_.controlled_varexo ; iy]; + if strcmp(expectation_type, 'perfect_foresight') + plan.constrained_perfect_foresight_ = [plan.constrained_perfect_foresight_ ; 1]; + else + plan.constrained_perfect_foresight_ = [plan.constrained_perfect_foresight_ ; 0]; + end end plan.constrained_date_{length(plan.constrained_date_) + 1} = date; plan.constrained_str_date_{length(plan.constrained_str_date_) + 1} = strings(date); plan.constrained_int_date_{length(plan.constrained_int_date_) + 1} = date - plan.date(1) + 1; plan.constrained_paths_{length(plan.constrained_paths_) + 1} = value; - elseif plan.options_cond_fcst_.controlled_varexo(i_ix) == iy % same exogenous and endogenous hard tune - [plan.constrained_str_date_{i_ix}, i1, i2] = union(strings(date), plan.constrained_str_date_{i_ix}); - plan.constrained_date_{i_ix} = [date(i1) plan.constrained_date_{i_ix}(i2)]; - plan.constrained_int_date_{i_ix} = [date(i1) - plan.date(1) + 1; plan.constrained_int_date_{i_ix}(i2)]; - plan.constrained_paths_{i_ix} = [value(i1)'; plan.constrained_paths_{i_ix}(i2)]; - else +elseif plan.options_cond_fcst_.controlled_varexo(i_ix) == iy % same exogenous and endogenous hard tune +[plan.constrained_str_date_{i_ix}, i1, i2] = union(strings(date), plan.constrained_str_date_{i_ix}); +plan.constrained_date_{i_ix} = [date(i1) plan.constrained_date_{i_ix}(i2)]; +plan.constrained_int_date_{i_ix} = [date(i1) - plan.date(1) + 1; plan.constrained_int_date_{i_ix}(i2)]; +plan.constrained_paths_{i_ix} = [value(i1)'; plan.constrained_paths_{i_ix}(i2)]; +else error(['impossible case you have two conditional forecasts:\n - one involving ' plan.endo_names{plan.options_cond_fcst_.controlled_varexo(i_ix),:} ' as control and ' plan_exo_names{plan.constrained_vars_(ix_)} ' as constrined endogenous\n - the other involving ' plan.endo_names{plan.options_cond_fcst_.controlled_varexo(iy),:} ' as control and ' plan_exo_names{plan.constrained_vars_(ix)} ' as constrined endogenous\n']); - end +end diff --git a/matlab/forcst.m b/matlab/forcst.m index 9c7654ae62..de824258a4 100644 --- a/matlab/forcst.m +++ b/matlab/forcst.m @@ -1,7 +1,7 @@ function [yf,int_width,int_width_ME]=forcst(dr,y0,horizon,var_list,M_,oo_,options_) % function [yf,int_width,int_width_ME]=forecst(dr,y0,horizon,var_list,M_,oo_,options_) % computes mean forecast for a given value of the parameters -% computes also confidence band for the forecast +% computes also confidence band for the forecast % % INPUTS: % dr: structure containing decision rules @@ -67,7 +67,7 @@ ghx1 = dr.ghx(inv_order_var(ivar),:); ghu1 = dr.ghu(inv_order_var(ivar),:); %initialize recursion -sigma_u = B*M_.Sigma_e*B'; +sigma_u = B*M_.Sigma_e*B'; sigma_u1 = ghu1*M_.Sigma_e*ghu1'; sigma_y = 0; %no uncertainty about the states diff --git a/matlab/forcst2.m b/matlab/forcst2.m index 43c2b4c4e9..621d44ec24 100644 --- a/matlab/forcst2.m +++ b/matlab/forcst2.m @@ -1,6 +1,6 @@ function yf=forcst2(y0,horizon,dr,n) % function yf=forcst2(y0,horizon,dr,n) -% +% % computes forecasts based on first order model solution, given shocks % drawn from the shock distribution, but not including measurement error % Inputs: @@ -11,7 +11,7 @@ function yf=forcst2(y0,horizon,dr,n) % % Outputs: % - yf [horizon+ykmin_ by endo_nbr by n] array of forecasts -% +% % Copyright (C) 2008-2016 Dynare Team % % This file is part of Dynare. @@ -64,4 +64,4 @@ for i=ykmin_+(1:horizon) end yf(dr.order_var,:,:) = yf; -yf=permute(yf,[2 1 3]); +yf=permute(yf,[2 1 3]); diff --git a/matlab/forcst2a.m b/matlab/forcst2a.m index c5ede306d0..72864ac3c0 100644 --- a/matlab/forcst2a.m +++ b/matlab/forcst2a.m @@ -1,6 +1,6 @@ function yf=forcst2a(y0,dr,e) % function yf=forcst2a(y0,dr,e) -% computes forecasts based on first order model solution, assuming the absence of shocks +% computes forecasts based on first order model solution, assuming the absence of shocks % Inputs: % - y0 [endo_nbr by maximum_endo_lag] matrix of starting values % - dr [structure] structure with Dynare decision rules @@ -48,4 +48,3 @@ for i=ykmin_+(1:horizon) end yf(:,dr.order_var) = yf; - diff --git a/matlab/forecast_graphs.m b/matlab/forecast_graphs.m index 108e0498b2..5631ff4b4d 100644 --- a/matlab/forecast_graphs.m +++ b/matlab/forecast_graphs.m @@ -1,7 +1,7 @@ function forecast_graphs(var_list,M_, oo_,options_) % function forecast_graphs(var_list,M_, oo_,options_) % Plots the classical forecasts created by dyn_forecast.m -% +% % Inputs: % o var_list character array with variable names % o M_ model structure @@ -73,7 +73,7 @@ for j= 1:nvar fprintf(fidTeX,'\\caption{Mean forecasts and %2.0f\\%% confidence intervals}\n',options_.forecasts.conf_sig*100); fprintf(fidTeX,'\\end{figure}\n'); fprintf(fidTeX,' \n'); - end + end n_fig =n_fig+1; eval(['hh=dyn_figure(options_.nodisplay,''Name'',''Forecasts (' int2str(n_fig) ')'');']); m = 1; @@ -81,7 +81,7 @@ for j= 1:nvar subplot(nr,nc,m); vn = deblank(endo_names(i_var(j),:)); obs = 0; -% $$$ k = strmatch(vn,varobs,'exact'); +% $$$ 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); @@ -118,11 +118,11 @@ end if isfield(oo_.forecast,'HPDinf_ME') var_names=fieldnames(oo_.forecast.HPDinf_ME); - + if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) fidTeX=write_LaTeX_header([M_.dname '/graphs/',fname,'_forcst_ME.tex']); end - + m = 1; n_fig = 1; hh=dyn_figure(options_.nodisplay,'Name','Forecasts including ME (I)'); @@ -156,12 +156,12 @@ if isfield(oo_.forecast,'HPDinf_ME') hold off m = m + 1; end - + if m > 1 dyn_saveas(hh,[dname '/graphs/forcst_ME' int2str(n_fig)],options_.nodisplay,options_.graph_format); if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) fprintf(fidTeX,'\\begin{figure}[H]\n'); - fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\centering \n'); fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s/graphs/forcst_ME%d}\n',options_.figures.textwidth*min((m-1)/nc,1),dname,n_fig); fprintf(fidTeX,'\\label{Fig:forcst_ME:%d}\n',n_fig); fprintf(fidTeX,'\\caption{Mean forecasts and %2.0f\\%% confidence intervals accounting for measurement error}\n',options_.forecasts.conf_sig*100); @@ -169,10 +169,10 @@ if isfield(oo_.forecast,'HPDinf_ME') fprintf(fidTeX,' \n'); end end - + if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) write_LaTeX_footer(fidTeX); - end + end end diff --git a/matlab/ftest.m b/matlab/ftest.m index 97bedb6e56..c72ed49d96 100644 --- a/matlab/ftest.m +++ b/matlab/ftest.m @@ -20,7 +20,7 @@ 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 @@ -59,7 +59,7 @@ end for i = 1:size(x,1) if ~ strcmp(nvx(i,:),nvy(i,:)) - error ('FTEST: The two files don''t have the same variables.') ; + error ('FTEST: The two files don''t have the same variables.') ; end end diff --git a/matlab/gauss_hermite_weights_and_nodes.m b/matlab/gauss_hermite_weights_and_nodes.m index 8bbc08cca7..37f2ddf927 100644 --- a/matlab/gauss_hermite_weights_and_nodes.m +++ b/matlab/gauss_hermite_weights_and_nodes.m @@ -66,7 +66,7 @@ nodes = sqrt(2)*nodes; %$ sum_of_weights = sum(weights); %$ %$ % Expected nodes (taken from Judd (1998, table 7.4). -%$ enodes = [-2.020182870; -0.9585724646; 0; 0.9585724646; 2.020182870]; +%$ enodes = [-2.020182870; -0.9585724646; 0; 0.9585724646; 2.020182870]; %$ %$ % Check the results. %$ t(1) = dassert(1.0,sum_of_weights,1e-12); @@ -79,7 +79,7 @@ nodes = sqrt(2)*nodes; %$ [nodes,weights] = gauss_hermite_weights_and_nodes(n); %$ %$ sum_of_weights = sum(weights); -%$ expectation = sum(weights.*nodes); +%$ expectation = sum(weights.*nodes); %$ variance = sum(weights.*(nodes.^2)); %$ %$ % Check the results. @@ -113,7 +113,7 @@ nodes = sqrt(2)*nodes; %$ [nodes,weights] = gauss_hermite_weights_and_nodes(n); %$ %$ sum_of_weights = sum(weights); -%$ expectation = sum(weights.*nodes*.1); +%$ expectation = sum(weights.*nodes*.1); %$ variance = sum(weights.*((nodes*.1).^2)); %$ %$ % Check the results. diff --git a/matlab/gauss_legendre_weights_and_nodes.m b/matlab/gauss_legendre_weights_and_nodes.m index 6bc7067b15..fa42e91651 100644 --- a/matlab/gauss_legendre_weights_and_nodes.m +++ b/matlab/gauss_legendre_weights_and_nodes.m @@ -124,7 +124,7 @@ end %@test:3 %$ [n,w] = gauss_legendre_weights_and_nodes(9,pi,2*pi); -%$ % Check that the +%$ % Check that the %$ t(1) = all(n>pi); %$ t(2) = all(n<2*pi); %$ t(3) = dassert(sum(w),pi,1e-12); diff --git a/matlab/gcompare.m b/matlab/gcompare.m index d8a1e2ae83..861aa894d9 100644 --- a/matlab/gcompare.m +++ b/matlab/gcompare.m @@ -1,5 +1,5 @@ function gcompare(s1,s2) -% GCOMPARE : GCOMPARE ( [ 'file1' ; 'file2' ] , [ 'var1' ; 'var2' ...] ) +% GCOMPARE : GCOMPARE ( [ 'file1' ; 'file2' ] , [ 'var1' ; 'var2' ...] ) % This optional command plots the trajectories of a list of % variables in two different simulations. One plot is drawn % for each variable. The trajectories must have been previously @@ -50,6 +50,3 @@ end % 06/18/01 MJ corrected treatment of options_.smpl % 06/24/01 MJ removed color specification - - - diff --git a/matlab/gensylv/gensylv.m b/matlab/gensylv/gensylv.m index a67d7de5ee..2920aca4d2 100644 --- a/matlab/gensylv/gensylv.m +++ b/matlab/gensylv/gensylv.m @@ -3,21 +3,21 @@ function [err, E] = gensylv(kron_prod,A,B,C0,D) % Solves a Sylvester equation. % % INPUTS -% kron_prod +% kron_prod % A % B % C % D -% +% % OUTPUTS % err [double] scalar: 1 indicates failure, 0 indicates success % E -% +% % ALGORITHM % none. % % SPECIAL REQUIREMENTS -% none. +% none. % Copyright (C) 1996-2017 Dynare Team % @@ -37,7 +37,7 @@ function [err, E] = gensylv(kron_prod,A,B,C0,D) % along with Dynare. If not, see <http://www.gnu.org/licenses/>. C = C0; for i=1:(kron_prod-1) - C = kron(C0,C); + C = kron(C0,C); end x0 = sylvester3(A,B,C,D); diff --git a/matlab/gensylv_fp.m b/matlab/gensylv_fp.m index 1174fbc4b4..51c96fceb8 100644 --- a/matlab/gensylv_fp.m +++ b/matlab/gensylv_fp.m @@ -7,22 +7,22 @@ function X = gensylv_fp(A, B, C, D, block, tol) % B % C % D -% block : block number (for storage purpose) +% block : block number (for storage purpose) % tol : convergence criteria % OUTPUTS % X solution -% +% % ALGORITHM % fixed point method % MARLLINY MONSALVE (2008): "Block linear method for large scale -% Sylvester equations", Computational & Applied Mathematics, Vol 27, n�1, +% Sylvester equations", Computational & Applied Mathematics, Vol 27, n°1, % p47-59 % ||A^-1||.||B||.||C|| < 1 is a suffisant condition: % - to get a unique solution for the Sylvester equation % - to get a convergent fixed-point algorithm % % SPECIAL REQUIREMENTS -% none. +% none. % Copyright (C) 1996-2017 Dynare Team % % This file is part of Dynare. @@ -62,7 +62,7 @@ while it_fp < maxit_fp && evol > tol Z_old = Z; Z = - (B * X * C + D); evol = max(sum(abs(Z - Z_old))); %norm_1 - %evol = max(sum(abs(Z - Z_old)')); %norm_inf + %evol = max(sum(abs(Z - Z_old)')); %norm_inf it_fp = it_fp + 1; end %fprintf('sylvester it_fp=%d evol=%g | ',it_fp,evol); diff --git a/matlab/getH.m b/matlab/getH.m index 33f8903766..fcee9242e3 100644 --- a/matlab/getH.m +++ b/matlab/getH.m @@ -13,14 +13,14 @@ function [H, dA, dOm, Hss, gp, d2A, d2Om, H2ss] = getH(A, B, estim_params_,M_,oo % not (-1 or -2) % indx: Index of estimated parameters in M_.params % indexo: Index of estimated standard deviations in M_.exo_names -% iv: Index of considered variables -% +% iv: Index of considered variables +% % Outputs: % H: dTAU/dTHETA: Jacobian of TAU, vectorized form of % linearized reduced form state space model, given ys [steady state], % A [transition matrix], B [matrix of shocks], Sigma [covariance of shocks] -% TAU = [ys; vec(A); dyn_vech(B*Sigma*B')]. -% dA: [endo_nbr by endo_nbr by (indx+indexo)] Jacobian of transition matrix A +% TAU = [ys; vec(A); dyn_vech(B*Sigma*B')]. +% dA: [endo_nbr by endo_nbr by (indx+indexo)] Jacobian of transition matrix A % dOm: [endo_nbr by endo_nbr by (indx+indexo)] Jacobian of Omega = (B*Sigma*B') % Hss: [endo_nbr by (indx)] Jacobian of steady state with respect to estimated % structural parameters only (indx) @@ -50,16 +50,16 @@ function [H, dA, dOm, Hss, gp, d2A, d2Om, H2ss] = getH(A, B, estim_params_,M_,oo % along with Dynare. If not, see <http://www.gnu.org/licenses/>. if nargin<7 || isempty(kronflag) - kronflag = 0; + kronflag = 0; end if nargin<8 || isempty(indx) - indx = []; + indx = []; end if nargin<9 || isempty(indexo) - indexo = []; + indexo = []; end if nargin<10 || isempty(iv) - iv = (1:length(A))'; + iv = (1:length(A))'; end [I,J]=find(M_.lead_lag_incidence'); @@ -96,7 +96,7 @@ if kronflag==-1 % perturbation end if nargout>5 H2 = hessian_sparse('thet2tau',[sqrt(diag(M_.Sigma_e(indexo,indexo))); M_.params(indx)], ... - options_.gstep,estim_params_,M_, oo_, indx,indexo,0,[],[],[],iv); + options_.gstep,estim_params_,M_, oo_, indx,indexo,0,[],[],[],iv); H2ss = zeros(m1,tot_param_nbr,tot_param_nbr); iax=find(triu(rand(tot_param_nbr,tot_param_nbr))); H2 = H2(:,iax); @@ -109,23 +109,23 @@ if kronflag==-1 % perturbation d2A(:,:) = H2(m1+1:m1+m1*m1,:); d2Om(:,:) = H2(m1+m1*m1+1:end,:); clear H2 -% tmp0=zeros(m1,m1); -% tmp0(iv,iv)=1; -% iax=find(tmp0); -% d2A=d2a(iax,:); -% iax=find(dyn_vech(tmp0)); -% d2Om=d2om(iax,:); + % tmp0=zeros(m1,m1); + % tmp0(iv,iv)=1; + % iax=find(tmp0); + % d2A=d2a(iax,:); + % iax=find(dyn_vech(tmp0)); + % d2Om=d2om(iax,:); end -% assignin('base','M_', M_); -% assignin('base','oo_', oo_); + % assignin('base','M_', M_); + % assignin('base','oo_', oo_); return end if kronflag==-2 if nargout>5 [residual, g1, g2 ] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', ... - M_.params, oo_.dr.ys, 1); + M_.params, oo_.dr.ys, 1); g22 = hessian_sparse('thet2tau',[M_.params(indx)],options_.gstep,estim_params_,M_, oo_, indx,[],-1); H2ss=full(g22(1:M_.endo_nbr,:)); H2ss = reshape(H2ss,[M_.endo_nbr param_nbr param_nbr]); @@ -145,132 +145,132 @@ if kronflag==-2 clear gx22; else [residual, g1 ] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', ... - M_.params, oo_.dr.ys, 1); + M_.params, oo_.dr.ys, 1); end gp = fjaco('thet2tau',[M_.params(indx)],estim_params_,M_, oo_, indx,[],-1); Hss=gp(1:M_.endo_nbr,:); gp=gp(M_.endo_nbr+1:end,:); gp = reshape(gp,[size(g1) param_nbr]); else -dyssdtheta=zeros(length(oo_.dr.ys),M_.param_nbr); -d2yssdtheta=zeros(length(oo_.dr.ys),M_.param_nbr,M_.param_nbr); -[residual, gg1] = feval([M_.fname,'_static'],oo_.dr.ys, oo_.exo_steady_state', M_.params); -df = feval([M_.fname,'_static_params_derivs'],oo_.dr.ys, repmat(oo_.exo_steady_state',[M_.maximum_exo_lag+M_.maximum_exo_lead+1]), ... - M_.params); -dyssdtheta = -gg1\df; -if nargout>5 - [residual, gg1, gg2] = feval([M_.fname,'_static'],oo_.dr.ys, oo_.exo_steady_state', M_.params); - [residual, g1, g2, g3] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', ... - M_.params, oo_.dr.ys, 1); - [nr, nc]=size(gg2); - - [df, gpx, d2f] = feval([M_.fname,'_static_params_derivs'],oo_.dr.ys, oo_.exo_steady_state', ... - M_.params);%, oo_.dr.ys, 1, dyssdtheta*0, d2yssdtheta); - d2f = get_all_resid_2nd_derivs(d2f,length(oo_.dr.ys),M_.param_nbr); - if isempty(find(gg2)) - for j=1:M_.param_nbr - d2yssdtheta(:,:,j) = -gg1\d2f(:,:,j); - end - else - gam = d2f*0; - for j=1:nr - tmp1 = (squeeze(gpx(j,:,:))'*dyssdtheta); - gam(j,:,:)=transpose(reshape(gg2(j,:),[nr nr])*dyssdtheta)*dyssdtheta ... - + tmp1 + tmp1'; - end - for j=1:M_.param_nbr - d2yssdtheta(:,:,j) = -gg1\(d2f(:,:,j)+gam(:,:,j)); + dyssdtheta=zeros(length(oo_.dr.ys),M_.param_nbr); + d2yssdtheta=zeros(length(oo_.dr.ys),M_.param_nbr,M_.param_nbr); + [residual, gg1] = feval([M_.fname,'_static'],oo_.dr.ys, oo_.exo_steady_state', M_.params); + df = feval([M_.fname,'_static_params_derivs'],oo_.dr.ys, repmat(oo_.exo_steady_state',[M_.maximum_exo_lag+M_.maximum_exo_lead+1]), ... + M_.params); + dyssdtheta = -gg1\df; + if nargout>5 + [residual, gg1, gg2] = feval([M_.fname,'_static'],oo_.dr.ys, oo_.exo_steady_state', M_.params); + [residual, g1, g2, g3] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', ... + M_.params, oo_.dr.ys, 1); + [nr, nc]=size(gg2); + + [df, gpx, d2f] = feval([M_.fname,'_static_params_derivs'],oo_.dr.ys, oo_.exo_steady_state', ... + M_.params);%, oo_.dr.ys, 1, dyssdtheta*0, d2yssdtheta); + d2f = get_all_resid_2nd_derivs(d2f,length(oo_.dr.ys),M_.param_nbr); + if isempty(find(gg2)) + for j=1:M_.param_nbr + d2yssdtheta(:,:,j) = -gg1\d2f(:,:,j); + end + else + gam = d2f*0; + for j=1:nr + tmp1 = (squeeze(gpx(j,:,:))'*dyssdtheta); + gam(j,:,:)=transpose(reshape(gg2(j,:),[nr nr])*dyssdtheta)*dyssdtheta ... + + tmp1 + tmp1'; + end + for j=1:M_.param_nbr + d2yssdtheta(:,:,j) = -gg1\(d2f(:,:,j)+gam(:,:,j)); + end + clear tmp1 gpx gam end - clear tmp1 gpx gam end -end -if any(any(isnan(dyssdtheta))) - [U,T] = schur(gg1); - qz_criterium=options_.qz_criterium; - e1 = abs(ordeig(T)) < qz_criterium-1; - k = sum(e1); % Number non stationary variables. -% n = length(e1)-k; % Number of stationary variables. - [U,T] = ordschur(U,T,e1); - T = T(k+1:end,k+1:end); - dyssdtheta = -U(:,k+1:end)*(T\U(:,k+1:end)')*df; - if nargout>5 - for j=1:length(indx) - d2yssdtheta(:,:,j) = -U(:,k+1:end)*(T\U(:,k+1:end)')*d2f(:,:,j); + if any(any(isnan(dyssdtheta))) + [U,T] = schur(gg1); + qz_criterium=options_.qz_criterium; + e1 = abs(ordeig(T)) < qz_criterium-1; + k = sum(e1); % Number non stationary variables. + % n = length(e1)-k; % Number of stationary variables. + [U,T] = ordschur(U,T,e1); + T = T(k+1:end,k+1:end); + dyssdtheta = -U(:,k+1:end)*(T\U(:,k+1:end)')*df; + if nargout>5 + for j=1:length(indx) + d2yssdtheta(:,:,j) = -U(:,k+1:end)*(T\U(:,k+1:end)')*d2f(:,:,j); + end end end -end -if nargout>5 - [df, gp, d2f, gpp, hp] = feval([M_.fname,'_params_derivs'],yy0, oo_.exo_steady_state', ... - M_.params, oo_.dr.ys, 1, dyssdtheta, d2yssdtheta); - H2ss = d2yssdtheta(oo_.dr.order_var,indx,indx); -else - [df, gp] = feval([M_.fname,'_params_derivs'],yy0, repmat(oo_.exo_steady_state',[M_.maximum_exo_lag+M_.maximum_exo_lead+1,1]), ... - M_.params, oo_.dr.ys, 1, dyssdtheta,d2yssdtheta); - [residual, g1, g2 ] = feval([M_.fname,'_dynamic'],yy0, repmat(oo_.exo_steady_state',[M_.maximum_exo_lag+M_.maximum_exo_lead+1,1]), ... - M_.params, oo_.dr.ys, 1); -end + if nargout>5 + [df, gp, d2f, gpp, hp] = feval([M_.fname,'_params_derivs'],yy0, oo_.exo_steady_state', ... + M_.params, oo_.dr.ys, 1, dyssdtheta, d2yssdtheta); + H2ss = d2yssdtheta(oo_.dr.order_var,indx,indx); + else + [df, gp] = feval([M_.fname,'_params_derivs'],yy0, repmat(oo_.exo_steady_state',[M_.maximum_exo_lag+M_.maximum_exo_lead+1,1]), ... + M_.params, oo_.dr.ys, 1, dyssdtheta,d2yssdtheta); + [residual, g1, g2 ] = feval([M_.fname,'_dynamic'],yy0, repmat(oo_.exo_steady_state',[M_.maximum_exo_lag+M_.maximum_exo_lead+1,1]), ... + M_.params, oo_.dr.ys, 1); + end -[nr, nc]=size(g2); -nc = sqrt(nc); -Hss = dyssdtheta(oo_.dr.order_var,indx); -dyssdtheta = dyssdtheta(I,:); -ns = max(max(M_.lead_lag_incidence)); % retrieve the number of states excluding columns for shocks -gp2 = gp*0; -for j=1:nr - [II JJ]=ind2sub([nc nc],find(g2(j,:))); - for i=1:nc - is = find(II==i); - is = is(find(JJ(is)<=ns)); - if ~isempty(is) - g20=full(g2(j,find(g2(j,:)))); - gp2(j,i,:)=g20(is)*dyssdtheta(JJ(is),:); + [nr, nc]=size(g2); + nc = sqrt(nc); + Hss = dyssdtheta(oo_.dr.order_var,indx); + dyssdtheta = dyssdtheta(I,:); + ns = max(max(M_.lead_lag_incidence)); % retrieve the number of states excluding columns for shocks + gp2 = gp*0; + for j=1:nr + [II JJ]=ind2sub([nc nc],find(g2(j,:))); + for i=1:nc + is = find(II==i); + is = is(find(JJ(is)<=ns)); + if ~isempty(is) + g20=full(g2(j,find(g2(j,:)))); + gp2(j,i,:)=g20(is)*dyssdtheta(JJ(is),:); + end end end -end -gp = gp+gp2; -gp = gp(:,:,indx); + gp = gp+gp2; + gp = gp(:,:,indx); -if nargout>5 -% h22 = get_all_hess_derivs(hp,nr,nc,M_.param_nbr); - g22 = gpp; - gp22 = sparse(nr*nc,param_nbr*param_nbr); - tmp1 = reshape(g3,[nr*nc*nc nc]); - tmp2=sparse(size(tmp1,1),M_.param_nbr); -% tmp2=tmp1*[dyssdtheta; zeros(nc-ns,M_.param_nbr)]; - tmpa=[dyssdtheta; zeros(nc-ns,M_.param_nbr)]; - tmpa=sparse(tmpa); - for j=1:M_.param_nbr - tmp2(:,j)=tmp1*tmpa(:,j); - end -% tmp2=sparse(tmp2); -% [i1 i2]=ind2sub([nc M_.param_nbr],[1:nc*M_.param_nbr]'); + if nargout>5 + % h22 = get_all_hess_derivs(hp,nr,nc,M_.param_nbr); + g22 = gpp; + gp22 = sparse(nr*nc,param_nbr*param_nbr); + tmp1 = reshape(g3,[nr*nc*nc nc]); + tmp2=sparse(size(tmp1,1),M_.param_nbr); + % tmp2=tmp1*[dyssdtheta; zeros(nc-ns,M_.param_nbr)]; + tmpa=[dyssdtheta; zeros(nc-ns,M_.param_nbr)]; + tmpa=sparse(tmpa); + for j=1:M_.param_nbr + tmp2(:,j)=tmp1*tmpa(:,j); + end + % tmp2=sparse(tmp2); + % [i1 i2]=ind2sub([nc M_.param_nbr],[1:nc*M_.param_nbr]'); - for j=1:nr - tmp0=reshape(g2(j,:),[nc nc]); - tmp0 = tmp0(:,1:ns)*reshape(d2yssdtheta(I,:,:),[ns,M_.param_nbr*M_.param_nbr]); - for i=1:nc - indo = sub2ind([nr nc nc], ones(nc,1)*j ,ones(nc,1)*i, (1:nc)'); - tmpx = (tmp2(indo,:))'*[dyssdtheta; zeros(nc-ns,M_.param_nbr)]; -% gp22(j,i,:,:)=squeeze(tmp1(j,i,:,:))'*[dyssdtheta; zeros(nc-ns,M_.param_nbr)]; - tmpu = (get_hess_deriv(hp,j,i,nc,M_.param_nbr))'*[dyssdtheta; zeros(nc-ns,M_.param_nbr)]; - tmpy = tmpx+tmpu+tmpu'+reshape(tmp0(i,:,:),[M_.param_nbr M_.param_nbr]); - tmpy = tmpy + get_2nd_deriv_mat(gpp,j,i,M_.param_nbr); - tmpy = tmpy(indx,indx); - if any(any(tmpy)) - ina = find(triu(tmpy)); - gp22(sub2ind([nr nc],j,i),ina)=transpose(tmpy(ina)); -% gp22(j,i,:,:)= reshape(tmpy,[1 1 M_.param_nbr M_.param_nbr]); + for j=1:nr + tmp0=reshape(g2(j,:),[nc nc]); + tmp0 = tmp0(:,1:ns)*reshape(d2yssdtheta(I,:,:),[ns,M_.param_nbr*M_.param_nbr]); + for i=1:nc + indo = sub2ind([nr nc nc], ones(nc,1)*j ,ones(nc,1)*i, (1:nc)'); + tmpx = (tmp2(indo,:))'*[dyssdtheta; zeros(nc-ns,M_.param_nbr)]; + % gp22(j,i,:,:)=squeeze(tmp1(j,i,:,:))'*[dyssdtheta; zeros(nc-ns,M_.param_nbr)]; + tmpu = (get_hess_deriv(hp,j,i,nc,M_.param_nbr))'*[dyssdtheta; zeros(nc-ns,M_.param_nbr)]; + tmpy = tmpx+tmpu+tmpu'+reshape(tmp0(i,:,:),[M_.param_nbr M_.param_nbr]); + tmpy = tmpy + get_2nd_deriv_mat(gpp,j,i,M_.param_nbr); + tmpy = tmpy(indx,indx); + if any(any(tmpy)) + ina = find(triu(tmpy)); + gp22(sub2ind([nr nc],j,i),ina)=transpose(tmpy(ina)); + % gp22(j,i,:,:)= reshape(tmpy,[1 1 M_.param_nbr M_.param_nbr]); + end end + % gp22(j,:,:,:)=gp22(j,:,:,:)+reshape(tmp0(:,1:ns)*d2yssdtheta(I,:,:),[1 nc M_.param_nbr M_.param_nbr]); end -% gp22(j,:,:,:)=gp22(j,:,:,:)+reshape(tmp0(:,1:ns)*d2yssdtheta(I,:,:),[1 nc M_.param_nbr M_.param_nbr]); - end -% g22 = g22+gp22; -% g22 = g22(:,:,indx,indx); - clear tmp0 tmp1 tmp2 tmpu tmpx tmpy + % g22 = g22+gp22; + % g22 = g22(:,:,indx,indx); + clear tmp0 tmp1 tmp2 tmpu tmpx tmpy inx=find(gp22); gx22=zeros(length(inx),5); for j=1:length(inx) @@ -282,7 +282,7 @@ if nargout>5 g22 = gx22; clear gx22 gp22; -end + end end @@ -463,13 +463,13 @@ else % generalized sylvester equation for j=1:length(indexo) dSig(indexo(j),indexo(j),j) = 2*sqrt(M_.Sigma_e(indexo(j),indexo(j))); y = B*dSig(:,:,j)*B'; -% y = y(nauxe+1:end,nauxe+1:end); -% H(:,j) = [zeros((m-nauxe)^2,1); dyn_vech(y)]; + % y = y(nauxe+1:end,nauxe+1:end); + % H(:,j) = [zeros((m-nauxe)^2,1); dyn_vech(y)]; H(:,j) = [zeros(m1^2,1); dyn_vech(y(iv,iv))]; if nargout>1 dOm(:,:,j) = y(iv,iv); end -% dSig(indexo(j),indexo(j)) = 0; + % dSig(indexo(j),indexo(j)) = 0; end end for j=1:param_nbr @@ -479,8 +479,8 @@ else % generalized sylvester equation dB(:,:,j) = y; end 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); + % x = x(nauxe+1:end,nauxe+1:end); + % y = y(nauxe+1:end,nauxe+1:end); if nargout>1 dA(:,:,j+length(indexo)) = x(iv,iv); dOm(:,:,j+length(indexo)) = y(iv,iv); @@ -521,7 +521,7 @@ if nargout > 5 cumjcount=0; jinx = []; x2x=sparse(m*m,param_nbr_2); -% x2x=[]; + % x2x=[]; for i=1:param_nbr for j=1:i elem1 = (get_2nd_deriv(D2g0,m,m,j,i)-get_2nd_deriv(D2g1,m,m,j,i)*A); @@ -538,7 +538,7 @@ if nargout > 5 if (j*i)==param_nbr^2 d = d(:,:,1:jcount); end -% d(find(abs(d)<1.e-12))=0; + % d(find(abs(d)<1.e-12))=0; xx2=sylvester3(a,b,c,d); flag=1; icount=0; @@ -546,12 +546,12 @@ if nargout > 5 [xx2, flag]=sylvester3a(xx2,a,b,c,d); icount = icount + 1; end -% inx = find(abs(xx2)>1.e-12); -% xx2(find(abs(xx2)<1.e-12))=0; + % inx = find(abs(xx2)>1.e-12); + % xx2(find(abs(xx2)<1.e-12))=0; x2x(:,cumjcount+1:cumjcount+jcount)=reshape(xx2,[m*m jcount]); cumjcount=cumjcount+jcount; -% [i1 i2 i3]=ind2sub(size(xx2),inx); -% x2x = [x2x; [i1 i2 jinx(i3,:) xx2(inx)]]; + % [i1 i2 i3]=ind2sub(size(xx2),inx); + % x2x = [x2x; [i1 i2 jinx(i3,:) xx2(inx)]]; jcount = 0; jinx = []; end @@ -579,7 +579,7 @@ if nargout > 5 if i==j d2Sig(indexo(j),indexo(j),j) = 2; y = B*d2Sig(:,:,j)*B'; -% y(abs(y)<1.e-8)=0; + % y(abs(y)<1.e-8)=0; d2Om_tmp(:,jcount) = dyn_vech(y(iv,iv)); end else @@ -587,12 +587,12 @@ if nargout > 5 iind = i-offset; if i<=offset y = dB(:,:,jind)*dSig(:,:,i)*B'+B*dSig(:,:,i)*dB(:,:,jind)'; -% y(abs(y)<1.e-8)=0; + % y(abs(y)<1.e-8)=0; d2Om_tmp(:,jcount) = dyn_vech(y(iv,iv)); else icount=icount+1; x = reshape(x2x(:,icount),[m m]); -% x = get_2nd_deriv(x2x,m,m,iind,jind);%xx2(:,:,jcount); + % x = get_2nd_deriv(x2x,m,m,iind,jind);%xx2(:,:,jcount); elem1 = (get_2nd_deriv(D2g0,m,m,iind,jind)-get_2nd_deriv(D2g1,m,m,iind,jind)*A); elem1 = elem1 -( Dg1(:,:,jind)*xx(:,:,iind) + Dg1(:,:,iind)*xx(:,:,jind) ); elemj0 = Dg0(:,:,jind)-Dg1(:,:,jind)*A-GAM1*xx(:,:,jind); @@ -603,9 +603,9 @@ if nargout > 5 % d2B(:,:,i+length(indexo),j+length(indexo)) = y; y = y*M_.Sigma_e*B'+B*M_.Sigma_e*y'+ ... dB(:,:,jind)*M_.Sigma_e*dB(:,:,iind)'+dB(:,:,iind)*M_.Sigma_e*dB(:,:,jind)'; -% x(abs(x)<1.e-8)=0; + % x(abs(x)<1.e-8)=0; d2A_tmp(:,jcount) = vec(x(iv,iv)); -% y(abs(y)<1.e-8)=0; + % y(abs(y)<1.e-8)=0; d2Om_tmp(:,jcount) = dyn_vech(y(iv,iv)); end end @@ -624,7 +624,7 @@ if nargout > 5 % d2Om = sparse(m1*(m1+1)/2,tot_param_nbr*(tot_param_nbr+1)/2); d2A_tmp = zeros(m1*m1,ncol); d2Om_tmp = zeros(m1*(m1+1)/2,ncol); - + end end end @@ -663,23 +663,23 @@ end if fsparse g22=sparse(m*n,npar*npar); else -g22=zeros(m,n,npar,npar); + g22=zeros(m,n,npar,npar); end % c=ones(npar,npar); % c=triu(c); % ic=find(c); for is=1:length(gpp) -% d=zeros(npar,npar); -% d(gpp(is,3),gpp(is,4))=1; -% indx = find(ic==find(d)); + % d=zeros(npar,npar); + % d(gpp(is,3),gpp(is,4))=1; + % indx = find(ic==find(d)); if fsparse g22(sub2ind([m,n],gpp(is,1),gpp(is,2)),sub2ind([npar,npar],gpp(is,3),gpp(is,4)))=gpp(is,5); g22(sub2ind([m,n],gpp(is,1),gpp(is,2)),sub2ind([npar,npar],gpp(is,4),gpp(is,3)))=gpp(is,5); else - g22(gpp(is,1),gpp(is,2),gpp(is,3),gpp(is,4))=gpp(is,5); - g22(gpp(is,1),gpp(is,2),gpp(is,4),gpp(is,3))=gpp(is,5); -end + g22(gpp(is,1),gpp(is,2),gpp(is,3),gpp(is,4))=gpp(is,5); + g22(gpp(is,1),gpp(is,2),gpp(is,4),gpp(is,3))=gpp(is,5); + end end return @@ -692,9 +692,9 @@ r22=zeros(m,npar,npar); % ic=find(c); for is=1:length(rpp) -% d=zeros(npar,npar); -% d(rpp(is,2),rpp(is,3))=1; -% indx = find(ic==find(d)); + % d=zeros(npar,npar); + % d(rpp(is,2),rpp(is,3))=1; + % indx = find(ic==find(d)); r22(rpp(is,1),rpp(is,2),rpp(is,3))=rpp(is,4); r22(rpp(is,1),rpp(is,3),rpp(is,2))=rpp(is,4); end diff --git a/matlab/getIrfShocksIndx.m b/matlab/getIrfShocksIndx.m index 737bfcfb1d..3325a2dfca 100644 --- a/matlab/getIrfShocksIndx.m +++ b/matlab/getIrfShocksIndx.m @@ -34,7 +34,7 @@ else for i=1:size(options_.irf_shocks,1) irf_shocks_indx(i) = find(strcmp(deblank(options_.irf_shocks(i,:)), cellstr(M_.exo_names))); end - irf_shocks_indx_unique=unique(irf_shocks_indx); + irf_shocks_indx_unique=unique(irf_shocks_indx); if options_.debug && (length(irf_shocks_indx_unique) ~= length(irf_shocks_indx)) fprintf('\nSTOCH_SIMUL: Warning: The IRFs for some shocks have been requested twice.\n') fprintf('STOCH_SIMUL: The redundant entries will be ignored.\n') diff --git a/matlab/getJJ.m b/matlab/getJJ.m index c9dfe41ed0..7f934b81ae 100644 --- a/matlab/getJJ.m +++ b/matlab/getJJ.m @@ -2,7 +2,7 @@ function [JJ, H, gam, gp, dA, dOm, dYss] = getJJ(A, B, estim_params_, M_,oo_,opt % function [JJ, H, gam, gp, dA, dOm, dYss] = getJJ(A, B, estim_params_, M_,oo_,options_,kronflag,indx,indexo,mf,nlags,useautocorr) % computes derivatives of 1st and 2nd order moments of observables with % respect to estimated parameters -% +% % Inputs: % A: Transition matrix of lagged states from Kalman filter % B: Matrix in state transition equation mapping shocks today to @@ -19,21 +19,21 @@ function [JJ, H, gam, gp, dA, dOm, dYss] = getJJ(A, B, estim_params_, M_,oo_,opt % correlations % useautocorr: Indicator on whether to use correlations (1) instead of % covariances (0) -% +% % Outputs: -% JJ: Jacobian of 1st and 2nd order moments of observables, i.e. dgam/dTHETA +% JJ: Jacobian of 1st and 2nd order moments of observables, i.e. dgam/dTHETA % (see below for definition of gam) % H: dTAU/dTHETA: Jacobian of TAU, vectorized form of % linearized reduced form state space model, given ys [steady state], % A [transition matrix], B [matrix of shocks], Sigma [covariance of shocks] % TAU = [ys; vec(A); dyn_vech(B*Sigma*B')]. -% gam: vector of theoretical moments of observed variables mf [JJ is the Jacobian of gam]. -% gam = [ys(mf); dyn_vech(GAM{1}); vec(GAM{j+1})]; for j=1:ar and where +% gam: vector of theoretical moments of observed variables mf [JJ is the Jacobian of gam]. +% gam = [ys(mf); dyn_vech(GAM{1}); vec(GAM{j+1})]; for j=1:ar and where % GAM is the first output of th_autocovariances % gp: Jacobian of linear rational expectation matrices [i.e. % Jacobian of dynamic model] with respect to estimated % structural parameters only (indx) -% dA: [endo_nbr by endo_nbr by (indx+indexo)] Jacobian of transition matrix A +% dA: [endo_nbr by endo_nbr by (indx+indexo)] Jacobian of transition matrix A % dOm: Jacobian of Omega = (B*Sigma*B') % dYss Jacobian of steady state with respect to estimated structural parameters only (indx) @@ -55,16 +55,16 @@ function [JJ, H, gam, gp, dA, dOm, dYss] = getJJ(A, B, estim_params_, M_,oo_,opt % along with Dynare. If not, see <http://www.gnu.org/licenses/>. if nargin<8 || isempty(indx) -% indx = [1:M_.param_nbr]; + % indx = [1:M_.param_nbr]; end if nargin<9 || isempty(indexo) indexo = []; end if nargin<11 || isempty(nlags) - nlags=3; + nlags=3; end if nargin<12 || isempty(useautocorr) - useautocorr=0; + useautocorr=0; end % if useautocorr, @@ -109,7 +109,7 @@ else 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); @@ -167,9 +167,9 @@ else end JJ(:,j+nexo) = dumm; end - + JJ = [ [zeros(length(mf),nexo) dYss(mf,:)]; JJ]; - + end if nargout >2 % sy=sy(mf,mf); diff --git a/matlab/get_Hessian.m b/matlab/get_Hessian.m index a878ad1117..fe74848dd6 100644 --- a/matlab/get_Hessian.m +++ b/matlab/get_Hessian.m @@ -28,146 +28,146 @@ function [Hess] = get_Hessian(T,R,Q,H,P,Y,DT,DYss,DOm,DH,DP,D2T,D2Yss,D2Om,D2H,D % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - k = size(DT,3); % number of structural parameters - smpl = size(Y,2); % Sample size. - pp = size(Y,1); % Maximum number of observed variables. - mm = size(T,2); % Number of state variables. - a = zeros(mm,1); % State vector. - Om = R*Q*transpose(R); % Variance of R times the vector of structural innovations. - t = 0; % Initialization of the time index. - oldK = 0; - notsteady = 1; % Steady state flag. - F_singular = 1; - - Hess = zeros(k,k); % Initialization of the Hessian - Da = zeros(mm,k); % State vector. - Dv = zeros(length(mf),k); - D2a = zeros(mm,k,k); % State vector. - D2v = zeros(length(mf),k,k); - - C = zeros(length(mf),mm); - for ii=1:length(mf); C(ii,mf(ii))=1;end % SELECTION MATRIX IN MEASUREMENT EQ. (FOR WHEN IT IS NOT CONSTANT) - dC = zeros(length(mf),mm,k); - d2C = zeros(length(mf),mm,k,k); - - s = zeros(pp,1); % CONSTANT TERM IN MEASUREMENT EQ. (FOR WHEN IT IS NOT CONSTANT) - ds = zeros(pp,1,k); - d2s = zeros(pp,1,k,k); - +k = size(DT,3); % number of structural parameters +smpl = size(Y,2); % Sample size. +pp = size(Y,1); % Maximum number of observed variables. +mm = size(T,2); % Number of state variables. +a = zeros(mm,1); % State vector. +Om = R*Q*transpose(R); % Variance of R times the vector of structural innovations. +t = 0; % Initialization of the time index. +oldK = 0; +notsteady = 1; % Steady state flag. +F_singular = 1; + +Hess = zeros(k,k); % Initialization of the Hessian +Da = zeros(mm,k); % State vector. +Dv = zeros(length(mf),k); +D2a = zeros(mm,k,k); % State vector. +D2v = zeros(length(mf),k,k); + +C = zeros(length(mf),mm); +for ii=1:length(mf); C(ii,mf(ii))=1;end % SELECTION MATRIX IN MEASUREMENT EQ. (FOR WHEN IT IS NOT CONSTANT) +dC = zeros(length(mf),mm,k); +d2C = zeros(length(mf),mm,k,k); + +s = zeros(pp,1); % CONSTANT TERM IN MEASUREMENT EQ. (FOR WHEN IT IS NOT CONSTANT) +ds = zeros(pp,1,k); +d2s = zeros(pp,1,k,k); + % for ii = 1:k -% DOm = DR(:,:,ii)*Q*transpose(R) + R*DQ(:,:,ii)*transpose(R) + R*Q*transpose(DR(:,:,ii)); +% DOm = DR(:,:,ii)*Q*transpose(R) + R*DQ(:,:,ii)*transpose(R) + R*Q*transpose(DR(:,:,ii)); % 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 - a = T*a; - P = T*P*transpose(T)+Om; - 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; - iF = inv(F); - K = P(:,mf)*iF; - - [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K); - [D2K,D2F,D2P1] = computeD2Kalman(T,DT,D2T,D2Om,P,DP,D2P,DH,mf,iF,K,DK); - tmp = (a+K*v); - - for ii = 1:k - Dv(:,ii) = -Da(mf,ii) - DYss(mf,ii); - % dai = da(:,:,ii); - dKi = DK(:,:,ii); - diFi = -iF*DF(:,:,ii)*iF; - dtmpi = Da(:,ii)+dKi*v+K*Dv(:,ii); - - - for jj = 1:ii - dFj = DF(:,:,jj); - diFj = -iF*DF(:,:,jj)*iF; - dKj = DK(:,:,jj); - d2Kij = D2K(:,:,jj,ii); - d2Fij = D2F(:,:,jj,ii); - d2iFij = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi; - dtmpj = Da(:,jj)+dKj*v+K*Dv(:,jj); - - d2vij = -D2Yss(mf,jj,ii) - D2a(mf,jj,ii); - d2tmpij = D2a(:,jj,ii) + d2Kij*v + dKj*Dv(:,ii) + dKi*Dv(:,jj) + K*d2vij; - D2a(:,jj,ii) = D2T(:,:,jj,ii)*tmp + DT(:,:,jj)*dtmpi + DT(:,:,ii)*dtmpj + T*d2tmpij; - - Hesst(ii,jj) = getHesst_ij(v,Dv(:,ii),Dv(:,jj),d2vij,iF,diFi,diFj,d2iFij,dFj,d2Fij); + a = T*a; + P = T*P*transpose(T)+Om; end - Da(:,ii) = DT(:,:,ii)*tmp + T*dtmpi; - end -% vecDPmf = reshape(DP(mf,mf,:),[],k); -% iPmf = inv(P(mf,mf)); - if t>=start - Hess = Hess + Hesst; - end - a = T*(a+K*v); - P = T*(P-K*P(mf,:))*transpose(T)+Om; - DP = DP1; - D2P = D2P1; + else + F_singular = 0; + iF = inv(F); + K = P(:,mf)*iF; + + [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K); + [D2K,D2F,D2P1] = computeD2Kalman(T,DT,D2T,D2Om,P,DP,D2P,DH,mf,iF,K,DK); + tmp = (a+K*v); + + for ii = 1:k + Dv(:,ii) = -Da(mf,ii) - DYss(mf,ii); + % dai = da(:,:,ii); + dKi = DK(:,:,ii); + diFi = -iF*DF(:,:,ii)*iF; + dtmpi = Da(:,ii)+dKi*v+K*Dv(:,ii); + + + for jj = 1:ii + dFj = DF(:,:,jj); + diFj = -iF*DF(:,:,jj)*iF; + dKj = DK(:,:,jj); + d2Kij = D2K(:,:,jj,ii); + d2Fij = D2F(:,:,jj,ii); + d2iFij = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi; + dtmpj = Da(:,jj)+dKj*v+K*Dv(:,jj); + + d2vij = -D2Yss(mf,jj,ii) - D2a(mf,jj,ii); + d2tmpij = D2a(:,jj,ii) + d2Kij*v + dKj*Dv(:,ii) + dKi*Dv(:,jj) + K*d2vij; + D2a(:,jj,ii) = D2T(:,:,jj,ii)*tmp + DT(:,:,jj)*dtmpi + DT(:,:,ii)*dtmpj + T*d2tmpij; + + Hesst(ii,jj) = getHesst_ij(v,Dv(:,ii),Dv(:,jj),d2vij,iF,diFi,diFj,d2iFij,dFj,d2Fij); + end + Da(:,ii) = DT(:,:,ii)*tmp + T*dtmpi; + end + % vecDPmf = reshape(DP(mf,mf,:),[],k); + % iPmf = inv(P(mf,mf)); + if t>=start + Hess = Hess + Hesst; end - notsteady = max(max(abs(K-oldK))) > riccati_tol; - oldK = K; + a = T*(a+K*v); + P = T*(P-K*P(mf,:))*transpose(T)+Om; + DP = DP1; + D2P = D2P1; 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') - 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+1; - while t < smpl - t = t+1; - v = Y(:,t)-a(mf); - tmp = (a+K*v); - for ii = 1:k - Dv(:,ii) = -Da(mf,ii)-DYss(mf,ii); - dKi = DK(:,:,ii); - diFi = -iF*DF(:,:,ii)*iF; - dtmpi = Da(:,ii)+dKi*v+K*Dv(:,ii); - - for jj = 1:ii - dFj = DF(:,:,jj); - diFj = -iF*DF(:,:,jj)*iF; - dKj = DK(:,:,jj); - d2Kij = D2K(:,:,jj,ii); - d2Fij = D2F(:,:,jj,ii); - d2iFij = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi; - dtmpj = Da(:,jj)+dKj*v+K*Dv(:,jj); - - d2vij = -D2Yss(mf,jj,ii) - D2a(mf,jj,ii); - d2tmpij = D2a(:,jj,ii) + d2Kij*v + dKj*Dv(:,ii) + dKi*Dv(:,jj) + K*d2vij; - D2a(:,jj,ii) = D2T(:,:,jj,ii)*tmp + DT(:,:,jj)*dtmpi + DT(:,:,ii)*dtmpj + T*d2tmpij; - - Hesst(ii,jj) = getHesst_ij(v,Dv(:,ii),Dv(:,jj),d2vij,iF,diFi,diFj,d2iFij,dFj,d2Fij); - end - Da(:,ii) = DT(:,:,ii)*tmp + T*dtmpi; - end - if t>=start - Hess = Hess + Hesst; + +if t < smpl + t0 = t+1; + while t < smpl + t = t+1; + v = Y(:,t)-a(mf); + tmp = (a+K*v); + for ii = 1:k + Dv(:,ii) = -Da(mf,ii)-DYss(mf,ii); + dKi = DK(:,:,ii); + diFi = -iF*DF(:,:,ii)*iF; + dtmpi = Da(:,ii)+dKi*v+K*Dv(:,ii); + + for jj = 1:ii + dFj = DF(:,:,jj); + diFj = -iF*DF(:,:,jj)*iF; + dKj = DK(:,:,jj); + d2Kij = D2K(:,:,jj,ii); + d2Fij = D2F(:,:,jj,ii); + d2iFij = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi; + dtmpj = Da(:,jj)+dKj*v+K*Dv(:,jj); + + d2vij = -D2Yss(mf,jj,ii) - D2a(mf,jj,ii); + d2tmpij = D2a(:,jj,ii) + d2Kij*v + dKj*Dv(:,ii) + dKi*Dv(:,jj) + K*d2vij; + D2a(:,jj,ii) = D2T(:,:,jj,ii)*tmp + DT(:,:,jj)*dtmpi + DT(:,:,ii)*dtmpj + T*d2tmpij; + + Hesst(ii,jj) = getHesst_ij(v,Dv(:,ii),Dv(:,jj),d2vij,iF,diFi,diFj,d2iFij,dFj,d2Fij); end - a = T*(a+K*v); + Da(:,ii) = DT(:,:,ii)*tmp + T*dtmpi; + end + if t>=start + Hess = Hess + Hesst; end -% Hess = Hess + .5*(smpl+t0-1)*(vecDPmf' * kron(iPmf,iPmf) * vecDPmf); - % for ii = 1:k; - % for jj = 1:ii - % H(ii,jj) = trace(iPmf*(.5*DP(mf,mf,ii)*iPmf*DP(mf,mf,jj) + Dv(:,ii)*Dv(:,jj)')); - % end - % end + a = T*(a+K*v); end - + % Hess = Hess + .5*(smpl+t0-1)*(vecDPmf' * kron(iPmf,iPmf) * vecDPmf); + % for ii = 1:k; + % for jj = 1:ii + % H(ii,jj) = trace(iPmf*(.5*DP(mf,mf,ii)*iPmf*DP(mf,mf,jj) + Dv(:,ii)*Dv(:,jj)')); + % end + % end +end + Hess = Hess + tril(Hess,-1)'; -Hess = -Hess/2; -% end of main function +Hess = -Hess/2; +% end of main function function Hesst_ij = getHesst_ij(e,dei,dej,d2eij,iS,diSi,diSj,d2iSij,dSj,d2Sij); % computes (i,j) term in the Hessian @@ -178,11 +178,11 @@ Hesst_ij = trace(diSi*dSj + iS*d2Sij) + e'*d2iSij*e + 2*(dei'*diSj*e + dei'*iS*d function [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K) - k = size(DT,3); - tmp = P-K*P(mf,:); +k = size(DT,3); +tmp = P-K*P(mf,:); for ii = 1:k - DF(:,:,ii) = DP(mf,mf,ii) + DH(:,:,ii); + DF(:,:,ii) = DP(mf,mf,ii) + DH(:,:,ii); DiF(:,:,ii) = -iF*DF(:,:,ii)*iF; DK(:,:,ii) = DP(:,mf,ii)*iF + P(:,mf)*DiF(:,:,ii); Dtmp = DP(:,:,ii) - DK(:,:,ii)*P(mf,:) - K*DP(mf,:,ii); @@ -194,9 +194,9 @@ end function [d2K,d2S,d2P1] = computeD2Kalman(A,dA,d2A,d2Om,P0,dP0,d2P0,DH,mf,iF,K0,dK0) % computes the second derivatives of the Kalman matrices % note: A=T in main func. - - k = size(dA,3); - tmp = P0-K0*P0(mf,:); + +k = size(dA,3); +tmp = P0-K0*P0(mf,:); [ns,no] = size(K0); % CPC = C*P0*C'; CPC = .5*(CPC+CPC');iF = inv(CPC); @@ -225,34 +225,31 @@ for ii = 1:k d2Aij = d2A(:,:,jj,ii); d2Pij = d2P0(:,:,jj,ii); d2Omij = d2Om(:,:,jj,ii); - - % second order - - d2Fij = d2Pij(mf,mf) ; - -% d2APC = d2Aij*P0*C' + A*d2Pij*C' + A*P0*d2Cij' + dAi*dPj*C' + dAj*dPi*C' + A*dPj*dCi' + A*dPi*dCj' + dAi*P0*dCj' + dAj*P0*dCi'; - d2APC = d2Pij(:,mf); - - d2iF = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi; - - d2Kij= d2Pij(:,mf)*iF + P0(:,mf)*d2iF + dP0(:,mf,jj)*diFi + dP0(:,mf,ii)*diFj; - - d2KCP = d2Kij*P0(mf,:) + K0*d2Pij(mf,:) + dKi*dP0(mf,:,jj) + dKj*dP0(mf,:,ii) ; - - dtmpi = dP0(:,:,ii) - dK0(:,:,ii)*P0(mf,:) - K0*dP0(mf,:,ii); - dtmpj = dP0(:,:,jj) - dK0(:,:,jj)*P0(mf,:) - K0*dP0(mf,:,jj); - d2tmp = d2Pij - d2KCP; - - d2AtmpA = d2Aij*tmp*A' + A*d2tmp*A' + A*tmp*d2Aij' + dAi*dtmpj*A' + dAj*dtmpi*A' + A*dtmpj*dAi' + A*dtmpi*dAj' + dAi*tmp*dAj' + dAj*tmp*dAi'; - - d2K(:,:,ii,jj) = d2Kij; %#ok<NASGU> - d2P1(:,:,ii,jj) = d2AtmpA + d2Omij; %#ok<*NASGU> - d2S(:,:,ii,jj) = d2Fij; -% d2iS(:,:,ii,jj) = d2iF; + + % second order + + d2Fij = d2Pij(mf,mf) ; + + % d2APC = d2Aij*P0*C' + A*d2Pij*C' + A*P0*d2Cij' + dAi*dPj*C' + dAj*dPi*C' + A*dPj*dCi' + A*dPi*dCj' + dAi*P0*dCj' + dAj*P0*dCi'; + d2APC = d2Pij(:,mf); + + d2iF = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi; + + d2Kij= d2Pij(:,mf)*iF + P0(:,mf)*d2iF + dP0(:,mf,jj)*diFi + dP0(:,mf,ii)*diFj; + + d2KCP = d2Kij*P0(mf,:) + K0*d2Pij(mf,:) + dKi*dP0(mf,:,jj) + dKj*dP0(mf,:,ii) ; + + dtmpi = dP0(:,:,ii) - dK0(:,:,ii)*P0(mf,:) - K0*dP0(mf,:,ii); + dtmpj = dP0(:,:,jj) - dK0(:,:,jj)*P0(mf,:) - K0*dP0(mf,:,jj); + d2tmp = d2Pij - d2KCP; + + d2AtmpA = d2Aij*tmp*A' + A*d2tmp*A' + A*tmp*d2Aij' + dAi*dtmpj*A' + dAj*dtmpi*A' + A*dtmpj*dAi' + A*dtmpi*dAj' + dAi*tmp*dAj' + dAj*tmp*dAi'; + + d2K(:,:,ii,jj) = d2Kij; %#ok<NASGU> + d2P1(:,:,ii,jj) = d2AtmpA + d2Omij; %#ok<*NASGU> + d2S(:,:,ii,jj) = d2Fij; + % d2iS(:,:,ii,jj) = d2iF; end end % end of computeD2Kalman - - - \ No newline at end of file diff --git a/matlab/get_all_parameters.m b/matlab/get_all_parameters.m index 93bc56f235..8857d66737 100644 --- a/matlab/get_all_parameters.m +++ b/matlab/get_all_parameters.m @@ -4,14 +4,14 @@ function xparam1=get_all_parameters(estim_params_,M_) % gets parameters values from M_.params into xparam1 (inverse mapping to set_all_parameters) % This is called if a model was calibrated before estimation to back out % parameter values -% +% % INPUTS -% estim_params_: Dynare structure describing the estimated parameters. -% M_: Dynare structure describing the model. +% estim_params_: Dynare structure describing the estimated parameters. +% M_: Dynare structure describing the model. % % OUTPUTS % xparam1: N*1 double vector of parameters from calibrated model that are to be estimated -% +% % SPECIAL REQUIREMENTS % none @@ -100,5 +100,5 @@ offset = nvx+ncx+nvn+ncn; % structural parameters if np - xparam1(offset+1:end)=M_.params(estim_params_.param_vals(:,1)); + xparam1(offset+1:end)=M_.params(estim_params_.param_vals(:,1)); end \ No newline at end of file diff --git a/matlab/get_dynare_random_generator_state.m b/matlab/get_dynare_random_generator_state.m index 513919c220..f5702e7043 100644 --- a/matlab/get_dynare_random_generator_state.m +++ b/matlab/get_dynare_random_generator_state.m @@ -1,8 +1,8 @@ function [state_u,state_n] = get_dynare_random_generator_state() % Get state of Matlab/Octave random generator depending on matlab -% (octave) version. +% (octave) version. % In older versions, Matlab kept one generator for uniformly distributed numbers and -% one for normally distributed numbers. +% one for normally distributed numbers. % For backward compatibility, we return two vectors, but, in recent % versions of Matlab and in Octave, we return two identical vectors. @@ -23,22 +23,22 @@ function [state_u,state_n] = get_dynare_random_generator_state() % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - matlab_random_streams = ~(isoctave || matlab_ver_less_than('7.7')); +matlab_random_streams = ~(isoctave || matlab_ver_less_than('7.7')); - if matlab_random_streams% Use new matlab interface. - if matlab_ver_less_than('7.12') - s = RandStream.getDefaultStream(); - else - s = RandStream.getGlobalStream(); - end - if isequal(s.Type,'legacy') - state_u = rand('state'); - state_n = randn('state'); - else - state_u = s.State; - state_n = state_u; - end - else% Use old matlab interface. +if matlab_random_streams% Use new matlab interface. + if matlab_ver_less_than('7.12') + s = RandStream.getDefaultStream(); + else + s = RandStream.getGlobalStream(); + end + if isequal(s.Type,'legacy') state_u = rand('state'); state_n = randn('state'); - end \ No newline at end of file + else + state_u = s.State; + state_n = state_u; + end +else% Use old matlab interface. + state_u = rand('state'); + state_n = randn('state'); +end \ No newline at end of file diff --git a/matlab/get_file_extension.m b/matlab/get_file_extension.m index d922b36ac5..b4fe5a2ade 100644 --- a/matlab/get_file_extension.m +++ b/matlab/get_file_extension.m @@ -2,15 +2,15 @@ function ext = get_file_extension(file) % returns the extension of a file. % -% INPUTS +% INPUTS % o file string, name of the file % -% OUTPUTS +% OUTPUTS % o ext string, extension. % -% REMARKS +% REMARKS % If the provided file name has no extension, the routine will return an empty array. - + % Copyright (C) 2013-2015 Dynare Team % % This file is part of Dynare. diff --git a/matlab/get_moments_size.m b/matlab/get_moments_size.m index aa8087c025..a036d1e9c3 100644 --- a/matlab/get_moments_size.m +++ b/matlab/get_moments_size.m @@ -4,10 +4,10 @@ function s=get_moments_size(options) % % INPUTS % options: structure of Dynare options -% +% % OUTPUTS % s: size of moments for a given model and options -% +% % SPECIAL REQUIREMENTS % none diff --git a/matlab/get_name_of_the_last_mh_file.m b/matlab/get_name_of_the_last_mh_file.m index 7634351251..357c7f88a7 100644 --- a/matlab/get_name_of_the_last_mh_file.m +++ b/matlab/get_name_of_the_last_mh_file.m @@ -1,14 +1,14 @@ function [mhname,info] = get_name_of_the_last_mh_file(M_) % This function returns the name of the last mh file and test if the metropolis was completed. % -% INPUTS -% M_ [structure] Dynare structure specifying the model. +% INPUTS +% M_ [structure] Dynare structure specifying the model. % -% OUTPUTS -% mhname [string] Name of the last mh file (with complete path). +% OUTPUTS +% mhname [string] Name of the last mh file (with complete path). % info [integer] Scalar. If info is equal to 1 then the predicted name of the last -% 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 +% 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-2013 Dynare Team diff --git a/matlab/get_optimal_policy_discount_factor.m b/matlab/get_optimal_policy_discount_factor.m index 67931b8ab1..61a418636b 100644 --- a/matlab/get_optimal_policy_discount_factor.m +++ b/matlab/get_optimal_policy_discount_factor.m @@ -2,11 +2,11 @@ function discount_factor=get_optimal_policy_discount_factor(params,param_names) %function discount_factor=get_optimal_policy_discount_factor(M) % get the value of Ramsey policy discount factor -% +% % INPUTS -% params: (vector) value of parameters +% params: (vector) value of parameters % param_names: (char array) list of parameter names -% +% % OUTPUTS % discount_factor (double) discount factor % @@ -30,4 +30,4 @@ function discount_factor=get_optimal_policy_discount_factor(params,param_names) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - discount_factor = params(find(strcmp('optimal_policy_discount_factor',cellstr(param_names)))); +discount_factor = params(find(strcmp('optimal_policy_discount_factor',cellstr(param_names)))); diff --git a/matlab/get_param_by_name.m b/matlab/get_param_by_name.m index 795ac88dff..1e5b907187 100644 --- a/matlab/get_param_by_name.m +++ b/matlab/get_param_by_name.m @@ -1,7 +1,7 @@ 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 % diff --git a/matlab/get_posterior_parameters.m b/matlab/get_posterior_parameters.m index 495f365657..3561f6f246 100644 --- a/matlab/get_posterior_parameters.m +++ b/matlab/get_posterior_parameters.m @@ -2,13 +2,13 @@ function xparam = get_posterior_parameters(type,field1) % function xparam = get_posterior_parameters(type) % Selects (estimated) parameters (posterior mode or posterior mean). -% -% INPUTS +% +% INPUTS % o type [char] = 'mode' or 'mean'. % o field_1 [char] optional field like 'mle_'. -% -% OUTPUTS -% o xparam vector of estimated parameters +% +% OUTPUTS +% o xparam vector of estimated parameters % % SPECIAL REQUIREMENTS % None. @@ -30,7 +30,7 @@ function xparam = get_posterior_parameters(type,field1) % 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_ +global estim_params_ oo_ options_ M_ if nargin<2 field1='posterior_'; diff --git a/matlab/get_subsamples_range_indx.m b/matlab/get_subsamples_range_indx.m index 1d114c6869..cb9b971f5d 100644 --- a/matlab/get_subsamples_range_indx.m +++ b/matlab/get_subsamples_range_indx.m @@ -39,5 +39,5 @@ range_indx = find(strcmp(range_label, estimation_info.subsamples(subsamples_indx if size(range_indx,2) ~= 1 error(['Error: Index not found in estimation_info.subsamples(' ... - num2str(subsamples_indx) ').range_index for label ' range_label]); + num2str(subsamples_indx) ').range_index for label ' range_label]); end diff --git a/matlab/get_variables_list.m b/matlab/get_variables_list.m index e4a3592259..966ebf7698 100644 --- a/matlab/get_variables_list.m +++ b/matlab/get_variables_list.m @@ -1,17 +1,17 @@ function [ivar,vartan,options_] = get_variables_list(options_,M_) % This function builds a vector of indices in varlist or varobs. -% -% INPUTS -% o options_ [structure] Describes global options. +% +% INPUTS +% o options_ [structure] Describes global options. % o M_ [structure] Describes the model. -% OUTPUTS +% OUTPUTS % o ivar [integer] nvar*1 vector of indices (nvar is the number % of variables). % o vartan [char] array of characters (with nvar rows). % o options_ [structure] Describes global options. -% -% ALGORITHM -% None. +% +% ALGORITHM +% None. % % SPECIAL REQUIREMENTS % None. diff --git a/matlab/get_variance_of_endogenous_variables.m b/matlab/get_variance_of_endogenous_variables.m index 33d3d9e221..965319b1bd 100644 --- a/matlab/get_variance_of_endogenous_variables.m +++ b/matlab/get_variance_of_endogenous_variables.m @@ -6,10 +6,10 @@ function vx1 = get_variance_of_endogenous_variables(dr,i_var) % INPUTS % dr: structure of decisions rules for stochastic simulations % i_var: indices of a variables list -% +% % OUTPUTS % vx1: variance-covariance matrix -% +% % SPECIAL REQUIREMENTS % none @@ -48,7 +48,7 @@ n = length(i_var); [vx,u] = lyapunov_symm(A,B*Sigma_e*B',options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold, [], options_.debug); if size(u,2) > 0 - i_stat = find(any(abs(ghx*u) < options_.Schur_vec_tol,2)); %only set those variances of objective function for which variance is finite + i_stat = find(any(abs(ghx*u) < options_.Schur_vec_tol,2)); %only set those variances of objective function for which variance is finite ghx = ghx(i_stat,:); ghu = ghu(i_stat,:); else @@ -57,4 +57,3 @@ end vx1 = Inf*ones(n,n); vx1(i_stat,i_stat) = ghx*vx*ghx'+ghu*Sigma_e*ghu'; - diff --git a/matlab/global_initialization.m b/matlab/global_initialization.m index cbeff6085e..d31c59e540 100644 --- a/matlab/global_initialization.m +++ b/matlab/global_initialization.m @@ -165,9 +165,9 @@ options_.nocorr = 0; options_.periods = 0; options_.noprint = 0; options_.SpectralDensity.trigger = 0; -options_.SpectralDensity.plot = 1; -options_.SpectralDensity.cutoff = 150; -options_.SpectralDensity.sdl = 0.01; +options_.SpectralDensity.plot = 1; +options_.SpectralDensity.cutoff = 150; +options_.SpectralDensity.sdl = 0.01; options_.nofunctions = false; options_.bandpass.indicator = 0; @@ -282,7 +282,7 @@ particle.resampling.number_of_partitions = 200; particle.mixture_state_variables = 5 ; particle.mixture_structural_shocks = 1 ; particle.mixture_measurement_shocks = 1 ; -% Online approach +% Online approach particle.liu_west_delta = 0.99 ; particle.liu_west_chol_sigma_bar = .01 ; % Options for setting the weights in conditional particle filters. @@ -471,7 +471,7 @@ options_.sub_draws = []; options_.gradient_method = 2; %used by csminwel and newrat options_.gradient_epsilon = 1e-6; %used by csminwel and newrat options_.posterior_sampler_options.sampling_opt = []; %extended set of options for individual posterior samplers -% Random Walk Metropolis-Hastings + % Random Walk Metropolis-Hastings options_.posterior_sampler_options.posterior_sampling_method = 'random_walk_metropolis_hastings'; options_.posterior_sampler_options.rwmh.proposal_distribution = 'rand_multivariate_normal'; options_.posterior_sampler_options.rwmh.student_degrees_of_freedom = 3; @@ -525,8 +525,8 @@ options_.estimation.moments_posterior_density.indicator = 1; options_.estimation.moments_posterior_density.gridpoints = 2^9; options_.estimation.moments_posterior_density.bandwidth = 0; % Rule of thumb optimal bandwidth parameter. options_.estimation.moments_posterior_density.kernel_function = 'gaussian'; % Gaussian kernel for Fast Fourrier Transform approximaton. -% Misc -% options_.conf_sig = 0.6; + % Misc + % options_.conf_sig = 0.6; oo_.exo_simul = []; oo_.endo_simul = []; ys0_ = []; @@ -632,7 +632,7 @@ options_.simpsa = simpsa; %solveopt optimizer solveopt.minimizer_indicator=-1; %use minimizer solveopt.TolX=1e-6; %accuracy of argument -solveopt.TolFun=1e-6; %accuracy of function +solveopt.TolFun=1e-6; %accuracy of function solveopt.MaxIter=15000; solveopt.verbosity=1; solveopt.TolXConstraint=1.e-8; @@ -841,4 +841,3 @@ set_dynare_seed('default'); if isfield(options_, 'global_init_file') run(options_.global_init_file); end - diff --git a/matlab/graph_decomp.m b/matlab/graph_decomp.m index 2993699cf0..f2c6705490 100644 --- a/matlab/graph_decomp.m +++ b/matlab/graph_decomp.m @@ -1,7 +1,7 @@ function []=graph_decomp(z,shock_names,endo_names,i_var,initial_date,DynareModel,DynareOptions) %function []=graph_decomp(z,shock_names,endo_names,i_var,initial_date,DynareModel,DynareOptions) % Plots the results from the shock_decomposition command -% +% % Inputs % z [n_var*(nshock+2)*nperiods] shock decomposition array, see shock_decomposition.m for details % shock_names [endo_nbr*string length] shock names from M_.exo_names @@ -131,8 +131,8 @@ for j=1:nvar fhandle = dyn_figure(DynareOptions.plot_shock_decomp.nodisplay,'Name',[preamble_txt fig_name_long strrep(fig_mode1, '_', ' ') ': ' deblank(endo_names(i_var(j),:)) '.'], 'PaperPositionMode', 'auto','PaperOrientation','landscape','renderermode','auto'); set(fhandle,'position' ,[50 50 1500 750]) ax=axes('Position',[0.1 0.1 0.6 0.8],'box','on'); -% plot(ax,x(2:end),z1(end,:),'k-','LineWidth',2) -% axis(ax,[xmin xmax ymin ymax]); + % plot(ax,x(2:end),z1(end,:),'k-','LineWidth',2) + % axis(ax,[xmin xmax ymin ymax]); hold on; for i=1:gend i_1 = i-1; @@ -175,7 +175,7 @@ for j=1:nvar end set(ax,'xlim',[xmin xmax]); hold off; - + axes('Position',[0.75 0.1 0.2 0.8]); axis([0 1 0 1]); axis off; @@ -184,7 +184,7 @@ for j=1:nvar height = 1/comp_nbr; for i=comp_nbr:-1:1 -% for i=1:comp_nbr + % for i=1:comp_nbr hl = fill([0 0 0.2 0.2],[y1 y1+0.7*height y1+0.7*height y1],i); hold on ht = text(0.3,y1+0.3*height,labels(i,:),'Interpreter','none'); @@ -222,7 +222,7 @@ for j=1:nvar fprintf(fidTeX,['\\caption{' preamble_txt fig_name_long strrep(fig_mode1, '_', ' ') ': $ %s $.}\n'],deblank(DynareModel.endo_names_tex(i_var(j),:))); fprintf(fidTeX,'\\end{figure}\n'); fprintf(fidTeX,' \n'); - end + end end %% write LaTeX-Footer diff --git a/matlab/graph_decomp_detail.m b/matlab/graph_decomp_detail.m index 5d42d0ce19..75951a4113 100644 --- a/matlab/graph_decomp_detail.m +++ b/matlab/graph_decomp_detail.m @@ -1,7 +1,7 @@ function []=graph_decomp_detail(z,shock_names,endo_names,i_var,initial_date,DynareModel,DynareOptions) %function []=graph_decomp_detail(z,shock_names,endo_names,i_var,initial_date,DynareModel,DynareOptions) % Plots the results from the shock_decomposition command -% +% % Inputs % z [n_var*(nshock+2)*nperiods] shock decomposition array, see shock_decomposition.m for details % shock_names [endo_nbr*string length] shock names from M_.exo_names @@ -59,7 +59,7 @@ fig_name_long = opts_decomp.fig_name; % fig_name = ['_' fig_name]; if screen_shocks -% fig_name1 = [fig_name1 '_screen']; + % fig_name1 = [fig_name1 '_screen']; fig_name_long = [fig_name_long ' SCREEN']; end @@ -83,7 +83,7 @@ else x = initial_period-1/freq:(1/freq):initial_period+(gend-1)/freq; end -ind_yrs = find(floor(x)==x); +ind_yrs = find(floor(x)==x); dind_tick = 1; if floor(length(ind_yrs)/3) dind_tick = floor(length(ind_yrs)/3); @@ -151,89 +151,89 @@ for j=1:nvar continue end for jf = 1:nfigs - fhandle = dyn_figure(DynareOptions.plot_shock_decomp.nodisplay,'Name',[preamble_txt fig_name_long strrep(fig_mode1, '_', ' ') ': ' deblank(endo_names(i_var(j),:)) ' (detail).'],'position',[200 100 650 850], 'PaperPositionMode', 'auto','PaperOrientation','portrait','renderermode','auto'); - a0=zeros(1,4); - a0(3)=inf; - a0(4)=-inf; - for ic=1+nrow*ncol*(jf-1):min(nrow*ncol*jf,comp_nbr) - i = ic-nrow*ncol*(jf-1); - zz = z1(ic,:); - zz(2,:)=z1(end,:)-zz; - ipos=zz>0; - ineg=zz<0; - hax = subplot(nrow,ncol,i); set(gca,'box','on') - hbar = bar(x(2:end),(zz.*ipos)','stacked'); - colormap([0.15 0.15 0.15;0.85 0.85 0.85]), - set(hbar,'edgecolor','flat'); - hold on, - hbar = bar(x(2:end),(zz.*ineg)','stacked'); - colormap([0.15 0.15 0.15;0.85 0.85 0.85]), - set(hbar,'edgecolor','flat'); - title(deblank(labels(ic,:)),'Interpreter','none'), - axis tight; - a=axis; - set(gca,'Xtick',xind_tick) - set(gca,'xlim',[xmin xmax]) - a0(3)=min(a(3),a0(3)); - a0(4)=max(a(4),a0(4)); - set(gca,'ylim',a0(3:4)) - hold on, h1=plot(x(2:end),z1(end,:),'k-','LineWidth',2); - if interactive & (~isoctave & use_shock_groups) - mydata.fig_name = DynareOptions.plot_shock_decomp.fig_name(2:end); - mydata.use_shock_groups = DynareOptions.plot_shock_decomp.use_shock_groups; - mydata.shock_group = shock_groups.(shock_ind{ic}); - mydata.shock_decomp = DynareOptions.plot_shock_decomp; - if ~isempty(mydata.shock_group.shocks{1}) - c = uicontextmenu; - hax.UIContextMenu=c; - browse_menu = uimenu(c,'Label','Browse group'); - expand_menu = uimenu(c,'Label','Expand group','Callback',['expand_group(''' mydata.use_shock_groups ''',''' deblank(mydata.shock_decomp.orig_varlist(j,:)) ''',' int2str(ic) ')']); - set(expand_menu,'UserData',mydata,'Tag',['group' int2str(ic)]); - for jmember = mydata.shock_group.shocks - uimenu('parent',browse_menu,'Label',char(jmember)) + fhandle = dyn_figure(DynareOptions.plot_shock_decomp.nodisplay,'Name',[preamble_txt fig_name_long strrep(fig_mode1, '_', ' ') ': ' deblank(endo_names(i_var(j),:)) ' (detail).'],'position',[200 100 650 850], 'PaperPositionMode', 'auto','PaperOrientation','portrait','renderermode','auto'); + a0=zeros(1,4); + a0(3)=inf; + a0(4)=-inf; + for ic=1+nrow*ncol*(jf-1):min(nrow*ncol*jf,comp_nbr) + i = ic-nrow*ncol*(jf-1); + zz = z1(ic,:); + zz(2,:)=z1(end,:)-zz; + ipos=zz>0; + ineg=zz<0; + hax = subplot(nrow,ncol,i); set(gca,'box','on') + hbar = bar(x(2:end),(zz.*ipos)','stacked'); + colormap([0.15 0.15 0.15;0.85 0.85 0.85]), + set(hbar,'edgecolor','flat'); + hold on, + hbar = bar(x(2:end),(zz.*ineg)','stacked'); + colormap([0.15 0.15 0.15;0.85 0.85 0.85]), + set(hbar,'edgecolor','flat'); + title(deblank(labels(ic,:)),'Interpreter','none'), + axis tight; + a=axis; + set(gca,'Xtick',xind_tick) + set(gca,'xlim',[xmin xmax]) + a0(3)=min(a(3),a0(3)); + a0(4)=max(a(4),a0(4)); + set(gca,'ylim',a0(3:4)) + hold on, h1=plot(x(2:end),z1(end,:),'k-','LineWidth',2); + if interactive & (~isoctave & use_shock_groups) + mydata.fig_name = DynareOptions.plot_shock_decomp.fig_name(2:end); + mydata.use_shock_groups = DynareOptions.plot_shock_decomp.use_shock_groups; + mydata.shock_group = shock_groups.(shock_ind{ic}); + mydata.shock_decomp = DynareOptions.plot_shock_decomp; + if ~isempty(mydata.shock_group.shocks{1}) + c = uicontextmenu; + hax.UIContextMenu=c; + browse_menu = uimenu(c,'Label','Browse group'); + expand_menu = uimenu(c,'Label','Expand group','Callback',['expand_group(''' mydata.use_shock_groups ''',''' deblank(mydata.shock_decomp.orig_varlist(j,:)) ''',' int2str(ic) ')']); + set(expand_menu,'UserData',mydata,'Tag',['group' int2str(ic)]); + for jmember = mydata.shock_group.shocks + uimenu('parent',browse_menu,'Label',char(jmember)) + end end end end - end - for isub=1:i - subplot(nrow,ncol,isub), - set(gca,'ylim',a0(3:4)) - end - -% make legend - axes('Position',[0.1 0.01 0.8 0.02],'units','normalized'); - axis([0 1 0 1]); - axis off; - hold on; - x1 = 0; - width = 1/2; - mylabels = {'Individual contrib.','Residual contrib.'}; - - for i=1:2 -% for i=1:comp_nbr - hl = fill([x1 x1 x1+0.3*width x1+0.3*width],[0 1 1 0],i); - hold on - ht = text(x1+0.4*width,0.3,mylabels{i},'Interpreter','none'); - hold on - x1 = x1 + width; - end - - - if nfigs>1 - suffix = ['_detail_' int2str(jf)]; - else - suffix = ['_detail']; - end - dyn_saveas(fhandle,[GraphDirectoryName, filesep, DynareModel.fname,'_shock_decomposition_',deblank(endo_names(i_var(j),:)),fig_mode1,fig_name suffix],DynareOptions.plot_shock_decomp.nodisplay,DynareOptions.plot_shock_decomp.graph_format); - if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.plot_shock_decomp.graph_format))) - fprintf(fidTeX,'\\begin{figure}[H]\n'); - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s/graphs/%s_shock_decomposition_%s}\n',DynareModel.fname,DynareModel.fname,[deblank(endo_names(i_var(j),:)) fig_mode1 fig_name suffix]); - fprintf(fidTeX,'\\label{Fig:shock_decomp_detail:%s}\n',[fig_mode deblank(endo_names(i_var(j),:)) fig_name suffix]); - fprintf(fidTeX,['\\caption{' preamble_txt fig_name_long strrep(fig_mode1, '_', ' ') ': $ %s $ (detail).}\n'],deblank(DynareModel.endo_names_tex(i_var(j),:))); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,' \n'); - end + for isub=1:i + subplot(nrow,ncol,isub), + set(gca,'ylim',a0(3:4)) + end + + % make legend + axes('Position',[0.1 0.01 0.8 0.02],'units','normalized'); + axis([0 1 0 1]); + axis off; + hold on; + x1 = 0; + width = 1/2; + mylabels = {'Individual contrib.','Residual contrib.'}; + + for i=1:2 + % for i=1:comp_nbr + hl = fill([x1 x1 x1+0.3*width x1+0.3*width],[0 1 1 0],i); + hold on + ht = text(x1+0.4*width,0.3,mylabels{i},'Interpreter','none'); + hold on + x1 = x1 + width; + end + + + if nfigs>1 + suffix = ['_detail_' int2str(jf)]; + else + suffix = ['_detail']; + end + dyn_saveas(fhandle,[GraphDirectoryName, filesep, DynareModel.fname,'_shock_decomposition_',deblank(endo_names(i_var(j),:)),fig_mode1,fig_name suffix],DynareOptions.plot_shock_decomp.nodisplay,DynareOptions.plot_shock_decomp.graph_format); + if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.plot_shock_decomp.graph_format))) + fprintf(fidTeX,'\\begin{figure}[H]\n'); + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s/graphs/%s_shock_decomposition_%s}\n',DynareModel.fname,DynareModel.fname,[deblank(endo_names(i_var(j),:)) fig_mode1 fig_name suffix]); + fprintf(fidTeX,'\\label{Fig:shock_decomp_detail:%s}\n',[fig_mode deblank(endo_names(i_var(j),:)) fig_name suffix]); + fprintf(fidTeX,['\\caption{' preamble_txt fig_name_long strrep(fig_mode1, '_', ' ') ': $ %s $ (detail).}\n'],deblank(DynareModel.endo_names_tex(i_var(j),:))); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,' \n'); + end end end diff --git a/matlab/gsa/Morris_Measure_Groups.m b/matlab/gsa/Morris_Measure_Groups.m index 1aa387f074..69dc1d713f 100644 --- a/matlab/gsa/Morris_Measure_Groups.m +++ b/matlab/gsa/Morris_Measure_Groups.m @@ -5,19 +5,19 @@ function [SAmeas, OutMatrix] = Morris_Measure_Groups(NumFact, Sample, Output, p, % ------------------------------------------------------------------------- % INPUTS % ------------------------------------------------------------------------- -% Group [NumFactor, NumGroups] := Matrix describing the groups. -% Each column represents one group. +% Group [NumFactor, NumGroups] := Matrix describing the groups. +% Each column represents one group. % The element of each column are zero if the factor is not in the % group. Otherwise it is 1. % -% Sample := Matrix of the Morris sampled trajectories +% Sample := Matrix of the Morris sampled trajectories % % Output := Matrix of the output(s) values in correspondence of each point % of each trajectory % % k = Number of factors % ------------------------------------------------------------------------- -% OUTPUTS +% OUTPUTS % OutMatrix (NumFactor*NumOutputs, 3)= [Mu*, Mu, StDev] % for each output it gives the three measures of each factor % ------------------------------------------------------------------------- @@ -45,9 +45,9 @@ function [SAmeas, OutMatrix] = Morris_Measure_Groups(NumFact, Sample, Output, p, % along with Dynare. If not, see <http://www.gnu.org/licenses/>. if nargin==0 - skipline() - disp('[SAmeas, OutMatrix] = Morris_Measure_Groups(NumFact, Sample, Output, p, Group);') - return + skipline() + disp('[SAmeas, OutMatrix] = Morris_Measure_Groups(NumFact, Sample, Output, p, Group);') + return end OutMatrix=[]; @@ -63,45 +63,45 @@ if NumGroups ~ 0 sizea = NumGroups; % Number of groups GroupMat=Group; GroupMat = GroupMat'; -else - sizea = NumFact; +else + sizea = NumFact; end r=size(Sample,1)/(sizea+1); % Number of trajectories % For Each Output for k=1:size(Output,2) - + OutValues=Output(:,k); - + % For each r trajectory for i=1:r - + % For each step j in the trajectory % Read the orientation matrix fact for the r-th sampling % Read the corresponding output values - Single_Sample = Sample(i+(i-1)*sizea:i+(i-1)*sizea+sizea,:); - Single_OutValues = OutValues(i+(i-1)*sizea:i+(i-1)*sizea+sizea,:); + Single_Sample = Sample(i+(i-1)*sizea:i+(i-1)*sizea+sizea,:); + Single_OutValues = OutValues(i+(i-1)*sizea:i+(i-1)*sizea+sizea,:); A = (Single_Sample(2:sizea+1,:)-Single_Sample(1:sizea,:))'; Delta = A(find(A)); % For each point of the fixed trajectory compute the values of the Morris function. The function % is partitioned in four parts, from order zero to order 4th. - for j=1:sizea % For each point in the trajectory i.e for each factor - % matrix of factor which changes + for j=1:sizea % For each point in the trajectory i.e for each factor + % matrix of factor which changes if NumGroups ~ 0 AuxFind (:,1) = A(:,j); -% AuxFind(find(A(:,j)),1)=1; -% Pippo = sum((Group - repmat(AuxFind,1,NumGroups)),1); -% Change_factor(j,i) = find(Pippo==0); - Change_factor = find(abs(AuxFind)>1e-010); + % AuxFind(find(A(:,j)),1)=1; + % Pippo = sum((Group - repmat(AuxFind,1,NumGroups)),1); + % Change_factor(j,i) = find(Pippo==0); + Change_factor = find(abs(AuxFind)>1e-010); % If we deal with groups we can only estimate the new mu* % measure since factors in the same groups can move in % opposite direction and the definition of the standard - % Morris mu cannopt be applied. + % Morris mu cannopt be applied. % In the new version the elementary effect is defined with % the absolute value. - %SAmeas(find(GroupMat(Change_factor(j,i),:)),i) = abs((Single_OutValues(j) - Single_OutValues(j+1) )/Delt); %(2/3)); - SAmeas(i,Change_factor') = abs((Single_OutValues(j) - Single_OutValues(j+1) )/Delt); + %SAmeas(find(GroupMat(Change_factor(j,i),:)),i) = abs((Single_OutValues(j) - Single_OutValues(j+1) )/Delt); %(2/3)); + SAmeas(i,Change_factor') = abs((Single_OutValues(j) - Single_OutValues(j+1) )/Delt); else Change_factor(j,i) = find(Single_Sample(j+1,:)-Single_Sample(j,:)); % If no groups --> we compute both the original and @@ -110,41 +110,41 @@ for k=1:size(Output,2) SAmeas(Change_factor(j,i),i) = (Single_OutValues(j+1) - Single_OutValues(j) )/Delt; %(2/3); else %=> -Delta SAmeas(Change_factor(j,i),i) = (Single_OutValues(j) - Single_OutValues(j+1) )/Delt; %(2/3); - end + end end end %for j=1:sizea - + end %for i=1:r - + if NumGroups ~ 0 SAmeas = SAmeas'; end % Compute Mu AbsMu and StDev if any(any(isnan(SAmeas))) - for j=1:NumFact - SAm = SAmeas(j,:); - SAm = SAm(find(~isnan(SAm))); - rr=length(SAm); - AbsMu(j,1) = sum(abs(SAm),2)/rr; - if NumGroups == 0 - Mu(j,1) = sum(SAm,2)/rr; - StDev(j,1) = sum((SAm - repmat(Mu(j),1,rr)).^2/(rr*(rr-1)),2).^0.5; - end - end + for j=1:NumFact + SAm = SAmeas(j,:); + SAm = SAm(find(~isnan(SAm))); + rr=length(SAm); + AbsMu(j,1) = sum(abs(SAm),2)/rr; + if NumGroups == 0 + Mu(j,1) = sum(SAm,2)/rr; + StDev(j,1) = sum((SAm - repmat(Mu(j),1,rr)).^2/(rr*(rr-1)),2).^0.5; + end + end else - AbsMu = sum(abs(SAmeas),2)/r; - if NumGroups == 0 - Mu = sum(SAmeas,2)/r; - StDev = sum((SAmeas - repmat(Mu,1,r)).^2/(r*(r-1)),2).^0.5; - end + AbsMu = sum(abs(SAmeas),2)/r; + if NumGroups == 0 + Mu = sum(SAmeas,2)/r; + StDev = sum((SAmeas - repmat(Mu,1,r)).^2/(r*(r-1)),2).^0.5; + end end % Define the output Matrix - if we have groups we cannot define the old % measure mu, only mu* makes sense if NumGroups > 0 - OutMatrix = [OutMatrix; AbsMu]; + OutMatrix = [OutMatrix; AbsMu]; else - OutMatrix = [OutMatrix; AbsMu, Mu, StDev]; + OutMatrix = [OutMatrix; AbsMu, Mu, StDev]; end end % For Each Output diff --git a/matlab/gsa/Sampling_Function_2.m b/matlab/gsa/Sampling_Function_2.m index 60255cafbb..bdb8d03eb7 100644 --- a/matlab/gsa/Sampling_Function_2.m +++ b/matlab/gsa/Sampling_Function_2.m @@ -1,42 +1,42 @@ function [Outmatrix, OutFact] = Sampling_Function_2(p, k, r, UB, LB, GroupMat) %[Outmatrix, OutFact] = Sampling_Function_2(p, k, r, UB, LB, GroupMat) -% Inputs: k (1,1) := number of factors examined or number of groups examined. +% Inputs: k (1,1) := number of factors examined or number of groups examined. % In case the groups are chosen the number of factors is stores in NumFact and -% sizea becomes the number of created groups. +% sizea becomes the number of created groups. % NumFact (1,1) := number of factors examined in the case when groups are chosen -% r (1,1) := sample size +% r (1,1) := sample size % p (1,1) := number of intervals considered in [0, 1] -% UB(sizea,1) := Upper Bound for each factor -% LB(sizea,1) := Lower Bound for each factor +% UB(sizea,1) := Upper Bound for each factor +% LB(sizea,1) := Lower Bound for each factor % GroupNumber(1,1) := Number of groups (eventually 0) -% GroupMat(NumFact,GroupNumber):= Matrix which describes the chosen groups. Each column represents a group and its elements +% GroupMat(NumFact,GroupNumber):= Matrix which describes the chosen groups. Each column represents a group and its elements % are set to 1 in correspondence of the factors that belong to the fixed group. All % the other elements are zero. -% Local Variables: -% sizeb (1,1) := sizea+1 +% Local Variables: +% sizeb (1,1) := sizea+1 % sizec (1,1) := 1 -% randmult (sizea,1) := vector of random +1 and -1 -% perm_e(1,sizea) := vector of sizea random permutated indeces +% randmult (sizea,1) := vector of random +1 and -1 +% perm_e(1,sizea) := vector of sizea random permutated indeces % fact(sizea) := vector containing the factor varied within each traj -% DDo(sizea,sizea) := D* in Morris, 1991 -% A(sizeb,sizea) := Jk+1,k in Morris, 1991 -% B(sizeb,sizea) := B in Morris, 1991 -% Po(sizea,sizea) := P* in Morris, 1991 +% DDo(sizea,sizea) := D* in Morris, 1991 +% A(sizeb,sizea) := Jk+1,k in Morris, 1991 +% B(sizeb,sizea) := B in Morris, 1991 +% Po(sizea,sizea) := P* in Morris, 1991 % Bo(sizeb,sizea) := B* in Morris, 1991 -% Ao(sizeb,sizec) := Jk+1,1 in Morris, 1991 -% xo(sizec,sizea) := x* in Morris, 1991 (starting point for the trajectory) +% Ao(sizeb,sizec) := Jk+1,1 in Morris, 1991 +% xo(sizec,sizea) := x* in Morris, 1991 (starting point for the trajectory) % In(sizeb,sizea) := for each loop orientation matrix. It corresponds to a trajectory % of k step in the parameter space and it provides a single elementary -% effect per factor +% effect per factor % MyInt() -% Fact(sizea,1) := for each loop vector indicating which factor or group of factors has been changed +% Fact(sizea,1) := for each loop vector indicating which factor or group of factors has been changed % in each step of the trajectory % AuxMat(sizeb,sizea) := Delta*0.5*((2*B - A) * DD0 + A) in Morris, 1991. The AuxMat is used as in Morris design % for single factor analysis, while it constitutes an intermediate step for the group analysis. % -% Output: Outmatrix(sizeb*r, sizea) := for the entire sample size computed In(i,j) matrices +% Output: Outmatrix(sizeb*r, sizea) := for the entire sample size computed In(i,j) matrices % OutFact(sizea*r,1) := for the entire sample size computed Fact(i,1) vectors -% +% % Note: B0 is constructed as in Morris design when groups are not considered. When groups are considered the routine % follows the following steps: % 1- Creation of P0 and DD0 matrices defined in Morris for the groups. This means that the dimensions of these @@ -44,7 +44,7 @@ function [Outmatrix, OutFact] = Sampling_Function_2(p, k, r, UB, LB, GroupMat) % 2- Creation of AuxMat matrix with (GroupNumber+1,GroupNumber) elements. % 3- Definition of GroupB0 starting from AuxMat, GroupMat and P0. % 4- The final B0 for groups is obtained as [ones(sizeb,1)*x0' + GroupB0]. The P0 permutation is present in GroupB0 -% and it's not necessary to permute the matrix (ones(sizeb,1)*x0') because it's already randomly created. +% and it's not necessary to permute the matrix (ones(sizeb,1)*x0') because it's already randomly created. % Reference: % A. Saltelli, K. Chan, E.M. Scott, "Sensitivity Analysis" on page 68 ss % @@ -82,76 +82,76 @@ GroupNumber = size(GroupMat,2); if GroupNumber ~ 0; sizea = size(GroupMat,2); -end +end sizeb = sizea + 1; sizec = 1; Outmatrix = []; OutFact = []; -% For each i generate a trajectory +% For each i generate a trajectory for i=1:r - + % Construct DD0 - OLD VERSION - it does not need communication toolbox % RAND(N,M) is an NXM matrix with random entries, chosen from a uniform distribution on the interval (0.0,1.0). % Note that DD0 tells if the factor have to be increased or ddecreased % by Delta. - randmult = ones(k,1); - v = rand(k,1); + randmult = ones(k,1); + v = rand(k,1); randmult (find(v < 0.5))=-1; randmult = repmat(randmult,1,k); DD0 = randmult .* eye(k); - + % Construct DD0 - NEW VERSION - it needs communication toolbox % randsrc(m) generates an m-by-m matrix, each of whose entries independently takes the value -1 with probability 1/2, % and 1 with probability 1/2. - % DD0 = randsrc(NumFact) .* eye(NumFact); - + % DD0 = randsrc(NumFact) .* eye(NumFact); + % Construct B (lower triangular) B = ones(sizeb,sizea); for j = 1:sizea - B(1:j,j)=0; + B(1:j,j)=0; end - + % Construct A0, A A0 = ones(sizeb,1); A = ones(sizeb,NumFact); % Construct the permutation matrix P0. In each column of P0 one randomly chosen element equals 1 - % while all the others equal zero. + % while all the others equal zero. % P0 tells the order in which order factors are changed in each % trajectory. P0 is created as it follows: % 1) All the elements of P0 are set equal to zero ==> P0 = zeros (sizea, sizea); - % 2) The function randperm create a random permutation of integer 1:sizea, without repetitions ==> perm_e; - % 3) In each column of P0 the element indicated in perm_e is set equal to one. - % Note that P0 is then used reading it by rows. + % 2) The function randperm create a random permutation of integer 1:sizea, without repetitions ==> perm_e; + % 3) In each column of P0 the element indicated in perm_e is set equal to one. + % Note that P0 is then used reading it by rows. P0 = zeros (sizea, sizea); perm_e = randperm(sizea); % RANDPERM(n) is a random permutation of the integers from 1 to n. for j = 1:sizea - P0(perm_e(j),j) = 1; - end - - % When groups are present the random permutation is done only on B. The effect is the same since - % the added part (A0*x0') is completely random. + P0(perm_e(j),j) = 1; + end + + % When groups are present the random permutation is done only on B. The effect is the same since + % the added part (A0*x0') is completely random. if GroupNumber ~ 0 B = B * (GroupMat*P0')'; end - + % Compute AuxMat both for single factors and groups analysis. For Single factors analysis % AuxMat is added to (A0*X0) and then permutated through P0. When groups are active AuxMat is % used to build GroupB0. AuxMat is created considering DD0. If the element on DD0 diagonal - % is 1 then AuxMat will start with zero and add Delta. If the element on DD0 diagonal is -1 + % is 1 then AuxMat will start with zero and add Delta. If the element on DD0 diagonal is -1 % then DD0 will start Delta and goes to zero. AuxMat = Delta*0.5*((2*B - A) * DD0 + A); - + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % a --> Define the random vector x0 for the factors. Note that x0 takes value in the hypercube - % [0,...,1-Delta]*[0,...,1-Delta]*[0,...,1-Delta]*[0,...,1-Delta] + % [0,...,1-Delta]*[0,...,1-Delta]*[0,...,1-Delta]*[0,...,1-Delta] MyInt = repmat([0:(1/(p-1)):(1-Delta)],NumFact,1); % Construct all possible values of the factors - + % OLD VERSION - it needs communication toolbox - % w = randint(NumFact,1,[1,size(MyInt,2)]); - + % w = randint(NumFact,1,[1,size(MyInt,2)]); + % NEW VERSION - construct a version of random integers % 1) create a vector of random integers % 2) divide [0,1] into the needed steps @@ -160,21 +160,21 @@ for i=1:r v = repmat(rand(NumFact,1),1,size(MyInt,2)+1); % 1) IntUsed = repmat([0:1/size(MyInt,2):1],NumFact,1); % 2) DiffAuxVec = IntUsed - v; % 3) - + for ii = 1:size(DiffAuxVec,1) w(1,ii) = max(find(DiffAuxVec(ii,:)<0)); % 4) end - x0 = MyInt(1,w)'; % Define x0 - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + x0 = MyInt(1,w)'; % Define x0 + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % b --> Compute the matrix B*, here indicated as B0. Each row in B0 is a - % trajectory for Morris Calculations. The dimension of B0 is (Numfactors+1,Numfactors) + % trajectory for Morris Calculations. The dimension of B0 is (Numfactors+1,Numfactors) if GroupNumber ~ 0 B0 = (A0*x0' + AuxMat); else B0 = (A0*x0' + AuxMat)*P0; end - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % c --> Compute values in the original intervals % B0 has values x(i,j) in [0, 1/(p -1), 2/(p -1), ... , 1]. % To obtain values in the original intervals [LB, UB] we compute @@ -187,8 +187,8 @@ for i=1:r Fact(1,j) = find(P0(j,:)); end Fact(1,sizea+1) = 0; - + Outmatrix = [Outmatrix; In]; OutFact = [OutFact; Fact']; - + end \ No newline at end of file diff --git a/matlab/gsa/cumplot.m b/matlab/gsa/cumplot.m index d210c81f95..bc4eb969b2 100644 --- a/matlab/gsa/cumplot.m +++ b/matlab/gsa/cumplot.m @@ -3,7 +3,7 @@ function h = cumplot(x) % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % Copyright (C) 2012 European Commission % Copyright (C) 2012 Dynare Team diff --git a/matlab/gsa/filt_mc_.m b/matlab/gsa/filt_mc_.m index bf37c148b9..b2dfb04117 100644 --- a/matlab/gsa/filt_mc_.m +++ b/matlab/gsa/filt_mc_.m @@ -11,7 +11,7 @@ function [rmse_MC, ixx] = filt_mc_(OutDir,options_gsa_,dataset_,dataset_info) % % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % Copyright (C) 2012-2016 European Commission % Copyright (C) 2012-2017 Dynare Team @@ -58,33 +58,33 @@ disp('Starting sensitivity analysis') disp('for the fit of EACH observed series ...') skipline() if ~options_.nograph -disp('Deleting old SA figures...') -a=dir([OutDir,filesep,'*.*']); -tmp1='0'; -if options_.opt_gsa.ppost - tmp=['_rmse_post']; -else - if options_.opt_gsa.pprior - tmp=['_rmse_prior']; + disp('Deleting old SA figures...') + a=dir([OutDir,filesep,'*.*']); + tmp1='0'; + if options_.opt_gsa.ppost + tmp=['_rmse_post']; else - tmp=['_rmse_mc']; - end - if options_gsa_.lik_only - tmp1 = [tmp,'_post_SA']; - tmp = [tmp,'_lik_SA']; - end -end -for j=1:length(a) - if strmatch([fname_,tmp],a(j).name) - disp(a(j).name) - delete([OutDir,filesep,a(j).name]) + if options_.opt_gsa.pprior + tmp=['_rmse_prior']; + else + tmp=['_rmse_mc']; + end + if options_gsa_.lik_only + tmp1 = [tmp,'_post_SA']; + tmp = [tmp,'_lik_SA']; + end end - if strmatch([fname_,tmp1],a(j).name) - disp(a(j).name) - delete([OutDir,filesep,a(j).name]) + for j=1:length(a) + if strmatch([fname_,tmp],a(j).name) + disp(a(j).name) + delete([OutDir,filesep,a(j).name]) + end + if strmatch([fname_,tmp1],a(j).name) + disp(a(j).name) + delete([OutDir,filesep,a(j).name]) + end end -end -disp('done !') + disp('done !') end nshock=estim_params_.nvx + estim_params_.nvn + estim_params_.ncx + estim_params_.ncn; @@ -139,7 +139,7 @@ if ~loadSA data_index = dataset_info.missing.aindex; missing_value = dataset_info.missing.state; for jx=1:gend - data_indx(jx,data_index{jx})=true; + data_indx(jx,data_index{jx})=true; end %stock_gend=data_info.gend; %stock_data = data_info.data; @@ -175,7 +175,7 @@ if ~loadSA disp('Computing RMSE''s...') for i=1:size(vvarvecm,1) vj=deblank(vvarvecm(i,:)); - + jxj(i) = strmatch(vj,lgy_(dr_.order_var,:),'exact'); js(i) = strmatch(vj,lgy_,'exact'); yss(i,:,:)=repmat(sto_ys(:,js(i))',[gend,1]); @@ -227,7 +227,7 @@ if ~loadSA end likelihood=logpo2(:)-lnprior(:); disp('... done!') - + if options_.opt_gsa.ppost save([OutDir,filesep,fnamtmp,'.mat'], 'x', 'logpo2', 'likelihood', 'rmse_MC', 'r2_MC', 'vvarvecm') if exist('xparam1_mean','var') @@ -322,7 +322,7 @@ if ~options_.opt_gsa.ppost && options_.opt_gsa.lik_only options_mcf.beha_title = 'better posterior kernel'; options_mcf.nobeha_title = 'worse posterior kernel'; mcf_analysis(x, ipost(1:nfilt), ipost(nfilt+1:end), options_mcf, options_); - + if options_.opt_gsa.pprior anam = 'rmse_prior_lik'; atitle = 'RMSE prior: Log Likelihood Kernel'; @@ -336,7 +336,7 @@ if ~options_.opt_gsa.ppost && options_.opt_gsa.lik_only options_mcf.beha_title = 'better likelihood'; options_mcf.nobeha_title = 'worse likelihood'; mcf_analysis(x, ilik(1:nfilt), ilik(nfilt+1:end), options_mcf, options_); - + else if options_.opt_gsa.ppost rmse_txt=rmse_pmean; @@ -425,19 +425,19 @@ else if options_.opt_gsa.ppost dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnprior',int2str(ifig)],options_.nodisplay,options_.graph_format); if options_.TeX - create_TeX_loader(options_,[OutDir '/' fname_ '_rmse_post_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_post_lnprior',options_.figures.textwidth*min((i-9*(ifig-1))/3,1)) + create_TeX_loader(options_,[OutDir '/' fname_ '_rmse_post_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_post_lnprior',options_.figures.textwidth*min((i-9*(ifig-1))/3,1)) end else if options_.opt_gsa.pprior dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_lnprior',int2str(ifig) ],options_.nodisplay,options_.graph_format); - if options_.TeX - create_TeX_loader(options_,[OutDir '/' fname_ '_rmse_prior_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_prior_lnprior',options_.figures.textwidth*min((i-9*(ifig-1))/3,1)) - end + if options_.TeX + create_TeX_loader(options_,[OutDir '/' fname_ '_rmse_prior_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_prior_lnprior',options_.figures.textwidth*min((i-9*(ifig-1))/3,1)) + end else dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_lnprior',int2str(ifig) ],options_.nodisplay,options_.graph_format); - if options_.TeX - create_TeX_loader(options_,[OutDir '/' fname_ '_rmse_mc_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_mc_lnprior',options_.figures.textwidth*min((i-9*(ifig-1))/3,1)) - end + if options_.TeX + create_TeX_loader(options_,[OutDir '/' fname_ '_rmse_mc_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_mc_lnprior',options_.figures.textwidth*min((i-9*(ifig-1))/3,1)) + end end end end @@ -545,7 +545,7 @@ else end end end - + if options_.TeX [pnames,pnames_tex]=get_LaTeX_parameter_names(M_,options_,estim_params_,bayestopt_); param_names = char(pnames); @@ -556,7 +556,7 @@ else param_names_tex = []; end - + skipline() title_string='RMSE over the MC sample:'; data_mat=[min(rmse_MC)' max(rmse_MC)']; @@ -566,7 +566,7 @@ else headers_tex=strvcat('\text{Variable}','\text{min yr RMSE}','\text{max yr RMSE}'); dyn_latex_table(M_,options_,title_string,'RMSE_MC',headers_tex,vvarvecm_tex,data_mat,0,15,5); end - + invar = find( std(rmse_MC)./mean(rmse_MC)<=0.0001 ); if ~isempty(invar) skipline(2) @@ -580,7 +580,7 @@ else ivar = find( std(rmse_MC)./mean(rmse_MC)>0.0001 ); vvarvecm=vvarvecm(ivar,:); rmse_MC=rmse_MC(:,ivar); - + skipline() % if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior, disp(['Sample filtered the ',num2str(pfilt*100),'% best RMSE''s for each observed series ...' ]) @@ -590,7 +590,7 @@ else % figure, boxplot(rmse_MC) % set(gca,'xticklabel',vvarvecm) % saveas(gcf,[fname_,'_SA_RMSE']) - + skipline(2) disp('RMSE ranges after filtering:') title_string='RMSE ranges after filtering:'; @@ -604,10 +604,10 @@ else data_mat=NaN(size(vvarvecm,1),5); for j=1:size(vvarvecm,1) data_mat(j,:)=[min(rmse_MC(ixx(1:nfilt0(j),j),j)) ... - max(rmse_MC(ixx(1:nfilt0(j),j),j)) ... - min(rmse_MC(ixx(nfilt0(j)+1:end,j),j)) ... - max(rmse_MC(ixx(nfilt0(j)+1:end,j),j)) ... - rmse_txt(j)]; + max(rmse_MC(ixx(1:nfilt0(j),j),j)) ... + min(rmse_MC(ixx(nfilt0(j)+1:end,j),j)) ... + max(rmse_MC(ixx(nfilt0(j)+1:end,j),j)) ... + rmse_txt(j)]; end %get formatting for additional header line val_width=15; @@ -622,7 +622,7 @@ else if any(data_mat) < 0 %add one character for minus sign values_length = values_length+1; end - + headers_length = max(size(deblank(headers(2:end,:)),2)); if ~isempty(val_width) val_width = max(max(headers_length,values_length)+2,val_width); @@ -631,7 +631,7 @@ else end value_format = sprintf('%%%d.%df',val_width,val_precis); header_string_format = sprintf('%%%ds',val_width); - + if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior optional_header=sprintf([label_format_leftbound,header_string_format,header_string_format,header_string_format,header_string_format],'','',['best ',num2str(pfilt*100),'% filtered'],'','remaining 90%'); else @@ -646,7 +646,7 @@ else end dyn_latex_table(M_,options_,title_string,'RMSE_ranges_after_filtering',headers_tex,vvarvecm_tex,data_mat,0,val_width,val_precis,optional_header); end - + %%%%% R2 table vvarvecm=vvarvecm0; skipline() @@ -658,13 +658,13 @@ else headers_tex=strvcat('\text{Variable}','\text{min yr R2}','\text{max yr R2}'); dyn_latex_table(M_,options_,title_string,'R2_MC',headers_tex,vvarvecm_tex,data_mat,0,15,5); end - + r2_MC=r2_MC(:,ivar); vvarvecm=vvarvecm(ivar,:); - + skipline() disp(['Sample filtered the ',num2str(pfilt*100),'% best R2''s for each observed series ...' ]) - + skipline() disp('R2 ranges after filtering:') title_string='R2 ranges after filtering:'; @@ -678,10 +678,10 @@ else data_mat=NaN(size(vvarvecm,1),5); for j=1:size(vvarvecm,1) data_mat(j,:)=[min(r2_MC(ixx(1:nfilt0(j),j),j)) ... - max(r2_MC(ixx(1:nfilt0(j),j),j)) ... - min(r2_MC(ixx(nfilt0(j)+1:end,j),j)) ... - max(r2_MC(ixx(nfilt0(j)+1:end,j),j)) ... - r2_txt(j)]; + max(r2_MC(ixx(1:nfilt0(j),j),j)) ... + min(r2_MC(ixx(nfilt0(j)+1:end,j),j)) ... + max(r2_MC(ixx(nfilt0(j)+1:end,j),j)) ... + r2_txt(j)]; end %get formatting for additional header line val_width=15; @@ -696,7 +696,7 @@ else if any(data_mat) < 0 %add one character for minus sign values_length = values_length+1; end - + headers_length = max(size(deblank(headers(2:end,:)),2)); if ~isempty(val_width) val_width = max(max(headers_length,values_length)+2,val_width); @@ -705,7 +705,7 @@ else end value_format = sprintf('%%%d.%df',val_width,val_precis); header_string_format = sprintf('%%%ds',val_width); - + if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior optional_header=sprintf([label_format_leftbound,header_string_format,header_string_format,header_string_format,header_string_format],'','',['best ',num2str(pfilt*100),'% filtered'],'','remaining 90%'); else @@ -720,8 +720,8 @@ else end dyn_latex_table(M_,options_,title_string,'R2_ranges_after_filtering',headers_tex,vvarvecm_tex,data_mat,0,val_width,val_precis,optional_header); end - - + + %%%% R2 table SP=zeros(npar+nshock,size(vvarvecm,1)); for j=1:size(vvarvecm,1) @@ -729,7 +729,7 @@ else SP(ns,j)=ones(size(ns)); SS(:,j)=SS(:,j).*SP(:,j); end - + for j=1:npar+nshock %estim_params_.np, nsp(j)=length(find(SP(j,:))); end @@ -742,7 +742,7 @@ else % snam2=bayestopt_.name(find(nsp>1)); % snam=bayestopt_.name(find(nsp>0)); nsnam=(find(nsp>1)); - + skipline(2) disp('These parameters do not affect significantly the fit of ANY observed series:') disp(snam0) @@ -752,11 +752,11 @@ else skipline() disp('These parameters affect MORE THAN ONE observed series: trade off exists!') disp(snam2) - - + + %pnam=bayestopt_.name(end-estim_params_.np+1:end); pnam=bayestopt_.name; - + % plot trade-offs if ~options_.nograph a00=jet(size(vvarvecm,1)); @@ -856,7 +856,7 @@ else end end end - + % now I plot by individual parameters for ix=1:ceil(length(nsnam)/5) hh = dyn_figure(options_.nodisplay,'name',[temp_name,' estimated params and shocks ',int2str(ix)]); @@ -923,66 +923,66 @@ else end end end - -% for j=1:size(SP,2), -% nsx(j)=length(find(SP(:,j))); -% end - -% skipline(2) -% disp('Sensitivity table (significance and direction):') -% vav=char(zeros(1, size(param_names,2)+3 )); -% ibl = 12-size(vvarvecm,2); -% for j=1:size(vvarvecm,1), -% vav = [vav, char(zeros(1,ibl)),vvarvecm(j,:)]; -% end -% disp(vav) -% for j=1:npar+nshock, %estim_params_.np, -% %disp([param_names(j,:), sprintf('%8.5g',SP(j,:))]) -% disp([param_names(j,:),' ', sprintf('%12.3g',PP(j,:))]) -% disp([char(zeros(1, size(param_names,2)+3 )),sprintf(' (%6g)',SS(j,:))]) -% end - - -% skipline() -% disp('Starting bivariate analysis:') -% -% for i=1:size(vvarvecm,1) -% if options_.opt_gsa.ppost -% fnam = ['rmse_post_',deblank(vvarvecm(i,:))]; -% else -% if options_.opt_gsa.pprior -% fnam = ['rmse_prior_',deblank(vvarvecm(i,:))]; -% else -% fnam = ['rmse_mc_',deblank(vvarvecm(i,:))]; -% end -% end -% stab_map_2(x(ixx(1:nfilt0(i),i),:),alpha2,pvalue,fnam, OutDir,[],[temp_name ' observed variable ' deblank(vvarvecm(i,:))]); -% -% % [pc,latent,explained] = pcacov(c0); -% % %figure, bar([explained cumsum(explained)]) -% % ifig=0; -% % j2=0; -% % for j=1:npar+nshock, -% % i2=find(abs(pc(:,j))>alphaPC); -% % if ~isempty(i2), -% % j2=j2+1; -% % if mod(j2,12)==1, -% % ifig=ifig+1; -% % figure('name',['PCA of the filtered sample ',deblank(vvarvecm(i,:)),' ',num2str(ifig)]), -% % end -% % subplot(3,4,j2-(ifig-1)*12) -% % bar(pc(i2,j)), -% % set(gca,'xticklabel',bayestopt_.name(i2)), -% % set(gca,'xtick',[1:length(i2)]) -% % title(['PC ',num2str(j),'. Explained ',num2str(explained(j)),'%']) -% % end -% % if (mod(j2,12)==0 | j==(npar+nshock)) & j2, -% % saveas(gcf,[fname_,'_SA_PCA_',deblank(vvarvecm(i,:)),'_',int2str(ifig)]) -% % end -% % end -% % close all -% end - + + % for j=1:size(SP,2), + % nsx(j)=length(find(SP(:,j))); + % end + + % skipline(2) + % disp('Sensitivity table (significance and direction):') + % vav=char(zeros(1, size(param_names,2)+3 )); + % ibl = 12-size(vvarvecm,2); + % for j=1:size(vvarvecm,1), + % vav = [vav, char(zeros(1,ibl)),vvarvecm(j,:)]; + % end + % disp(vav) + % for j=1:npar+nshock, %estim_params_.np, + % %disp([param_names(j,:), sprintf('%8.5g',SP(j,:))]) + % disp([param_names(j,:),' ', sprintf('%12.3g',PP(j,:))]) + % disp([char(zeros(1, size(param_names,2)+3 )),sprintf(' (%6g)',SS(j,:))]) + % end + + + % skipline() + % disp('Starting bivariate analysis:') + % + % for i=1:size(vvarvecm,1) + % if options_.opt_gsa.ppost + % fnam = ['rmse_post_',deblank(vvarvecm(i,:))]; + % else + % if options_.opt_gsa.pprior + % fnam = ['rmse_prior_',deblank(vvarvecm(i,:))]; + % else + % fnam = ['rmse_mc_',deblank(vvarvecm(i,:))]; + % end + % end + % stab_map_2(x(ixx(1:nfilt0(i),i),:),alpha2,pvalue,fnam, OutDir,[],[temp_name ' observed variable ' deblank(vvarvecm(i,:))]); + % + % % [pc,latent,explained] = pcacov(c0); + % % %figure, bar([explained cumsum(explained)]) + % % ifig=0; + % % j2=0; + % % for j=1:npar+nshock, + % % i2=find(abs(pc(:,j))>alphaPC); + % % if ~isempty(i2), + % % j2=j2+1; + % % if mod(j2,12)==1, + % % ifig=ifig+1; + % % figure('name',['PCA of the filtered sample ',deblank(vvarvecm(i,:)),' ',num2str(ifig)]), + % % end + % % subplot(3,4,j2-(ifig-1)*12) + % % bar(pc(i2,j)), + % % set(gca,'xticklabel',bayestopt_.name(i2)), + % % set(gca,'xtick',[1:length(i2)]) + % % title(['PC ',num2str(j),'. Explained ',num2str(explained(j)),'%']) + % % end + % % if (mod(j2,12)==0 | j==(npar+nshock)) & j2, + % % saveas(gcf,[fname_,'_SA_PCA_',deblank(vvarvecm(i,:)),'_',int2str(ifig)]) + % % end + % % end + % % close all + % end + end function []=create_TeX_loader(options_,figpath,label_number,caption,label_name,scale_factor) @@ -1006,7 +1006,7 @@ end function [pnames,pnames_tex]=get_LaTeX_parameter_names(M_,options_,estim_params_,bayestopt_) np=size(bayestopt_.name,1); pnames=cell(np,1); -pnames_tex=cell(np,1); +pnames_tex=cell(np,1); for ii=1:length(bayestopt_.name) if options_.TeX [param_name_temp, param_name_tex_temp]= get_the_name(ii,options_.TeX,M_,estim_params_,options_); @@ -1017,4 +1017,3 @@ for ii=1:length(bayestopt_.name) pnames{ii,1} = param_name_temp; end end - diff --git a/matlab/gsa/ghx2transition.m b/matlab/gsa/ghx2transition.m index fc957a7aa2..df404577a9 100644 --- a/matlab/gsa/ghx2transition.m +++ b/matlab/gsa/ghx2transition.m @@ -3,7 +3,7 @@ function [A,B] = ghx2transition(mm,iv,ic,aux) % % Adapted by M. Ratto (from kalman_transition_matrix.m) % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % % Copyright (C) 2012-2017 Dynare Team @@ -25,10 +25,10 @@ function [A,B] = ghx2transition(mm,iv,ic,aux) global oo_ M_ - [nr1, nc1] = size(mm); - ghx = mm(:, [1:(nc1-M_.exo_nbr)]); - ghu = mm(:, [(nc1-M_.exo_nbr+1):end] ); - if nargin == 1 +[nr1, nc1] = size(mm); +ghx = mm(:, [1:(nc1-M_.exo_nbr)]); +ghu = mm(:, [(nc1-M_.exo_nbr+1):end] ); +if nargin == 1 oo_.dr.ghx = ghx; oo_.dr.ghu = ghu; endo_nbr = M_.endo_nbr; @@ -40,18 +40,18 @@ global oo_ M_ k = find(aux(:,2) > nspred); aux(:,2) = aux(:,2) + nstatic; aux(k,2) = aux(k,2) + M_.nfwrd; - end - n_iv = length(iv); - n_ir1 = size(aux,1); - nr = n_iv + n_ir1; - - A = zeros(nr,nr); - B = zeros(nr,M_.exo_nbr); - - i_n_iv = 1:n_iv; - A(i_n_iv,ic) = ghx(iv,:); - if n_ir1 > 0 +end +n_iv = length(iv); +n_ir1 = size(aux,1); +nr = n_iv + n_ir1; + +A = zeros(nr,nr); +B = zeros(nr,M_.exo_nbr); + +i_n_iv = 1:n_iv; +A(i_n_iv,ic) = ghx(iv,:); +if n_ir1 > 0 A(n_iv+1:end,:) = sparse(aux(:,1),aux(:,2),ones(n_ir1,1),n_ir1,nr); - end - - B(i_n_iv,:) = ghu(iv,:); +end + +B(i_n_iv,:) = ghu(iv,:); diff --git a/matlab/gsa/gsa_plotmatrix.m b/matlab/gsa/gsa_plotmatrix.m index 7b6e44ded2..634ea4f453 100644 --- a/matlab/gsa/gsa_plotmatrix.m +++ b/matlab/gsa/gsa_plotmatrix.m @@ -1,10 +1,10 @@ function gsa_plotmatrix(type,varargin) % function gsa_plotmatrix(type,varargin) -% extended version of the standard MATLAB plotmatrix +% extended version of the standard MATLAB plotmatrix % % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % Copyright (C) 2011-2012 European Commission % Copyright (C) 2011-2012 Dynare Team @@ -38,31 +38,31 @@ end iexplosive = iunstable(~ismember(iunstable,[iindeterm;iwrong])); switch type - case 'all' - x=[lpmat0 lpmat]; - NumberOfDraws=size(x,1); - B=NumberOfDraws; - case 'stable' - x=[lpmat0(istable,:) lpmat(istable,:)]; - NumberOfDraws=size(x,1); - B=NumberOfDraws; - case 'nosolution' - x=[lpmat0(iunstable,:) lpmat(iunstable,:)]; - NumberOfDraws=size(x,1); - B=NumberOfDraws; - case 'unstable' - x=[lpmat0(iexplosive,:) lpmat(iexplosive,:)]; - NumberOfDraws=size(x,1); - B=NumberOfDraws; - case 'indeterm' - x=[lpmat0(iindeterm,:) lpmat(iindeterm,:)]; - NumberOfDraws=size(x,1); - B=NumberOfDraws; - case 'wrong' - x=[lpmat0(iwrong,:) lpmat(iwrong,:)]; - NumberOfDraws=size(x,1); - B=NumberOfDraws; - + case 'all' + x=[lpmat0 lpmat]; + NumberOfDraws=size(x,1); + B=NumberOfDraws; + case 'stable' + x=[lpmat0(istable,:) lpmat(istable,:)]; + NumberOfDraws=size(x,1); + B=NumberOfDraws; + case 'nosolution' + x=[lpmat0(iunstable,:) lpmat(iunstable,:)]; + NumberOfDraws=size(x,1); + B=NumberOfDraws; + case 'unstable' + x=[lpmat0(iexplosive,:) lpmat(iexplosive,:)]; + NumberOfDraws=size(x,1); + B=NumberOfDraws; + case 'indeterm' + x=[lpmat0(iindeterm,:) lpmat(iindeterm,:)]; + NumberOfDraws=size(x,1); + B=NumberOfDraws; + case 'wrong' + x=[lpmat0(iwrong,:) lpmat(iwrong,:)]; + NumberOfDraws=size(x,1); + B=NumberOfDraws; + end if isempty(x) diff --git a/matlab/gsa/gsa_skewness.m b/matlab/gsa/gsa_skewness.m index 24ced80133..4f09b91ca2 100644 --- a/matlab/gsa/gsa_skewness.m +++ b/matlab/gsa/gsa_skewness.m @@ -2,7 +2,7 @@ function s=gsa_skewness(y) % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % Copyright (C) 2012 European Commission % Copyright (C) 2012 Dynare Team @@ -24,6 +24,6 @@ function s=gsa_skewness(y) % y=stand_(y); % s=mean(y.^3); - m2=mean((y-mean(y)).^2); - m3=mean((y-mean(y)).^3); - s=m3/m2^1.5; \ No newline at end of file +m2=mean((y-mean(y)).^2); +m3=mean((y-mean(y)).^3); +s=m3/m2^1.5; \ No newline at end of file diff --git a/matlab/gsa/gsa_speed.m b/matlab/gsa/gsa_speed.m index fbbf58e74b..d3b3d2b460 100644 --- a/matlab/gsa/gsa_speed.m +++ b/matlab/gsa/gsa_speed.m @@ -3,7 +3,7 @@ function [tadj, iff] = gsa_speed(A,B,mf,p) % % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % Copyright (C) 2012 European Commission % Copyright (C) 2012 Dynare Team @@ -34,24 +34,24 @@ disp('Computing speed of adjustement ...') h = dyn_waitbar(0,'Speed of adjustement...'); for i=1:nrun - irf=zeros(nvar,nshock); - a=squeeze(A(:,:,i)); - b=squeeze(B(:,:,i)); - IFF=inv(eye(nstate)-a)*b; - iff(:,:,i)=IFF(mf,:); - IF=IFF-b; - - t=0; - while any(any(irf<0.5)) - t=t+1; - IFT=((eye(nstate)-a^(t+1))*inv(eye(nstate)-a))*b-b; - irf=IFT(mf,:)./(IF(mf,:)+eps); - irf = irf.*(abs(IF(mf,:))>1.e-7)+(abs(IF(mf,:))<=1.e-7); - %irf=ft(mf,:); - tt=(irf>0.5).*t; - tadj(:,:,i)=((tt-tadj(:,:,i))==tt).*tt+tadj(:,:,i); - end - dyn_waitbar(i/nrun,h) + irf=zeros(nvar,nshock); + a=squeeze(A(:,:,i)); + b=squeeze(B(:,:,i)); + IFF=inv(eye(nstate)-a)*b; + iff(:,:,i)=IFF(mf,:); + IF=IFF-b; + + t=0; + while any(any(irf<0.5)) + t=t+1; + IFT=((eye(nstate)-a^(t+1))*inv(eye(nstate)-a))*b-b; + irf=IFT(mf,:)./(IF(mf,:)+eps); + irf = irf.*(abs(IF(mf,:))>1.e-7)+(abs(IF(mf,:))<=1.e-7); + %irf=ft(mf,:); + tt=(irf>0.5).*t; + tadj(:,:,i)=((tt-tadj(:,:,i))==tt).*tt+tadj(:,:,i); + end + dyn_waitbar(i/nrun,h) end skipline() disp('.. done !') diff --git a/matlab/gsa/log_trans_.m b/matlab/gsa/log_trans_.m index f31b434d3c..5d35c1c6ad 100644 --- a/matlab/gsa/log_trans_.m +++ b/matlab/gsa/log_trans_.m @@ -2,7 +2,7 @@ function [yy, xdir, isig, lam]=log_trans_(y0,xdir0,isig,lam) % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % Copyright (C) 2012 European Commission % Copyright (C) 2012 Dynare Team @@ -29,57 +29,57 @@ if nargin==4 end if nargin==1 - xdir0=''; + xdir0=''; end f=@(lam,y)gsa_skewness(log(y+lam)); isig=1; if ~(max(y0)<0 | min(y0)>0) - if gsa_skewness(y0)<0, - isig=-1; - y0=-y0; - end - n=hist(y0,10); - if n(1)>20*n(end) - try - lam=fzero(f,[-min(y0)+10*eps -min(y0)+abs(median(y0))],[],y0); - catch - yl(1)=f(-min(y0)+10*eps,y0); - yl(2)=f(-min(y0)+abs(median(y0)),y0); - if abs(yl(1))<abs(yl(2)) - lam=-min(y0)+eps; - else - lam = -min(y0)+abs(median(y0)); %abs(100*(1+min(y0))); - end + if gsa_skewness(y0)<0, + isig=-1; + y0=-y0; end - yy = log(y0+lam); - xdir=[xdir0,'_logskew']; - else - isig=0; - lam=0; - yy = log(y0.^2); - xdir=[xdir0,'_logsquared']; - end -else - if max(y0)<0 - isig=-1; - y0=-y0; - %yy=log(-y0); - xdir=[xdir0,'_minuslog']; - elseif min(y0)>0 - %yy=log(y0); - xdir=[xdir0,'_log']; - end - try - lam=fzero(f,[-min(y0)+10*eps -min(y0)+median(y0)],[],y0); - catch - yl(1)=f(-min(y0)+10*eps,y0); - yl(2)=f(-min(y0)+abs(median(y0)),y0); - if abs(yl(1))<abs(yl(2)) - lam=-min(y0)+eps; + n=hist(y0,10); + if n(1)>20*n(end) + try + lam=fzero(f,[-min(y0)+10*eps -min(y0)+abs(median(y0))],[],y0); + catch + yl(1)=f(-min(y0)+10*eps,y0); + yl(2)=f(-min(y0)+abs(median(y0)),y0); + if abs(yl(1))<abs(yl(2)) + lam=-min(y0)+eps; + else + lam = -min(y0)+abs(median(y0)); %abs(100*(1+min(y0))); + end + end + yy = log(y0+lam); + xdir=[xdir0,'_logskew']; else - lam = -min(y0)+abs(median(y0)); %abs(100*(1+min(y0))); + isig=0; + lam=0; + yy = log(y0.^2); + xdir=[xdir0,'_logsquared']; + end +else + if max(y0)<0 + isig=-1; + y0=-y0; + %yy=log(-y0); + xdir=[xdir0,'_minuslog']; + elseif min(y0)>0 + %yy=log(y0); + xdir=[xdir0,'_log']; + end + try + lam=fzero(f,[-min(y0)+10*eps -min(y0)+median(y0)],[],y0); + catch + yl(1)=f(-min(y0)+10*eps,y0); + yl(2)=f(-min(y0)+abs(median(y0)),y0); + if abs(yl(1))<abs(yl(2)) + lam=-min(y0)+eps; + else + lam = -min(y0)+abs(median(y0)); %abs(100*(1+min(y0))); + end end - end - lam = max(lam,0); - yy = log(y0+lam); + lam = max(lam,0); + yy = log(y0+lam); end diff --git a/matlab/gsa/map_calibration.m b/matlab/gsa/map_calibration.m index 8a1729f0fd..c7f707d492 100644 --- a/matlab/gsa/map_calibration.m +++ b/matlab/gsa/map_calibration.m @@ -2,7 +2,7 @@ function map_calibration(OutputDirectoryName, Model, DynareOptions, DynareResult % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % Copyright (C) 2014-2016 European Commission % Copyright (C) 2014-2017 Dynare Team @@ -28,7 +28,7 @@ np = EstimatedParameters.np; nshock = EstimatedParameters.nvx + EstimatedParameters.nvn + EstimatedParameters.ncx + EstimatedParameters.ncn; pnames=cell(np,1); pnames_tex=cell(np,1); -for jj=1:np +for jj=1:np if DynareOptions.TeX [param_name_temp, param_name_tex_temp]= get_the_name(nshock+jj, DynareOptions.TeX, Model, EstimatedParameters, DynareOptions); pnames_tex{jj,1} = strrep(param_name_tex_temp,'$',''); @@ -92,12 +92,12 @@ if init for ij=1:nbr_irf_restrictions mat_irf{ij}=NaN(Nsam,length(DynareOptions.endogenous_prior_restrictions.irf{ij,3})); end - + mat_moment=cell(nbr_moment_restrictions,1); for ij=1:nbr_moment_restrictions mat_moment{ij}=NaN(Nsam,length(DynareOptions.endogenous_prior_restrictions.moment{ij,3})); end - + irestrictions = [1:Nsam]; h = dyn_waitbar(0,'Please wait...'); for j=1:Nsam @@ -127,7 +127,7 @@ if init dyn_waitbar(j/Nsam,h,['MC iteration ',int2str(j),'/',int2str(Nsam)]) end dyn_waitbar_close(h); - + irestrictions=irestrictions(find(irestrictions)); xmat=lpmat(irestrictions,:); skipline() @@ -165,7 +165,7 @@ if ~isempty(indx_irf) end disp('done !') skipline() - + % For single legend search which has maximum nbr of restrictions all_irf_couples = cellstr([char(endo_prior_restrictions.irf(:,1)) char(endo_prior_restrictions.irf(:,2))]); irf_couples = unique(all_irf_couples); @@ -188,7 +188,7 @@ if ~isempty(indx_irf) time_matrix{plot_indx(ij)} = [time_matrix{plot_indx(ij)} endo_prior_restrictions.irf{ij,3}]; end iplot_indx = ones(size(plot_indx)); - + indx_irf = indx_irf(irestrictions,:); if ~DynareOptions.nograph h1=dyn_figure(DynareOptions.nodisplay,'name',[type ' evaluation of irf restrictions']); @@ -260,7 +260,7 @@ if ~isempty(indx_irf) if ~isempty(indx1) && ~isempty(indx2) mcf_analysis(xmat(:,nshock+1:end), indx1, indx2, options_mcf, DynareOptions); end - + % [proba, dproba] = stab_map_1(xmat, indx1, indx2, aname, 0); % indplot=find(proba<pvalue_ks); % if ~isempty(indplot) @@ -360,7 +360,7 @@ if ~isempty(indx_moment) end disp('done !') skipline() - + %get parameter names including standard deviations np=size(BayesInfo.name,1); name=cell(np,1); @@ -402,7 +402,7 @@ if ~isempty(indx_moment) time_matrix{plot_indx(ij)} = [time_matrix{plot_indx(ij)} endo_prior_restrictions.moment{ij,3}]; end iplot_indx = ones(size(plot_indx)); - + indx_moment = indx_moment(irestrictions,:); if ~DynareOptions.nograph h2=dyn_figure(DynareOptions.nodisplay,'name',[type ' evaluation of moment restrictions']); @@ -412,7 +412,7 @@ if ~isempty(indx_moment) ncol=nrow-1; end end - + for ij=1:nbr_moment_restrictions mat_moment{ij}=mat_moment{ij}(irestrictions,:); moment_matrix{plot_indx(ij)} = [moment_matrix{plot_indx(ij)} mat_moment{ij}]; @@ -470,7 +470,7 @@ if ~isempty(indx_moment) if ~isempty(indx1) && ~isempty(indx2) mcf_analysis(xmat, indx1, indx2, options_mcf, DynareOptions); end - + % [proba, dproba] = stab_map_1(xmat, indx1, indx2, aname, 0); % indplot=find(proba<pvalue_ks); % if ~isempty(indplot) @@ -538,7 +538,7 @@ if ~isempty(indx_moment) dyn_saveas(h2,[OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions'],DynareOptions.nodisplay,DynareOptions.graph_format); create_TeX_loader(DynareOptions,[OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions'],[type ' evaluation of moment restrictions'],'moment_restrictions',type,DynareOptions.figures.textwidth*min(ij/ncol,1)) end - + skipline() end return diff --git a/matlab/gsa/map_ident_.m b/matlab/gsa/map_ident_.m index 50f27cc2da..fa23574dd2 100644 --- a/matlab/gsa/map_ident_.m +++ b/matlab/gsa/map_ident_.m @@ -2,7 +2,7 @@ function map_ident_(OutputDirectoryName,opt_gsa) % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % Copyright (C) 2012-2016 European Commission % Copyright (C) 2012-2017 Dynare Team @@ -32,23 +32,23 @@ itrans = opt_gsa.trans_ident; np = estim_params_.np; if opt_gsa.load_ident_files - gsa_flag=0; + gsa_flag=0; else - gsa_flag=-2; + gsa_flag=-2; end pnames = M_.param_names(estim_params_.param_vals(:,1),:); - if opt_gsa.pprior +if opt_gsa.pprior -filetoload=[OutputDirectoryName '/' fname_ '_prior']; - else -filetoload=[OutputDirectoryName '/' fname_ '_mc']; - end + filetoload=[OutputDirectoryName '/' fname_ '_prior']; +else + filetoload=[OutputDirectoryName '/' fname_ '_mc']; +end load(filetoload,'lpmat','lpmat0','istable','T','yys','nspred','nboth','nfwrd') if ~isempty(lpmat0) - lpmatx=lpmat0(istable,:); + lpmatx=lpmat0(istable,:); else - lpmatx=[]; + lpmatx=[]; end Nsam = size(lpmat,1); nshock = size(lpmat0,2); @@ -57,139 +57,139 @@ npT = np+nshock; fname_ = M_.fname; if opt_gsa.load_ident_files==0 - % th moments -% options_.ar = min(3,options_.ar); - - mss = yys(bayestopt_.mfys,:); - mss = teff(mss(:,istable),Nsam,istable); - yys = teff(yys(oo_.dr.order_var,istable),Nsam,istable); - if exist('T') - [vdec, cc, ac] = mc_moments(T, lpmatx, oo_.dr); - else - return - end - - - if opt_gsa.morris==2 - pdraws = dynare_identification(options_.options_ident,[lpmatx lpmat(istable,:)]); -% [pdraws, TAU, GAM] = dynare_identification(options_.options_ident,[lpmatx lpmat(istable,:)]); - if ~isempty(pdraws) && max(max(abs(pdraws-[lpmatx lpmat(istable,:)])))==0 - disp(['Sample check OK ', num2str(max(max(abs(pdraws-[lpmatx lpmat(istable,:)]))))]), - clear pdraws; + % th moments + % options_.ar = min(3,options_.ar); + + mss = yys(bayestopt_.mfys,:); + mss = teff(mss(:,istable),Nsam,istable); + yys = teff(yys(oo_.dr.order_var,istable),Nsam,istable); + if exist('T') + [vdec, cc, ac] = mc_moments(T, lpmatx, oo_.dr); + else + return end -% for j=1:length(istable), gas(:,j)=[vech(cc(:,:,j)); vec(ac(:,:,j))]; end -% if ~isempty(mss), -% gas = [mss(istable,:)'; gas]; -% end -% if max(max(abs(GAM-gas)))<=1.e-8, -% disp(['Moments check OK ',num2str(max(max(abs(GAM-gas))))]), - clear GAM gas -% end - end - if opt_gsa.morris~=1 & M_.exo_nbr>1 - ifig=0; - for j=1:M_.exo_nbr - if mod(j,6)==1 - hh=dyn_figure(options_.nodisplay,'name',['Variance decomposition shocks']); - ifig=ifig+1; - iplo=0; - end - iplo=iplo+1; - subplot(2,3,iplo) - myboxplot(squeeze(vdec(:,j,:))',[],'.',[],10) - % boxplot(squeeze(vdec(:,j,:))','whis',10,'symbol','.r') - set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:size(options_.varobs,1)]) - set(gca,'xlim',[0.5 size(options_.varobs,1)+0.5]) - set(gca,'ylim',[-2 102]) - for ip=1:size(options_.varobs,1) - text(ip,-4,deblank(options_.varobs(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') - end - xlabel(' ') - ylabel(' ') - title(M_.exo_names(j,:),'interpreter','none') - if mod(j,6)==0 | j==M_.exo_nbr - dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_vdec_exo_',int2str(ifig)],options_.nodisplay,options_.graph_format); - create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_vdec_exo_',int2str(ifig)],ifig,['Variance decomposition shocks'],'vdec_exo',options_.figures.textwidth*min(iplo/3,1)) - end + + + if opt_gsa.morris==2 + pdraws = dynare_identification(options_.options_ident,[lpmatx lpmat(istable,:)]); + % [pdraws, TAU, GAM] = dynare_identification(options_.options_ident,[lpmatx lpmat(istable,:)]); + if ~isempty(pdraws) && max(max(abs(pdraws-[lpmatx lpmat(istable,:)])))==0 + disp(['Sample check OK ', num2str(max(max(abs(pdraws-[lpmatx lpmat(istable,:)]))))]), + clear pdraws; + end + % for j=1:length(istable), gas(:,j)=[vech(cc(:,:,j)); vec(ac(:,:,j))]; end + % if ~isempty(mss), + % gas = [mss(istable,:)'; gas]; + % end + % if max(max(abs(GAM-gas)))<=1.e-8, + % disp(['Moments check OK ',num2str(max(max(abs(GAM-gas))))]), + clear GAM gas + % end + end + if opt_gsa.morris~=1 & M_.exo_nbr>1 + ifig=0; + for j=1:M_.exo_nbr + if mod(j,6)==1 + hh=dyn_figure(options_.nodisplay,'name',['Variance decomposition shocks']); + ifig=ifig+1; + iplo=0; + end + iplo=iplo+1; + subplot(2,3,iplo) + myboxplot(squeeze(vdec(:,j,:))',[],'.',[],10) + % boxplot(squeeze(vdec(:,j,:))','whis',10,'symbol','.r') + set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:size(options_.varobs,1)]) + set(gca,'xlim',[0.5 size(options_.varobs,1)+0.5]) + set(gca,'ylim',[-2 102]) + for ip=1:size(options_.varobs,1) + text(ip,-4,deblank(options_.varobs(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + end + xlabel(' ') + ylabel(' ') + title(M_.exo_names(j,:),'interpreter','none') + if mod(j,6)==0 | j==M_.exo_nbr + dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_vdec_exo_',int2str(ifig)],options_.nodisplay,options_.graph_format); + create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_vdec_exo_',int2str(ifig)],ifig,['Variance decomposition shocks'],'vdec_exo',options_.figures.textwidth*min(iplo/3,1)) + end + end + end + for j=1:size(cc,1) + cc(j,j,:)=stand_(squeeze(log(cc(j,j,:))))./2; end - end - for j=1:size(cc,1) - cc(j,j,:)=stand_(squeeze(log(cc(j,j,:))))./2; - end - [vdec, j0, ir_vdec, ic_vdec] = teff(vdec,Nsam,istable); - [cc, j0, ir_cc, ic_cc] = teff(cc,Nsam,istable); - [ac, j0, ir_ac, ic_ac] = teff(ac,Nsam,istable); - - [nr1, nc1, nnn] = size(T); + [vdec, j0, ir_vdec, ic_vdec] = teff(vdec,Nsam,istable); + [cc, j0, ir_cc, ic_cc] = teff(cc,Nsam,istable); + [ac, j0, ir_ac, ic_ac] = teff(ac,Nsam,istable); + + [nr1, nc1, nnn] = size(T); endo_nbr = M_.endo_nbr; nstatic = M_.nstatic; nspred = M_.nspred; iv = (1:endo_nbr)'; ic = [ nstatic+(1:nspred) endo_nbr+(1:size(oo_.dr.ghx,2)-nspred) ]'; - + dr.ghx = T(:, [1:(nc1-M_.exo_nbr)],1); dr.ghu = T(:, [(nc1-M_.exo_nbr+1):end], 1); [Aa,Bb] = kalman_transition_matrix(dr,iv,ic,M_.exo_nbr); -% bayestopt_.restrict_var_list, ... -% bayestopt_.restrict_columns, ... -% bayestopt_.restrict_aux, M_.exo_nbr); - A = zeros(size(Aa,1),size(Aa,2)+size(Aa,1),length(istable)); - % Sig(estim_params_.var_exo(:,1))=lpmatx(1,:).^2; - if ~isempty(lpmatx) - set_shocks_param(lpmatx(1,:)); - end - A(:,:,1)=[Aa, triu(Bb*M_.Sigma_e*Bb')]; - for j=2:length(istable) - dr.ghx = T(:, [1:(nc1-M_.exo_nbr)],j); - dr.ghu = T(:, [(nc1-M_.exo_nbr+1):end], j); - [Aa,Bb] = kalman_transition_matrix(dr, iv, ic, M_.exo_nbr); -% bayestopt_.restrict_var_list, ... -% bayestopt_.restrict_columns, ... -% bayestopt_.restrict_aux, M_.exo_nbr); + % bayestopt_.restrict_var_list, ... + % bayestopt_.restrict_columns, ... + % bayestopt_.restrict_aux, M_.exo_nbr); + A = zeros(size(Aa,1),size(Aa,2)+size(Aa,1),length(istable)); + % Sig(estim_params_.var_exo(:,1))=lpmatx(1,:).^2; if ~isempty(lpmatx) - set_shocks_param(lpmatx(j,:)); + set_shocks_param(lpmatx(1,:)); end - A(:,:,j)=[Aa, triu(Bb*M_.Sigma_e*Bb')]; - end - clear T - clear lpmatx - - [nr,nc,nn]=size(A); - io=bayestopt_.mf2; - % T1=A(io,1:nr,:); - % ino=find(~ismember([1:nr],io)); - % T2=A(ino,1:nr,:); - R=A(:,nr+1:nc,:); -% [tadj, iff] = gsa_speed(A(1:nr,1:nr,:),R,io,0.5); -% [tadj, j0, ir_tadj, ic_tadj] = teff(tadj,Nsam,istable); -% [iff, j0, ir_if, ic_if] = teff(iff,Nsam,istable); - - - [yt, j0]=teff(A,Nsam,istable); - yt = [yys yt]; - if opt_gsa.morris==2 -% iii=find(std(yt(istable,:))>1.e-8); -% if max(max(abs(TAU-yt(istable,iii)')))<= 1.e-8, -% err = max(max(abs(TAU-yt(istable,iii)'))); -% disp(['Model check OK ',num2str(err)]), - clear TAU A -% end - else - clear A - end - % [yt1, j01]=teff(T1,Nsam,istable); - % [yt2, j02]=teff(T2,Nsam,istable); - % [ytr, j0r]=teff(R,Nsam,istable); - % - % yt=[yt1 yt2 ytr]; - save([OutputDirectoryName,'/',fname_,'_main_eff.mat'],'ac','cc','vdec','yt','mss') + A(:,:,1)=[Aa, triu(Bb*M_.Sigma_e*Bb')]; + for j=2:length(istable) + dr.ghx = T(:, [1:(nc1-M_.exo_nbr)],j); + dr.ghu = T(:, [(nc1-M_.exo_nbr+1):end], j); + [Aa,Bb] = kalman_transition_matrix(dr, iv, ic, M_.exo_nbr); + % bayestopt_.restrict_var_list, ... + % bayestopt_.restrict_columns, ... + % bayestopt_.restrict_aux, M_.exo_nbr); + if ~isempty(lpmatx) + set_shocks_param(lpmatx(j,:)); + end + A(:,:,j)=[Aa, triu(Bb*M_.Sigma_e*Bb')]; + end + clear T + clear lpmatx + + [nr,nc,nn]=size(A); + io=bayestopt_.mf2; + % T1=A(io,1:nr,:); + % ino=find(~ismember([1:nr],io)); + % T2=A(ino,1:nr,:); + R=A(:,nr+1:nc,:); + % [tadj, iff] = gsa_speed(A(1:nr,1:nr,:),R,io,0.5); + % [tadj, j0, ir_tadj, ic_tadj] = teff(tadj,Nsam,istable); + % [iff, j0, ir_if, ic_if] = teff(iff,Nsam,istable); + + + [yt, j0]=teff(A,Nsam,istable); + yt = [yys yt]; + if opt_gsa.morris==2 + % iii=find(std(yt(istable,:))>1.e-8); + % if max(max(abs(TAU-yt(istable,iii)')))<= 1.e-8, + % err = max(max(abs(TAU-yt(istable,iii)'))); + % disp(['Model check OK ',num2str(err)]), + clear TAU A + % end + else + clear A + end + % [yt1, j01]=teff(T1,Nsam,istable); + % [yt2, j02]=teff(T2,Nsam,istable); + % [ytr, j0r]=teff(R,Nsam,istable); + % + % yt=[yt1 yt2 ytr]; + save([OutputDirectoryName,'/',fname_,'_main_eff.mat'],'ac','cc','vdec','yt','mss') else - if opt_gsa.morris==2 -% [pdraws, TAU, GAM] = dynare_identification([1:npT]); %,[lpmatx lpmat(istable,:)]); -% [pdraws, TAU, GAM] = dynare_identification(options_.options_ident); - pdraws = dynare_identification(options_.options_ident); - end - load([OutputDirectoryName,'/',fname_,'_main_eff.mat'],'ac','cc','vdec','yt','mss') + if opt_gsa.morris==2 + % [pdraws, TAU, GAM] = dynare_identification([1:npT]); %,[lpmatx lpmat(istable,:)]); + % [pdraws, TAU, GAM] = dynare_identification(options_.options_ident); + pdraws = dynare_identification(options_.options_ident); + end + load([OutputDirectoryName,'/',fname_,'_main_eff.mat'],'ac','cc','vdec','yt','mss') end % for j=1:nr, @@ -206,1352 +206,1352 @@ end % yt = yt(:,j0); if opt_gsa.morris==1 - %OutputDir = CheckPath('gsa/screen'); - if ~isempty(vdec) - if opt_gsa.load_ident_files==0 - SAMorris = []; - for i=1:size(vdec,2) - [SAmeas, SAMorris(:,:,i)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], vdec(:,i),nliv); - end - SAvdec = squeeze(SAMorris(:,1,:))'; - save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'SAvdec','vdec','ir_vdec','ic_vdec') - else - load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAvdec','vdec','ir_vdec','ic_vdec') - end - - hh = dyn_figure(options_.nodisplay,'name','Screening identification: variance decomposition'); -% boxplot(SAvdec,'whis',10,'symbol','r.') - myboxplot(SAvdec,[],'.',[],10) - set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) - set(gca,'xlim',[0.5 npT+0.5]) - ydum = get(gca,'ylim'); - set(gca,'ylim',[0 ydum(2)]) - set(gca,'position',[0.13 0.2 0.775 0.7]) - for ip=1:npT - text(ip,-2,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') - end - xlabel(' ') - title('Elementary effects variance decomposition') - dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_vdec'],options_.nodisplay,options_.graph_format); - create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_vdec'],1,'Screening identification: variance decomposition','morris_vdec',1) - else - save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'vdec') - - end - -% ifig = 0; -% for j=1:size(options_.varobs,1) -% if mod(j,6)==1 -% figure('name',['EET variance decomposition observed variables']); -% ifig=ifig+1; -% iplo=0; -% end -% iplo=iplo+1; -% subplot(3,2,iplo) -% iv = find(ir_vdec==j); -% if ~isempty(iv) -% if length(iv)>1 -% % boxplot(SAvdec(iv,:),'whis',3,'symbol','r.'); -% myboxplot(SAvdec(iv,:),[],'.',[],3) -% else -% plot(SAvdec(iv,:),'r.'); -% end -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) -% set(gca,'xlim',[0.5 npT+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% for ip=1:npT, -% text(ip,-2,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% end -% title(options_.varobs(j,:),'interpreter','none') -% if mod(j,6)==0 | j==size(options_.varobs,1) -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_vdec_varobs_',int2str(ifig)]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_vdec_varobs_',int2str(ifig)]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_vdec_varobs_',int2str(ifig)]); -% close(gcf) -% end -% end -% -% ifig = 0; -% for j=1:M_.exo_nbr, -% if mod(j,6)==1 -% figure('name',['EET variance decomposition shocks']); -% ifig=ifig+1; -% iplo=0; -% end -% iplo=iplo+1; -% subplot(3,2,iplo) -% iv = find(ic_vdec==j); -% if ~isempty(iv) -% if length(iv)>1 -% % boxplot(SAvdec(iv,:),'whis',3,'symbol','r.'); -% myboxplot(SAvdec(iv,:),[],'.',[],3) -% else -% plot(SAvdec(iv,:),'r.'); -% end -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) -% set(gca,'xlim',[0.5 npT+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% for ip=1:npT, -% text(ip,-2,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% end -% title(M_.exo_names(j,:),'interpreter','none') -% if mod(j,6)==0 | j==M_.exo_nbr, -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_vdec_exo_',int2str(ifig)]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_vdec_exo_',int2str(ifig)]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_vdec_exo_',int2str(ifig)]); -% close(gcf), -% end -% end + %OutputDir = CheckPath('gsa/screen'); + if ~isempty(vdec) + if opt_gsa.load_ident_files==0 + SAMorris = []; + for i=1:size(vdec,2) + [SAmeas, SAMorris(:,:,i)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], vdec(:,i),nliv); + end + SAvdec = squeeze(SAMorris(:,1,:))'; + save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'SAvdec','vdec','ir_vdec','ic_vdec') + else + load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAvdec','vdec','ir_vdec','ic_vdec') + end + hh = dyn_figure(options_.nodisplay,'name','Screening identification: variance decomposition'); + % boxplot(SAvdec,'whis',10,'symbol','r.') + myboxplot(SAvdec,[],'.',[],10) + set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) + set(gca,'xlim',[0.5 npT+0.5]) + ydum = get(gca,'ylim'); + set(gca,'ylim',[0 ydum(2)]) + set(gca,'position',[0.13 0.2 0.775 0.7]) + for ip=1:npT + text(ip,-2,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + end + xlabel(' ') + title('Elementary effects variance decomposition') + dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_vdec'],options_.nodisplay,options_.graph_format); + create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_vdec'],1,'Screening identification: variance decomposition','morris_vdec',1) + else + save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'vdec') - if opt_gsa.load_ident_files==0 - SAMorris = []; - ccac = [mss cc ac]; - for i=1:size(ccac,2) - [SAmeas, SAMorris(:,:,i)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], [ccac(:,i)],nliv); - end - SAcc = squeeze(SAMorris(:,1,:))'; - SAcc = SAcc./(max(SAcc')'*ones(1,npT)); - save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'SAcc','cc','ir_cc','ic_cc','-append') - save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'ac','ir_ac','ic_ac','-append') - else - load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAcc','cc','ir_cc','ic_cc') - load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'ac','ir_ac','ic_ac') - end - - hh=dyn_figure(options_.nodisplay,'name','Screening identification: theoretical moments'); -% boxplot(SAcc,'whis',10,'symbol','r.') - myboxplot(SAcc,[],'.',[],10) - set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) - set(gca,'xlim',[0.5 npT+0.5]) - ydum = get(gca,'ylim'); - set(gca,'ylim',[0 1]) - set(gca,'position',[0.13 0.2 0.775 0.7]) - for ip=1:npT - text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') - end - xlabel(' ') - title('Elementary effects in the moments') - dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_moments'],options_.nodisplay,options_.graph_format); - create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_moments'],1,'Screening identification: theoretical moments','morris_moments',1) - -% close(gcf), - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% MORRIS FOR DERIVATIVES -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -% if opt_gsa.load_ident_files==0, -% for j=1:npT, -% SAMorris = []; -% ddd=NaN(size(lpmat,1),size(JJ,1)); -% ddd(istable,:) = squeeze(JJ(:,j,:))'; -% for i=1:size(ddd,2), -% [SAmeas, SAMorris(:,:,i)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], [ddd(:,i)],nliv); -% end -% SAddd(:,:,j) = squeeze(SAMorris(:,1,:))'; -% SAddd(:,:,j) = SAddd(:,:,j)./(max(SAddd(:,:,j)')'*ones(1,npT)); -% sad(:,j) = median(SAddd(find(~isnan(squeeze(SAddd(:,1,j)))),:,j))'; -% end -% save([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAddd','sad','-append') -% else -% load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAddd','sad') -% end -% figure, -% contourf(sad,10), colorbar -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) -% set(gca,'yticklabel',' ','fontsize',10,'ytick',[1:npT]) -% for ip=1:npT, -% text(ip,0.9,['D(',bayestopt_.name{ip},')'],'rotation',90,'HorizontalAlignment','right','interpreter','none') -% text(0.9,ip,[bayestopt_.name{ip}],'rotation',0,'HorizontalAlignment','right','interpreter','none') -% end -% [m,im]=max(sad); -% iii = find((im-[1:npT])==0); -% disp('Most identified params') -% disp(bayestopt_.name(iii)) - - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% END OF MORRIS FOR DERIVATIVES -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -% ifig = 0; -% for j=1:size(options_.varobs,1) -% if mod(j,6)==1 -% figure('name',['EET cross-correlations']); -% ifig=ifig+1; -% iplo=0; -% end -% iplo=iplo+1; -% subplot(3,2,iplo) -% iv = find(ir_cc==j); -% iv = [iv; find(ic_cc==j)]; -% if ~isempty(iv) -% if length(iv)>1 -% % boxplot(SAcc(iv,:),'whis',3,'symbol','r.'); -% myboxplot(SAcc(iv,:),[],'.',[],3) -% else -% plot(SAcc(iv,:),'r.'); -% end -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) -% set(gca,'xlim',[0.5 npT+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% for ip=1:npT, -% text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% end -% title(options_.varobs(j,:),'interpreter','none') -% if mod(j,6)==0 | j==size(options_.varobs,1) -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_cc_',int2str(ifig)]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_cc_',int2str(ifig)]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_cc_',int2str(ifig)]); -% close(gcf), -% end -% end + end + % ifig = 0; + % for j=1:size(options_.varobs,1) + % if mod(j,6)==1 + % figure('name',['EET variance decomposition observed variables']); + % ifig=ifig+1; + % iplo=0; + % end + % iplo=iplo+1; + % subplot(3,2,iplo) + % iv = find(ir_vdec==j); + % if ~isempty(iv) + % if length(iv)>1 + % % boxplot(SAvdec(iv,:),'whis',3,'symbol','r.'); + % myboxplot(SAvdec(iv,:),[],'.',[],3) + % else + % plot(SAvdec(iv,:),'r.'); + % end + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) + % set(gca,'xlim',[0.5 npT+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % for ip=1:npT, + % text(ip,-2,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % end + % title(options_.varobs(j,:),'interpreter','none') + % if mod(j,6)==0 | j==size(options_.varobs,1) + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_vdec_varobs_',int2str(ifig)]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_vdec_varobs_',int2str(ifig)]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_vdec_varobs_',int2str(ifig)]); + % close(gcf) + % end + % end + % + % ifig = 0; + % for j=1:M_.exo_nbr, + % if mod(j,6)==1 + % figure('name',['EET variance decomposition shocks']); + % ifig=ifig+1; + % iplo=0; + % end + % iplo=iplo+1; + % subplot(3,2,iplo) + % iv = find(ic_vdec==j); + % if ~isempty(iv) + % if length(iv)>1 + % % boxplot(SAvdec(iv,:),'whis',3,'symbol','r.'); + % myboxplot(SAvdec(iv,:),[],'.',[],3) + % else + % plot(SAvdec(iv,:),'r.'); + % end + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) + % set(gca,'xlim',[0.5 npT+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % for ip=1:npT, + % text(ip,-2,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % end + % title(M_.exo_names(j,:),'interpreter','none') + % if mod(j,6)==0 | j==M_.exo_nbr, + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_vdec_exo_',int2str(ifig)]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_vdec_exo_',int2str(ifig)]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_vdec_exo_',int2str(ifig)]); + % close(gcf), + % end + % end -% if opt_gsa.load_ident_files==0, -% SAMorris = []; -% for i=1:size(ac,2), -% [SAmeas, SAMorris(:,:,i)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], ac(:,i),nliv); -% end -% %end -% SAac = squeeze(SAMorris(:,1,:))'; -% save([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAac','ac','ir_ac','ic_ac','-append') -% else -% load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAac','ac','ir_ac','ic_ac') -% end -% figure, -% % boxplot(SAac,'whis',10,'symbol','r.') -% myboxplot(SAac,[],'.',[],10) -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) -% set(gca,'xlim',[0.5 npT+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% set(gca,'position',[0.13 0.2 0.775 0.7]) -% for ip=1:npT, -% text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% title('EET All auto-correlations') -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_ac']) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_ac']); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_ac']); -% close(gcf), - -% ifig = 0; -% for j=1:size(options_.varobs,1) -% if mod(j,6)==1 -% figure('name',['EET auto-correlations']); -% ifig=ifig+1; -% iplo=0; -% end -% iplo=iplo+1; -% subplot(3,2,iplo) -% iv = find(ir_ac==j); -% if ~isempty(iv) -% if length(iv)>1 -% % boxplot(SAac(iv,:),'whis',3,'symbol','r.'); -% myboxplot(SAac(iv,:),[],'.',[],3) -% else -% plot(SAac(iv,:),'r.'); -% end -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) -% set(gca,'xlim',[0.5 npT+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% for ip=1:npT, -% text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% end -% title(options_.varobs(j,:),'interpreter','none') -% if mod(j,6)==0 | j==size(options_.varobs,1) -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_ac_',int2str(ifig)]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_ac_',int2str(ifig)]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_ac_',int2str(ifig)]); -% close(gcf), -% end -% end -% if opt_gsa.load_ident_files==0, -% js=0; -% %for j=1:size(tadj,1), -% SAMorris = []; -% for i=1:size(tadj,2), -% js=js+1; -% [SAmeas, SAMorris(:,:,js)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], tadj(:,i),nliv); -% end -% %end -% SAM = squeeze(SAMorris(nshock+1:end,1,:)); -% for j=1:js, -% SAtadj(:,j)=SAM(:,j)./(max(SAM(:,j))+eps); -% end -% SAtadj = SAtadj'; -% save([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAtadj','tadj','ir_tadj','ic_tadj','-append') -% else -% load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAtadj','tadj','ir_tadj','ic_tadj') -% end -% if opt_gsa.load_ident_files==0, -% js=0; -% SAMorris = []; -% for i=1:size(iff,2), -% js=js+1; -% [SAmeas, SAMorriss(:,:,js)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], iff(:,i),nliv); -% end -% SAM = squeeze(SAMorriss(nshock+1:end,1,:)); -% for j=1:js, -% SAIF(:,j)=SAM(:,j)./(max(SAM(:,j))+eps); -% end -% SAIF = SAIF'; -% save([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAIF','iff','ir_if','ic_if','-append') -% else -% load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAIF','iff','ir_if','ic_if') -% end -% figure, -% %bar(SAtadj), -% % boxplot(SAtadj,'whis',10,'symbol','r.') -% myboxplot(SAtadj,[],'.',[],10) -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) -% set(gca,'xlim',[0.5 np+0.5]) -% set(gca,'ylim',[0 1]) -% set(gca,'position',[0.13 0.2 0.775 0.7]) -% for ip=1:np, -% text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% title('All half-life') -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_tadj']) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_tadj']); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_tadj']); -% close(gcf), - -% ifig = 0; -% for j=1:size(options_.varobs,1) -% if mod(j,6)==1 -% figure('name',['EET speed of adjustment observed variables']); -% ifig=ifig+1; -% iplo=0; -% end -% iplo=iplo+1; -% subplot(3,2,iplo) -% iv = find(ir_tadj==j); -% if ~isempty(iv) -% if length(iv)>1 -% % boxplot(SAtadj(iv,:),'whis',3,'symbol','r.'); -% myboxplot(SAtadj(iv,:),[],'.',[],3) -% else -% plot(SAtadj(iv,:),'r.'); -% end -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) -% set(gca,'xlim',[0.5 np+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% for ip=1:np, -% text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% end -% title(options_.varobs(j,:),'interpreter','none') -% if mod(j,6)==0 | j==size(options_.varobs,1) -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_tadj_varobs_',int2str(ifig)]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_tadj_varobs_',int2str(ifig)]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_tadj_varobs_',int2str(ifig)]); -% close(gcf), -% end -% end + if opt_gsa.load_ident_files==0 + SAMorris = []; + ccac = [mss cc ac]; + for i=1:size(ccac,2) + [SAmeas, SAMorris(:,:,i)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], [ccac(:,i)],nliv); + end + SAcc = squeeze(SAMorris(:,1,:))'; + SAcc = SAcc./(max(SAcc')'*ones(1,npT)); + save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'SAcc','cc','ir_cc','ic_cc','-append') + save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'ac','ir_ac','ic_ac','-append') + else + load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAcc','cc','ir_cc','ic_cc') + load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'ac','ir_ac','ic_ac') + end -% ifig = 0; -% for j=1:M_.exo_nbr, -% if mod(j,6)==1 -% figure('name',['EET speed of adjustment shocks']); -% ifig=ifig+1; -% iplo=0; -% end -% iplo=iplo+1; -% subplot(3,2,iplo) -% iv = find(ic_tadj==j); -% if ~isempty(iv) -% if length(iv)>1 -% % boxplot(SAtadj(iv,:),'whis',3,'symbol','r.'); -% myboxplot(SAtadj(iv,:),[],'.',[],3) -% else -% plot(SAtadj(iv,:),'r.'); -% end -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) -% set(gca,'xlim',[0.5 np+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% for ip=1:np, -% text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% end -% title(M_.exo_names(j,:),'interpreter','none') -% if mod(j,6)==0 | j==M_.exo_nbr, -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_tadj_exo_',int2str(ifig)]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_tadj_exo_',int2str(ifig)]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_tadj_exo_',int2str(ifig)]); -% close(gcf), -% end -% end + hh=dyn_figure(options_.nodisplay,'name','Screening identification: theoretical moments'); + % boxplot(SAcc,'whis',10,'symbol','r.') + myboxplot(SAcc,[],'.',[],10) + set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) + set(gca,'xlim',[0.5 npT+0.5]) + ydum = get(gca,'ylim'); + set(gca,'ylim',[0 1]) + set(gca,'position',[0.13 0.2 0.775 0.7]) + for ip=1:npT + text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + end + xlabel(' ') + title('Elementary effects in the moments') + dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_moments'],options_.nodisplay,options_.graph_format); + create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_moments'],1,'Screening identification: theoretical moments','morris_moments',1) -% figure, -% %bar(SAIF), -% % boxplot(SAIF,'whis',10,'symbol','r.') -% myboxplot(SAIF,[],'.',[],10) -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) -% set(gca,'xlim',[0.5 np+0.5]) -% set(gca,'ylim',[0 1]) -% set(gca,'position',[0.13 0.2 0.775 0.7]) -% for ip=1:np, -% text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% ylabel('Elementary Effects') -% title('Steady state gains (impact factors)') -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_gain']) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_gain']); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_gain']); -% close(gcf), - %figure, bar(SAIF'), title('All Gain Relationships') -% ifig = 0; -% for j=1:size(options_.varobs,1) -% if mod(j,6)==1 -% figure('name',['EET steady state gain observed series']); -% ifig=ifig+1; -% iplo=0; -% end -% iplo=iplo+1; -% subplot(3,2,iplo) -% iv = find(ir_if==j); -% if ~isempty(iv) -% if length(iv)>1 -% % boxplot(SAIF(iv,:),'whis',10,'symbol','r.'); -% myboxplot(SAIF(iv,:),[],'.',[],10) -% else -% plot(SAIF(iv,:),'r.'); -% end -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) -% set(gca,'xlim',[0.5 np+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% for ip=1:np, -% text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% end -% title(options_.varobs(j,:),'interpreter','none') -% if mod(j,6)==0 | j==size(options_.varobs,1) -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_gain_varobs_',int2str(ifig)]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_gain_varobs_',int2str(ifig)]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_gain_varobs_',int2str(ifig)]); -% close(gcf), -% end -% end -% -% ifig = 0; -% for j=1:M_.exo_nbr, -% if mod(j,6)==1 -% figure('name',['EET steady state gain shocks']); -% ifig=ifig+1; -% iplo=0; -% end -% iplo=iplo+1; -% subplot(3,2,iplo) -% iv = find(ic_if==j); -% if ~isempty(iv) -% if length(iv)>1 -% % boxplot(SAIF(iv,:),'whis',3,'symbol','r.'); -% myboxplot(SAIF(iv,:),[],'.',[],3) -% else -% plot(SAIF(iv,:),'r.'); -% end -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) -% set(gca,'xlim',[0.5 np+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% for ip=1:np, -% text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% end -% title(M_.exo_names(j,:),'interpreter','none') -% if mod(j,6)==0 | j==M_.exo_nbr, -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_gain_exo_',int2str(ifig)]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_gain_exo_',int2str(ifig)]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_gain_exo_',int2str(ifig)]); -% close(gcf), -% end -% end + % close(gcf), + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + % MORRIS FOR DERIVATIVES + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - if opt_gsa.load_ident_files==0 - SAMorris = []; - for j=1:j0 - [SAmeas, SAMorris(:,:,j)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], yt(:,j),nliv); - end - -% SAM = squeeze(SAMorris(nshock+1:end,1,:)); - SAM = squeeze(SAMorris(1:end,1,:)); - for j=1:j0 - SAnorm(:,j)=SAM(:,j)./max(SAM(:,j)); - irex(j)=length(find(SAnorm(:,j)>0.01)); - end - [dum, irel]=sort(irex); - -% SAMmu = squeeze(SAMorris(nshock+1:end,2,:)); - SAMmu = squeeze(SAMorris(1:end,2,:)); - for j=1:j0 - SAmunorm(:,j)=SAMmu(:,j)./max(SAM(:,j)); % normalised w.r.t. mu* - end -% SAMsig = squeeze(SAMorris(nshock+1:end,3,:)); - SAMsig = squeeze(SAMorris(1:end,3,:)); - for j=1:j0 - SAsignorm(:,j)=SAMsig(:,j)./max(SAMsig(:,j)); - end - save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'SAnorm','SAmunorm','SAsignorm','-append') - else - load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAnorm','SAmunorm','SAsignorm') - end - hh=dyn_figure(options_.nodisplay,'name','Screening identification: model'); %bar(SAnorm(:,irel)) -% boxplot(SAnorm','whis',10,'symbol','r.') - myboxplot(SAnorm',[],'.',[],10) - set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) - set(gca,'xlim',[0.5 npT+0.5]) - set(gca,'ylim',[0 1]) - set(gca,'position',[0.13 0.2 0.775 0.7]) - xlabel(' ') - for ip=1:npT -% text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') - text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') - end - xlabel(' ') - title('Elementary effects in the model') - dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_par'],options_.nodisplay,options_.graph_format); - create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_par'],1,'Screening identification: model','morris_par',1) - -% hh=dyn_figure(options_.nodisplay); %bar(SAmunorm(:,irel)) -% % boxplot(SAmunorm','whis',10,'symbol','r.') -% myboxplot(SAmunorm',[],'.',[],10) -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) -% set(gca,'xlim',[0.5 npT+0.5]) -% set(gca,'ylim',[-1 1]) -% set(gca,'position',[0.13 0.2 0.775 0.7]) -% xlabel(' ') -% for ip=1:npT, -% text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% title('\mu in the model') -% dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morrismu_par'],options_.nodisplay,options_.graph_format); -% -% hh=dyn_figure(options_.nodisplay); %bar(SAsignorm(:,irel)) -% % boxplot(SAsignorm','whis',10,'symbol','r.') -% myboxplot(SAsignorm',[],'.',[],10) -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) -% set(gca,'xlim',[0.5 npT+0.5]) -% set(gca,'ylim',[0 1]) -% set(gca,'position',[0.13 0.2 0.775 0.7]) -% xlabel(' ') -% for ip=1:npT, -% text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% title('\sigma in the model') -% dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morrissig_par'],options_.nodisplay,options_.graph_format); - - % figure, bar(SAnorm(:,irel)') - % set(gca,'xtick',[1:j0]) - % set(gca,'xlim',[0.5 j0+0.5]) - % title('Elementary effects relationships') - % saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_redform']) - % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_redform']); - % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_redform']); + % if opt_gsa.load_ident_files==0, + % for j=1:npT, + % SAMorris = []; + % ddd=NaN(size(lpmat,1),size(JJ,1)); + % ddd(istable,:) = squeeze(JJ(:,j,:))'; + % for i=1:size(ddd,2), + % [SAmeas, SAMorris(:,:,i)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], [ddd(:,i)],nliv); + % end + % SAddd(:,:,j) = squeeze(SAMorris(:,1,:))'; + % SAddd(:,:,j) = SAddd(:,:,j)./(max(SAddd(:,:,j)')'*ones(1,npT)); + % sad(:,j) = median(SAddd(find(~isnan(squeeze(SAddd(:,1,j)))),:,j))'; + % end + % save([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAddd','sad','-append') + % else + % load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAddd','sad') + % end + % figure, + % contourf(sad,10), colorbar + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) + % set(gca,'yticklabel',' ','fontsize',10,'ytick',[1:npT]) + % for ip=1:npT, + % text(ip,0.9,['D(',bayestopt_.name{ip},')'],'rotation',90,'HorizontalAlignment','right','interpreter','none') + % text(0.9,ip,[bayestopt_.name{ip}],'rotation',0,'HorizontalAlignment','right','interpreter','none') + % end + % [m,im]=max(sad); + % iii = find((im-[1:npT])==0); + % disp('Most identified params') + % disp(bayestopt_.name(iii)) + + + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + % END OF MORRIS FOR DERIVATIVES + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + % ifig = 0; + % for j=1:size(options_.varobs,1) + % if mod(j,6)==1 + % figure('name',['EET cross-correlations']); + % ifig=ifig+1; + % iplo=0; + % end + % iplo=iplo+1; + % subplot(3,2,iplo) + % iv = find(ir_cc==j); + % iv = [iv; find(ic_cc==j)]; + % if ~isempty(iv) + % if length(iv)>1 + % % boxplot(SAcc(iv,:),'whis',3,'symbol','r.'); + % myboxplot(SAcc(iv,:),[],'.',[],3) + % else + % plot(SAcc(iv,:),'r.'); + % end + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) + % set(gca,'xlim',[0.5 npT+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % for ip=1:npT, + % text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % end + % title(options_.varobs(j,:),'interpreter','none') + % if mod(j,6)==0 | j==size(options_.varobs,1) + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_cc_',int2str(ifig)]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_cc_',int2str(ifig)]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_cc_',int2str(ifig)]); + % close(gcf), + % end + % end + + + % if opt_gsa.load_ident_files==0, + % SAMorris = []; + % for i=1:size(ac,2), + % [SAmeas, SAMorris(:,:,i)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], ac(:,i),nliv); + % end + % %end + % SAac = squeeze(SAMorris(:,1,:))'; + % save([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAac','ac','ir_ac','ic_ac','-append') + % else + % load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAac','ac','ir_ac','ic_ac') + % end + % figure, + % % boxplot(SAac,'whis',10,'symbol','r.') + % myboxplot(SAac,[],'.',[],10) + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) + % set(gca,'xlim',[0.5 npT+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % set(gca,'position',[0.13 0.2 0.775 0.7]) + % for ip=1:npT, + % text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % title('EET All auto-correlations') + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_ac']) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_ac']); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_ac']); + % close(gcf), + + % ifig = 0; + % for j=1:size(options_.varobs,1) + % if mod(j,6)==1 + % figure('name',['EET auto-correlations']); + % ifig=ifig+1; + % iplo=0; + % end + % iplo=iplo+1; + % subplot(3,2,iplo) + % iv = find(ir_ac==j); + % if ~isempty(iv) + % if length(iv)>1 + % % boxplot(SAac(iv,:),'whis',3,'symbol','r.'); + % myboxplot(SAac(iv,:),[],'.',[],3) + % else + % plot(SAac(iv,:),'r.'); + % end + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) + % set(gca,'xlim',[0.5 npT+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % for ip=1:npT, + % text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % end + % title(options_.varobs(j,:),'interpreter','none') + % if mod(j,6)==0 | j==size(options_.varobs,1) + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_ac_',int2str(ifig)]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_ac_',int2str(ifig)]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_ac_',int2str(ifig)]); + % close(gcf), + % end + % end + + % if opt_gsa.load_ident_files==0, + % js=0; + % %for j=1:size(tadj,1), + % SAMorris = []; + % for i=1:size(tadj,2), + % js=js+1; + % [SAmeas, SAMorris(:,:,js)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], tadj(:,i),nliv); + % end + % %end + % SAM = squeeze(SAMorris(nshock+1:end,1,:)); + % for j=1:js, + % SAtadj(:,j)=SAM(:,j)./(max(SAM(:,j))+eps); + % end + % SAtadj = SAtadj'; + % save([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAtadj','tadj','ir_tadj','ic_tadj','-append') + % else + % load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAtadj','tadj','ir_tadj','ic_tadj') + % end + % if opt_gsa.load_ident_files==0, + % js=0; + % SAMorris = []; + % for i=1:size(iff,2), + % js=js+1; + % [SAmeas, SAMorriss(:,:,js)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], iff(:,i),nliv); + % end + % SAM = squeeze(SAMorriss(nshock+1:end,1,:)); + % for j=1:js, + % SAIF(:,j)=SAM(:,j)./(max(SAM(:,j))+eps); + % end + % SAIF = SAIF'; + % save([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAIF','iff','ir_if','ic_if','-append') + % else + % load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAIF','iff','ir_if','ic_if') + % end + % figure, + % %bar(SAtadj), + % % boxplot(SAtadj,'whis',10,'symbol','r.') + % myboxplot(SAtadj,[],'.',[],10) + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) + % set(gca,'xlim',[0.5 np+0.5]) + % set(gca,'ylim',[0 1]) + % set(gca,'position',[0.13 0.2 0.775 0.7]) + % for ip=1:np, + % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % title('All half-life') + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_tadj']) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_tadj']); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_tadj']); + % close(gcf), + + % ifig = 0; + % for j=1:size(options_.varobs,1) + % if mod(j,6)==1 + % figure('name',['EET speed of adjustment observed variables']); + % ifig=ifig+1; + % iplo=0; + % end + % iplo=iplo+1; + % subplot(3,2,iplo) + % iv = find(ir_tadj==j); + % if ~isempty(iv) + % if length(iv)>1 + % % boxplot(SAtadj(iv,:),'whis',3,'symbol','r.'); + % myboxplot(SAtadj(iv,:),[],'.',[],3) + % else + % plot(SAtadj(iv,:),'r.'); + % end + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) + % set(gca,'xlim',[0.5 np+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % for ip=1:np, + % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % end + % title(options_.varobs(j,:),'interpreter','none') + % if mod(j,6)==0 | j==size(options_.varobs,1) + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_tadj_varobs_',int2str(ifig)]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_tadj_varobs_',int2str(ifig)]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_tadj_varobs_',int2str(ifig)]); + % close(gcf), + % end + % end + + % ifig = 0; + % for j=1:M_.exo_nbr, + % if mod(j,6)==1 + % figure('name',['EET speed of adjustment shocks']); + % ifig=ifig+1; + % iplo=0; + % end + % iplo=iplo+1; + % subplot(3,2,iplo) + % iv = find(ic_tadj==j); + % if ~isempty(iv) + % if length(iv)>1 + % % boxplot(SAtadj(iv,:),'whis',3,'symbol','r.'); + % myboxplot(SAtadj(iv,:),[],'.',[],3) + % else + % plot(SAtadj(iv,:),'r.'); + % end + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) + % set(gca,'xlim',[0.5 np+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % for ip=1:np, + % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % end + % title(M_.exo_names(j,:),'interpreter','none') + % if mod(j,6)==0 | j==M_.exo_nbr, + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_tadj_exo_',int2str(ifig)]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_tadj_exo_',int2str(ifig)]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_tadj_exo_',int2str(ifig)]); + % close(gcf), + % end + % end + + % figure, + % %bar(SAIF), + % % boxplot(SAIF,'whis',10,'symbol','r.') + % myboxplot(SAIF,[],'.',[],10) + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) + % set(gca,'xlim',[0.5 np+0.5]) + % set(gca,'ylim',[0 1]) + % set(gca,'position',[0.13 0.2 0.775 0.7]) + % for ip=1:np, + % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % ylabel('Elementary Effects') + % title('Steady state gains (impact factors)') + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_gain']) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_gain']); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_gain']); + % close(gcf), + %figure, bar(SAIF'), title('All Gain Relationships') + % ifig = 0; + % for j=1:size(options_.varobs,1) + % if mod(j,6)==1 + % figure('name',['EET steady state gain observed series']); + % ifig=ifig+1; + % iplo=0; + % end + % iplo=iplo+1; + % subplot(3,2,iplo) + % iv = find(ir_if==j); + % if ~isempty(iv) + % if length(iv)>1 + % % boxplot(SAIF(iv,:),'whis',10,'symbol','r.'); + % myboxplot(SAIF(iv,:),[],'.',[],10) + % else + % plot(SAIF(iv,:),'r.'); + % end + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) + % set(gca,'xlim',[0.5 np+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % for ip=1:np, + % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % end + % title(options_.varobs(j,:),'interpreter','none') + % if mod(j,6)==0 | j==size(options_.varobs,1) + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_gain_varobs_',int2str(ifig)]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_gain_varobs_',int2str(ifig)]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_gain_varobs_',int2str(ifig)]); + % close(gcf), + % end + % end + % + % ifig = 0; + % for j=1:M_.exo_nbr, + % if mod(j,6)==1 + % figure('name',['EET steady state gain shocks']); + % ifig=ifig+1; + % iplo=0; + % end + % iplo=iplo+1; + % subplot(3,2,iplo) + % iv = find(ic_if==j); + % if ~isempty(iv) + % if length(iv)>1 + % % boxplot(SAIF(iv,:),'whis',3,'symbol','r.'); + % myboxplot(SAIF(iv,:),[],'.',[],3) + % else + % plot(SAIF(iv,:),'r.'); + % end + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) + % set(gca,'xlim',[0.5 np+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % for ip=1:np, + % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % end + % title(M_.exo_names(j,:),'interpreter','none') + % if mod(j,6)==0 | j==M_.exo_nbr, + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_gain_exo_',int2str(ifig)]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_gain_exo_',int2str(ifig)]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_gain_exo_',int2str(ifig)]); + % close(gcf), + % end + % end + + + if opt_gsa.load_ident_files==0 + SAMorris = []; + for j=1:j0 + [SAmeas, SAMorris(:,:,j)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], yt(:,j),nliv); + end + + % SAM = squeeze(SAMorris(nshock+1:end,1,:)); + SAM = squeeze(SAMorris(1:end,1,:)); + for j=1:j0 + SAnorm(:,j)=SAM(:,j)./max(SAM(:,j)); + irex(j)=length(find(SAnorm(:,j)>0.01)); + end + [dum, irel]=sort(irex); + + % SAMmu = squeeze(SAMorris(nshock+1:end,2,:)); + SAMmu = squeeze(SAMorris(1:end,2,:)); + for j=1:j0 + SAmunorm(:,j)=SAMmu(:,j)./max(SAM(:,j)); % normalised w.r.t. mu* + end + % SAMsig = squeeze(SAMorris(nshock+1:end,3,:)); + SAMsig = squeeze(SAMorris(1:end,3,:)); + for j=1:j0 + SAsignorm(:,j)=SAMsig(:,j)./max(SAMsig(:,j)); + end + save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'SAnorm','SAmunorm','SAsignorm','-append') + else + load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAnorm','SAmunorm','SAsignorm') + end + hh=dyn_figure(options_.nodisplay,'name','Screening identification: model'); %bar(SAnorm(:,irel)) + % boxplot(SAnorm','whis',10,'symbol','r.') + myboxplot(SAnorm',[],'.',[],10) + set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) + set(gca,'xlim',[0.5 npT+0.5]) + set(gca,'ylim',[0 1]) + set(gca,'position',[0.13 0.2 0.775 0.7]) + xlabel(' ') + for ip=1:npT + % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + end + xlabel(' ') + title('Elementary effects in the model') + dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_par'],options_.nodisplay,options_.graph_format); + create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_par'],1,'Screening identification: model','morris_par',1) + + % hh=dyn_figure(options_.nodisplay); %bar(SAmunorm(:,irel)) + % % boxplot(SAmunorm','whis',10,'symbol','r.') + % myboxplot(SAmunorm',[],'.',[],10) + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) + % set(gca,'xlim',[0.5 npT+0.5]) + % set(gca,'ylim',[-1 1]) + % set(gca,'position',[0.13 0.2 0.775 0.7]) + % xlabel(' ') + % for ip=1:npT, + % text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % title('\mu in the model') + % dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morrismu_par'],options_.nodisplay,options_.graph_format); + % + % hh=dyn_figure(options_.nodisplay); %bar(SAsignorm(:,irel)) + % % boxplot(SAsignorm','whis',10,'symbol','r.') + % myboxplot(SAsignorm',[],'.',[],10) + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) + % set(gca,'xlim',[0.5 npT+0.5]) + % set(gca,'ylim',[0 1]) + % set(gca,'position',[0.13 0.2 0.775 0.7]) + % xlabel(' ') + % for ip=1:npT, + % text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % title('\sigma in the model') + % dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morrissig_par'],options_.nodisplay,options_.graph_format); + + % figure, bar(SAnorm(:,irel)') + % set(gca,'xtick',[1:j0]) + % set(gca,'xlim',[0.5 j0+0.5]) + % title('Elementary effects relationships') + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_redform']) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_redform']); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_redform']); elseif opt_gsa.morris==3 return - - np=estim_params_.np; - na=(4*np+1)*opt_gsa.Nsam; - for j=1:j0 - [idex(j,:), yd(j,:)] = spop_ide(lpmat, yt(:,j), opt_gsa.Nsam, 5-1); - end - iok=find(~isnan(yt(1:opt_gsa.Nsam,1))); - yr=NaN*ones(size(lpmat,1),j0); - for j=1:j0, - ys(j,:)=yd(j,:)./max(yd(j,:)); - [dum, is]=sort(yt(iok,j)); - yr(iok(is),j)=[1:length(iok)]'./length(iok); - yr(istable(length(iok)+1:end),j) = interp1(yt(iok,j),yr(iok,j),yt(istable(length(iok)+1:end),j),'','extrap'); - ineg=find(yr(:,j)<0); - if any(ineg) - [dum, is]=sort(yr(ineg,j)); - yr(ineg(is),j)=-[length(ineg):-1:1]./length(iok); + + np=estim_params_.np; + na=(4*np+1)*opt_gsa.Nsam; + for j=1:j0 + [idex(j,:), yd(j,:)] = spop_ide(lpmat, yt(:,j), opt_gsa.Nsam, 5-1); + end + iok=find(~isnan(yt(1:opt_gsa.Nsam,1))); + yr=NaN*ones(size(lpmat,1),j0); + for j=1:j0, + ys(j,:)=yd(j,:)./max(yd(j,:)); + [dum, is]=sort(yt(iok,j)); + yr(iok(is),j)=[1:length(iok)]'./length(iok); + yr(istable(length(iok)+1:end),j) = interp1(yt(iok,j),yr(iok,j),yt(istable(length(iok)+1:end),j),'','extrap'); + ineg=find(yr(:,j)<0); + if any(ineg) + [dum, is]=sort(yr(ineg,j)); + yr(ineg(is),j)=-[length(ineg):-1:1]./length(iok); + end + [idex_r(j,:), yd_r(j,:)] = spop_ide(lpmat, yr(:,j), opt_gsa.Nsam, 5-1); + ys_r(j,:)=yd_r(j,:)./max(yd_r(j,:)); + + end, + figure, bar((idex.*ys)./opt_gsa.Nsam), title('Relationships') + figure, bar((idex.*ys)'./opt_gsa.Nsam), title('Parameters') + figure, bar((idex_r.*ys_r)./opt_gsa.Nsam), title('Relationships rank') + figure, bar((idex_r.*ys_r)'./opt_gsa.Nsam), title('Parameters rank') + [v0,d0]=eig(corrcoef(yt(iok,:))); + ee=diag(d0); + ee=ee([end:-1:1])./j0; + i0=length(find(ee>0.01)); + v0=v0(:,[end:-1:1]); + for j=1:i0 + [idex_pc(j,:), yd_pc(j,:)] = spop_ide(lpmat, yt*v0(:,j), opt_gsa.Nsam, 5-1); + end + for j=1:i0 + ys_pc(j,:)=yd_pc(j,:)./max(yd_pc(j,:)); + end, + figure, bar((idex_pc.*ys_pc)./opt_gsa.Nsam), title('Relationships PCA') + figure, bar((idex_pc.*ys_pc)'./opt_gsa.Nsam), title('Parameters PCA') + + [vr,dr]=eig(corrcoef(yr(iok,:))); + er=diag(dr); + er=er([end:-1:1])./j0; + ir0=length(find(er>0.01)); + vr=vr(:,[end:-1:1]); + for j=1:ir0 + [idex_pcr(j,:), yd_pcr(j,:)] = spop_ide(lpmat, yr*vr(:,j), opt_gsa.Nsam, 5-1); + end + for j=1:ir0 + ys_pcr(j,:)=yd_pcr(j,:)./max(yd_pcr(j,:)); end - [idex_r(j,:), yd_r(j,:)] = spop_ide(lpmat, yr(:,j), opt_gsa.Nsam, 5-1); - ys_r(j,:)=yd_r(j,:)./max(yd_r(j,:)); - - end, - figure, bar((idex.*ys)./opt_gsa.Nsam), title('Relationships') - figure, bar((idex.*ys)'./opt_gsa.Nsam), title('Parameters') - figure, bar((idex_r.*ys_r)./opt_gsa.Nsam), title('Relationships rank') - figure, bar((idex_r.*ys_r)'./opt_gsa.Nsam), title('Parameters rank') - [v0,d0]=eig(corrcoef(yt(iok,:))); - ee=diag(d0); - ee=ee([end:-1:1])./j0; - i0=length(find(ee>0.01)); - v0=v0(:,[end:-1:1]); - for j=1:i0 - [idex_pc(j,:), yd_pc(j,:)] = spop_ide(lpmat, yt*v0(:,j), opt_gsa.Nsam, 5-1); - end - for j=1:i0 - ys_pc(j,:)=yd_pc(j,:)./max(yd_pc(j,:)); - end, - figure, bar((idex_pc.*ys_pc)./opt_gsa.Nsam), title('Relationships PCA') - figure, bar((idex_pc.*ys_pc)'./opt_gsa.Nsam), title('Parameters PCA') - - [vr,dr]=eig(corrcoef(yr(iok,:))); - er=diag(dr); - er=er([end:-1:1])./j0; - ir0=length(find(er>0.01)); - vr=vr(:,[end:-1:1]); - for j=1:ir0 - [idex_pcr(j,:), yd_pcr(j,:)] = spop_ide(lpmat, yr*vr(:,j), opt_gsa.Nsam, 5-1); - end - for j=1:ir0 - ys_pcr(j,:)=yd_pcr(j,:)./max(yd_pcr(j,:)); - end - figure, bar((idex_pcr.*ys_pcr)./opt_gsa.Nsam), title('Relationships rank PCA') - figure, bar((idex_pcr.*ys_pcr)'./opt_gsa.Nsam), title('Parameters rank PCA') - + figure, bar((idex_pcr.*ys_pcr)./opt_gsa.Nsam), title('Relationships rank PCA') + figure, bar((idex_pcr.*ys_pcr)'./opt_gsa.Nsam), title('Parameters rank PCA') + elseif opt_gsa.morris==2 % ISKREV staff - return + return + - else % main effects analysis - - if itrans==0 - fsuffix = ''; - elseif itrans==1 - fsuffix = '_log'; - else - fsuffix = '_rank'; - end - - imap=[1:npT]; - - if isempty(lpmat0) - x0=lpmat(istable,:); - else - - x0=[lpmat0(istable,:), lpmat(istable,:)]; - end - nrun=length(istable); - nest=min(250,nrun); - nfit=min(1000,nrun); - -% opt_gsa.load_ident_files=0; - -% if opt_gsa.load_ident_files==0, -% try -% EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAvdec','vdec','ir_vdec','ic_vdec'); -% catch -% EET=[]; -% end -% SAvdec=zeros(size(vdec,2),npT); -% -% for j=1:size(vdec,2), -% if itrans==0, -% y0 = vdec(istable,j); -% elseif itrans==1, -% y0 = log_trans_(vdec(istable,j)); -% else -% y0 = trank(vdec(istable,j)); -% end -% if ~isempty(EET), -% % imap=find(EET.SAvdec(j,:)); -% % [dum, isort]=sort(-EET.SAvdec(j,:)); -% imap=find(EET.SAvdec(j,:) >= (0.1.*max(EET.SAvdec(j,:))) ); -% end -% gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ... -% 2, [],[],[],0,[OutputDirectoryName,'/map_vdec',fsuffix,int2str(j)], pnames); -% if nfit>nest, -% gsa_(j) = gsa_sdp(y0(1:nfit), x0(1:nfit,imap), ... -% -2, gsa_(j).nvr*nest^3/nfit^3,[],[],0,[OutputDirectoryName,'/map_vdec',fsuffix,int2str(j)], pnames); -% end -% -% SAvdec(j,imap)=gsa_(j).si; -% imap_vdec{j}=imap; -% end -% save([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_vdec','SAvdec','vdec','ir_vdec','ic_vdec','-append') -% else -% load([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_vdec','SAvdec','vdec','ir_vdec','ic_vdec') -% end -% figure, -% % boxplot(SAvdec,'whis',10,'symbol','r.') -% myboxplot(SAvdec,[],'.',[],10) -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) -% set(gca,'xlim',[0.5 npT+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% set(gca,'position',[0.13 0.2 0.775 0.7]) -% for ip=1:npT, -% text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% title(['Main effects variance decomposition ',fsuffix],'interpreter','none') -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_vdec',fsuffix]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix]); -% close(gcf), -% -% ifig = 0; -% for j=1:size(options_.varobs,1) -% if mod(j,6)==1 -% figure('name',['Main effects observed variance decomposition ',fsuffix]); -% ifig=ifig+1; -% iplo=0; -% end -% iplo=iplo+1; -% subplot(3,2,iplo) -% iv = find(ir_vdec==j); -% if ~isempty(iv) -% if length(iv)>1 -% % boxplot(SAvdec(iv,:),'whis',10,'symbol','r.'); -% myboxplot(SAvdec(iv,:),[],'.',[],10) -% else -% plot(SAvdec(iv,:),'r.'); -% end -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) -% set(gca,'xlim',[0.5 npT+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% for ip=1:npT, -% text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% end -% title(options_.varobs(j,:),'interpreter','none') -% if mod(j,6)==0 | j==size(options_.varobs,1) -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_vdec',fsuffix,'_varobs_',int2str(ifig)]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix,'_varobs_',int2str(ifig)]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix,'_varobs_',int2str(ifig)]); -% close(gcf), -% end -% end -% -% ifig = 0; -% for j=1:M_.exo_nbr, -% if mod(j,6)==1 -% figure('name',['Main effects shocks variance decomposition ',fsuffix]); -% ifig=ifig+1; -% iplo=0; -% end -% iplo=iplo+1; -% subplot(3,2,iplo) -% iv = find(ic_vdec==j); -% if ~isempty(iv) -% if length(iv)>1 -% % boxplot(SAvdec(iv,:),'whis',3,'symbol','r.'); -% myboxplot(SAvdec(iv,:),[],'.',[],10) -% else -% plot(SAvdec(iv,:),'r.'); -% end -% set(gca,'xticklabel',' ','fontsize',3,'xtick',[1:np]) -% set(gca,'xlim',[0.5 npT+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% for ip=1:npT, -% text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% set(gca,'fontsize',10) -% end -% title(M_.exo_names(j,:),'interpreter','none','fontsize',10) -% if mod(j,6)==0 | j==M_.exo_nbr -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_vdec',fsuffix,'_exo_',int2str(ifig)]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix,'_exo_',int2str(ifig)]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix,'_exo_',int2str(ifig)]); -% close(gcf), -% end -% end - if opt_gsa.load_ident_files==0 - try - EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAcc','ir_cc','ic_cc'); - catch - EET=[]; - end - ccac = stand_([mss cc ac]); - [pcc, dd] = eig(cov(ccac(istable,:))); - [latent, isort] = sort(-diag(dd)); - latent = -latent; - figure, bar(latent) - title('Eigenvalues in PCA') - pcc=pcc(:,isort); - ccac = ccac*pcc; -% npca = min(40, max(find(cumsum(latent)./length(latent)<0.99))+1); - npca = max(find(cumsum(latent)./length(latent)<0.99))+1; - siPCA = (EET.SAcc'*abs(pcc'))'; -% siPCA = siPCA./(max(siPCA')'*ones(1,npT)).*(latent*ones(1,npT)); - siPCA = siPCA./(max(siPCA')'*ones(1,npT)); -% siPCA = sum(siPCA,1); -% siPCA = siPCA./max(siPCA); - SAcc=zeros(size(ccac,2),npT); - for j=1:npca %size(ccac,2), if itrans==0 - y0 = ccac(istable,j); + fsuffix = ''; elseif itrans==1 - y0 = log_trans_(ccac(istable,j)); + fsuffix = '_log'; else - y0 = trank(ccac(istable,j)); + fsuffix = '_rank'; end - if ~isempty(EET) -% imap=find(EET.SAvdec(j,:)); -% [dum, isort]=sort(-EET.SAvdec(j,:)); - imap=find(siPCA(j,:) >= (0.1.*max(siPCA(j,:))) ); -% imap=find(EET.SAcc(j,:) >= (0.1.*max(EET.SAcc(j,:))) ); + + imap=[1:npT]; + + if isempty(lpmat0) + x0=lpmat(istable,:); + else + + x0=[lpmat0(istable,:), lpmat(istable,:)]; end - gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ... - 2, [],[],[],0,[OutputDirectoryName,'/map_cc',fsuffix,int2str(j)], pnames); -% if nfit>nest, -% gsa_(j) = gsa_sdp(y0(1:nfit), x0(1:nfit,imap), ... -% -2, gsa_(j).nvr*nest^3/nfit^3,[],[],0,[OutputDirectoryName,'/map_cc',fsuffix,int2str(j)], pnames); -% end - SAcc(j,imap)=gsa_(j).si; - imap_cc{j}=imap; - - end - save([OutputDirectoryName,'/map_cc',fsuffix,'.mat'],'gsa_') - save([OutputDirectoryName,'/',fname_,'_main_eff.mat'],'imap_cc','SAcc','ccac','-append') - else - load([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_cc','SAcc','ccac') - - end -% figure, -% % boxplot(SAcc,'whis',10,'symbol','r.') -% myboxplot(SAcc,[],'.',[],10) -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) -% set(gca,'xlim',[0.5 npT+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% set(gca,'position',[0.13 0.2 0.775 0.7]) -% for ip=1:npT, -% text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% ylabel(' ') -% title(['Main effects moments''s PCA ',fsuffix],'interpreter','none') -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_cc',fsuffix]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_moments',fsuffix]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_moments',fsuffix]); -% close(gcf), - -% ifig = 0; -% for j=1:size(options_.varobs,1) -% if mod(j,6)==1 -% figure('name',['Main effects cross-covariances ',fsuffix]); -% ifig=ifig+1; -% iplo=0; -% end -% iplo=iplo+1; -% subplot(3,2,iplo) -% iv = find(ir_cc==j); -% iv = [iv; find(ic_cc==j)]; -% if ~isempty(iv) -% if length(iv)>1 -% % boxplot(SAcc(iv,:),'whis',10,'symbol','r.'); -% myboxplot(SAcc(iv,:),[],'.',[],10) -% else -% plot(SAcc(iv,:),'r.'); -% end -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) -% set(gca,'xlim',[0.5 npT+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% for ip=1:npT, -% text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% set(gca,'fontsize',10) -% end -% title(options_.varobs(j,:),'interpreter','none','fontsize',10) -% if mod(j,6)==0 | j==size(options_.varobs,1) -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_cc',fsuffix,'_',int2str(ifig)]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_cc',fsuffix,'_',int2str(ifig)]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_cc',fsuffix,'_',int2str(ifig)]); -% close(gcf), -% end -% end -% -% if opt_gsa.load_ident_files==0, -% try -% EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAac','ir_ac','ic_ac'); -% catch -% EET=[]; -% end -% SAac=zeros(size(ac,2),npT); -% for j=1:size(ac,2), -% if itrans==0, -% y0 = ac(istable,j); -% elseif itrans==1, -% y0 = log_trans_(ac(istable,j)); -% else -% y0 = trank(ac(istable,j)); -% end -% if ~isempty(EET), -% imap=find(EET.SAac(j,:) >= (0.1.*max(EET.SAac(j,:))) ); -% end -% % gsa_(j) = gsa_sdp_dyn( y0, lpmat(istable,:), ... -% % gsa_flag, [],[],[],0,[OutputDirectoryName,'/map_ac',fsuffix,int2str(j)], pnames); -% gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ... -% 2, [],[],[],0,[OutputDirectoryName,'/map_ac',fsuffix,int2str(j)], pnames); -% if nfit>nest, -% gsa_(j) = gsa_sdp(y0(1:nfit), x0(1:nfit,imap), ... -% -2, gsa_(j).nvr*nest^3/nfit^3,[],[],0,[OutputDirectoryName,'/map_ac',fsuffix,int2str(j)], pnames); -% end -% SAac(j,imap)=gsa_(j).si; -% imap_ac{j}=imap; -% -% end -% save([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_ac','SAac','ac','ir_ac','ic_ac','-append') -% else -% load([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_ac','SAac','ac','ir_ac','ic_ac') -% end -% -% figure, -% % boxplot(SAac,'whis',10,'symbol','r.') -% myboxplot(SAac,[],'.',[],10) -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) -% set(gca,'xlim',[0.5 npT+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% set(gca,'position',[0.13 0.2 0.775 0.7]) -% for ip=1:np, -% text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% title(['Main effects 1 lag auto-covariances ',fsuffix],'interpreter','none') -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_ac',fsuffix]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_ac',fsuffix]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_ac',fsuffix]); -% close(gcf), -% -% ifig = 0; -% for j=1:size(options_.varobs,1) -% if mod(j,6)==1 -% figure('name',['Main effects auto-covariances ',fsuffix]); -% ifig=ifig+1; -% iplo = 0; -% end -% iplo=iplo+1; -% subplot(3,2,iplo) -% iv = find(ir_ac==j); -% %iv = [iv; find(ic_ac==j)]; -% if ~isempty(iv) -% if length(iv)>1 -% % boxplot(SAac(iv,:),'whis',10,'symbol','r.'); -% myboxplot(SAac(iv,:),[],'.',[],10) -% else -% plot(SAac(iv,:),'r.'); -% end -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) -% set(gca,'xlim',[0.5 npT+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% for ip=1:npT, -% text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% set(gca,'fontsize',10) -% end -% title(options_.varobs(j,:),'interpreter','none','fontsize',10) -% if mod(j,6)==0 | j==size(options_.varobs,1) -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_ac',fsuffix,'_',int2str(ifig)]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_ac',fsuffix,'_',int2str(ifig)]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_ac',fsuffix,'_',int2str(ifig)]); -% close(gcf), -% end -% end - -% x0=x0(:,nshock+1:end); - imap=[1:npT]; - -% if opt_gsa.load_ident_files==0, -% try -% EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAtadj','ir_tadj','ic_tadj'); -% ny=size(EET.SAtadj,1); -% catch -% EET=[]; -% end -% SAtadj=zeros(size(tadj,2),np); -% for j=1:size(tadj,2), -% if itrans==0, -% y0 = tadj(istable,j); -% elseif itrans==1, -% y0 = log_trans_(tadj(istable,j)); -% else -% y0 = trank(tadj(istable,j)); -% end -% if ~isempty(EET), -% if size(tadj,2)~=ny, -% jj=find(EET.ir_tadj==ir_tadj(j)); -% jj=jj(find(EET.ic_tadj(jj)==ic_tadj(j))); -% if ~isempty(jj), -% imap=find(EET.SAtadj(jj,:) >= (0.1.*max(EET.SAtadj(jj,:))) ); -% else -% imap=[1:np]; -% end -% else -% imap=find(EET.SAtadj(j,:) >= (0.1.*max(EET.SAtadj(j,:))) ); -% end -% end -% % gsa_(j) = gsa_sdp_dyn( y0, lpmat(istable,:), ... -% % gsa_flag, [],[],[],0,[OutputDirectoryName,'/map_tadj',fsuffix,int2str(j)], pnames); -% gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ... -% 2, [],[],[],0,[OutputDirectoryName,'/map_tadj',fsuffix,int2str(j)], pnames); -% if nfit>nest, -% gsa_(j) = gsa_sdp(y0(1:nfit), x0(1:nfit,imap), ... -% -2, gsa_(j).nvr*nest^3/nfit^3,[],[],0,[OutputDirectoryName,'/map_tadj',fsuffix,int2str(j)], pnames); -% end -% SAtadj(j,imap)=gsa_(j).si; -% imap_tadj{j}=imap; -% -% end -% save([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_tadj','SAtadj','tadj','ir_tadj','ic_tadj','-append') -% else -% load([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_tadj','SAtadj','tadj','ir_tadj','ic_tadj') -% end -% -% figure, -% % boxplot(SAtadj,'whis',10,'symbol','r.') -% myboxplot(SAtadj,[],'.',[],10) -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) -% set(gca,'xlim',[0.5 np+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% set(gca,'position',[0.13 0.2 0.775 0.7]) -% for ip=1:np, -% text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% title(['Main effects speed of adjustment ',fsuffix],'interpreter','none') -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_tadj',fsuffix]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix]); -% close(gcf), -% -% ifig = 0; -% for j=1:size(options_.varobs,1) -% if mod(j,6)==1 -% figure('name',['Main effects observed speed adjustment ',fsuffix]); -% ifig=ifig+1; -% iplo = 0; -% end -% iplo=iplo+1; -% subplot(3,2,iplo) -% iv = find(ir_tadj==j); -% if ~isempty(iv) -% if length(iv)>1 -% % boxplot(SAtadj(iv,:),'whis',3,'symbol','r.'); -% myboxplot(SAtadj(iv,:),[],'.',[],10) -% else -% plot(SAtadj(iv,:),'r.'); -% end -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) -% set(gca,'xlim',[0.5 np+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% for ip=1:np, -% text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% end -% title(options_.varobs(j,:),'interpreter','none') -% if mod(j,6)==0 | j==size(options_.varobs,1) -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_tadj',fsuffix,'_varobs_',int2str(ifig)]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix,'_varobs_',int2str(ifig)]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix,'_varobs_',int2str(ifig)]); -% close(gcf), -% end -% end -% -% ifig = 0; -% for j=1:M_.exo_nbr, -% if mod(j,6)==1 -% figure('name',['Main effects shocks speed of adjustment ',fsuffix]); -% ifig=ifig+1; -% iplo=0; -% end -% iplo=iplo+1; -% subplot(3,2,iplo) -% iv = find(ic_tadj==j); -% if ~isempty(iv) -% if length(iv)>1 -% % boxplot(SAtadj(iv,:),'whis',3,'symbol','r.'); -% myboxplot(SAtadj(iv,:),[],'.',[],10) -% else -% plot(SAtadj(iv,:),'r.'); -% end -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) -% set(gca,'xlim',[0.5 np+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% for ip=1:np, -% text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% end -% title(M_.exo_names(j,:),'interpreter','none') -% if mod(j,6)==0 | j==M_.exo_nbr, -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_tadj',fsuffix,'_exo_',int2str(ifig)]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix,'_exo_',int2str(ifig)]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix,'_exo_',int2str(ifig)]); -% close(gcf), -% end -% end -% -% -% if opt_gsa.load_ident_files==0, -% try -% EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAIF','ir_if','ic_if'); -% catch -% EET=[]; -% end -% SAif=zeros(size(iff,2),np); -% for j=1:size(iff,2), -% if itrans==0, -% y0 = iff(istable,j); -% elseif itrans==1, -% y0 = log_trans_(iff(istable,j)); -% else -% y0 = trank(iff(istable,j)); -% end -% if ~isempty(EET), -% imap=find(EET.SAIF(j,:) >= (0.1.*max(EET.SAIF(j,:))) ); -% end -% % gsa_(j) = gsa_sdp_dyn( y0, lpmat(istable,:), ... -% % gsa_flag, [],[],[],0,[OutputDirectoryName,'/map_if',fsuffix,int2str(j)], pnames); -% gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ... -% 2, [],[],[],0,[OutputDirectoryName,'/map_if',fsuffix,int2str(j)], pnames); -% if nfit>nest, -% gsa_(j) = gsa_sdp(y0(1:nfit), x0(1:nfit,imap), ... -% -2, gsa_(j).nvr*nest^3/nfit^3,[],[],0,[OutputDirectoryName,'/map_if',fsuffix,int2str(j)], pnames); -% end -% SAif(j,imap)=gsa_(j).si; -% imap_if{j}=imap; -% -% end -% save([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_if','SAif','iff','ir_if','ic_if','-append') -% else -% load([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_if','SAif','iff','ir_if','ic_if') -% end -% -% figure, -% % boxplot(SAif,'whis',10,'symbol','r.') -% myboxplot(SAif,[],'.',[],10) -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) -% set(gca,'xlim',[0.5 np+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% set(gca,'position',[0.13 0.2 0.775 0.7]) -% for ip=1:np, -% text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% title(['Main effects impact factors ',fsuffix],'interpreter','none') -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_if',fsuffix]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_if',fsuffix]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_if',fsuffix]); -% close(gcf), -% -% ifig = 0; -% for j=1:size(options_.varobs,1) -% if mod(j,6)==1 -% figure('name',['Main effects observed impact factors ',fsuffix]); -% ifig=ifig+1; -% iplo = 0; -% end -% iplo=iplo+1; -% subplot(3,2,iplo) -% iv = find(ir_if==j); -% if ~isempty(iv) -% if length(iv)>1 -% % boxplot(SAif(iv,:),'whis',3,'symbol','r.'); -% myboxplot(SAif(iv,:),[],'.',[],10) -% else -% plot(SAif(iv,:),'r.'); -% end -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) -% set(gca,'xlim',[0.5 np+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% for ip=1:np, -% text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% end -% title(options_.varobs(j,:),'interpreter','none') -% if mod(j,6)==0 | j==size(options_.varobs,1) -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_if',fsuffix,'_varobs_',int2str(ifig)]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_if',fsuffix,'_varobs_',int2str(ifig)]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_if',fsuffix,'_varobs_',int2str(ifig)]); -% close(gcf), -% end -% end -% -% ifig = 0; -% for j=1:M_.exo_nbr, -% if mod(j,6)==1 -% figure('name',['Main effects shocks impact factors ',fsuffix]); -% ifig=ifig+1; -% iplo=0; -% end -% iplo=iplo+1; -% subplot(3,2,iplo) -% iv = find(ic_if==j); -% if ~isempty(iv) -% if length(iv)>1 -% % boxplot(SAif(iv,:),'whis',3,'symbol','r.'); -% myboxplot(SAif(iv,:),[],'.',[],10) -% else -% plot(SAif(iv,:),'r.'); -% end -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) -% set(gca,'xlim',[0.5 np+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% for ip=1:np, -% text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% end -% title(M_.exo_names(j,:),'interpreter','none') -% if mod(j,6)==0 | j==M_.exo_nbr -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_if',fsuffix,'_exo_',int2str(ifig)]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_if',fsuffix,'_exo_',int2str(ifig)]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_if',fsuffix,'_exo_',int2str(ifig)]); -% close(gcf), -% end -% end -% SAmom = [SAvdec' SAcc' SAac']'; -% SAdyn = [SAtadj' SAif']'; -% SAall = [SAmom(:,nshock+1:end)' SAdyn']'; -% -% figure, -% % boxplot(SAtadj,'whis',10,'symbol','r.') -% myboxplot(SAmom,[],'.',[],10) -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) -% set(gca,'xlim',[0.5 npT+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% set(gca,'position',[0.13 0.2 0.775 0.7]) -% for ip=1:npT, -% % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% title(['Main effects theoretical moments ',fsuffix],'interpreter','none') -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_moments',fsuffix]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_moments',fsuffix]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_moments',fsuffix]); -% % close(gcf), -% -% figure, -% % boxplot(SAtadj,'whis',10,'symbol','r.') -% myboxplot(SAdyn,[],'.',[],10) -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) -% set(gca,'xlim',[0.5 np+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% set(gca,'position',[0.13 0.2 0.775 0.7]) -% for ip=1:np, -% text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% % text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% title(['Main effects short-long term dynamics ',fsuffix],'interpreter','none') -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_dynamics',fsuffix]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_dynamics',fsuffix]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_dynamics',fsuffix]); -% % close(gcf), -% -% figure, -% % boxplot(SAtadj,'whis',10,'symbol','r.') -% myboxplot(SAall,[],'.',[],10) -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) -% set(gca,'xlim',[0.5 np+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% set(gca,'position',[0.13 0.2 0.775 0.7]) -% for ip=1:np, -% text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% % text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% title(['Main effects all ',fsuffix],'interpreter','none') -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_ALL',fsuffix]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_ALL',fsuffix]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_ALL',fsuffix]); -% % close(gcf), - -% for j=1:size(SAall,1), -% SAallN(j,:)=SAall(j,:)./max(SAall(j,:)); -% end -% SAmean=mean(SAallN); -% for j=1:size(SAmom,1), -% SAmomN(j,:)=SAmom(j,1:nshock)./max(SAmom(j,1:nshock)); -% end -% SAmomN(find(isnan(SAmomN)))=0; -% SAmeanexo=mean(SAmomN(:,1:nshock)); - -% figure, bar(latent'*SAcc), - hh=dyn_figure(options_.nodisplay,'Name',['Identifiability indices in the ',fsuffix,' moments.']); - bar(sum(SAcc)) - set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) - set(gca,'xlim',[0.5 npT+0.5]) - ydum = get(gca,'ylim'); - set(gca,'ylim',[0 ydum(2)]) - set(gca,'position',[0.13 0.2 0.775 0.7]) - for ip=1:npT - text(ip,-0.02*(ydum(2)),bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + nrun=length(istable); + nest=min(250,nrun); + nfit=min(1000,nrun); + + % opt_gsa.load_ident_files=0; + + % if opt_gsa.load_ident_files==0, + % try + % EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAvdec','vdec','ir_vdec','ic_vdec'); + % catch + % EET=[]; + % end + % SAvdec=zeros(size(vdec,2),npT); + % + % for j=1:size(vdec,2), + % if itrans==0, + % y0 = vdec(istable,j); + % elseif itrans==1, + % y0 = log_trans_(vdec(istable,j)); + % else + % y0 = trank(vdec(istable,j)); + % end + % if ~isempty(EET), + % % imap=find(EET.SAvdec(j,:)); + % % [dum, isort]=sort(-EET.SAvdec(j,:)); + % imap=find(EET.SAvdec(j,:) >= (0.1.*max(EET.SAvdec(j,:))) ); + % end + % gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ... + % 2, [],[],[],0,[OutputDirectoryName,'/map_vdec',fsuffix,int2str(j)], pnames); + % if nfit>nest, + % gsa_(j) = gsa_sdp(y0(1:nfit), x0(1:nfit,imap), ... + % -2, gsa_(j).nvr*nest^3/nfit^3,[],[],0,[OutputDirectoryName,'/map_vdec',fsuffix,int2str(j)], pnames); + % end + % + % SAvdec(j,imap)=gsa_(j).si; + % imap_vdec{j}=imap; + % end + % save([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_vdec','SAvdec','vdec','ir_vdec','ic_vdec','-append') + % else + % load([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_vdec','SAvdec','vdec','ir_vdec','ic_vdec') + % end + % figure, + % % boxplot(SAvdec,'whis',10,'symbol','r.') + % myboxplot(SAvdec,[],'.',[],10) + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) + % set(gca,'xlim',[0.5 npT+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % set(gca,'position',[0.13 0.2 0.775 0.7]) + % for ip=1:npT, % text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') - end - xlabel(' ') - title(['Identifiability indices in the ',fsuffix,' moments.'],'interpreter','none') - dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_ident_ALL',fsuffix],options_.nodisplay,options_.graph_format); - create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_ident_ALL',fsuffix],1,['Identifiability indices in the ',fsuffix,' moments.'],['ident_ALL',fsuffix]',1) - -% figure, bar(SAmeanexo), -% set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:nshock]) -% set(gca,'xlim',[0.5 nshock+0.5]) -% ydum = get(gca,'ylim'); -% set(gca,'ylim',[0 ydum(2)]) -% set(gca,'position',[0.13 0.2 0.775 0.7]) -% for ip=1:nshock, -% % text(ip,-0.02*(ydum(2)),deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') -% text(ip,-0.02*(ydum(2)),bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') -% end -% xlabel(' ') -% title(['Identifiability indices for shocks',fsuffix],'interpreter','none') -% saveas(gcf,[OutputDirectoryName,'/',fname_,'_ident_SHOCKS',fsuffix]) -% eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_ident_SHOCKS',fsuffix]); -% eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_ident_SHOCKS',fsuffix]); + % % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % title(['Main effects variance decomposition ',fsuffix],'interpreter','none') + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_vdec',fsuffix]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix]); + % close(gcf), + % + % ifig = 0; + % for j=1:size(options_.varobs,1) + % if mod(j,6)==1 + % figure('name',['Main effects observed variance decomposition ',fsuffix]); + % ifig=ifig+1; + % iplo=0; + % end + % iplo=iplo+1; + % subplot(3,2,iplo) + % iv = find(ir_vdec==j); + % if ~isempty(iv) + % if length(iv)>1 + % % boxplot(SAvdec(iv,:),'whis',10,'symbol','r.'); + % myboxplot(SAvdec(iv,:),[],'.',[],10) + % else + % plot(SAvdec(iv,:),'r.'); + % end + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) + % set(gca,'xlim',[0.5 npT+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % for ip=1:npT, + % text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + % % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % end + % title(options_.varobs(j,:),'interpreter','none') + % if mod(j,6)==0 | j==size(options_.varobs,1) + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_vdec',fsuffix,'_varobs_',int2str(ifig)]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix,'_varobs_',int2str(ifig)]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix,'_varobs_',int2str(ifig)]); + % close(gcf), + % end + % end + % + % ifig = 0; + % for j=1:M_.exo_nbr, + % if mod(j,6)==1 + % figure('name',['Main effects shocks variance decomposition ',fsuffix]); + % ifig=ifig+1; + % iplo=0; + % end + % iplo=iplo+1; + % subplot(3,2,iplo) + % iv = find(ic_vdec==j); + % if ~isempty(iv) + % if length(iv)>1 + % % boxplot(SAvdec(iv,:),'whis',3,'symbol','r.'); + % myboxplot(SAvdec(iv,:),[],'.',[],10) + % else + % plot(SAvdec(iv,:),'r.'); + % end + % set(gca,'xticklabel',' ','fontsize',3,'xtick',[1:np]) + % set(gca,'xlim',[0.5 npT+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % for ip=1:npT, + % text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + % % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % set(gca,'fontsize',10) + % end + % title(M_.exo_names(j,:),'interpreter','none','fontsize',10) + % if mod(j,6)==0 | j==M_.exo_nbr + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_vdec',fsuffix,'_exo_',int2str(ifig)]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix,'_exo_',int2str(ifig)]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix,'_exo_',int2str(ifig)]); + % close(gcf), + % end + % end + + if opt_gsa.load_ident_files==0 + try + EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAcc','ir_cc','ic_cc'); + catch + EET=[]; + end + ccac = stand_([mss cc ac]); + [pcc, dd] = eig(cov(ccac(istable,:))); + [latent, isort] = sort(-diag(dd)); + latent = -latent; + figure, bar(latent) + title('Eigenvalues in PCA') + pcc=pcc(:,isort); + ccac = ccac*pcc; + % npca = min(40, max(find(cumsum(latent)./length(latent)<0.99))+1); + npca = max(find(cumsum(latent)./length(latent)<0.99))+1; + siPCA = (EET.SAcc'*abs(pcc'))'; + % siPCA = siPCA./(max(siPCA')'*ones(1,npT)).*(latent*ones(1,npT)); + siPCA = siPCA./(max(siPCA')'*ones(1,npT)); + % siPCA = sum(siPCA,1); + % siPCA = siPCA./max(siPCA); + SAcc=zeros(size(ccac,2),npT); + for j=1:npca %size(ccac,2), + if itrans==0 + y0 = ccac(istable,j); + elseif itrans==1 + y0 = log_trans_(ccac(istable,j)); + else + y0 = trank(ccac(istable,j)); + end + if ~isempty(EET) + % imap=find(EET.SAvdec(j,:)); + % [dum, isort]=sort(-EET.SAvdec(j,:)); + imap=find(siPCA(j,:) >= (0.1.*max(siPCA(j,:))) ); + % imap=find(EET.SAcc(j,:) >= (0.1.*max(EET.SAcc(j,:))) ); + end + gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ... + 2, [],[],[],0,[OutputDirectoryName,'/map_cc',fsuffix,int2str(j)], pnames); + % if nfit>nest, + % gsa_(j) = gsa_sdp(y0(1:nfit), x0(1:nfit,imap), ... + % -2, gsa_(j).nvr*nest^3/nfit^3,[],[],0,[OutputDirectoryName,'/map_cc',fsuffix,int2str(j)], pnames); + % end + SAcc(j,imap)=gsa_(j).si; + imap_cc{j}=imap; + + end + save([OutputDirectoryName,'/map_cc',fsuffix,'.mat'],'gsa_') + save([OutputDirectoryName,'/',fname_,'_main_eff.mat'],'imap_cc','SAcc','ccac','-append') + else + load([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_cc','SAcc','ccac') + + end + % figure, + % % boxplot(SAcc,'whis',10,'symbol','r.') + % myboxplot(SAcc,[],'.',[],10) + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) + % set(gca,'xlim',[0.5 npT+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % set(gca,'position',[0.13 0.2 0.775 0.7]) + % for ip=1:npT, + % text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + % % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % ylabel(' ') + % title(['Main effects moments''s PCA ',fsuffix],'interpreter','none') + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_cc',fsuffix]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_moments',fsuffix]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_moments',fsuffix]); + % close(gcf), + + % ifig = 0; + % for j=1:size(options_.varobs,1) + % if mod(j,6)==1 + % figure('name',['Main effects cross-covariances ',fsuffix]); + % ifig=ifig+1; + % iplo=0; + % end + % iplo=iplo+1; + % subplot(3,2,iplo) + % iv = find(ir_cc==j); + % iv = [iv; find(ic_cc==j)]; + % if ~isempty(iv) + % if length(iv)>1 + % % boxplot(SAcc(iv,:),'whis',10,'symbol','r.'); + % myboxplot(SAcc(iv,:),[],'.',[],10) + % else + % plot(SAcc(iv,:),'r.'); + % end + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) + % set(gca,'xlim',[0.5 npT+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % for ip=1:npT, + % text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + % % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % set(gca,'fontsize',10) + % end + % title(options_.varobs(j,:),'interpreter','none','fontsize',10) + % if mod(j,6)==0 | j==size(options_.varobs,1) + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_cc',fsuffix,'_',int2str(ifig)]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_cc',fsuffix,'_',int2str(ifig)]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_cc',fsuffix,'_',int2str(ifig)]); + % close(gcf), + % end + % end + % + % if opt_gsa.load_ident_files==0, + % try + % EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAac','ir_ac','ic_ac'); + % catch + % EET=[]; + % end + % SAac=zeros(size(ac,2),npT); + % for j=1:size(ac,2), + % if itrans==0, + % y0 = ac(istable,j); + % elseif itrans==1, + % y0 = log_trans_(ac(istable,j)); + % else + % y0 = trank(ac(istable,j)); + % end + % if ~isempty(EET), + % imap=find(EET.SAac(j,:) >= (0.1.*max(EET.SAac(j,:))) ); + % end + % % gsa_(j) = gsa_sdp_dyn( y0, lpmat(istable,:), ... + % % gsa_flag, [],[],[],0,[OutputDirectoryName,'/map_ac',fsuffix,int2str(j)], pnames); + % gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ... + % 2, [],[],[],0,[OutputDirectoryName,'/map_ac',fsuffix,int2str(j)], pnames); + % if nfit>nest, + % gsa_(j) = gsa_sdp(y0(1:nfit), x0(1:nfit,imap), ... + % -2, gsa_(j).nvr*nest^3/nfit^3,[],[],0,[OutputDirectoryName,'/map_ac',fsuffix,int2str(j)], pnames); + % end + % SAac(j,imap)=gsa_(j).si; + % imap_ac{j}=imap; + % + % end + % save([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_ac','SAac','ac','ir_ac','ic_ac','-append') + % else + % load([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_ac','SAac','ac','ir_ac','ic_ac') + % end + % + % figure, + % % boxplot(SAac,'whis',10,'symbol','r.') + % myboxplot(SAac,[],'.',[],10) + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) + % set(gca,'xlim',[0.5 npT+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % set(gca,'position',[0.13 0.2 0.775 0.7]) + % for ip=1:np, + % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % title(['Main effects 1 lag auto-covariances ',fsuffix],'interpreter','none') + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_ac',fsuffix]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_ac',fsuffix]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_ac',fsuffix]); + % close(gcf), + % + % ifig = 0; + % for j=1:size(options_.varobs,1) + % if mod(j,6)==1 + % figure('name',['Main effects auto-covariances ',fsuffix]); + % ifig=ifig+1; + % iplo = 0; + % end + % iplo=iplo+1; + % subplot(3,2,iplo) + % iv = find(ir_ac==j); + % %iv = [iv; find(ic_ac==j)]; + % if ~isempty(iv) + % if length(iv)>1 + % % boxplot(SAac(iv,:),'whis',10,'symbol','r.'); + % myboxplot(SAac(iv,:),[],'.',[],10) + % else + % plot(SAac(iv,:),'r.'); + % end + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) + % set(gca,'xlim',[0.5 npT+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % for ip=1:npT, + % text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + % % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % set(gca,'fontsize',10) + % end + % title(options_.varobs(j,:),'interpreter','none','fontsize',10) + % if mod(j,6)==0 | j==size(options_.varobs,1) + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_ac',fsuffix,'_',int2str(ifig)]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_ac',fsuffix,'_',int2str(ifig)]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_ac',fsuffix,'_',int2str(ifig)]); + % close(gcf), + % end + % end + + % x0=x0(:,nshock+1:end); + imap=[1:npT]; + + % if opt_gsa.load_ident_files==0, + % try + % EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAtadj','ir_tadj','ic_tadj'); + % ny=size(EET.SAtadj,1); + % catch + % EET=[]; + % end + % SAtadj=zeros(size(tadj,2),np); + % for j=1:size(tadj,2), + % if itrans==0, + % y0 = tadj(istable,j); + % elseif itrans==1, + % y0 = log_trans_(tadj(istable,j)); + % else + % y0 = trank(tadj(istable,j)); + % end + % if ~isempty(EET), + % if size(tadj,2)~=ny, + % jj=find(EET.ir_tadj==ir_tadj(j)); + % jj=jj(find(EET.ic_tadj(jj)==ic_tadj(j))); + % if ~isempty(jj), + % imap=find(EET.SAtadj(jj,:) >= (0.1.*max(EET.SAtadj(jj,:))) ); + % else + % imap=[1:np]; + % end + % else + % imap=find(EET.SAtadj(j,:) >= (0.1.*max(EET.SAtadj(j,:))) ); + % end + % end + % % gsa_(j) = gsa_sdp_dyn( y0, lpmat(istable,:), ... + % % gsa_flag, [],[],[],0,[OutputDirectoryName,'/map_tadj',fsuffix,int2str(j)], pnames); + % gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ... + % 2, [],[],[],0,[OutputDirectoryName,'/map_tadj',fsuffix,int2str(j)], pnames); + % if nfit>nest, + % gsa_(j) = gsa_sdp(y0(1:nfit), x0(1:nfit,imap), ... + % -2, gsa_(j).nvr*nest^3/nfit^3,[],[],0,[OutputDirectoryName,'/map_tadj',fsuffix,int2str(j)], pnames); + % end + % SAtadj(j,imap)=gsa_(j).si; + % imap_tadj{j}=imap; + % + % end + % save([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_tadj','SAtadj','tadj','ir_tadj','ic_tadj','-append') + % else + % load([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_tadj','SAtadj','tadj','ir_tadj','ic_tadj') + % end + % + % figure, + % % boxplot(SAtadj,'whis',10,'symbol','r.') + % myboxplot(SAtadj,[],'.',[],10) + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) + % set(gca,'xlim',[0.5 np+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % set(gca,'position',[0.13 0.2 0.775 0.7]) + % for ip=1:np, + % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % title(['Main effects speed of adjustment ',fsuffix],'interpreter','none') + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_tadj',fsuffix]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix]); + % close(gcf), + % + % ifig = 0; + % for j=1:size(options_.varobs,1) + % if mod(j,6)==1 + % figure('name',['Main effects observed speed adjustment ',fsuffix]); + % ifig=ifig+1; + % iplo = 0; + % end + % iplo=iplo+1; + % subplot(3,2,iplo) + % iv = find(ir_tadj==j); + % if ~isempty(iv) + % if length(iv)>1 + % % boxplot(SAtadj(iv,:),'whis',3,'symbol','r.'); + % myboxplot(SAtadj(iv,:),[],'.',[],10) + % else + % plot(SAtadj(iv,:),'r.'); + % end + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) + % set(gca,'xlim',[0.5 np+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % for ip=1:np, + % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % end + % title(options_.varobs(j,:),'interpreter','none') + % if mod(j,6)==0 | j==size(options_.varobs,1) + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_tadj',fsuffix,'_varobs_',int2str(ifig)]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix,'_varobs_',int2str(ifig)]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix,'_varobs_',int2str(ifig)]); + % close(gcf), + % end + % end + % + % ifig = 0; + % for j=1:M_.exo_nbr, + % if mod(j,6)==1 + % figure('name',['Main effects shocks speed of adjustment ',fsuffix]); + % ifig=ifig+1; + % iplo=0; + % end + % iplo=iplo+1; + % subplot(3,2,iplo) + % iv = find(ic_tadj==j); + % if ~isempty(iv) + % if length(iv)>1 + % % boxplot(SAtadj(iv,:),'whis',3,'symbol','r.'); + % myboxplot(SAtadj(iv,:),[],'.',[],10) + % else + % plot(SAtadj(iv,:),'r.'); + % end + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) + % set(gca,'xlim',[0.5 np+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % for ip=1:np, + % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % end + % title(M_.exo_names(j,:),'interpreter','none') + % if mod(j,6)==0 | j==M_.exo_nbr, + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_tadj',fsuffix,'_exo_',int2str(ifig)]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix,'_exo_',int2str(ifig)]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix,'_exo_',int2str(ifig)]); + % close(gcf), + % end + % end + % + % + % if opt_gsa.load_ident_files==0, + % try + % EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAIF','ir_if','ic_if'); + % catch + % EET=[]; + % end + % SAif=zeros(size(iff,2),np); + % for j=1:size(iff,2), + % if itrans==0, + % y0 = iff(istable,j); + % elseif itrans==1, + % y0 = log_trans_(iff(istable,j)); + % else + % y0 = trank(iff(istable,j)); + % end + % if ~isempty(EET), + % imap=find(EET.SAIF(j,:) >= (0.1.*max(EET.SAIF(j,:))) ); + % end + % % gsa_(j) = gsa_sdp_dyn( y0, lpmat(istable,:), ... + % % gsa_flag, [],[],[],0,[OutputDirectoryName,'/map_if',fsuffix,int2str(j)], pnames); + % gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ... + % 2, [],[],[],0,[OutputDirectoryName,'/map_if',fsuffix,int2str(j)], pnames); + % if nfit>nest, + % gsa_(j) = gsa_sdp(y0(1:nfit), x0(1:nfit,imap), ... + % -2, gsa_(j).nvr*nest^3/nfit^3,[],[],0,[OutputDirectoryName,'/map_if',fsuffix,int2str(j)], pnames); + % end + % SAif(j,imap)=gsa_(j).si; + % imap_if{j}=imap; + % + % end + % save([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_if','SAif','iff','ir_if','ic_if','-append') + % else + % load([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_if','SAif','iff','ir_if','ic_if') + % end + % + % figure, + % % boxplot(SAif,'whis',10,'symbol','r.') + % myboxplot(SAif,[],'.',[],10) + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) + % set(gca,'xlim',[0.5 np+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % set(gca,'position',[0.13 0.2 0.775 0.7]) + % for ip=1:np, + % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % title(['Main effects impact factors ',fsuffix],'interpreter','none') + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_if',fsuffix]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_if',fsuffix]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_if',fsuffix]); + % close(gcf), + % + % ifig = 0; + % for j=1:size(options_.varobs,1) + % if mod(j,6)==1 + % figure('name',['Main effects observed impact factors ',fsuffix]); + % ifig=ifig+1; + % iplo = 0; + % end + % iplo=iplo+1; + % subplot(3,2,iplo) + % iv = find(ir_if==j); + % if ~isempty(iv) + % if length(iv)>1 + % % boxplot(SAif(iv,:),'whis',3,'symbol','r.'); + % myboxplot(SAif(iv,:),[],'.',[],10) + % else + % plot(SAif(iv,:),'r.'); + % end + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) + % set(gca,'xlim',[0.5 np+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % for ip=1:np, + % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % end + % title(options_.varobs(j,:),'interpreter','none') + % if mod(j,6)==0 | j==size(options_.varobs,1) + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_if',fsuffix,'_varobs_',int2str(ifig)]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_if',fsuffix,'_varobs_',int2str(ifig)]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_if',fsuffix,'_varobs_',int2str(ifig)]); + % close(gcf), + % end + % end + % + % ifig = 0; + % for j=1:M_.exo_nbr, + % if mod(j,6)==1 + % figure('name',['Main effects shocks impact factors ',fsuffix]); + % ifig=ifig+1; + % iplo=0; + % end + % iplo=iplo+1; + % subplot(3,2,iplo) + % iv = find(ic_if==j); + % if ~isempty(iv) + % if length(iv)>1 + % % boxplot(SAif(iv,:),'whis',3,'symbol','r.'); + % myboxplot(SAif(iv,:),[],'.',[],10) + % else + % plot(SAif(iv,:),'r.'); + % end + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) + % set(gca,'xlim',[0.5 np+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % for ip=1:np, + % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % end + % title(M_.exo_names(j,:),'interpreter','none') + % if mod(j,6)==0 | j==M_.exo_nbr + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_if',fsuffix,'_exo_',int2str(ifig)]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_if',fsuffix,'_exo_',int2str(ifig)]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_if',fsuffix,'_exo_',int2str(ifig)]); + % close(gcf), + % end + % end + % SAmom = [SAvdec' SAcc' SAac']'; + % SAdyn = [SAtadj' SAif']'; + % SAall = [SAmom(:,nshock+1:end)' SAdyn']'; + % + % figure, + % % boxplot(SAtadj,'whis',10,'symbol','r.') + % myboxplot(SAmom,[],'.',[],10) + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) + % set(gca,'xlim',[0.5 npT+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % set(gca,'position',[0.13 0.2 0.775 0.7]) + % for ip=1:npT, + % % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % title(['Main effects theoretical moments ',fsuffix],'interpreter','none') + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_moments',fsuffix]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_moments',fsuffix]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_moments',fsuffix]); + % % close(gcf), + % + % figure, + % % boxplot(SAtadj,'whis',10,'symbol','r.') + % myboxplot(SAdyn,[],'.',[],10) + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) + % set(gca,'xlim',[0.5 np+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % set(gca,'position',[0.13 0.2 0.775 0.7]) + % for ip=1:np, + % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % % text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % title(['Main effects short-long term dynamics ',fsuffix],'interpreter','none') + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_dynamics',fsuffix]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_dynamics',fsuffix]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_dynamics',fsuffix]); + % % close(gcf), + % + % figure, + % % boxplot(SAtadj,'whis',10,'symbol','r.') + % myboxplot(SAall,[],'.',[],10) + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) + % set(gca,'xlim',[0.5 np+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % set(gca,'position',[0.13 0.2 0.775 0.7]) + % for ip=1:np, + % text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % % text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % title(['Main effects all ',fsuffix],'interpreter','none') + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_ALL',fsuffix]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_ALL',fsuffix]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_ALL',fsuffix]); + % % close(gcf), + + % for j=1:size(SAall,1), + % SAallN(j,:)=SAall(j,:)./max(SAall(j,:)); + % end + % SAmean=mean(SAallN); + % for j=1:size(SAmom,1), + % SAmomN(j,:)=SAmom(j,1:nshock)./max(SAmom(j,1:nshock)); + % end + % SAmomN(find(isnan(SAmomN)))=0; + % SAmeanexo=mean(SAmomN(:,1:nshock)); + + % figure, bar(latent'*SAcc), + hh=dyn_figure(options_.nodisplay,'Name',['Identifiability indices in the ',fsuffix,' moments.']); + bar(sum(SAcc)) + set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT]) + set(gca,'xlim',[0.5 npT+0.5]) + ydum = get(gca,'ylim'); + set(gca,'ylim',[0 ydum(2)]) + set(gca,'position',[0.13 0.2 0.775 0.7]) + for ip=1:npT + text(ip,-0.02*(ydum(2)),bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + % text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + end + xlabel(' ') + title(['Identifiability indices in the ',fsuffix,' moments.'],'interpreter','none') + dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_ident_ALL',fsuffix],options_.nodisplay,options_.graph_format); + create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_ident_ALL',fsuffix],1,['Identifiability indices in the ',fsuffix,' moments.'],['ident_ALL',fsuffix]',1) + + % figure, bar(SAmeanexo), + % set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:nshock]) + % set(gca,'xlim',[0.5 nshock+0.5]) + % ydum = get(gca,'ylim'); + % set(gca,'ylim',[0 ydum(2)]) + % set(gca,'position',[0.13 0.2 0.775 0.7]) + % for ip=1:nshock, + % % text(ip,-0.02*(ydum(2)),deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + % text(ip,-0.02*(ydum(2)),bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') + % end + % xlabel(' ') + % title(['Identifiability indices for shocks',fsuffix],'interpreter','none') + % saveas(gcf,[OutputDirectoryName,'/',fname_,'_ident_SHOCKS',fsuffix]) + % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_ident_SHOCKS',fsuffix]); + % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_ident_SHOCKS',fsuffix]); end return diff --git a/matlab/gsa/mc_moments.m b/matlab/gsa/mc_moments.m index cee56c22d3..b7464a7e0d 100644 --- a/matlab/gsa/mc_moments.m +++ b/matlab/gsa/mc_moments.m @@ -19,19 +19,19 @@ function [vdec, cc, ac] = mc_moments(mm, ss, dr) global options_ M_ estim_params_ oo_ - [nr1, nc1, nsam] = size(mm); - nobs=size(options_.varobs,2); - disp('Computing theoretical moments ...') - h = dyn_waitbar(0,'Theoretical moments ...'); - vdec = zeros(nobs,M_.exo_nbr,nsam); - cc = zeros(nobs,nobs,nsam); - ac = zeros(nobs,nobs*options_.ar,nsam); - - for j=1:nsam +[nr1, nc1, nsam] = size(mm); +nobs=size(options_.varobs,2); +disp('Computing theoretical moments ...') +h = dyn_waitbar(0,'Theoretical moments ...'); +vdec = zeros(nobs,M_.exo_nbr,nsam); +cc = zeros(nobs,nobs,nsam); +ac = zeros(nobs,nobs*options_.ar,nsam); + +for j=1:nsam oo_.dr.ghx = mm(:, [1:(nc1-M_.exo_nbr)],j); oo_.dr.ghu = mm(:, [(nc1-M_.exo_nbr+1):end], j); if ~isempty(ss) - set_shocks_param(ss(j,:)); + set_shocks_param(ss(j,:)); end [vdec(:,:,j), corr, autocorr, z, zz] = th_moments(oo_.dr,options_.varobs); cc(:,:,j)=triu(corr); @@ -41,7 +41,7 @@ global options_ M_ estim_params_ oo_ end ac(:,:,j)=dum; dyn_waitbar(j/nsam,h) - end - dyn_waitbar_close(h) - skipline() - disp('... done !') +end +dyn_waitbar_close(h) +skipline() +disp('... done !') diff --git a/matlab/gsa/mcf_analysis.m b/matlab/gsa/mcf_analysis.m index a8661722ca..5523d7d7b7 100644 --- a/matlab/gsa/mcf_analysis.m +++ b/matlab/gsa/mcf_analysis.m @@ -1,84 +1,84 @@ -function indmcf = mcf_analysis(lpmat, ibeha, inobeha, options_mcf, DynareOptions) -% -% Written by Marco Ratto -% Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu -% - -% Copyright (C) 2014 European Commission -% Copyright (C) 2016 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/>. - -pvalue_ks = options_mcf.pvalue_ks; -pvalue_corr = options_mcf.pvalue_corr; -alpha2 = options_mcf.alpha2; -param_names = options_mcf.param_names; - -if DynareOptions.TeX - if ~isfield(options_mcf,'param_names_tex') - param_names_tex = options_mcf.param_names; - else - param_names_tex = options_mcf.param_names_tex; - end -end -amcf_name = options_mcf.amcf_name; -amcf_title = options_mcf.amcf_title; -beha_title = options_mcf.beha_title; -nobeha_title = options_mcf.nobeha_title; -title = options_mcf.title; -fname_ = options_mcf.fname_; -xparam1=[]; -if isfield(options_mcf,'xparam1') - xparam1=options_mcf.xparam1; -end -OutputDirectoryName = options_mcf.OutputDirectoryName; - -[proba, dproba] = stab_map_1(lpmat, ibeha, inobeha, [],0); -indmcf=find(proba<pvalue_ks); -[tmp,jtmp] = sort(proba(indmcf),2,'ascend'); -indmcf = indmcf(jtmp); -if ~isempty(indmcf) - skipline() - headers=char('Parameter','d-stat','p-value'); - labels=char(param_names(indmcf,:)); - data_mat=[dproba(indmcf)' proba(indmcf)']; - options_temp.noprint=0; - dyntable(options_temp,['Smirnov statistics in driving ', title],headers,labels,data_mat,size(labels,2)+2,16,3); - if DynareOptions.TeX - labels_TeX=param_names_tex(indmcf,:); - M_temp.dname=OutputDirectoryName ; - M_temp.fname=fname_; - dyn_latex_table(M_temp,options_temp,['Smirnov statistics in driving ', strrep(title,'_','\\_')],amcf_name,headers,labels_TeX,data_mat,size(labels,2)+2,16,6); - end -end - - -if length(ibeha)>10 && length(inobeha)>10 - indcorr1 = stab_map_2(lpmat(ibeha,:),alpha2, pvalue_corr, beha_title); - indcorr2 = stab_map_2(lpmat(inobeha,:),alpha2, pvalue_corr, nobeha_title); - indcorr = union(indcorr1(:), indcorr2(:)); - indcorr = indcorr(~ismember(indcorr(:),indmcf)); - indmcf = [indmcf(:); indcorr(:)]; -end -if ~isempty(indmcf) && ~DynareOptions.nograph - skipline() - xx=[]; - if ~ isempty(xparam1), xx=xparam1(indmcf); end - scatter_mcf(lpmat(ibeha,indmcf),lpmat(inobeha,indmcf), param_names(indmcf,:), ... - '.', [fname_,'_',amcf_name], OutputDirectoryName, amcf_title,xx, DynareOptions, ... - beha_title, nobeha_title) -end +function indmcf = mcf_analysis(lpmat, ibeha, inobeha, options_mcf, DynareOptions) +% +% Written by Marco Ratto +% Joint Research Centre, The European Commission, +% marco.ratto@ec.europa.eu +% + +% Copyright (C) 2014 European Commission +% Copyright (C) 2016 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/>. + +pvalue_ks = options_mcf.pvalue_ks; +pvalue_corr = options_mcf.pvalue_corr; +alpha2 = options_mcf.alpha2; +param_names = options_mcf.param_names; + +if DynareOptions.TeX + if ~isfield(options_mcf,'param_names_tex') + param_names_tex = options_mcf.param_names; + else + param_names_tex = options_mcf.param_names_tex; + end +end +amcf_name = options_mcf.amcf_name; +amcf_title = options_mcf.amcf_title; +beha_title = options_mcf.beha_title; +nobeha_title = options_mcf.nobeha_title; +title = options_mcf.title; +fname_ = options_mcf.fname_; +xparam1=[]; +if isfield(options_mcf,'xparam1') + xparam1=options_mcf.xparam1; +end +OutputDirectoryName = options_mcf.OutputDirectoryName; + +[proba, dproba] = stab_map_1(lpmat, ibeha, inobeha, [],0); +indmcf=find(proba<pvalue_ks); +[tmp,jtmp] = sort(proba(indmcf),2,'ascend'); +indmcf = indmcf(jtmp); +if ~isempty(indmcf) + skipline() + headers=char('Parameter','d-stat','p-value'); + labels=char(param_names(indmcf,:)); + data_mat=[dproba(indmcf)' proba(indmcf)']; + options_temp.noprint=0; + dyntable(options_temp,['Smirnov statistics in driving ', title],headers,labels,data_mat,size(labels,2)+2,16,3); + if DynareOptions.TeX + labels_TeX=param_names_tex(indmcf,:); + M_temp.dname=OutputDirectoryName ; + M_temp.fname=fname_; + dyn_latex_table(M_temp,options_temp,['Smirnov statistics in driving ', strrep(title,'_','\\_')],amcf_name,headers,labels_TeX,data_mat,size(labels,2)+2,16,6); + end +end + + +if length(ibeha)>10 && length(inobeha)>10 + indcorr1 = stab_map_2(lpmat(ibeha,:),alpha2, pvalue_corr, beha_title); + indcorr2 = stab_map_2(lpmat(inobeha,:),alpha2, pvalue_corr, nobeha_title); + indcorr = union(indcorr1(:), indcorr2(:)); + indcorr = indcorr(~ismember(indcorr(:),indmcf)); + indmcf = [indmcf(:); indcorr(:)]; +end +if ~isempty(indmcf) && ~DynareOptions.nograph + skipline() + xx=[]; + if ~ isempty(xparam1), xx=xparam1(indmcf); end + scatter_mcf(lpmat(ibeha,indmcf),lpmat(inobeha,indmcf), param_names(indmcf,:), ... + '.', [fname_,'_',amcf_name], OutputDirectoryName, amcf_title,xx, DynareOptions, ... + beha_title, nobeha_title) +end diff --git a/matlab/gsa/myboxplot.m b/matlab/gsa/myboxplot.m index 39eba89603..cdb4b4661d 100644 --- a/matlab/gsa/myboxplot.m +++ b/matlab/gsa/myboxplot.m @@ -3,7 +3,7 @@ function sout = myboxplot (data,notched,symbol,vertical,maxwhisker) % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % Copyright (C) 2012 European Commission % Copyright (C) 2012 Dynare Team @@ -36,10 +36,10 @@ a=1-notched; % ## figure out how many data sets we have if iscell(data) - nc = length(data); + nc = length(data); else -% if isvector(data), data = data(:); end - nc = size(data,2); + % if isvector(data), data = data(:); end + nc = size(data,2); end % ## compute statistics @@ -63,60 +63,60 @@ for i=1:nc else col = data(:,i); end -% ## Skip missing data -% % % % % % % col(isnan(col) | isna (col)) = []; - col(isnan(col)) = []; - - % ## Remember the data length - nd = length(col); - box(i) = nd; - if (nd > 1) -% ## min,max and quartiles -% s(1:5,i) = statistics(col)(1:5); -s(1,i)=min(col); -s(5,i)=max(col); -s(2,i)=myprctilecol(col,25); -s(3,i)=myprctilecol(col,50); -s(4,i)=myprctilecol(col,75); - - - - - - - - -% ## confidence interval for the median - est = 1.57*(s(4,i)-s(2,i))/sqrt(nd); - s(6,i) = max([s(3,i)-est, s(2,i)]); - s(7,i) = min([s(3,i)+est, s(4,i)]); -% ## whiskers out to the last point within the desired inter-quartile range - IQR = maxwhisker*(s(4,i)-s(2,i)); - whisker_y(:,i) = [min(col(col >= s(2,i)-IQR)); s(2,i)]; - whisker_y(:,nc+i) = [max(col(col <= s(4,i)+IQR)); s(4,i)]; -% ## outliers beyond 1 and 2 inter-quartile ranges - outliers = col((col < s(2,i)-IQR & col >= s(2,i)-2*IQR) | (col > s(4,i)+IQR & col <= s(4,i)+2*IQR)); - outliers2 = col(col < s(2,i)-2*IQR | col > s(4,i)+2*IQR); - outliers_x = [outliers_x; i*ones(size(outliers))]; - outliers_y = [outliers_y; outliers]; - outliers2_x = [outliers2_x; i*ones(size(outliers2))]; - outliers2_y = [outliers2_y; outliers2]; - elseif (nd == 1) -% ## all statistics collapse to the value of the point - s(:,i) = col; -% ## single point data sets are plotted as outliers. - outliers_x = [outliers_x; i]; - outliers_y = [outliers_y; col]; - else -% ## no statistics if no points - s(:,i) = NaN; - end + % ## Skip missing data + % % % % % % % col(isnan(col) | isna (col)) = []; + col(isnan(col)) = []; + + % ## Remember the data length + nd = length(col); + box(i) = nd; + if (nd > 1) + % ## min,max and quartiles + % s(1:5,i) = statistics(col)(1:5); + s(1,i)=min(col); + s(5,i)=max(col); + s(2,i)=myprctilecol(col,25); + s(3,i)=myprctilecol(col,50); + s(4,i)=myprctilecol(col,75); + + + + + + + + + % ## confidence interval for the median + est = 1.57*(s(4,i)-s(2,i))/sqrt(nd); + s(6,i) = max([s(3,i)-est, s(2,i)]); + s(7,i) = min([s(3,i)+est, s(4,i)]); + % ## whiskers out to the last point within the desired inter-quartile range + IQR = maxwhisker*(s(4,i)-s(2,i)); + whisker_y(:,i) = [min(col(col >= s(2,i)-IQR)); s(2,i)]; + whisker_y(:,nc+i) = [max(col(col <= s(4,i)+IQR)); s(4,i)]; + % ## outliers beyond 1 and 2 inter-quartile ranges + outliers = col((col < s(2,i)-IQR & col >= s(2,i)-2*IQR) | (col > s(4,i)+IQR & col <= s(4,i)+2*IQR)); + outliers2 = col(col < s(2,i)-2*IQR | col > s(4,i)+2*IQR); + outliers_x = [outliers_x; i*ones(size(outliers))]; + outliers_y = [outliers_y; outliers]; + outliers2_x = [outliers2_x; i*ones(size(outliers2))]; + outliers2_y = [outliers2_y; outliers2]; + elseif (nd == 1) + % ## all statistics collapse to the value of the point + s(:,i) = col; + % ## single point data sets are plotted as outliers. + outliers_x = [outliers_x; i]; + outliers_y = [outliers_y; col]; + else + % ## no statistics if no points + s(:,i) = NaN; + end end % % % % if isempty(outliers2_y) % % % % outliers2_y= % ## Note which boxes don't have enough stats chop = find(box <= 1); - + % ## Draw a box around the quartiles, with width proportional to the number of % ## items in the box. Draw notches if desired. box = box*0.23/max(box); @@ -135,7 +135,7 @@ whisker_x(:,[chop,chop+nc]) = []; whisker_y(:,[chop,chop+nc]) = []; median_x(:,chop) = []; median_y(:,chop) = []; -% % % % +% % % % % ## Add caps to the remaining whiskers cap_x = whisker_x; cap_x(1,:) =cap_x(1,:)- 0.05; @@ -146,7 +146,7 @@ cap_y = whisker_y([1,1],:); % #whisker_x,whisker_y % #median_x,median_y % #cap_x,cap_y -% +% % ## Do the plot mm=min(min(data)); @@ -154,25 +154,25 @@ MM=max(max(data)); if vertical plot (quartile_x, quartile_y, 'b', ... - whisker_x, whisker_y, 'b--', ... - cap_x, cap_y, 'k', ... - median_x, median_y, 'r', ... - outliers_x, outliers_y, [symbol(1),'r'], ... - outliers2_x, outliers2_y, [symbol(2),'r']); - set(gca,'XTick',1:nc); - set(gca, 'XLim', [0.5, nc+0.5]); - set(gca, 'YLim', [mm-(MM-mm)*0.05-eps, MM+(MM-mm)*0.05+eps]); + whisker_x, whisker_y, 'b--', ... + cap_x, cap_y, 'k', ... + median_x, median_y, 'r', ... + outliers_x, outliers_y, [symbol(1),'r'], ... + outliers2_x, outliers2_y, [symbol(2),'r']); + set(gca,'XTick',1:nc); + set(gca, 'XLim', [0.5, nc+0.5]); + set(gca, 'YLim', [mm-(MM-mm)*0.05-eps, MM+(MM-mm)*0.05+eps]); else -% % % % % plot (quartile_y, quartile_x, "b;;", -% % % % % whisker_y, whisker_x, "b;;", -% % % % % cap_y, cap_x, "b;;", -% % % % % median_y, median_x, "r;;", -% % % % % outliers_y, outliers_x, [symbol(1),"r;;"], -% % % % % outliers2_y, outliers2_x, [symbol(2),"r;;"]); + % % % % % plot (quartile_y, quartile_x, "b;;", + % % % % % whisker_y, whisker_x, "b;;", + % % % % % cap_y, cap_x, "b;;", + % % % % % median_y, median_x, "r;;", + % % % % % outliers_y, outliers_x, [symbol(1),"r;;"], + % % % % % outliers2_y, outliers2_x, [symbol(2),"r;;"]); end if nargout - sout=s; + sout=s; end % % % endfunction \ No newline at end of file diff --git a/matlab/gsa/myprctilecol.m b/matlab/gsa/myprctilecol.m index 21c139d6b9..2cc7f473f6 100644 --- a/matlab/gsa/myprctilecol.m +++ b/matlab/gsa/myprctilecol.m @@ -2,7 +2,7 @@ function y = myprctilecol(x,p) % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % Copyright (C) 2012 European Commission % Copyright (C) 2012 Dynare Team @@ -27,10 +27,10 @@ xx = sort(x); if m==1 | n==1 m = max(m,n); - if m == 1 - y = x*ones(length(p),1); - return - end + if m == 1 + y = x*ones(length(p),1); + return + end n = 1; q = 100*(0.5:m - 0.5)./m; xx = [min(x); xx(:); max(x)]; diff --git a/matlab/gsa/pick.m b/matlab/gsa/pick.m index 8a3f53a556..9ff6e2c05c 100644 --- a/matlab/gsa/pick.m +++ b/matlab/gsa/pick.m @@ -1,90 +1,90 @@ -function pick -% -% Copyright (C) 2001-2017 European Commission -% -% This file is part of GLUEWIN -% GLUEWIN is a MATLAB code designed for analysing the output -% of Monte Carlo runs when empirical observations of the model output are available -% and implements the GSA-GLUE methodology by Ratto et al. [1], based on a combination -% of GLUE (Generalised Likelihood Uncertainty Estimation) by K. Beven [2] and GSA -% Global Sensitivity Analysis) [3].'] -% The program has been developed by M. Ratto, European Commission, Joint Research Centre, -% Institute for the Protection and Security of The Citizen, Technological and Economic Risk Management, -% Applied Statistics, as a deliverable of the IMPACT project -% (EC Fifth Framework Programme, SCA Project, IST-1999-11313, DG-INFSO). -% -% The graphical layout of the code is inspired by the freeware GLUE package by K. Beven, -% vailable at the Lancaster University web site on the page [4]: -% http://www.es.lancs.ac.uk/hfdg/glue.html -% to which the GLUEWIN code introduces several extensions and additional options. -% Thanks are due to R. Girardi, A. Rossi, A. Saltelli, S. Tarantola and U. Callies for numerous -% comments and suggestions. -% For more information, please contact marco.ratto@ec.europa.eu -% -% Disclaimer: This software has been developed at the Joint Research Centre of European Commission -% by officers in the course of their official duties. This software is not subject to copyright -% protection and is in the public domain. It is an experimental system. The Joint Research Centre -% of European Commission assumes no responsibility whatsoever for its use by other parties -% and makes no guarantees, expressed or implied, about its quality, reliability, or any other -% characteristic. We would appreciate acknowledgement if the software is used. -% -% [1] Ratto, M., Tarantola, S., A. Saltelli, Sensitivity analysis in model calibration: GSA-GLUE approach. -% 'Computer Physics Communications, 136, 2001, 212-224 -% [2] Beven K.J., Binley A., The Future of Distributed Models: Model Calibration and Uncertainty -% 'Prediction, Hydrological Processes, 6, 279-298, 1992 -% [3] Saltelli, A., K. Chan, M. Scott, Editors, (2000), Sensitivity analysis, John Wiley & Sons -% 'publishers, Probability and Statistics series. -% [4] Beven K., GLUE for Windows User manual, 1998. - - - -pmenu=findobj(gcf,'type','uicontextmenu','Tag','Run viewer'); -button1=findobj(gcf,'type','uimenu','Tag','save params'); -button2=findobj(gcf,'type','uimenu','Tag','eval params'); -%button=get(pmenu,'children'); -gg=gco; -ax0=gca; -set(gg,'buttondownfcn',[]); -c=get(gca,'currentpoint'); -x=c(1,1); -y=c(1,2); -X=get(gco,'xdata'); -Y=get(gco,'ydata'); -dx=get(gca,'xlim'); -dy=get(gca,'ylim'); -pos=get(gca,'position'); -scalex=dx(2)-dx(1); -scaley=dy(2)-dy(1); -if length(X)>1 - K = dsearchn([(Y./scaley)' (X./scalex)'],[y/scaley x/scalex]); -else - az=get(gca,'children'); - T =get(az(end),'ydata'); - [dum K]=max(T); -end - -KK=K; - -set(button1,'Label',['Save ',num2str(K)],'Callback',['scatter_callback(',num2str(KK),',''save'')']); -set(button2,'Label',['Eval ',num2str(K)],'Callback',['scatter_callback(',num2str(KK),',''eval'')']); -hh=findobj(gcf,'type','axes','Tag','scatter'); -for k=1:length(hh) - axes(hh(k)); - dum=get(gca,'children'); - dumx=get(dum(end),'xdata'); - dumy=get(dum(end),'ydata'); - xmid=min(dumx) + 0.5*(max(dumx)-min(dumx)); - hold on - plot(dumx(KK),dumy(KK),'or'); - if dumx(KK) < xmid - text(dumx(KK),dumy(KK),[' ',num2str(K)], ... - 'FontWeight','Bold',... - 'Color','r'); - else - text(dumx(KK),dumy(KK),[num2str(K),' '], ... - 'HorizontalAlignment','right', ... - 'FontWeight','Bold',... - 'Color','r'); - end - hold off +function pick +% +% Copyright (C) 2001-2017 European Commission +% +% This file is part of GLUEWIN +% GLUEWIN is a MATLAB code designed for analysing the output +% of Monte Carlo runs when empirical observations of the model output are available +% and implements the GSA-GLUE methodology by Ratto et al. [1], based on a combination +% of GLUE (Generalised Likelihood Uncertainty Estimation) by K. Beven [2] and GSA +% Global Sensitivity Analysis) [3].'] +% The program has been developed by M. Ratto, European Commission, Joint Research Centre, +% Institute for the Protection and Security of The Citizen, Technological and Economic Risk Management, +% Applied Statistics, as a deliverable of the IMPACT project +% (EC Fifth Framework Programme, SCA Project, IST-1999-11313, DG-INFSO). +% +% The graphical layout of the code is inspired by the freeware GLUE package by K. Beven, +% vailable at the Lancaster University web site on the page [4]: +% http://www.es.lancs.ac.uk/hfdg/glue.html +% to which the GLUEWIN code introduces several extensions and additional options. +% Thanks are due to R. Girardi, A. Rossi, A. Saltelli, S. Tarantola and U. Callies for numerous +% comments and suggestions. +% For more information, please contact marco.ratto@ec.europa.eu +% +% Disclaimer: This software has been developed at the Joint Research Centre of European Commission +% by officers in the course of their official duties. This software is not subject to copyright +% protection and is in the public domain. It is an experimental system. The Joint Research Centre +% of European Commission assumes no responsibility whatsoever for its use by other parties +% and makes no guarantees, expressed or implied, about its quality, reliability, or any other +% characteristic. We would appreciate acknowledgement if the software is used. +% +% [1] Ratto, M., Tarantola, S., A. Saltelli, Sensitivity analysis in model calibration: GSA-GLUE approach. +% 'Computer Physics Communications, 136, 2001, 212-224 +% [2] Beven K.J., Binley A., The Future of Distributed Models: Model Calibration and Uncertainty +% 'Prediction, Hydrological Processes, 6, 279-298, 1992 +% [3] Saltelli, A., K. Chan, M. Scott, Editors, (2000), Sensitivity analysis, John Wiley & Sons +% 'publishers, Probability and Statistics series. +% [4] Beven K., GLUE for Windows User manual, 1998. + + + +pmenu=findobj(gcf,'type','uicontextmenu','Tag','Run viewer'); +button1=findobj(gcf,'type','uimenu','Tag','save params'); +button2=findobj(gcf,'type','uimenu','Tag','eval params'); +%button=get(pmenu,'children'); +gg=gco; +ax0=gca; +set(gg,'buttondownfcn',[]); +c=get(gca,'currentpoint'); +x=c(1,1); +y=c(1,2); +X=get(gco,'xdata'); +Y=get(gco,'ydata'); +dx=get(gca,'xlim'); +dy=get(gca,'ylim'); +pos=get(gca,'position'); +scalex=dx(2)-dx(1); +scaley=dy(2)-dy(1); +if length(X)>1 + K = dsearchn([(Y./scaley)' (X./scalex)'],[y/scaley x/scalex]); +else + az=get(gca,'children'); + T =get(az(end),'ydata'); + [dum K]=max(T); +end + +KK=K; + +set(button1,'Label',['Save ',num2str(K)],'Callback',['scatter_callback(',num2str(KK),',''save'')']); +set(button2,'Label',['Eval ',num2str(K)],'Callback',['scatter_callback(',num2str(KK),',''eval'')']); +hh=findobj(gcf,'type','axes','Tag','scatter'); +for k=1:length(hh) + axes(hh(k)); + dum=get(gca,'children'); + dumx=get(dum(end),'xdata'); + dumy=get(dum(end),'ydata'); + xmid=min(dumx) + 0.5*(max(dumx)-min(dumx)); + hold on + plot(dumx(KK),dumy(KK),'or'); + if dumx(KK) < xmid + text(dumx(KK),dumy(KK),[' ',num2str(K)], ... + 'FontWeight','Bold',... + 'Color','r'); + else + text(dumx(KK),dumy(KK),[num2str(K),' '], ... + 'HorizontalAlignment','right', ... + 'FontWeight','Bold',... + 'Color','r'); + end + hold off end \ No newline at end of file diff --git a/matlab/gsa/prior_draw_gsa.m b/matlab/gsa/prior_draw_gsa.m index a54fda1b3b..3078b3f0cd 100644 --- a/matlab/gsa/prior_draw_gsa.m +++ b/matlab/gsa/prior_draw_gsa.m @@ -1,22 +1,22 @@ function pdraw = prior_draw_gsa(init,rdraw) % Draws from the prior distributions for use with Sensitivity Toolbox for DYNARE -% +% % INPUTS % o init [integer] scalar equal to 1 (first call) or 0. -% o rdraw -% -% OUTPUTS -% o pdraw [double] draw from the joint prior density. +% o rdraw +% +% OUTPUTS +% o pdraw [double] draw from the joint prior density. % -% ALGORITHM -% ... +% ALGORITHM +% ... % % SPECIAL REQUIREMENTS % MATLAB Statistics Toolbox -% +% % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % Copyright (C) 2012-2015 European Commission % Copyright (C) 2012-2015 Dynare Team @@ -38,7 +38,7 @@ function pdraw = prior_draw_gsa(init,rdraw) global bayestopt_ options_ estim_params_ M_ persistent npar pshape p6 p7 p3 p4 lbcum ubcum - + if init pshape = bayestopt_.pshape; p6 = bayestopt_.p6; @@ -56,40 +56,40 @@ if init bounds.lb = max(bounds.lb,lb); bounds.ub = min(bounds.ub,ub); else % estimated parameters but no declared priors - % No priors are declared so Dynare will estimate the model by - % maximum likelihood with inequality constraints for the parameters. + % No priors are declared so Dynare will estimate the model by + % maximum likelihood with inequality constraints for the parameters. bounds.lb = lb; bounds.ub = ub; end % set bounds for cumulative probabilities for i = 1:npar - switch pshape(i) - case 5% Uniform prior. - p4(i) = min(p4(i),bounds.ub(i)); - p3(i) = max(p3(i),bounds.lb(i)); - case 3% Gaussian prior. - lbcum(i) = 0.5 * erfc(-(bounds.lb(i)-p6(i))/p7(i) ./ sqrt(2)); - ubcum(i) = 0.5 * erfc(-(bounds.ub(i)-p6(i))/p7(i) ./ sqrt(2)); - case 2% Gamma prior. - lbcum(i) = gamcdf(bounds.lb(i)-p3(i),p6(i),p7(i)); - ubcum(i) = gamcdf(bounds.ub(i)-p3(i),p6(i),p7(i)); - case 1% Beta distribution (TODO: generalized beta distribution) - lbcum(i) = betainc((bounds.lb(i)-p3(i))./(p4(i)-p3(i)),p6(i),p7(i)); - ubcum(i) = betainc((bounds.ub(i)-p3(i))./(p4(i)-p3(i)),p6(i),p7(i)); - case 4% INV-GAMMA1 distribution - % TO BE CHECKED - lbcum(i) = gamcdf(1/(bounds.ub(i)-p3(i))^2,p7(i)/2,2/p6(i)); - ubcum(i) = gamcdf(1/(bounds.lb(i)-p3(i))^2,p7(i)/2,2/p6(i)); - case 6% INV-GAMMA2 distribution - % TO BE CHECKED - lbcum(i) = gamcdf(1/(bounds.ub(i)-p3(i)),p7(i)/2,2/p6(i)); - ubcum(i) = gamcdf(1/(bounds.lb(i)-p3(i)),p7(i)/2,2/p6(i)); - case 8 - lbcum(i) = weibcdf(bounds.lb(i)-p3(i),p6(i),p7(i)); - ubcum(i) = weibcdf(bounds.ub(i)-p3(i),p6(i),p7(i)); - otherwise - % Nothing to do here. - end + switch pshape(i) + case 5% Uniform prior. + p4(i) = min(p4(i),bounds.ub(i)); + p3(i) = max(p3(i),bounds.lb(i)); + case 3% Gaussian prior. + lbcum(i) = 0.5 * erfc(-(bounds.lb(i)-p6(i))/p7(i) ./ sqrt(2)); + ubcum(i) = 0.5 * erfc(-(bounds.ub(i)-p6(i))/p7(i) ./ sqrt(2)); + case 2% Gamma prior. + lbcum(i) = gamcdf(bounds.lb(i)-p3(i),p6(i),p7(i)); + ubcum(i) = gamcdf(bounds.ub(i)-p3(i),p6(i),p7(i)); + case 1% Beta distribution (TODO: generalized beta distribution) + lbcum(i) = betainc((bounds.lb(i)-p3(i))./(p4(i)-p3(i)),p6(i),p7(i)); + ubcum(i) = betainc((bounds.ub(i)-p3(i))./(p4(i)-p3(i)),p6(i),p7(i)); + case 4% INV-GAMMA1 distribution + % TO BE CHECKED + lbcum(i) = gamcdf(1/(bounds.ub(i)-p3(i))^2,p7(i)/2,2/p6(i)); + ubcum(i) = gamcdf(1/(bounds.lb(i)-p3(i))^2,p7(i)/2,2/p6(i)); + case 6% INV-GAMMA2 distribution + % TO BE CHECKED + lbcum(i) = gamcdf(1/(bounds.ub(i)-p3(i)),p7(i)/2,2/p6(i)); + ubcum(i) = gamcdf(1/(bounds.lb(i)-p3(i)),p7(i)/2,2/p6(i)); + case 8 + lbcum(i) = weibcdf(bounds.lb(i)-p3(i),p6(i),p7(i)); + ubcum(i) = weibcdf(bounds.ub(i)-p3(i),p6(i),p7(i)); + otherwise + % Nothing to do here. + end end return end @@ -106,11 +106,11 @@ for i = 1:npar pdraw(:,i) = gaminv(rdraw(:,i),p6(i),p7(i))+p3(i); case 1% Beta distribution (TODO: generalized beta distribution) pdraw(:,i) = betainv(rdraw(:,i),p6(i),p7(i))*(p4(i)-p3(i))+p3(i); - case 4% INV-GAMMA1 distribution - % TO BE CHECKED + case 4% INV-GAMMA1 distribution + % TO BE CHECKED pdraw(:,i) = sqrt(1./gaminv(rdraw(:,i),p7(i)/2,2/p6(i)))+p3(i); - case 6% INV-GAMMA2 distribution - % TO BE CHECKED + case 6% INV-GAMMA2 distribution + % TO BE CHECKED pdraw(:,i) = 1./gaminv(rdraw(:,i),p7(i)/2,2/p6(i))+p3(i); case 8 pdraw(:,i) = wblinv(rdraw(:,i),p6(i),p7(i))+p3(i); @@ -118,5 +118,3 @@ for i = 1:npar % Nothing to do here. end end - - diff --git a/matlab/gsa/read_data.m b/matlab/gsa/read_data.m index 85674bc5e2..9b8c16c40b 100644 --- a/matlab/gsa/read_data.m +++ b/matlab/gsa/read_data.m @@ -1,7 +1,7 @@ function [gend, data] = read_data() % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % Copyright (C) 2012-2015 European Commission % Copyright (C) 2012-2015 Dynare Team @@ -30,15 +30,15 @@ gend = options_.nobs; rawdata = rawdata(options_.first_obs:options_.first_obs+gend-1,:); if options_.loglinear == 1 & ~options_.logdata - rawdata = log(rawdata); + rawdata = log(rawdata); end if options_.prefilter == 1 - data = transpose(rawdata-ones(gend,1)* mean(rawdata,1)); + data = transpose(rawdata-ones(gend,1)* mean(rawdata,1)); else - data = transpose(rawdata); + data = transpose(rawdata); end if ~isreal(rawdata) - error(['There are complex values in the data. Probably a wrong' ... - ' transformation']) + error(['There are complex values in the data. Probably a wrong' ... + ' transformation']) end diff --git a/matlab/gsa/redform_map.m b/matlab/gsa/redform_map.m index 7d1b3787d7..a7ae7f712d 100644 --- a/matlab/gsa/redform_map.m +++ b/matlab/gsa/redform_map.m @@ -13,7 +13,7 @@ function redform_map(dirname,options_gsa_) % % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % Copyright (C) 2012-2016 European Commission % Copyright (C) 2012-2017 Dynare Team @@ -55,7 +55,7 @@ np = estim_params_.np; nshock = estim_params_.nvx + estim_params_.nvn + estim_params_.ncx + estim_params_.ncn; pnames=cell(np,1); pnames_tex=cell(np,1); -for jj=1:np +for jj=1:np if options_.TeX [param_name_temp, param_name_tex_temp]= get_the_name(nshock+jj,options_.TeX,M_,estim_params_,options_); pnames_tex{jj,1} = strrep(param_name_tex_temp,'$',''); @@ -158,7 +158,7 @@ for j=1:size(anamendo,1) skipline() disp(['[', namendo,' vs ',namexo,']']) - + if ~isempty(iexo) %y0=squeeze(T(iendo,iexo+nspred,istable)); y0=squeeze(T(iendo,iexo+nspred,:)); @@ -193,7 +193,7 @@ for j=1:size(anamendo,1) mkdir(xdir) end if ~options_.nograph - hf=dyn_figure(options_.nodisplay,'name',['Reduced Form Mapping (Monte Carlo Filtering): ',namendo,' vs ', namexo]); + hf=dyn_figure(options_.nodisplay,'name',['Reduced Form Mapping (Monte Carlo Filtering): ',namendo,' vs ', namexo]); hc = cumplot(y0); a=axis; delete(hc); % hist(mat_moment{ij}), @@ -211,7 +211,7 @@ for j=1:size(anamendo,1) end si(:,js) = NaN(np,1); delete([xdir, '/*threshold*.*']) - + atitle0=['Reduced Form Mapping (Monte Carlo Filtering) for ',namendo,' vs ', namexo]; aname=[type '_' namendo '_vs_' namexo '_threshold']; atitle=[type ' Reduced Form Mapping (Monte Carlo Filtering): Parameter(s) driving ',namendo,' vs ',namexo]; @@ -224,7 +224,7 @@ for j=1:size(anamendo,1) if ~isempty(iy) && ~isempty(iyc) fprintf(['%4.1f%% of the ',type,' support matches ',atitle0,'\n'],length(iy)/length(y0)*100) icheck = mcf_analysis(x0, iy, iyc, options_mcf, options_); - + lpmat=x0(iy,:); if nshocks lpmat0=xx0(iy,:); @@ -239,7 +239,7 @@ for j=1:size(anamendo,1) atitle0=['Monte Carlo Filtering for ',namendo,' vs ', namexo]; options_mcf.title = atitle0; indmcf = redform_mcf(y0, x0, options_mcf, options_); - + end end else @@ -254,7 +254,7 @@ for j=1:size(anamendo,1) options_map.OutputDirectoryName = xdir0; silog(:,js) = redform_private(x0, y0, options_map, options_); end - + if isempty(threshold) && ~options_.nograph figure(hfig) subplot(3,3,iplo), @@ -274,12 +274,12 @@ for j=1:size(anamendo,1) text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') end title([logflag,' ',namendo,' vs ',namexo],'interpreter','none') - if iplo==9 + if iplo==9 dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_.nodisplay,options_.graph_format); create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],[logflag,' ',strrep(namendo,'_','\_'),' vs ',strrep(namexo,'_','\_')],['redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],1) end end - + end end end @@ -294,7 +294,7 @@ for j=1:size(anamendo,1) ilagendo=strmatch(namlagendo,M_.endo_names(oo_.dr.order_var(M_.nstatic+1:M_.nstatic+nsok),:),'exact'); skipline() disp(['[', namendo,' vs lagged ',namlagendo,']']) - + if ~isempty(ilagendo) %y0=squeeze(T(iendo,ilagendo,istable)); y0=squeeze(T(iendo,ilagendo,:)); @@ -329,7 +329,7 @@ for j=1:size(anamendo,1) mkdir(xdir) end if ~options_.nograph - hf=dyn_figure(options_.nodisplay,'name',['Reduced Form Mapping (Monte Carlo Filtering): ',namendo,' vs lagged ', namlagendo]); + hf=dyn_figure(options_.nodisplay,'name',['Reduced Form Mapping (Monte Carlo Filtering): ',namendo,' vs lagged ', namlagendo]); hc = cumplot(y0); a=axis; delete(hc); % hist(mat_moment{ij}), @@ -345,9 +345,9 @@ for j=1:size(anamendo,1) dyn_saveas(hf,[xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namlagendo],options_.nodisplay,options_.graph_format); create_TeX_loader(options_,[xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namlagendo],['Reduced Form Mapping (Monte Carlo Filtering): ',strrep(namendo,'_','\_'),' vs lagged ', strrep(namlagendo,'_','\_')],[type '_' namendo,'_vs_', namlagendo],1) end - + delete([xdir, '/*threshold*.*']) - + atitle0=['Reduced Form Mapping (Monte Carlo Filtering) for ',namendo,' vs ', namlagendo]; aname=[type '_' namendo '_vs_' namlagendo '_threshold']; atitle=[type ' Reduced Form Mapping (Monte Carlo Filtering): Parameter(s) driving ',namendo,' vs ',namlagendo]; @@ -361,7 +361,7 @@ for j=1:size(anamendo,1) fprintf(['%4.1f%% of the ',type,' support matches ',atitle0,'\n'],length(iy)/length(y0)*100) icheck = mcf_analysis(x0, iy, iyc, options_mcf, options_); - + lpmat=x0(iy,:); if nshocks lpmat0=xx0(iy,:); @@ -369,7 +369,7 @@ for j=1:size(anamendo,1) istable=[1:length(iy)]; save([xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namlagendo '_threshold' ],'lpmat','lpmat0','istable','y0','x0','xx0','iy','iyc') lpmat=[]; lpmat0=[]; istable=[]; - + else icheck = []; end @@ -391,7 +391,7 @@ for j=1:size(anamendo,1) options_map.OutputDirectoryName = xdir0; silog(:,js) = redform_private(x0, y0, options_map, options_); end - + if isempty(threshold) && ~options_.nograph figure(hfig), subplot(3,3,iplo), @@ -416,7 +416,7 @@ for j=1:size(anamendo,1) create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],[logflag,' ',strrep(namendo,'_','\_'),' vs ',strrep(namlagendo,'_','\_'),'(-1)'],['redform_', namendo,'_vs_lags_',logflag,':',num2str(ifig)],1) end end - + end end end @@ -429,7 +429,7 @@ end if isempty(threshold) && ~options_.nograph if ilog==0 hfig=dyn_figure(options_.nodisplay,'name','Reduced Form GSA'); %bar(si) - % boxplot(si','whis',10,'symbol','r.') + % boxplot(si','whis',10,'symbol','r.') myboxplot(si',[],'.',[],10) xlabel(' ') set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) @@ -445,7 +445,7 @@ if isempty(threshold) && ~options_.nograph else hfig=dyn_figure(options_.nodisplay,'name','Reduced Form GSA'); %bar(silog) - % boxplot(silog','whis',10,'symbol','r.') + % boxplot(silog','whis',10,'symbol','r.') myboxplot(silog',[],'.',[],10) set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np]) xlabel(' ') @@ -458,7 +458,7 @@ if isempty(threshold) && ~options_.nograph title('Reduced form GSA - Log-transformed elements') dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_gsa_log'],options_.nodisplay,options_.graph_format); create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_gsa_log'],'Reduced form GSA - Log-transformed elements','redform_gsa_log') - + end end @@ -494,15 +494,15 @@ if iload==0 nest=min(250,nest); nfit=min(1000,nrun); % dotheplots = (nfit<=nest); -% gsa_ = gsa_sdp(y0(1:nest), x0(1:nest,:), 2, [],[-1 -1 -1 -1 -1 0],[],0,[fname,'_est'], pnames); + % gsa_ = gsa_sdp(y0(1:nest), x0(1:nest,:), 2, [],[-1 -1 -1 -1 -1 0],[],0,[fname,'_est'], pnames); [ys,is] = sort(y0); istep = ceil(nrun/nest); if istep>1 - iest = is(floor(istep/2):istep:end); - nest = length(iest); - irest = is(setdiff([1:nrun],[floor(istep/2):istep:nrun])); - istep = ceil(length(irest)/(nfit-nest)); - ifit = union(iest, irest(1:istep:end)); + iest = is(floor(istep/2):istep:end); + nest = length(iest); + irest = is(setdiff([1:nrun],[floor(istep/2):istep:nrun])); + istep = ceil(length(irest)/(nfit-nest)); + ifit = union(iest, irest(1:istep:end)); else warning('the number of samples is too small for ANOVA estimation') si=nan(np,1); @@ -512,9 +512,9 @@ if iload==0 ifit = union(ifit, irest(end)); end nfit=length(ifit); -% ifit = union(iest, irest(randperm(nrun-nest,nfit-nest))); -% ifit = iest; -% nfit=nest; + % ifit = union(iest, irest(randperm(nrun-nest,nfit-nest))); + % ifit = iest; + % nfit=nest; ipred = setdiff([1:nrun],ifit); if ilog @@ -522,7 +522,7 @@ if iload==0 y1 = log(y0*isig+lam); end if ~options_.nograph - hfig=dyn_figure(options_.nodisplay,'name',options_map.figtitle); + hfig=dyn_figure(options_.nodisplay,'name',options_map.figtitle); subplot(221) if ilog hist(y1,30) @@ -544,61 +544,61 @@ if iload==0 if ilog [gsa22, gsa1, gsax] = ss_anova_log(y1(iest), x0(iest,:), isig, lam, gsa0); end -% if (gsa1.out.bic-gsa0.out.bic) < 10, -% y00=y0; -% gsa00=gsa0; -% gsa0=gsa1; -% y0=y1; -% ilog=1; -% end -if nfit>nest - % gsa_ = gsa_sdp(y0(1:nfit), x0(1:nfit,:), -2, gsa_.nvr*nest^3/nfit^3,[-1 -1 -1 -1 -1 0],[],0,fname, pnames); - nvr = gsa0.nvr*nest^3/nfit^3; - nvr(gsa0.stat<2) = gsa0.nvr(gsa0.stat<2)*nest^5/nfit^5; - gsa_ = ss_anova(y0(ifit), x0(ifit,:), 1, 0, 2, nvr); - if ilog - gsa0 = gsa_; - nvr1 = gsa1.nvr*nest^3/nfit^3; - nvr1(gsa1.stat<2) = gsa1.nvr(gsa1.stat<2)*nest^5/nfit^5; - nvrx = gsax.nvr*nest^3/nfit^3; - nvrx(gsax.stat<2) = gsax.nvr(gsax.stat<2)*nest^5/nfit^5; - [gsa22, gsa1, gsax] = ss_anova_log(y1(ifit), x0(ifit,:), isig, lam, gsa0, [nvr1' nvrx']); -% gsa1 = ss_anova(y1(ifit), x0(ifit,:), 1, 0, 2, nvr); -% gsa2=gsa1; -% gsa2.y = gsa0.y; -% gsa2.fit = (exp(gsa1.fit)-lam)*isig; -% gsa2.f0 = mean(gsa2.fit); -% gsa2.out.SSE = sum((gsa2.fit-gsa2.y).^2); -% gsa2.out.bic = gsa2.out.bic-nest*log(gsa1.out.SSE)+nest*log(gsa2.out.SSE); -% gsa2.r2 = 1-cov(gsa2.fit-gsa2.y)/cov(gsa2.y); -% for j=1:np, -% gsa2.fs(:,j) = exp(gsa1.fs(:,j)).*mean(exp(gsa1.fit-gsa1.f(:,j)))*isig-lam*isig-gsa2.f0; -% gsa2.f(:,j) = exp(gsa1.f(:,j)).*mean(exp(gsa1.fit-gsa1.f(:,j)))*isig-lam*isig-gsa2.f0; -% gsa2.si(j) = var(gsa2.f(:,j))/var(gsa2.y); -% end -% nvr = gsax.nvr*nest^3/nfit^3; -% nvr(gsax.stat<2) = gsax.nvr(gsax.stat<2)*nest^5/nfit^5; -% gsax = ss_anova([gsa2.y-gsa2.fit], x0(ifit,:), 1, 0, 2, nvr); -% gsa22=gsa2; -% gsa22.fit = gsa2.fit+gsax.fit; -% gsa22.f0 = mean(gsa22.fit); -% gsa22.out.SSE = sum((gsa22.fit-gsa22.y).^2); -% gsa22.out.bic = nest*log(gsa22.out.SSE/nest) + (gsax.out.df+gsa2.out.df-1)*log(nest); -% gsa22.r2 = 1-sum((gsa22.fit-gsa22.y).^2)/sum((gsa22.y-mean(gsa22.y)).^2); -% for j=1:np, -% gsa22.fs(:,j) = gsa2.fs(:,j)+gsax.fs(:,j); -% gsa22.f(:,j) = gsa2.f(:,j)+gsax.f(:,j); -% gsa22.si(j) = var(gsa22.f(:,j))/var(gsa22.y); -% end - gsa_ = gsa22; - end -else - if ilog - gsa_ = gsa22; + % if (gsa1.out.bic-gsa0.out.bic) < 10, + % y00=y0; + % gsa00=gsa0; + % gsa0=gsa1; + % y0=y1; + % ilog=1; + % end + if nfit>nest + % gsa_ = gsa_sdp(y0(1:nfit), x0(1:nfit,:), -2, gsa_.nvr*nest^3/nfit^3,[-1 -1 -1 -1 -1 0],[],0,fname, pnames); + nvr = gsa0.nvr*nest^3/nfit^3; + nvr(gsa0.stat<2) = gsa0.nvr(gsa0.stat<2)*nest^5/nfit^5; + gsa_ = ss_anova(y0(ifit), x0(ifit,:), 1, 0, 2, nvr); + if ilog + gsa0 = gsa_; + nvr1 = gsa1.nvr*nest^3/nfit^3; + nvr1(gsa1.stat<2) = gsa1.nvr(gsa1.stat<2)*nest^5/nfit^5; + nvrx = gsax.nvr*nest^3/nfit^3; + nvrx(gsax.stat<2) = gsax.nvr(gsax.stat<2)*nest^5/nfit^5; + [gsa22, gsa1, gsax] = ss_anova_log(y1(ifit), x0(ifit,:), isig, lam, gsa0, [nvr1' nvrx']); + % gsa1 = ss_anova(y1(ifit), x0(ifit,:), 1, 0, 2, nvr); + % gsa2=gsa1; + % gsa2.y = gsa0.y; + % gsa2.fit = (exp(gsa1.fit)-lam)*isig; + % gsa2.f0 = mean(gsa2.fit); + % gsa2.out.SSE = sum((gsa2.fit-gsa2.y).^2); + % gsa2.out.bic = gsa2.out.bic-nest*log(gsa1.out.SSE)+nest*log(gsa2.out.SSE); + % gsa2.r2 = 1-cov(gsa2.fit-gsa2.y)/cov(gsa2.y); + % for j=1:np, + % gsa2.fs(:,j) = exp(gsa1.fs(:,j)).*mean(exp(gsa1.fit-gsa1.f(:,j)))*isig-lam*isig-gsa2.f0; + % gsa2.f(:,j) = exp(gsa1.f(:,j)).*mean(exp(gsa1.fit-gsa1.f(:,j)))*isig-lam*isig-gsa2.f0; + % gsa2.si(j) = var(gsa2.f(:,j))/var(gsa2.y); + % end + % nvr = gsax.nvr*nest^3/nfit^3; + % nvr(gsax.stat<2) = gsax.nvr(gsax.stat<2)*nest^5/nfit^5; + % gsax = ss_anova([gsa2.y-gsa2.fit], x0(ifit,:), 1, 0, 2, nvr); + % gsa22=gsa2; + % gsa22.fit = gsa2.fit+gsax.fit; + % gsa22.f0 = mean(gsa22.fit); + % gsa22.out.SSE = sum((gsa22.fit-gsa22.y).^2); + % gsa22.out.bic = nest*log(gsa22.out.SSE/nest) + (gsax.out.df+gsa2.out.df-1)*log(nest); + % gsa22.r2 = 1-sum((gsa22.fit-gsa22.y).^2)/sum((gsa22.y-mean(gsa22.y)).^2); + % for j=1:np, + % gsa22.fs(:,j) = gsa2.fs(:,j)+gsax.fs(:,j); + % gsa22.f(:,j) = gsa2.f(:,j)+gsax.f(:,j); + % gsa22.si(j) = var(gsa22.f(:,j))/var(gsa22.y); + % end + gsa_ = gsa22; + end else - gsa_ = gsa0; + if ilog + gsa_ = gsa22; + else + gsa_ = gsa0; + end end -end save([fname,'_map.mat'],'gsa_') [sidum, iii]=sort(-gsa_.si); gsa_.x0=x00(ifit,:); @@ -613,13 +613,13 @@ end subplot(223), plot(y0(ifit),[gsa_.fit y0(ifit)],'.'), r2 = gsa_.r2; -% if ilog, -% plot(y00(ifit),[log_trans_(gsa_.fit,'',isig,lam) y00(ifit)],'.'), -% r2 = 1 - cov(log_trans_(gsa_.fit,'',isig,lam)-y00(ifit))/cov(y00(ifit)); -% else -% plot(y0(ifit),[gsa_.fit y0(ifit)],'.'), -% r2 = gsa_.r2; -% end + % if ilog, + % plot(y00(ifit),[log_trans_(gsa_.fit,'',isig,lam) y00(ifit)],'.'), + % r2 = 1 - cov(log_trans_(gsa_.fit,'',isig,lam)-y00(ifit))/cov(y00(ifit)); + % else + % plot(y0(ifit),[gsa_.fit y0(ifit)],'.'), + % r2 = gsa_.r2; + % end title(['Learning sample fit - R2=' num2str(r2,2)],'interpreter','none') if nfit<nrun if ilog @@ -643,7 +643,7 @@ end end else % gsa_ = gsa_sdp_dyn(y0, x0, 0, [],[],[],0,fname, pnames); -% gsa_ = gsa_sdp(y0, x0, 0, [],[],[],0,fname, pnames); + % gsa_ = gsa_sdp(y0, x0, 0, [],[],[],0,fname, pnames); load([fname,'_map.mat'],'gsa_') if ~options_.nograph yf = ss_anova_fcast(x0, gsa_); @@ -727,7 +727,7 @@ function indmcf = redform_mcf(y0, x0, options_mcf, options_) hfig=dyn_figure(options_.nodisplay,'name',options_mcf.amcf_title); [post_mean, post_median, post_var, hpd_interval, post_deciles, ... - density] = posterior_moments(y0,1,0.9); + density] = posterior_moments(y0,1,0.9); post_deciles = [-inf; post_deciles; inf]; for jt=1:10 @@ -763,16 +763,16 @@ aa(2)=0.02; set(hleg,'Position',aa); if ~isoctave annotation('textbox', [0.25,0.01,0.5,0.05], ... - 'String', options_mcf.title, ... - 'Color','black',... - 'FontWeight','bold',... - 'interpreter','none',... - 'horizontalalignment','center'); + 'String', options_mcf.title, ... + 'Color','black',... + 'FontWeight','bold',... + 'interpreter','none',... + 'horizontalalignment','center'); end dyn_saveas(hfig,[options_mcf.OutputDirectoryName filesep options_mcf.fname_,'_',options_mcf.amcf_name],options_.nodisplay,options_.graph_format); create_TeX_loader(options_,[options_mcf.OutputDirectoryName filesep options_mcf.fname_,'_',options_mcf.amcf_name],strrep(options_mcf.amcf_title,'_','\_'),[options_mcf.fname_,'_',options_mcf.amcf_name]) - + return function []=create_TeX_loader(options_,figpath,caption,label_name,scale_factor) diff --git a/matlab/gsa/redform_screen.m b/matlab/gsa/redform_screen.m index 1a53b7e536..d4c0071746 100644 --- a/matlab/gsa/redform_screen.m +++ b/matlab/gsa/redform_screen.m @@ -8,7 +8,7 @@ function redform_screen(dirname, options_gsa_) % % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % Copyright (C) 2012-2016 European Commission % Copyright (C) 2012-2017 Dynare Team @@ -40,7 +40,7 @@ nliv = options_gsa_.morris_nliv; pnames = M_.param_names(estim_params_.param_vals(:,1),:); if nargin==0 - dirname=''; + dirname=''; end load([dirname,'/',M_.fname,'_prior'],'lpmat','lpmat0','istable','T'); @@ -54,95 +54,95 @@ nsok = length(find(M_.lead_lag_incidence(M_.maximum_lag,:))); js=0; for j=1:size(anamendo,1) - namendo=deblank(anamendo(j,:)); - iendo=strmatch(namendo,M_.endo_names(oo_.dr.order_var,:),'exact'); - - iplo=0; - ifig=0; - for jx=1:size(anamexo,1) - namexo=deblank(anamexo(jx,:)); - iexo=strmatch(namexo,M_.exo_names,'exact'); - - if ~isempty(iexo) - y0=teff(T(iendo,iexo+nspred,:),kn,istable); - if ~isempty(y0) - if mod(iplo,9)==0 - ifig=ifig+1; - hh=dyn_figure(options_.nodisplay,'name',[namendo,' vs. shocks ',int2str(ifig)]); - iplo=0; + namendo=deblank(anamendo(j,:)); + iendo=strmatch(namendo,M_.endo_names(oo_.dr.order_var,:),'exact'); + + iplo=0; + ifig=0; + for jx=1:size(anamexo,1) + namexo=deblank(anamexo(jx,:)); + iexo=strmatch(namexo,M_.exo_names,'exact'); + + if ~isempty(iexo) + y0=teff(T(iendo,iexo+nspred,:),kn,istable); + if ~isempty(y0) + if mod(iplo,9)==0 + ifig=ifig+1; + hh=dyn_figure(options_.nodisplay,'name',[namendo,' vs. shocks ',int2str(ifig)]); + iplo=0; + end + iplo=iplo+1; + js=js+1; + subplot(3,3,iplo), + [SAmeas, SAMorris] = Morris_Measure_Groups(np+nshock, [lpmat0 lpmat], y0,nliv); + SAM = squeeze(SAMorris(nshock+1:end,1)); + SA(:,js)=SAM./(max(SAM)+eps); + [saso, iso] = sort(-SA(:,js)); + bar(SA(iso(1:min(np,10)),js)) + %set(gca,'xticklabel',pnames(iso(1:min(np,10)),:),'fontsize',8) + set(gca,'xticklabel',' ','fontsize',10) + set(gca,'xlim',[0.5 10.5]) + for ip=1:min(np,10) + text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + end + title([namendo,' vs. ',namexo],'interpreter','none') + if iplo==9 + dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],options_.nodisplay,options_.graph_format); + create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],ifig,[namendo,' vs. shocks ',int2str(ifig)],[namendo,'_vs_shock'],1) + end + + end end - iplo=iplo+1; - js=js+1; - subplot(3,3,iplo), - [SAmeas, SAMorris] = Morris_Measure_Groups(np+nshock, [lpmat0 lpmat], y0,nliv); - SAM = squeeze(SAMorris(nshock+1:end,1)); - SA(:,js)=SAM./(max(SAM)+eps); - [saso, iso] = sort(-SA(:,js)); - bar(SA(iso(1:min(np,10)),js)) - %set(gca,'xticklabel',pnames(iso(1:min(np,10)),:),'fontsize',8) - set(gca,'xticklabel',' ','fontsize',10) - set(gca,'xlim',[0.5 10.5]) - for ip=1:min(np,10) - text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') - end - title([namendo,' vs. ',namexo],'interpreter','none') - if iplo==9 - dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],options_.nodisplay,options_.graph_format); - create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],ifig,[namendo,' vs. shocks ',int2str(ifig)],[namendo,'_vs_shock'],1) - end - - end end - end - if iplo<9 && iplo>0 && ifig - dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_shocks_',num2str(ifig)],options_.nodisplay,options_.graph_format); - create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],ifig,[namendo,' vs. shocks ',int2str(ifig)],[namendo,'_vs_shock'],options_.figures.textwidth*min(iplo/3)) - end - - iplo=0; - ifig=0; - for je=1:size(anamlagendo,1) - namlagendo=deblank(anamlagendo(je,:)); - ilagendo=strmatch(namlagendo,M_.endo_names(oo_.dr.order_var(M_.nstatic+1:M_.nstatic+nsok),:),'exact'); - - if ~isempty(ilagendo) - y0=teff(T(iendo,ilagendo,:),kn,istable); - if ~isempty(y0) - if mod(iplo,9)==0 - ifig=ifig+1; - hh=dyn_figure(options_.nodisplay,'name',[namendo,' vs. lagged endogenous ',int2str(ifig)]); - iplo=0; - end - iplo=iplo+1; - js=js+1; - subplot(3,3,iplo), - [SAmeas, SAMorris] = Morris_Measure_Groups(np+nshock, [lpmat0 lpmat], y0,nliv); - SAM = squeeze(SAMorris(nshock+1:end,1)); - SA(:,js)=SAM./(max(SAM)+eps); - [saso, iso] = sort(-SA(:,js)); - bar(SA(iso(1:min(np,10)),js)) - %set(gca,'xticklabel',pnames(iso(1:min(np,10)),:),'fontsize',8) - set(gca,'xticklabel',' ','fontsize',10) - set(gca,'xlim',[0.5 10.5]) - for ip=1:min(np,10) - text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') - end + if iplo<9 && iplo>0 && ifig + dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_shocks_',num2str(ifig)],options_.nodisplay,options_.graph_format); + create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],ifig,[namendo,' vs. shocks ',int2str(ifig)],[namendo,'_vs_shock'],options_.figures.textwidth*min(iplo/3)) + end - title([namendo,' vs. ',namlagendo,'(-1)'],'interpreter','none') - if iplo==9 - dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],options_.nodisplay,options_.graph_format); - create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],ifig,[namendo,' vs. lagged endogenous ',int2str(ifig)],[namendo,'_vs_lags'],1) + iplo=0; + ifig=0; + for je=1:size(anamlagendo,1) + namlagendo=deblank(anamlagendo(je,:)); + ilagendo=strmatch(namlagendo,M_.endo_names(oo_.dr.order_var(M_.nstatic+1:M_.nstatic+nsok),:),'exact'); + + if ~isempty(ilagendo) + y0=teff(T(iendo,ilagendo,:),kn,istable); + if ~isempty(y0) + if mod(iplo,9)==0 + ifig=ifig+1; + hh=dyn_figure(options_.nodisplay,'name',[namendo,' vs. lagged endogenous ',int2str(ifig)]); + iplo=0; + end + iplo=iplo+1; + js=js+1; + subplot(3,3,iplo), + [SAmeas, SAMorris] = Morris_Measure_Groups(np+nshock, [lpmat0 lpmat], y0,nliv); + SAM = squeeze(SAMorris(nshock+1:end,1)); + SA(:,js)=SAM./(max(SAM)+eps); + [saso, iso] = sort(-SA(:,js)); + bar(SA(iso(1:min(np,10)),js)) + %set(gca,'xticklabel',pnames(iso(1:min(np,10)),:),'fontsize',8) + set(gca,'xticklabel',' ','fontsize',10) + set(gca,'xlim',[0.5 10.5]) + for ip=1:min(np,10) + text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + end + + title([namendo,' vs. ',namlagendo,'(-1)'],'interpreter','none') + if iplo==9 + dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],options_.nodisplay,options_.graph_format); + create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],ifig,[namendo,' vs. lagged endogenous ',int2str(ifig)],[namendo,'_vs_lags'],1) + end + end end - end end - end - if iplo<9 && iplo>0 && ifig - dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],options_.nodisplay,options_.graph_format); - create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],ifig,[namendo,' vs. lagged endogenous ',int2str(ifig)],[namendo,'_vs_lags'],options_.figures.textwidth*min(iplo/3)) - end + if iplo<9 && iplo>0 && ifig + dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],options_.nodisplay,options_.graph_format); + create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],ifig,[namendo,' vs. lagged endogenous ',int2str(ifig)],[namendo,'_vs_lags'],options_.figures.textwidth*min(iplo/3)) + end end -hh=dyn_figure(options_.nodisplay,'Name','Reduced form screening'); +hh=dyn_figure(options_.nodisplay,'Name','Reduced form screening'); %bar(SA) % boxplot(SA','whis',10,'symbol','r.') myboxplot(SA',[],'.',[],10) @@ -151,7 +151,7 @@ set(gca,'xlim',[0.5 np+0.5]) set(gca,'ylim',[0 1]) set(gca,'position',[0.13 0.2 0.775 0.7]) for ip=1:np - text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') + text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') end xlabel(' ') ylabel('Elementary Effects') @@ -177,4 +177,3 @@ if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) fprintf(fidTeX,'%% End Of TeX file. \n'); fclose(fidTeX); end - diff --git a/matlab/gsa/scatter_analysis.m b/matlab/gsa/scatter_analysis.m index 4550e58782..d526b3f0ea 100644 --- a/matlab/gsa/scatter_analysis.m +++ b/matlab/gsa/scatter_analysis.m @@ -39,7 +39,7 @@ fname_ = options_scatter.fname_; xparam1=[]; if isfield(options_scatter,'xparam1') xparam1=options_scatter.xparam1; -end +end OutputDirectoryName = options_scatter.OutputDirectoryName; if ~DynareOptions.nograph diff --git a/matlab/gsa/scatter_callback.m b/matlab/gsa/scatter_callback.m index 84b7d9ec06..61345107ca 100644 --- a/matlab/gsa/scatter_callback.m +++ b/matlab/gsa/scatter_callback.m @@ -32,11 +32,11 @@ x=x{2}; xparam1=x(K,:)'; switch type - case 'save' - save(['my_params_' int2str(K)],'xparam1') - - case 'eval' - disp('Evaluating smoother ...') - [oo_, M_]=evaluate_smoother(xparam1,M_.endo_names,M_,oo_,options_,bayestopt_,estim_params_); - % [rmse, lnam, r2,vv] = plot_fit(obsname{:}); + case 'save' + save(['my_params_' int2str(K)],'xparam1') + + case 'eval' + disp('Evaluating smoother ...') + [oo_, M_]=evaluate_smoother(xparam1,M_.endo_names,M_,oo_,options_,bayestopt_,estim_params_); + % [rmse, lnam, r2,vv] = plot_fit(obsname{:}); end diff --git a/matlab/gsa/scatter_mcf.m b/matlab/gsa/scatter_mcf.m index 0f48f636b8..211b2e74bb 100644 --- a/matlab/gsa/scatter_mcf.m +++ b/matlab/gsa/scatter_mcf.m @@ -1,183 +1,183 @@ -function scatter_mcf(X,Y,vnames,plotsymbol, fnam, dirname, figtitle, xparam1, DynareOptions, beha_name, non_beha_name) -% -% Written by Marco Ratto -% Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu - -% Copyright (C) 2014-2016 European Commission -% Copyright (C) 2014-2017 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/>. - -% PURPOSE: Pairwise scatter plots of the columns of x and y after -% Monte Carlo filtering -%--------------------------------------------------- -% USAGE: scatter_mcf(x,y,vnames,pltsym,diagon) -% or scatter_mcf(x,y) which relies on defaults -% where: -% x = an nxk matrix with columns containing behavioural sample -% y = an mxk matrix with columns containing non-behavioural sample -% vnames = a vector of variable names -% (default = numeric labels 1,2,3 etc.) -% pltsym = a plt symbol -% (default = '.' for npts > 100, 'o' for npts < 100 - - -Z=[X;Y]; -[n,p] = size(X); -% X = X - ones(n,1)*min(Z); -% X = X ./ (ones(n,1)*max(Z)); -[n,p] = size(Y); -% Y = Y - ones(n,1)*min(Z); -% Y = Y ./ (ones(n,1)*max(Z)); -[n,p] = size(Z); -clear Z; - -nflag = 0; -if nargin >=3 - nflag = 1; -end - -if nargin<4 || isempty(plotsymbol) - if n*p<100, plotsymbol = 'o'; - else plotsymbol = '.'; - end -end - -if nargin<5 - fnam=''; -end -if nargin<6 - dirname=''; - nograph=1; -else - nograph=0; -end -if nargin<7 - figtitle=fnam; -end -if nargin<8 - xparam1=[]; -end -if nargin<10 - beha_name = 'BEHAVIOUR'; - non_beha_name = 'NON-BEHAVIOUR'; -end -if nargin==10 - non_beha_name = ['NON-' beha_name]; -end - -figtitle_tex=strrep(figtitle,'_','\_'); - -fig_nam_=[fnam]; -if ~nograph - hh=dyn_figure(DynareOptions.nodisplay,'name',figtitle); -end - -bf = 0.1; -ffs = 0.05/(p-1); -ffl = (1-2*bf-0.05)/p; -if p>1 - fL = linspace(bf,1-bf+ffs,p+1); -else - fL = bf; -end -for i = 1:p - for j = 1:p - h = axes('position',[fL(i),fL(p+1-j),ffl,ffl]); - if i==j - h1=cumplot(X(:,j)); - % set(h1,'color',[0 0 1], 'linestyle','--','LineWidth',1.5) - set(h1,'color',[0 0 1],'LineWidth',1.5) - hold on, - h2=cumplot(Y(:,j)); - set(h2,'color',[1 0 0],'LineWidth',1.5) - if ~isempty(xparam1) - hold on, plot(xparam1([j j]),[0 1],'k--') - end - if j<p - set(gca,'XTickLabel',[],'XTick',[]); - else - grid off - end - set(gca,'YTickLabel',[],'YTick',[]); - else - if j>i - plot(X(:,i),X(:,j),[plotsymbol,'b']) - hold on, - plot(Y(:,i),Y(:,j),[plotsymbol,'r']) - else - plot(Y(:,i),Y(:,j),[plotsymbol,'r']) - hold on, - plot(X(:,i),X(:,j),[plotsymbol,'b']) - end - if ~isempty(xparam1) - hold on, plot(xparam1(i),xparam1(j),'s','MarkerFaceColor',[0 0.75 0],'MarkerEdgeColor',[0 0.75 0]) - end - hold off; - % axis([-0.1 1.1 -0.1 1.1]) - if i<p - set(gca,'YTickLabel',[],'YTick',[]); - else - set(gca,'yaxislocation','right'); - end - if j<p - set(gca,'XTickLabel',[],'XTick',[]); - end - end - if nflag == 1 - set(gca,'fontsize',9); - end - if i==1 - if nflag == 1 - ylabel(vnames(j,:),'Rotation',45,'interpreter','none', ... - 'HorizontalAlignment','right','VerticalAlignment','middle'); - else - ylabel([num2str(j),' '],'Rotation',90) - end - end - if j==1 - if nflag == 1 - title(vnames(i,:),'interpreter','none','Rotation',45, ... - 'HorizontalAlignment','left','VerticalAlignment','bottom') - else - title(num2str(i)) - end - end - drawnow - end -end -if ~isoctave - annotation('textbox', [0.1,0,0.35,0.05],'String', beha_name,'Color','Blue','horizontalalignment','center','interpreter','none'); - annotation('textbox', [0.55,0,0.35,0.05],'String', non_beha_name,'Color','Red','horizontalalignment','center','interpreter','none'); -end - -if ~nograph - dyn_saveas(hh,[dirname,filesep,fig_nam_],DynareOptions.nodisplay,DynareOptions.graph_format); - if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format))) - fidTeX = fopen([dirname,'/',fig_nam_ '.tex'],'w'); - fprintf(fidTeX,'%% TeX eps-loader file generated by scatter_mcf.m (Dynare).\n'); - fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']); - fprintf(fidTeX,'\\begin{figure}[H]\n'); - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s}\n',strrep([dirname,'/',fig_nam_],'\','/')); - fprintf(fidTeX,'\\caption{%s.}',figtitle_tex); - fprintf(fidTeX,'\\label{Fig:%s}\n',fig_nam_); - fprintf(fidTeX,'\\end{figure}\n\n'); - fprintf(fidTeX,'%% End Of TeX file. \n'); - fclose(fidTeX); - end +function scatter_mcf(X,Y,vnames,plotsymbol, fnam, dirname, figtitle, xparam1, DynareOptions, beha_name, non_beha_name) +% +% Written by Marco Ratto +% Joint Research Centre, The European Commission, +% marco.ratto@ec.europa.eu + +% Copyright (C) 2014-2016 European Commission +% Copyright (C) 2014-2017 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/>. + +% PURPOSE: Pairwise scatter plots of the columns of x and y after +% Monte Carlo filtering +%--------------------------------------------------- +% USAGE: scatter_mcf(x,y,vnames,pltsym,diagon) +% or scatter_mcf(x,y) which relies on defaults +% where: +% x = an nxk matrix with columns containing behavioural sample +% y = an mxk matrix with columns containing non-behavioural sample +% vnames = a vector of variable names +% (default = numeric labels 1,2,3 etc.) +% pltsym = a plt symbol +% (default = '.' for npts > 100, 'o' for npts < 100 + + +Z=[X;Y]; +[n,p] = size(X); +% X = X - ones(n,1)*min(Z); +% X = X ./ (ones(n,1)*max(Z)); +[n,p] = size(Y); +% Y = Y - ones(n,1)*min(Z); +% Y = Y ./ (ones(n,1)*max(Z)); +[n,p] = size(Z); +clear Z; + +nflag = 0; +if nargin >=3 + nflag = 1; +end + +if nargin<4 || isempty(plotsymbol) + if n*p<100, plotsymbol = 'o'; + else plotsymbol = '.'; + end +end + +if nargin<5 + fnam=''; +end +if nargin<6 + dirname=''; + nograph=1; +else + nograph=0; +end +if nargin<7 + figtitle=fnam; +end +if nargin<8 + xparam1=[]; +end +if nargin<10 + beha_name = 'BEHAVIOUR'; + non_beha_name = 'NON-BEHAVIOUR'; +end +if nargin==10 + non_beha_name = ['NON-' beha_name]; +end + +figtitle_tex=strrep(figtitle,'_','\_'); + +fig_nam_=[fnam]; +if ~nograph + hh=dyn_figure(DynareOptions.nodisplay,'name',figtitle); +end + +bf = 0.1; +ffs = 0.05/(p-1); +ffl = (1-2*bf-0.05)/p; +if p>1 + fL = linspace(bf,1-bf+ffs,p+1); +else + fL = bf; +end +for i = 1:p + for j = 1:p + h = axes('position',[fL(i),fL(p+1-j),ffl,ffl]); + if i==j + h1=cumplot(X(:,j)); + % set(h1,'color',[0 0 1], 'linestyle','--','LineWidth',1.5) + set(h1,'color',[0 0 1],'LineWidth',1.5) + hold on, + h2=cumplot(Y(:,j)); + set(h2,'color',[1 0 0],'LineWidth',1.5) + if ~isempty(xparam1) + hold on, plot(xparam1([j j]),[0 1],'k--') + end + if j<p + set(gca,'XTickLabel',[],'XTick',[]); + else + grid off + end + set(gca,'YTickLabel',[],'YTick',[]); + else + if j>i + plot(X(:,i),X(:,j),[plotsymbol,'b']) + hold on, + plot(Y(:,i),Y(:,j),[plotsymbol,'r']) + else + plot(Y(:,i),Y(:,j),[plotsymbol,'r']) + hold on, + plot(X(:,i),X(:,j),[plotsymbol,'b']) + end + if ~isempty(xparam1) + hold on, plot(xparam1(i),xparam1(j),'s','MarkerFaceColor',[0 0.75 0],'MarkerEdgeColor',[0 0.75 0]) + end + hold off; + % axis([-0.1 1.1 -0.1 1.1]) + if i<p + set(gca,'YTickLabel',[],'YTick',[]); + else + set(gca,'yaxislocation','right'); + end + if j<p + set(gca,'XTickLabel',[],'XTick',[]); + end + end + if nflag == 1 + set(gca,'fontsize',9); + end + if i==1 + if nflag == 1 + ylabel(vnames(j,:),'Rotation',45,'interpreter','none', ... + 'HorizontalAlignment','right','VerticalAlignment','middle'); + else + ylabel([num2str(j),' '],'Rotation',90) + end + end + if j==1 + if nflag == 1 + title(vnames(i,:),'interpreter','none','Rotation',45, ... + 'HorizontalAlignment','left','VerticalAlignment','bottom') + else + title(num2str(i)) + end + end + drawnow + end +end +if ~isoctave + annotation('textbox', [0.1,0,0.35,0.05],'String', beha_name,'Color','Blue','horizontalalignment','center','interpreter','none'); + annotation('textbox', [0.55,0,0.35,0.05],'String', non_beha_name,'Color','Red','horizontalalignment','center','interpreter','none'); +end + +if ~nograph + dyn_saveas(hh,[dirname,filesep,fig_nam_],DynareOptions.nodisplay,DynareOptions.graph_format); + if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format))) + fidTeX = fopen([dirname,'/',fig_nam_ '.tex'],'w'); + fprintf(fidTeX,'%% TeX eps-loader file generated by scatter_mcf.m (Dynare).\n'); + fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']); + fprintf(fidTeX,'\\begin{figure}[H]\n'); + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s}\n',strrep([dirname,'/',fig_nam_],'\','/')); + fprintf(fidTeX,'\\caption{%s.}',figtitle_tex); + fprintf(fidTeX,'\\label{Fig:%s}\n',fig_nam_); + fprintf(fidTeX,'\\end{figure}\n\n'); + fprintf(fidTeX,'%% End Of TeX file. \n'); + fclose(fidTeX); + end end \ No newline at end of file diff --git a/matlab/gsa/scatter_plots.m b/matlab/gsa/scatter_plots.m index 852ae5b400..f9cf1fa4c4 100644 --- a/matlab/gsa/scatter_plots.m +++ b/matlab/gsa/scatter_plots.m @@ -56,25 +56,25 @@ if nargin<5 || isempty(fnam) fnam='scatter_plot'; end if nargin<6 || isempty(dirname) - dirname=''; - nograph=1; - DynareOptions.nodisplay=0; + dirname=''; + nograph=1; + DynareOptions.nodisplay=0; else - nograph=0; + nograph=0; end if nargin<7 || isempty(figtitle) - figtitle=fnam; + figtitle=fnam; end if nargin<8 - xparam1=[]; + xparam1=[]; end figtitle_tex=strrep(figtitle,'_','\_'); fig_nam_=[fnam]; - hh=dyn_figure(DynareOptions.nodisplay,'name',figtitle); - set(hh,'userdata',{X,xp}) +hh=dyn_figure(DynareOptions.nodisplay,'name',figtitle); +set(hh,'userdata',{X,xp}) bf = 0.1; ffs = 0.05/(p-1); @@ -111,7 +111,7 @@ for i = 1:p %% if ~isoctave - % Define a context menu; it is not attached to anything + % Define a context menu; it is not attached to anything hcmenu = uicontextmenu('Callback','pick','Tag','Run viewer'); % Define callbacks for context menu % items that change linestyle @@ -150,7 +150,7 @@ for i = 1:p if i==1 if nflag == 1 ylabel(vnames(j,:),'Rotation',45,'interpreter','none', ... - 'HorizontalAlignment','right','VerticalAlignment','middle'); + 'HorizontalAlignment','right','VerticalAlignment','middle'); else ylabel([num2str(j),' '],'Rotation',90) end @@ -158,7 +158,7 @@ for i = 1:p if j==1 if nflag == 1 title(vnames(i,:),'interpreter','none','Rotation',45, ... - 'HorizontalAlignment','left','VerticalAlignment','bottom') + 'HorizontalAlignment','left','VerticalAlignment','bottom') else title(num2str(i)) end diff --git a/matlab/gsa/set_shocks_param.m b/matlab/gsa/set_shocks_param.m index 8902dfb102..485f64ec94 100644 --- a/matlab/gsa/set_shocks_param.m +++ b/matlab/gsa/set_shocks_param.m @@ -67,7 +67,7 @@ if ncx end %build covariance matrix from correlation matrix and variances already on %diagonal -Sigma_e = diag(sqrt(diag(Sigma_e)))*Correlation_matrix*diag(sqrt(diag(Sigma_e))); +Sigma_e = diag(sqrt(diag(Sigma_e)))*Correlation_matrix*diag(sqrt(diag(Sigma_e))); %if calibrated covariances, set them now to their stored value if isfield(estim_params_,'calibrated_covariances') Sigma_e(estim_params_.calibrated_covariances.position)=estim_params_.calibrated_covariances.cov_value; @@ -93,7 +93,7 @@ if isfield(estim_params_,'calibrated_covariances_ME') H(estim_params_.calibrated_covariances_ME.position)=estim_params_.calibrated_covariances_ME.cov_value; end - + % updating matrices in M if nvx || ncx M_.Sigma_e = Sigma_e; @@ -101,5 +101,5 @@ if nvx || ncx end if nvn || ncn M_.H = H; - M_.Correlation_matrix_ME=Correlation_matrix_ME; -end \ No newline at end of file + M_.Correlation_matrix_ME=Correlation_matrix_ME; +end \ No newline at end of file diff --git a/matlab/gsa/smirnov.m b/matlab/gsa/smirnov.m index 2a96a2a7df..a2fa7f4727 100644 --- a/matlab/gsa/smirnov.m +++ b/matlab/gsa/smirnov.m @@ -4,7 +4,7 @@ function [H,prob,d] = smirnov(x1 , x2 , alpha, iflag ) % % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % Copyright (C) 2012 European Commission % Copyright (C) 2012 Dynare Team @@ -64,10 +64,10 @@ end % lam = max((sqrt(n) + 0.12 + 0.11/sqrt(n)) * d , 0); -if iflag == 0 +if iflag == 0 j = [1:101]'; prob = 2 * sum((-1).^(j-1).*exp(-2*lam*lam*j.^2)); - + prob=max(prob,0); prob=min(1,prob); else diff --git a/matlab/gsa/stab_map_.m b/matlab/gsa/stab_map_.m index 20a61b844f..03ad56e880 100644 --- a/matlab/gsa/stab_map_.m +++ b/matlab/gsa/stab_map_.m @@ -32,7 +32,7 @@ function x0 = stab_map_(OutputDirectoryName,opt_gsa) % % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % Copyright (C) 2012-2016 European Commission % Copyright (C) 2012-2016 Dynare Team @@ -99,8 +99,8 @@ if ~isempty(bayestopt_) && any(bayestopt_.pshape > 0) bounds.lb = max(bounds.lb,lb); bounds.ub = min(bounds.ub,ub); else % estimated parameters but no declared priors - % No priors are declared so Dynare will estimate the model by - % maximum likelihood with inequality constraints for the parameters. + % No priors are declared so Dynare will estimate the model by + % maximum likelihood with inequality constraints for the parameters. bounds.lb = lb; bounds.ub = ub; if opt_gsa.prior_range==0 @@ -119,7 +119,7 @@ options_mcf.alpha2 = alpha2; name=cell(np,1); name_tex=cell(np,1); -for jj=1:np +for jj=1:np if options_.TeX [param_name_temp, param_name_tex_temp]= get_the_name(nshock+jj,options_.TeX,M_,estim_params_,options_); name_tex{jj,1} = strrep(param_name_tex_temp,'$',''); @@ -159,9 +159,9 @@ if fload==0 Nsam=size(lpmat,1); lpmat0 = lpmat(:,1:nshock); lpmat = lpmat(:,nshock+1:end); -% elseif opt_gsa.morris==3, -% lpmat = prep_ide(Nsam,np,5); -% Nsam=size(lpmat,1); + % elseif opt_gsa.morris==3, + % lpmat = prep_ide(Nsam,np,5); + % Nsam=size(lpmat,1); else if np<52 && ilptau>0 [lpmat] = qmc_sequence(np, int64(1), 0, Nsam)'; @@ -180,14 +180,14 @@ if fload==0 end % try dummy=prior_draw_gsa(1); %initialize persistent variables - % catch - % if pprior, - % if opt_gsa.prior_range==0; - % error('Some unknown prior is specified or ML estimation,: use prior_range=1 option!!'); - % end - % end - % - % end + % catch + % if pprior, + % if opt_gsa.prior_range==0; + % error('Some unknown prior is specified or ML estimation,: use prior_range=1 option!!'); + % end + % end + % + % end if pprior for j=1:nshock if opt_gsa.morris~=1 @@ -257,12 +257,12 @@ if fload==0 if neighborhood_width>0 && isempty(options_.mode_file) xparam1 = get_all_parameters(estim_params_,M_); else - eval(['load ' options_.mode_file '.mat;']); + eval(['load ' options_.mode_file '.mat;']); end if neighborhood_width>0 for j=1:nshock if opt_gsa.morris ~= 1 - lpmat0(:,j) = randperm(Nsam)'./(Nsam+1); %latin hypercube + lpmat0(:,j) = randperm(Nsam)'./(Nsam+1); %latin hypercube end ub=min([bounds.ub(j) xparam1(j)*(1+neighborhood_width)]); lb=max([bounds.lb(j) xparam1(j)*(1-neighborhood_width)]); @@ -335,7 +335,7 @@ if fload==0 egg=zeros(length(dr_.eigval),Nsam); end if infox(j,1) -% disp('no solution'), + % disp('no solution'), if isfield(oo_.dr,'ghx') oo_.dr=rmfield(oo_.dr,'ghx'); end @@ -457,23 +457,23 @@ if fload==0 if pprior if ~prepSA save([OutputDirectoryName filesep fname_ '_prior.mat'], ... - 'bkpprior','lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun', ... - 'egg','yys','nspred','nboth','nfwrd','infox') + 'bkpprior','lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun', ... + 'egg','yys','nspred','nboth','nfwrd','infox') else save([OutputDirectoryName filesep fname_ '_prior.mat'], ... - 'bkpprior','lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun', ... - 'egg','yys','T','nspred','nboth','nfwrd','infox') + 'bkpprior','lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun', ... + 'egg','yys','T','nspred','nboth','nfwrd','infox') end else if ~prepSA save([OutputDirectoryName filesep fname_ '_mc.mat'], ... - 'lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun', ... - 'egg','yys','nspred','nboth','nfwrd','infox') + 'lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun', ... + 'egg','yys','nspred','nboth','nfwrd','infox') else save([OutputDirectoryName filesep fname_ '_mc.mat'], ... - 'lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun', ... - 'egg','yys','T','nspred','nboth','nfwrd','infox') + 'lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun', ... + 'egg','yys','T','nspred','nboth','nfwrd','infox') end end else @@ -601,7 +601,7 @@ if length(iunstable)>0 || length(iwrong)>0 if length(iunstable)<Nsam || length(istable)>1 itot = [1:Nsam]; isolve = itot(find(~ismember(itot,iwrong))); % dynare could find a solution - % Blanchard Kahn + % Blanchard Kahn if neighborhood_width options_mcf.xparam1 = xparam1(nshock+1:end); end @@ -622,7 +622,7 @@ if length(iunstable)>0 || length(iwrong)>0 options_mcf.title = 'indeterminacy'; mcf_analysis(lpmat, itmp, iindeterm, options_mcf, options_); end - + if ~isempty(ixun) itmp = isolve(find(~ismember(isolve,ixun))); options_mcf.amcf_name = aunstname; @@ -632,7 +632,7 @@ if length(iunstable)>0 || length(iwrong)>0 options_mcf.title = 'instability'; mcf_analysis(lpmat, itmp, ixun, options_mcf, options_); end - + inorestriction = istable(find(~ismember(istable,irestriction))); % violation of prior restrictions iwrong = iwrong(find(~ismember(iwrong,inorestriction))); % what went wrong beyond prior restrictions if ~isempty(iwrong) @@ -644,7 +644,7 @@ if length(iunstable)>0 || length(iwrong)>0 options_mcf.title = 'inability to find a solution'; mcf_analysis(lpmat, itmp, iwrong, options_mcf, options_); end - + if ~isempty(irestriction) if neighborhood_width options_mcf.xparam1 = xparam1; @@ -679,7 +679,7 @@ if length(iunstable)>0 || length(iwrong)>0 x0=0.5.*(bounds.ub(1:nshock)-bounds.lb(1:nshock))+bounds.lb(1:nshock); x0 = [x0; lpmat(iok,:)']; end - + M_ = set_all_parameters(x0,estim_params_,M_); [oo_.dr,info,M_,options_,oo_] = resol(0,M_,options_,oo_); % stoch_simul([]); @@ -704,7 +704,3 @@ if isfield(opt,'nomoments') end options_.irf=opt.irf; options_.noprint=opt.noprint; - - - - diff --git a/matlab/gsa/stab_map_1.m b/matlab/gsa/stab_map_1.m index 0bd9888e7a..092b50daa4 100644 --- a/matlab/gsa/stab_map_1.m +++ b/matlab/gsa/stab_map_1.m @@ -8,7 +8,7 @@ function [proba, dproba] = stab_map_1(lpmat, ibehaviour, inonbehaviour, aname, i % iplot = 1 plot cumulative distributions (default) % iplot = 0 no plots % ipar = index array of parameters to plot -% dirname = (OPTIONAL) path of the directory where to save +% dirname = (OPTIONAL) path of the directory where to save % (default: current directory) % pcrit = (OPTIONAL) critical value of the pvalue below which show the plots % @@ -18,7 +18,7 @@ function [proba, dproba] = stab_map_1(lpmat, ibehaviour, inonbehaviour, aname, i % % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % Copyright (C) 2012-2016 European Commission % Copyright (C) 2012-2017 Dynare Team @@ -41,14 +41,14 @@ function [proba, dproba] = stab_map_1(lpmat, ibehaviour, inonbehaviour, aname, i global estim_params_ bayestopt_ M_ options_ if nargin<5 - iplot=1; + iplot=1; end fname_ = M_.fname; if nargin<7 - dirname=''; + dirname=''; end if nargin<9, - atitle=aname; + atitle=aname; end nshock = estim_params_.nvx; @@ -60,27 +60,27 @@ npar=size(lpmat,2); ishock= npar>estim_params_.np; if nargin<6 - ipar=[]; + ipar=[]; end if nargin<8 || isempty(pcrit) - pcrit=1; + pcrit=1; end -% Smirnov test for Blanchard; +% Smirnov test for Blanchard; for j=1:npar - [H,P,KSSTAT] = smirnov(lpmat(ibehaviour,j),lpmat(inonbehaviour,j)); - proba(j)=P; - dproba(j)=KSSTAT; + [H,P,KSSTAT] = smirnov(lpmat(ibehaviour,j),lpmat(inonbehaviour,j)); + proba(j)=P; + dproba(j)=KSSTAT; end if isempty(ipar) -% ipar=find(dproba>dcrit); + % ipar=find(dproba>dcrit); ipar=find(proba<pcrit); end nparplot=length(ipar); if iplot && ~options_.nograph lpmat=lpmat(:,ipar); ftit=bayestopt_.name(ipar+nshock*(1-ishock)); - + for i=1:ceil(nparplot/12) hh=dyn_figure(options_.nodisplay,'name',atitle); for j=1+12*(i-1):min(nparplot,12*i) diff --git a/matlab/gsa/stab_map_2.m b/matlab/gsa/stab_map_2.m index d13435d11b..f4b958355e 100644 --- a/matlab/gsa/stab_map_2.m +++ b/matlab/gsa/stab_map_2.m @@ -3,7 +3,7 @@ function indcorr = stab_map_2(x,alpha2, pvalue_crit, fnam, dirname,xparam1,figti % % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % Copyright (C) 2011-2016 European Commission % Copyright (C) 2011-2017 Dynare Team @@ -30,17 +30,17 @@ nsam=size(x,1); ishock= npar>estim_params_.np; nograph = options_.nograph; if nargin<4 - fnam=''; + fnam=''; end if nargin<5 - dirname=''; - nograph=1; + dirname=''; + nograph=1; end if nargin<6 - xparam1=[]; + xparam1=[]; end if nargin<7 - figtitle=fnam; + figtitle=fnam; end ys_ = oo_.dr.ys; @@ -60,12 +60,12 @@ fig_nam_=strrep(fig_nam_,' ','_'); ifig=0; j2=0; if ishock==0 - npar=estim_params_.np; - if ~isempty(xparam1) - xparam1=xparam1(nshock+1:end); - end + npar=estim_params_.np; + if ~isempty(xparam1) + xparam1=xparam1(nshock+1:end); + end else - npar=estim_params_.np+nshock; + npar=estim_params_.np+nshock; end skipline(); title_string=['Correlation analysis for ',fnam]; @@ -112,54 +112,54 @@ for j=1:npar tmp_name=(['[',param_name_temp1,',',param_name_temp2,']']); name{entry_iter,1}=tmp_name; end - end + end data_mat(entry_iter,1)=c0(i2(jx),j); entry_iter=entry_iter+1; - + if ~nograph if mod(j2,12)==1 - ifig=ifig+1; - hh=dyn_figure(options_.nodisplay,'name',[figtitle,' sample bivariate projection ', num2str(ifig)]); - end - subplot(3,4,j2-(ifig-1)*12) - % bar(c0(i2,j)), - % set(gca,'xticklabel',bayestopt_.name(i2)), - % set(gca,'xtick',[1:length(i2)]) - %plot(stock_par(ixx(nfilt+1:end,i),j),stock_par(ixx(nfilt+1:end,i),i2(jx)),'.k') - %hold on, - plot(x(:,j),x(:,i2(jx)),'.') - if ~isempty(xparam1) - hold on, plot(xparam1(j),xparam1(i2(jx)),'ro') - end - % xlabel(deblank(estim_params_.param_names(j,:)),'interpreter','none'), - % ylabel(deblank(estim_params_.param_names(i2(jx),:)),'interpreter','none'), - if ishock - xlabel(bayestopt_.name{j},'interpreter','none'), - ylabel(bayestopt_.name{i2(jx)},'interpreter','none'), - else - xlabel(bayestopt_.name{j+nshock},'interpreter','none'), - ylabel(bayestopt_.name{i2(jx)+nshock},'interpreter','none'), - end - title(['cc = ',num2str(c0(i2(jx),j))]) - if (mod(j2,12)==0) && j2>0 - dyn_saveas(hh,[dirname,filesep,fig_nam_,int2str(ifig)],options_.nodisplay,options_.graph_format); - if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) - fidTeX = fopen([dirname,filesep,fig_nam_,int2str(ifig),'.tex'],'w'); - fprintf(fidTeX,'%% TeX eps-loader file generated by stab_map_2.m (Dynare).\n'); - fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']); - fprintf(fidTeX,'\\begin{figure}[H]\n'); - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s}\n',strrep([dirname,'/',fig_nam_,int2str(ifig)],'\','/')); - fprintf(fidTeX,'\\caption{%s.}',[figtitle,' sample bivariate projection ', num2str(ifig)]); - fprintf(fidTeX,'\\label{Fig:%s:%u}\n',fig_nam_,ifig); - fprintf(fidTeX,'\\end{figure}\n\n'); - fprintf(fidTeX,'%% End Of TeX file. \n'); - fclose(fidTeX); + ifig=ifig+1; + hh=dyn_figure(options_.nodisplay,'name',[figtitle,' sample bivariate projection ', num2str(ifig)]); + end + subplot(3,4,j2-(ifig-1)*12) + % bar(c0(i2,j)), + % set(gca,'xticklabel',bayestopt_.name(i2)), + % set(gca,'xtick',[1:length(i2)]) + %plot(stock_par(ixx(nfilt+1:end,i),j),stock_par(ixx(nfilt+1:end,i),i2(jx)),'.k') + %hold on, + plot(x(:,j),x(:,i2(jx)),'.') + if ~isempty(xparam1) + hold on, plot(xparam1(j),xparam1(i2(jx)),'ro') + end + % xlabel(deblank(estim_params_.param_names(j,:)),'interpreter','none'), + % ylabel(deblank(estim_params_.param_names(i2(jx),:)),'interpreter','none'), + if ishock + xlabel(bayestopt_.name{j},'interpreter','none'), + ylabel(bayestopt_.name{i2(jx)},'interpreter','none'), + else + xlabel(bayestopt_.name{j+nshock},'interpreter','none'), + ylabel(bayestopt_.name{i2(jx)+nshock},'interpreter','none'), + end + title(['cc = ',num2str(c0(i2(jx),j))]) + if (mod(j2,12)==0) && j2>0 + dyn_saveas(hh,[dirname,filesep,fig_nam_,int2str(ifig)],options_.nodisplay,options_.graph_format); + if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) + fidTeX = fopen([dirname,filesep,fig_nam_,int2str(ifig),'.tex'],'w'); + fprintf(fidTeX,'%% TeX eps-loader file generated by stab_map_2.m (Dynare).\n'); + fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']); + fprintf(fidTeX,'\\begin{figure}[H]\n'); + fprintf(fidTeX,'\\centering \n'); + fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s}\n',strrep([dirname,'/',fig_nam_,int2str(ifig)],'\','/')); + fprintf(fidTeX,'\\caption{%s.}',[figtitle,' sample bivariate projection ', num2str(ifig)]); + fprintf(fidTeX,'\\label{Fig:%s:%u}\n',fig_nam_,ifig); + fprintf(fidTeX,'\\end{figure}\n\n'); + fprintf(fidTeX,'%% End Of TeX file. \n'); + fclose(fidTeX); + end end - end end end - + end end if ~nograph && (j==(npar)) && j2>0 && (mod(j2,12)~=0) @@ -177,7 +177,7 @@ for j=1:npar fprintf(fidTeX,'%% End Of TeX file. \n'); fclose(fidTeX); end - end + end end if j2==0 diff --git a/matlab/gsa/stand_.m b/matlab/gsa/stand_.m index b6a087a531..f4bb05ce1e 100644 --- a/matlab/gsa/stand_.m +++ b/matlab/gsa/stand_.m @@ -11,7 +11,7 @@ function [y, meany, stdy] = stand_(x) % % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % Copyright (C) 2012 European Commission % Copyright (C) 2012 Dynare Team% @@ -35,8 +35,8 @@ if nargin==0 end for j=1:size(x,2) -meany(j)=mean(x(find(~isnan(x(:,j))),j)); -stdy(j)=std(x(find(~isnan(x(:,j))),j)); + meany(j)=mean(x(find(~isnan(x(:,j))),j)); + stdy(j)=std(x(find(~isnan(x(:,j))),j)); y(:,j)=(x(:,j)-meany(j))./stdy(j); end % end of m-file \ No newline at end of file diff --git a/matlab/gsa/tcrit.m b/matlab/gsa/tcrit.m index ba5f85a9ef..cc7c8ad6af 100644 --- a/matlab/gsa/tcrit.m +++ b/matlab/gsa/tcrit.m @@ -1,12 +1,12 @@ function t_crit = tcrit(n,pval0) % function t_crit = tcrit(n,pval0) % -% given the p-value pval0, the function givese the -% critical value t_crit of the t-distribution with n degress of freedom +% given the p-value pval0, the function givese the +% critical value t_crit of the t-distribution with n degress of freedom % % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % Copyright (C) 2011-2012 European Commission % Copyright (C) 2011-2012 Dynare Team @@ -43,108 +43,108 @@ pval0=max(pval0,min(pval)); ncol=min(find(pval<=pval0))+1; t_crit=[ - 1 3.078 6.314 12.706 31.821 63.657 318.313 - 2 1.886 2.920 4.303 6.965 9.925 22.327 - 3 1.638 2.353 3.182 4.541 5.841 10.215 - 4 1.533 2.132 2.776 3.747 4.604 7.173 - 5 1.476 2.015 2.571 3.365 4.032 5.893 - 6 1.440 1.943 2.447 3.143 3.707 5.208 - 7 1.415 1.895 2.365 2.998 3.499 4.782 - 8 1.397 1.860 2.306 2.896 3.355 4.499 - 9 1.383 1.833 2.262 2.821 3.250 4.296 - 10 1.372 1.812 2.228 2.764 3.169 4.143 - 11 1.363 1.796 2.201 2.718 3.106 4.024 - 12 1.356 1.782 2.179 2.681 3.055 3.929 - 13 1.350 1.771 2.160 2.650 3.012 3.852 - 14 1.345 1.761 2.145 2.624 2.977 3.787 - 15 1.341 1.753 2.131 2.602 2.947 3.733 - 16 1.337 1.746 2.120 2.583 2.921 3.686 - 17 1.333 1.740 2.110 2.567 2.898 3.646 - 18 1.330 1.734 2.101 2.552 2.878 3.610 - 19 1.328 1.729 2.093 2.539 2.861 3.579 - 20 1.325 1.725 2.086 2.528 2.845 3.552 - 21 1.323 1.721 2.080 2.518 2.831 3.527 - 22 1.321 1.717 2.074 2.508 2.819 3.505 - 23 1.319 1.714 2.069 2.500 2.807 3.485 - 24 1.318 1.711 2.064 2.492 2.797 3.467 - 25 1.316 1.708 2.060 2.485 2.787 3.450 - 26 1.315 1.706 2.056 2.479 2.779 3.435 - 27 1.314 1.703 2.052 2.473 2.771 3.421 - 28 1.313 1.701 2.048 2.467 2.763 3.408 - 29 1.311 1.699 2.045 2.462 2.756 3.396 - 30 1.310 1.697 2.042 2.457 2.750 3.385 - 31 1.309 1.696 2.040 2.453 2.744 3.375 - 32 1.309 1.694 2.037 2.449 2.738 3.365 - 33 1.308 1.692 2.035 2.445 2.733 3.356 - 34 1.307 1.691 2.032 2.441 2.728 3.348 - 35 1.306 1.690 2.030 2.438 2.724 3.340 - 36 1.306 1.688 2.028 2.434 2.719 3.333 - 37 1.305 1.687 2.026 2.431 2.715 3.326 - 38 1.304 1.686 2.024 2.429 2.712 3.319 - 39 1.304 1.685 2.023 2.426 2.708 3.313 - 40 1.303 1.684 2.021 2.423 2.704 3.307 - 41 1.303 1.683 2.020 2.421 2.701 3.301 - 42 1.302 1.682 2.018 2.418 2.698 3.296 - 43 1.302 1.681 2.017 2.416 2.695 3.291 - 44 1.301 1.680 2.015 2.414 2.692 3.286 - 45 1.301 1.679 2.014 2.412 2.690 3.281 - 46 1.300 1.679 2.013 2.410 2.687 3.277 - 47 1.300 1.678 2.012 2.408 2.685 3.273 - 48 1.299 1.677 2.011 2.407 2.682 3.269 - 49 1.299 1.677 2.010 2.405 2.680 3.265 - 50 1.299 1.676 2.009 2.403 2.678 3.261 - 51 1.298 1.675 2.008 2.402 2.676 3.258 - 52 1.298 1.675 2.007 2.400 2.674 3.255 - 53 1.298 1.674 2.006 2.399 2.672 3.251 - 54 1.297 1.674 2.005 2.397 2.670 3.248 - 55 1.297 1.673 2.004 2.396 2.668 3.245 - 56 1.297 1.673 2.003 2.395 2.667 3.242 - 57 1.297 1.672 2.002 2.394 2.665 3.239 - 58 1.296 1.672 2.002 2.392 2.663 3.237 - 59 1.296 1.671 2.001 2.391 2.662 3.234 - 60 1.296 1.671 2.000 2.390 2.660 3.232 - 61 1.296 1.670 2.000 2.389 2.659 3.229 - 62 1.295 1.670 1.999 2.388 2.657 3.227 - 63 1.295 1.669 1.998 2.387 2.656 3.225 - 64 1.295 1.669 1.998 2.386 2.655 3.223 - 65 1.295 1.669 1.997 2.385 2.654 3.220 - 66 1.295 1.668 1.997 2.384 2.652 3.218 - 67 1.294 1.668 1.996 2.383 2.651 3.216 - 68 1.294 1.668 1.995 2.382 2.650 3.214 - 69 1.294 1.667 1.995 2.382 2.649 3.213 - 70 1.294 1.667 1.994 2.381 2.648 3.211 - 71 1.294 1.667 1.994 2.380 2.647 3.209 - 72 1.293 1.666 1.993 2.379 2.646 3.207 - 73 1.293 1.666 1.993 2.379 2.645 3.206 - 74 1.293 1.666 1.993 2.378 2.644 3.204 - 75 1.293 1.665 1.992 2.377 2.643 3.202 - 76 1.293 1.665 1.992 2.376 2.642 3.201 - 77 1.293 1.665 1.991 2.376 2.641 3.199 - 78 1.292 1.665 1.991 2.375 2.640 3.198 - 79 1.292 1.664 1.990 2.374 2.640 3.197 - 80 1.292 1.664 1.990 2.374 2.639 3.195 - 81 1.292 1.664 1.990 2.373 2.638 3.194 - 82 1.292 1.664 1.989 2.373 2.637 3.193 - 83 1.292 1.663 1.989 2.372 2.636 3.191 - 84 1.292 1.663 1.989 2.372 2.636 3.190 - 85 1.292 1.663 1.988 2.371 2.635 3.189 - 86 1.291 1.663 1.988 2.370 2.634 3.188 - 87 1.291 1.663 1.988 2.370 2.634 3.187 - 88 1.291 1.662 1.987 2.369 2.633 3.185 - 89 1.291 1.662 1.987 2.369 2.632 3.184 - 90 1.291 1.662 1.987 2.368 2.632 3.183 - 91 1.291 1.662 1.986 2.368 2.631 3.182 - 92 1.291 1.662 1.986 2.368 2.630 3.181 - 93 1.291 1.661 1.986 2.367 2.630 3.180 - 94 1.291 1.661 1.986 2.367 2.629 3.179 - 95 1.291 1.661 1.985 2.366 2.629 3.178 - 96 1.290 1.661 1.985 2.366 2.628 3.177 - 97 1.290 1.661 1.985 2.365 2.627 3.176 - 98 1.290 1.661 1.984 2.365 2.627 3.175 - 99 1.290 1.660 1.984 2.365 2.626 3.175 -100 1.290 1.660 1.984 2.364 2.626 3.174 -inf 1.282 1.645 1.960 2.326 2.576 3.090 -]; + 1 3.078 6.314 12.706 31.821 63.657 318.313 + 2 1.886 2.920 4.303 6.965 9.925 22.327 + 3 1.638 2.353 3.182 4.541 5.841 10.215 + 4 1.533 2.132 2.776 3.747 4.604 7.173 + 5 1.476 2.015 2.571 3.365 4.032 5.893 + 6 1.440 1.943 2.447 3.143 3.707 5.208 + 7 1.415 1.895 2.365 2.998 3.499 4.782 + 8 1.397 1.860 2.306 2.896 3.355 4.499 + 9 1.383 1.833 2.262 2.821 3.250 4.296 + 10 1.372 1.812 2.228 2.764 3.169 4.143 + 11 1.363 1.796 2.201 2.718 3.106 4.024 + 12 1.356 1.782 2.179 2.681 3.055 3.929 + 13 1.350 1.771 2.160 2.650 3.012 3.852 + 14 1.345 1.761 2.145 2.624 2.977 3.787 + 15 1.341 1.753 2.131 2.602 2.947 3.733 + 16 1.337 1.746 2.120 2.583 2.921 3.686 + 17 1.333 1.740 2.110 2.567 2.898 3.646 + 18 1.330 1.734 2.101 2.552 2.878 3.610 + 19 1.328 1.729 2.093 2.539 2.861 3.579 + 20 1.325 1.725 2.086 2.528 2.845 3.552 + 21 1.323 1.721 2.080 2.518 2.831 3.527 + 22 1.321 1.717 2.074 2.508 2.819 3.505 + 23 1.319 1.714 2.069 2.500 2.807 3.485 + 24 1.318 1.711 2.064 2.492 2.797 3.467 + 25 1.316 1.708 2.060 2.485 2.787 3.450 + 26 1.315 1.706 2.056 2.479 2.779 3.435 + 27 1.314 1.703 2.052 2.473 2.771 3.421 + 28 1.313 1.701 2.048 2.467 2.763 3.408 + 29 1.311 1.699 2.045 2.462 2.756 3.396 + 30 1.310 1.697 2.042 2.457 2.750 3.385 + 31 1.309 1.696 2.040 2.453 2.744 3.375 + 32 1.309 1.694 2.037 2.449 2.738 3.365 + 33 1.308 1.692 2.035 2.445 2.733 3.356 + 34 1.307 1.691 2.032 2.441 2.728 3.348 + 35 1.306 1.690 2.030 2.438 2.724 3.340 + 36 1.306 1.688 2.028 2.434 2.719 3.333 + 37 1.305 1.687 2.026 2.431 2.715 3.326 + 38 1.304 1.686 2.024 2.429 2.712 3.319 + 39 1.304 1.685 2.023 2.426 2.708 3.313 + 40 1.303 1.684 2.021 2.423 2.704 3.307 + 41 1.303 1.683 2.020 2.421 2.701 3.301 + 42 1.302 1.682 2.018 2.418 2.698 3.296 + 43 1.302 1.681 2.017 2.416 2.695 3.291 + 44 1.301 1.680 2.015 2.414 2.692 3.286 + 45 1.301 1.679 2.014 2.412 2.690 3.281 + 46 1.300 1.679 2.013 2.410 2.687 3.277 + 47 1.300 1.678 2.012 2.408 2.685 3.273 + 48 1.299 1.677 2.011 2.407 2.682 3.269 + 49 1.299 1.677 2.010 2.405 2.680 3.265 + 50 1.299 1.676 2.009 2.403 2.678 3.261 + 51 1.298 1.675 2.008 2.402 2.676 3.258 + 52 1.298 1.675 2.007 2.400 2.674 3.255 + 53 1.298 1.674 2.006 2.399 2.672 3.251 + 54 1.297 1.674 2.005 2.397 2.670 3.248 + 55 1.297 1.673 2.004 2.396 2.668 3.245 + 56 1.297 1.673 2.003 2.395 2.667 3.242 + 57 1.297 1.672 2.002 2.394 2.665 3.239 + 58 1.296 1.672 2.002 2.392 2.663 3.237 + 59 1.296 1.671 2.001 2.391 2.662 3.234 + 60 1.296 1.671 2.000 2.390 2.660 3.232 + 61 1.296 1.670 2.000 2.389 2.659 3.229 + 62 1.295 1.670 1.999 2.388 2.657 3.227 + 63 1.295 1.669 1.998 2.387 2.656 3.225 + 64 1.295 1.669 1.998 2.386 2.655 3.223 + 65 1.295 1.669 1.997 2.385 2.654 3.220 + 66 1.295 1.668 1.997 2.384 2.652 3.218 + 67 1.294 1.668 1.996 2.383 2.651 3.216 + 68 1.294 1.668 1.995 2.382 2.650 3.214 + 69 1.294 1.667 1.995 2.382 2.649 3.213 + 70 1.294 1.667 1.994 2.381 2.648 3.211 + 71 1.294 1.667 1.994 2.380 2.647 3.209 + 72 1.293 1.666 1.993 2.379 2.646 3.207 + 73 1.293 1.666 1.993 2.379 2.645 3.206 + 74 1.293 1.666 1.993 2.378 2.644 3.204 + 75 1.293 1.665 1.992 2.377 2.643 3.202 + 76 1.293 1.665 1.992 2.376 2.642 3.201 + 77 1.293 1.665 1.991 2.376 2.641 3.199 + 78 1.292 1.665 1.991 2.375 2.640 3.198 + 79 1.292 1.664 1.990 2.374 2.640 3.197 + 80 1.292 1.664 1.990 2.374 2.639 3.195 + 81 1.292 1.664 1.990 2.373 2.638 3.194 + 82 1.292 1.664 1.989 2.373 2.637 3.193 + 83 1.292 1.663 1.989 2.372 2.636 3.191 + 84 1.292 1.663 1.989 2.372 2.636 3.190 + 85 1.292 1.663 1.988 2.371 2.635 3.189 + 86 1.291 1.663 1.988 2.370 2.634 3.188 + 87 1.291 1.663 1.988 2.370 2.634 3.187 + 88 1.291 1.662 1.987 2.369 2.633 3.185 + 89 1.291 1.662 1.987 2.369 2.632 3.184 + 90 1.291 1.662 1.987 2.368 2.632 3.183 + 91 1.291 1.662 1.986 2.368 2.631 3.182 + 92 1.291 1.662 1.986 2.368 2.630 3.181 + 93 1.291 1.661 1.986 2.367 2.630 3.180 + 94 1.291 1.661 1.986 2.367 2.629 3.179 + 95 1.291 1.661 1.985 2.366 2.629 3.178 + 96 1.290 1.661 1.985 2.366 2.628 3.177 + 97 1.290 1.661 1.985 2.365 2.627 3.176 + 98 1.290 1.661 1.984 2.365 2.627 3.175 + 99 1.290 1.660 1.984 2.365 2.626 3.175 + 100 1.290 1.660 1.984 2.364 2.626 3.174 + inf 1.282 1.645 1.960 2.326 2.576 3.090 + ]; if n<=100 t_crit=t_crit(n,ncol); diff --git a/matlab/gsa/teff.m b/matlab/gsa/teff.m index da2d047416..e047256a02 100644 --- a/matlab/gsa/teff.m +++ b/matlab/gsa/teff.m @@ -3,7 +3,7 @@ function [yt, j0, ir, ic]=teff(T,Nsam,istable) % % Written by Marco Ratto % Joint Research Centre, The European Commission, -% marco.ratto@ec.europa.eu +% marco.ratto@ec.europa.eu % % Reference: % M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006. @@ -28,32 +28,32 @@ function [yt, j0, ir, ic]=teff(T,Nsam,istable) ndim = (length(size(T))); if ndim==3 -if nargin==1 - Nsam=size(T,3); - istable = [1:Nsam]'; -end -tmax=max(T,[],3); -tmin=min(T,[],3); -[ir, ic]=(find( (tmax-tmin)>1.e-8)); -j0 = length(ir); -yt=zeros(Nsam, j0); + if nargin==1 + Nsam=size(T,3); + istable = [1:Nsam]'; + end + tmax=max(T,[],3); + tmin=min(T,[],3); + [ir, ic]=(find( (tmax-tmin)>1.e-8)); + j0 = length(ir); + yt=zeros(Nsam, j0); -for j=1:j0 - y0=squeeze(T(ir(j),ic(j),:)); - %y1=ones(size(lpmat,1),1)*NaN; - y1=ones(Nsam,1)*NaN; - y1(istable,1)=y0; - yt(:,j)=y1; -end + for j=1:j0 + y0=squeeze(T(ir(j),ic(j),:)); + %y1=ones(size(lpmat,1),1)*NaN; + y1=ones(Nsam,1)*NaN; + y1(istable,1)=y0; + yt(:,j)=y1; + end else -tmax=max(T,[],2); -tmin=min(T,[],2); -ir=(find( (tmax-tmin)>1.e-8)); -j0 = length(ir); -yt=NaN(Nsam, j0); -yt(istable,:)=T(ir,:)'; + tmax=max(T,[],2); + tmin=min(T,[],2); + ir=(find( (tmax-tmin)>1.e-8)); + j0 = length(ir); + yt=NaN(Nsam, j0); + yt(istable,:)=T(ir,:)'; + - end %clear y0 y1; diff --git a/matlab/gsa/th_moments.m b/matlab/gsa/th_moments.m index 95df0b459c..9b886e8519 100644 --- a/matlab/gsa/th_moments.m +++ b/matlab/gsa/th_moments.m @@ -79,5 +79,3 @@ if options_.ar > 0 zz(:,i) = diag(gamma_y{i+1}(i1,i1)); end end - - diff --git a/matlab/gsa/trank.m b/matlab/gsa/trank.m index 42eff73ce8..914d3849ce 100644 --- a/matlab/gsa/trank.m +++ b/matlab/gsa/trank.m @@ -29,6 +29,6 @@ function yr = trank(y) [nr, nc] = size(y); for j=1:nc - [dum, is]=sort(y(:,j)); - yr(is,j)=[1:nr]'./nr; + [dum, is]=sort(y(:,j)); + yr(is,j)=[1:nr]'./nr; end diff --git a/matlab/hessian.m b/matlab/hessian.m index 4faa4c5000..844251f7cf 100644 --- a/matlab/hessian.m +++ b/matlab/hessian.m @@ -12,19 +12,19 @@ function hessian_mat = hessian(func,x, gstep, varargin) % --*-- Unitary tests -- % hessian_mat [double] Hessian matrix % % ALGORITHM -% Uses Abramowitz and Stegun (1965) formulas 25.3.23 +% Uses Abramowitz and Stegun (1965) formulas 25.3.23 % \[ % \frac{\partial^2 f_{0,0}}{\partial {x^2}} = \frac{1}{h^2}\left( f_{1,0} - 2f_{0,0} + f_{ - 1,0} \right) % \] % and 25.3.27 p. 884 -% +% % \[ % \frac{\partial ^2f_{0,0}}{\partial x\partial y} = \frac{-1}{2h^2}\left(f_{1,0} + f_{-1,0} + f_{0,1} + f_{0,-1} - 2f_{0,0} - f_{1,1} - f_{-1,-1} \right) % \] % % SPECIAL REQUIREMENTS % none -% +% % Copyright (C) 2001-2017 Dynare Team % @@ -43,7 +43,7 @@ function hessian_mat = hessian(func,x, gstep, varargin) % --*-- Unitary tests -- % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. -if ~isa(func, 'function_handle') +if ~isa(func, 'function_handle') func = str2func(func); end @@ -67,7 +67,7 @@ for i=1:n xh1(i) = x(i)-h_1(i); f_1(:,i) = feval(func, xh1, varargin{:}); %reset parameter - xh1(i) = x(i); + xh1(i) = x(i); end xh_1 = xh1; @@ -75,14 +75,14 @@ temp = f1+f_1-f0*ones(1, n); %term f_(1,0)+f_(-1,0)-f_(0,0) used later hessian_mat = zeros(size(f0,1), n*n); -for i=1:n - if i > 1 - %fill symmetric part of Hessian based on previously computed results +for i=1:n + if i > 1 + %fill symmetric part of Hessian based on previously computed results k = [i:n:n*(i-1)]; hessian_mat(:,(i-1)*n+1:(i-1)*n+i-1) = hessian_mat(:,k); - end + end hessian_mat(:,(i-1)*n+i) = (f1(:,i)+f_1(:,i)-2*f0)./(h1(i)*h_1(i)); %formula 25.3.23 - for j=i+1:n + for j=i+1:n %step in up direction xh1(i) = x(i)+h1(i); xh1(j) = x(j)+h_1(j); @@ -90,12 +90,12 @@ for i=1:n 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)); %formula 25.3.27 - %reset grid points + %reset grid points xh1(i) = x(i); xh1(j) = x(j); xh_1(i) = x(i); xh_1(j) = x(j); - end + end end diff --git a/matlab/hessian_sparse.m b/matlab/hessian_sparse.m index eb447f8d34..a15024c34f 100644 --- a/matlab/hessian_sparse.m +++ b/matlab/hessian_sparse.m @@ -16,7 +16,7 @@ function hessian_mat = hessian_sparse(func,x,gstep,varargin) % % SPECIAL REQUIREMENTS % none -% +% % Copyright (C) 2001-2012 Dynare Team % @@ -35,7 +35,7 @@ function hessian_mat = hessian_sparse(func,x,gstep,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 ~isa(func, 'function_handle') +if ~isa(func, 'function_handle') func = str2func(func); end n=size(x,1); @@ -49,7 +49,7 @@ xh1=x; f0=feval(func,x,varargin{:}); f1=zeros(size(f0,1),n); f_1=f1; -for i=1:n +for i=1:n xh1(i)=x(i)+h1(i); f1(:,i)=feval(func,xh1,varargin{:}); xh1(i)=x(i)-h_1(i); @@ -59,15 +59,15 @@ end xh_1=xh1; hessian_mat = sparse(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); -% hessian_mat(:,k)=0; -% end +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); + % hessian_mat(:,k)=0; + % 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=1:i-1 + for j=1:i-1 xh1(i)=x(i)+h1(i); xh1(j)=x(j)+h_1(j); xh_1(i)=x(i)-h1(i); @@ -77,5 +77,5 @@ for i=1:n xh1(j)=x(j); xh_1(i)=x(i); xh_1(j)=x(j); - end + end end \ No newline at end of file diff --git a/matlab/histvalf.m b/matlab/histvalf.m index 6e2712cebc..75838ec531 100644 --- a/matlab/histvalf.m +++ b/matlab/histvalf.m @@ -86,4 +86,3 @@ for i = 1:length(outvars) end M_.endo_histval(j, :) = getfield(S, ov_); end - diff --git a/matlab/homotopy1.m b/matlab/homotopy1.m index e7de1f16a7..956a86431f 100644 --- a/matlab/homotopy1.m +++ b/matlab/homotopy1.m @@ -90,7 +90,7 @@ for i=1:step_nbr+1 % if homotopy step is not successful, current values of steady % state are not modified oo.steady_state = steady_state; - else + else M.params = old_params; oo.exo_steady_state = old_exo; oo.exo_det_steady_state = old_exo_det; diff --git a/matlab/homotopy2.m b/matlab/homotopy2.m index 8e1318a86b..efcdbf85ee 100644 --- a/matlab/homotopy2.m +++ b/matlab/homotopy2.m @@ -99,7 +99,7 @@ for i = 1:nv end disp([ 'HOMOTOPY mode 2: lauching solver with ' deblank(varname) ' = ' num2str(v) ' ...']) - + oo_.steady_state = steady_(M_,options_,oo_); end end diff --git a/matlab/homotopy3.m b/matlab/homotopy3.m index a506bb6b66..2f3a4f3178 100644 --- a/matlab/homotopy3.m +++ b/matlab/homotopy3.m @@ -91,11 +91,11 @@ 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; [steady_state,params,info] = steady_(M,options,oo); @@ -121,8 +121,8 @@ while iter <= step_nbr disp('HOMOTOPY mode 3: failed step, now dividing increment by 2...') inc = inc/2; oo.steady_state = old_ss; - end - + end + curvalues = last_values + inc; kplus = find(curvalues(iplus) >= targetvalues(iplus)); curvalues(iplus(kplus)) = targetvalues(iplus(kplus)); @@ -136,7 +136,7 @@ while iter <= step_nbr oo.exo_det_steady_state = old_exo_det_steady_state; return end - + iter = iter + 1; end disp('HOMOTOPY mode 3: failed, maximum iterations reached') diff --git a/matlab/ident_bruteforce.m b/matlab/ident_bruteforce.m index 238e3a5a02..34725ade4c 100644 --- a/matlab/ident_bruteforce.m +++ b/matlab/ident_bruteforce.m @@ -12,7 +12,7 @@ function [pars, cosnJ] = ident_bruteforce(J,n,TeX, pnames_TeX,tittxt) % pnames_TeX [char] list of tex names % tittxt [string] string indicating the title text for % graphs and figures -% +% % OUTPUTS % pars : cell array with groupf of params for each column of J for 1 to n % cosnJ : the cosn of each column with the selected group of columns @@ -85,7 +85,7 @@ for ll = 1:n fprintf(fidTeX,['%% ' datestr(now,0)]); fprintf(fidTeX,' \n'); fprintf(fidTeX,' \n'); - + fprintf(fidTeX,'{\\tiny \n'); fprintf(fidTeX,'\\begin{longtable}{llc} \n'); fprintf(fidTeX,['\\caption{Collinearity patterns with ',int2str(ll),' parameter(s): ',tittxt,'}\n ']); @@ -111,9 +111,9 @@ for ll = 1:n end end fprintf(fidTeX,'$%s$ & [%s] & %7.3f \\\\ \n',... - pnames_TeX(i,:),... - plist,... - cosnJ(i,ll)); + pnames_TeX(i,:),... + plist,... + cosnJ(i,ll)); end fprintf(fidTeX,'\\bottomrule \n'); fprintf(fidTeX,'\\end{longtable}\n'); diff --git a/matlab/identification_analysis.m b/matlab/identification_analysis.m index 1ea6b54308..c59e08ec6d 100644 --- a/matlab/identification_analysis.m +++ b/matlab/identification_analysis.m @@ -9,14 +9,14 @@ function [ide_hess, ide_moments, ide_model, ide_lre, derivatives_info, info, opt % o options_ident [structure] identification options % o dataset_ [structure] the dataset after required transformation % o dataset_info [structure] Various informations about the dataset (descriptive statistics and missing observations) info for Kalman Filter -% o prior_exist [integer] +% o prior_exist [integer] % =1 when prior exists and indentification is checked only for estimated params and shocks % =0 when prior is not defined and indentification is checked for all params and shocks % o name_tex [char] list of tex names % o init [integer] flag for initialization of persistent vars % o tittxt [string] string indicating the title text for % graphs and figures -% +% % OUTPUTS % o ide_hess [structure] identification results using Asymptotic Hessian % o ide_moments [structure] identification results using theoretical moments @@ -24,7 +24,7 @@ function [ide_hess, ide_moments, ide_model, ide_lre, derivatives_info, info, opt % o ide_lre [structure] identification results using LRE model % o derivatives_info [structure] info about analytic derivs % o info output from dynare resolve -% +% % SPECIAL REQUIREMENTS % None @@ -42,7 +42,7 @@ function [ide_hess, ide_moments, ide_model, ide_lre, derivatives_info, info, opt % 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 +% 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_ bayestopt_ estim_params_ @@ -63,7 +63,7 @@ periods = options_ident.periods; max_dim_cova_group = options_ident.max_dim_cova_group; normalize_jacobians = options_ident.normalize_jacobians; kron_flag = options_ident.analytic_derivation_mode; - + [I,J]=find(M_.lead_lag_incidence'); ide_hess = struct(); @@ -78,8 +78,8 @@ if info(1)==0 tau=[oo_.dr.ys(oo_.dr.order_var); vec(A); dyn_vech(B*M_.Sigma_e*B')]; yy0=oo_.dr.ys(I); [residual, g1 ] = feval([M_.fname,'_dynamic'],yy0, ... - repmat(oo_.exo_steady_state',[M_.maximum_exo_lag+M_.maximum_exo_lead+1]), M_.params, ... - oo_.dr.ys, 1); + repmat(oo_.exo_steady_state',[M_.maximum_exo_lag+M_.maximum_exo_lead+1]), M_.params, ... + oo_.dr.ys, 1); vg1 = [oo_.dr.ys(oo_.dr.order_var); vec(g1)]; [JJ, H, gam, gp, dA, dOm, dYss] = getJJ(A, B, estim_params_, M_,oo0,options_,kron_flag,indx,indexo,bayestopt_.mf2,nlags,useautocorr); @@ -95,7 +95,7 @@ if info(1)==0 end while length(indJJ)<nparam && nlags<10 disp('The number of moments with non-zero derivative is smaller than the number of parameters') - disp(['Try increasing ar = ', int2str(nlags+1)]) + disp(['Try increasing ar = ', int2str(nlags+1)]) nlags=nlags+1; [JJ, H, gam, gp, dA, dOm, dYss] = getJJ(A, B, estim_params_, M_,oo0,options_,kron_flag,indx,indexo,bayestopt_.mf2,nlags,useautocorr); derivatives_info.DT=dA; @@ -106,8 +106,8 @@ if info(1)==0 end if length(indJJ)<nparam disp('The number of moments with non-zero derivative is smaller than the number of parameters') - disp('up to 10 lags: check your model') - disp('Either further increase ar or reduce the list of estimated parameters') + disp('up to 10 lags: check your model') + disp('Either further increase ar or reduce the list of estimated parameters') error('identification_analysis: there are not enough moments and too many parameters'), end indH = (find(max(abs(H'),[],1)>1.e-8)); @@ -117,7 +117,7 @@ if info(1)==0 LRE(:,1)=vg1(indLRE); GAM(:,1)=gam(indJJ); siJ = (JJ(indJJ,:)); - siH = (H(indH,:)); + siH = (H(indH,:)); siLRE = (gp(indLRE,:)); ide_strength_J=NaN(1,nparam); ide_strength_J_prior=NaN(1,nparam); @@ -137,7 +137,7 @@ if info(1)==0 end % normaliz = max([normaliz; normaliz1]); normaliz1(isinf(normaliz1)) = 1; - + else normaliz1 = NaN(1,nparam); end @@ -153,17 +153,17 @@ if info(1)==0 analytic_derivation = options_.analytic_derivation; options_.analytic_derivation = -2; info = stoch_simul(char(options_.varobs)); - dataset_ = dseries(oo_.endo_simul(options_.varobs_id,100+1:end)',dates('1Q1'), options_.varobs); + dataset_ = dseries(oo_.endo_simul(options_.varobs_id,100+1:end)',dates('1Q1'), options_.varobs); derivatives_info.no_DLIK=1; %bounds = prior_bounds(bayestopt_, options_.prior_trunc); - [fval,info,cost_flag,DLIK,AHess,ys,trend_coeff,M_,options_,bayestopt_,oo_] = dsge_likelihood(params',dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_,derivatives_info); -% fval = DsgeLikelihood(xparam1,data_info,options_,M_,estim_params_,bayestopt_,oo_); + [fval,info,cost_flag,DLIK,AHess,ys,trend_coeff,M_,options_,bayestopt_,oo_] = dsge_likelihood(params',dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_,derivatives_info); + % fval = DsgeLikelihood(xparam1,data_info,options_,M_,estim_params_,bayestopt_,oo_); options_.analytic_derivation = analytic_derivation; AHess=-AHess; if min(eig(AHess))<-1.e-10 error('identification_analysis: Analytic Hessian is not positive semi-definite!') end -% chol(AHess); + % chol(AHess); ide_hess.AHess= AHess; deltaM = sqrt(diag(AHess)); iflag=any((deltaM.*deltaM)==0); @@ -181,23 +181,23 @@ if info(1)==0 cmm = siJ(:,ind1)*((AHess(ind1,ind1))\siJ(:,ind1)'); temp1=((AHess(ind1,ind1))\siH(:,ind1)'); diag_chh=sum(siH(:,ind1)'.*temp1)'; -% chh = siH(:,ind1)*((AHess(ind1,ind1))\siH(:,ind1)'); + % chh = siH(:,ind1)*((AHess(ind1,ind1))\siH(:,ind1)'); ind1=ind1(ind1>offset); clre = siLRE(:,ind1-offset)*((AHess(ind1,ind1))\siLRE(:,ind1-offset)'); rhoM=sqrt(1./diag(inv(tildaM(indok,indok)))); -% deltaM = deltaM.*abs(params'); + % deltaM = deltaM.*abs(params'); flag_score=1; catch -% replic = max([replic, nparam*(nparam+1)/2*10]); + % replic = max([replic, nparam*(nparam+1)/2*10]); replic = max([replic, length(indJJ)*3]); cmm = simulated_moment_uncertainty(indJJ, periods, replic,options_,M_,oo_); -% [V,D,W]=eig(cmm); + % [V,D,W]=eig(cmm); sd=sqrt(diag(cmm)); cc=cmm./(sd*sd'); if isoctave || matlab_ver_less_than('8.3') [V,D]=eig(cc); %fix for older Matlab versions that do not support computing left eigenvalues, see http://mathworks.com/help/releases/R2012b/matlab/ref/eig.html - [W,junk] = eig(cc.'); + [W,junk] = eig(cc.'); W = conj(W); else [V,D,W]=eig(cc); @@ -206,21 +206,21 @@ if info(1)==0 siTMP=siJ./repmat(sd,[1 nparam]); MIM=(siTMP'*V(:,id))*(D(id,id)\(W(:,id)'*siTMP)); clear siTMP; -% MIM=siJ(:,indok)'*(cmm\siJ(:,indok)); -% look for independent moments! -% % % sd=sqrt(diag(cmm)); -% % % cc=cmm./(sd*sd'); -% % % ix=[]; -% % % for jc=1:length(cmm), -% % % jcheck=find(abs(cc(:,jc))>(1-1.e-6)); -% % % ix=[ix; jcheck(jcheck>jc)]; -% % % end -% % % iy=find(~ismember([1:length(cmm)],ix)); -% % % indJJ=indJJ(iy); -% % % GAM=GAM(iy); -% % % cmm=cmm(iy,iy); -% % % siJ = (JJ(indJJ,:)); -% % % MIM=siJ'*(cmm\siJ); + % MIM=siJ(:,indok)'*(cmm\siJ(:,indok)); + % look for independent moments! + % % % sd=sqrt(diag(cmm)); + % % % cc=cmm./(sd*sd'); + % % % ix=[]; + % % % for jc=1:length(cmm), + % % % jcheck=find(abs(cc(:,jc))>(1-1.e-6)); + % % % ix=[ix; jcheck(jcheck>jc)]; + % % % end + % % % iy=find(~ismember([1:length(cmm)],ix)); + % % % indJJ=indJJ(iy); + % % % GAM=GAM(iy); + % % % cmm=cmm(iy,iy); + % % % siJ = (JJ(indJJ,:)); + % % % MIM=siJ'*(cmm\siJ); ide_hess.AHess= MIM; deltaM = sqrt(diag(MIM)); iflag=any((deltaM.*deltaM)==0); @@ -231,12 +231,12 @@ if info(1)==0 [ide_hess.cond, ide_hess.ind0, ide_hess.indno, ide_hess.ino, ide_hess.Mco, ide_hess.Pco] = identification_checks(tildaM, 1); end indok = find(max(ide_hess.indno,[],1)==0); -% rhoM=sqrt(1-1./diag(inv(tildaM))); -% rhoM=(1-1./diag(inv(tildaM))); + % rhoM=sqrt(1-1./diag(inv(tildaM))); + % rhoM=(1-1./diag(inv(tildaM))); ind1=find(ide_hess.ind0); temp1=((MIM(ind1,ind1))\siH(:,ind1)'); diag_chh=sum(siH(:,ind1)'.*temp1)'; -% chh = siH(:,ind1)*((MIM(ind1,ind1))\siH(:,ind1)'); + % chh = siH(:,ind1)*((MIM(ind1,ind1))\siH(:,ind1)'); ind1=ind1(ind1>offset); clre = siLRE(:,ind1-offset)*((MIM(ind1,ind1))\siLRE(:,ind1-offset)'); if ~isempty(indok) @@ -260,11 +260,11 @@ if info(1)==0 end % siJnorm = vnorm(siJ(inok,:)).*normaliz; quant=[]; -% inok = find((abs(TAU)<1.e-8)); -% isok = find((abs(TAU)>=1.e-8)); -% quant(isok,:) = siH(isok,:)./repmat(TAU(isok,1),1,nparam); -% quant(inok,:) = siH(inok,:)./repmat(mean(abs(TAU)),length(inok),nparam); -% quant = siH./repmat(sqrt(diag(chh)),1,nparam); + % inok = find((abs(TAU)<1.e-8)); + % isok = find((abs(TAU)>=1.e-8)); + % quant(isok,:) = siH(isok,:)./repmat(TAU(isok,1),1,nparam); + % quant(inok,:) = siH(inok,:)./repmat(mean(abs(TAU)),length(inok),nparam); + % quant = siH./repmat(sqrt(diag(chh)),1,nparam); iy = find(diag_chh); indH=indH(iy); siH=siH(iy,:); @@ -280,10 +280,10 @@ if info(1)==0 end % siHnorm = vnorm(siH./repmat(TAU,1,nparam)).*normaliz; quant=[]; -% inok = find((abs(LRE)<1.e-8)); -% isok = find((abs(LRE)>=1.e-8)); -% quant(isok,:) = siLRE(isok,:)./repmat(LRE(isok,1),1,np); -% quant(inok,:) = siLRE(inok,:)./repmat(mean(abs(LRE)),length(inok),np); + % inok = find((abs(LRE)<1.e-8)); + % isok = find((abs(LRE)>=1.e-8)); + % quant(isok,:) = siLRE(isok,:)./repmat(LRE(isok,1),1,np); + % quant(inok,:) = siLRE(inok,:)./repmat(mean(abs(LRE)),length(inok),np); diag_clre = diag(clre); iy = find(diag_clre); indLRE=indLRE(iy); @@ -299,14 +299,14 @@ if info(1)==0 siLREnorm=[]; end % siLREnorm = vnorm(siLRE./repmat(LRE,1,nparam-offset)).*normaliz(offset+1:end); - ide_hess.ide_strength_J=ide_strength_J; - ide_hess.ide_strength_J_prior=ide_strength_J_prior; - ide_hess.deltaM=deltaM; - ide_hess.deltaM_prior=deltaM_prior; - ide_moments.siJnorm=siJnorm; - ide_model.siHnorm=siHnorm; - ide_lre.siLREnorm=siLREnorm; - ide_hess.flag_score=flag_score; + ide_hess.ide_strength_J=ide_strength_J; + ide_hess.ide_strength_J_prior=ide_strength_J_prior; + ide_hess.deltaM=deltaM; + ide_hess.deltaM_prior=deltaM_prior; + ide_moments.siJnorm=siJnorm; + ide_model.siHnorm=siHnorm; + ide_lre.siLREnorm=siLREnorm; + ide_hess.flag_score=flag_score; end if normalize_jacobians normH = max(abs(siH)')'; @@ -329,14 +329,14 @@ if info(1)==0 ide_moments.GAM=GAM; ide_model.TAU=TAU; ide_lre.LRE=LRE; -% [ide_checks.idemodel_Mco, ide_checks.idemoments_Mco, ide_checks.idelre_Mco, ... -% ide_checks.idemodel_Pco, ide_checks.idemoments_Pco, ide_checks.idelre_Pco, ... -% ide_checks.idemodel_cond, ide_checks.idemoments_cond, ide_checks.idelre_cond, ... -% ide_checks.idemodel_ee, ide_checks.idemoments_ee, ide_checks.idelre_ee, ... -% ide_checks.idemodel_ind, ide_checks.idemoments_ind, ... -% ide_checks.idemodel_indno, ide_checks.idemoments_indno, ... -% ide_checks.idemodel_ino, ide_checks.idemoments_ino] = ... -% identification_checks(H(indH,:)./normH(:,ones(nparam,1)),JJ(indJJ,:)./normJ(:,ones(nparam,1)), gp(indLRE,:)./normLRE(:,ones(size(gp,2),1))); + % [ide_checks.idemodel_Mco, ide_checks.idemoments_Mco, ide_checks.idelre_Mco, ... + % ide_checks.idemodel_Pco, ide_checks.idemoments_Pco, ide_checks.idelre_Pco, ... + % ide_checks.idemodel_cond, ide_checks.idemoments_cond, ide_checks.idelre_cond, ... + % ide_checks.idemodel_ee, ide_checks.idemoments_ee, ide_checks.idelre_ee, ... + % ide_checks.idemodel_ind, ide_checks.idemoments_ind, ... + % ide_checks.idemodel_indno, ide_checks.idemoments_indno, ... + % ide_checks.idemodel_ino, ide_checks.idemoments_ino] = ... + % identification_checks(H(indH,:)./normH(:,ones(nparam,1)),JJ(indJJ,:)./normJ(:,ones(nparam,1)), gp(indLRE,:)./normLRE(:,ones(size(gp,2),1))); [ide_moments.cond, ide_moments.ind0, ide_moments.indno, ide_moments.ino, ide_moments.Mco, ide_moments.Pco, ide_moments.jweak, ide_moments.jweak_pair] = ... identification_checks(JJ(indJJ,:)./normJ, 0); [ide_model.cond, ide_model.ind0, ide_model.indno, ide_model.ino, ide_model.Mco, ide_model.Pco, ide_model.jweak, ide_model.jweak_pair] = ... diff --git a/matlab/identification_checks.m b/matlab/identification_checks.m index 19c4b987b1..e52fa960d8 100644 --- a/matlab/identification_checks.m +++ b/matlab/identification_checks.m @@ -7,17 +7,17 @@ function [condJ, ind0, indnoJ, ixnoJ, McoJ, PcoJ, jweak, jweak_pair] = identific % derivatives of output w.r.t. parameters and shocks % o JJ [matrix] [nparams x nparams] IF hess_flag==1 % information matrix -% +% % OUTPUTS % o cond condition number of JJ % o ind0 [array] binary indicator for non-zero columns of H -% o indnoJ [matrix] index of non-identified params +% o indnoJ [matrix] index of non-identified params % o ixnoJ number of rows in indnoJ % o Mco [array] multicollinearity coefficients -% o Pco [matrix] pairwise correlations +% o Pco [matrix] pairwise correlations % o jweak [binary array] gives 1 if the parameter has Mco=1(with tolerance 1.e-10) % o jweak_pair [binary matrix] gives 1 if a couple parameters has Pco=1(with tolerance 1.e-10) -% +% % SPECIAL REQUIREMENTS % None @@ -49,7 +49,7 @@ if size(JJ,1)>1 ind1 = find(vnorm(JJ)>=eps); % take non-zero columns else ind1 = find(abs(JJ)>=eps); % take non-zero columns -end +end JJ1 = JJ(:,ind1); [eu,ee2,ee1] = svd( JJ1, 0 ); condJ= cond(JJ1); @@ -70,17 +70,17 @@ if npar>0 && (rankJ<npar) end if icheck -JJ1 = JJ(:,ind1); -[eu,ee2,ee1] = svd( JJ1, 0 ); -condJ= cond(JJ1); -rankJ = rank(JJ); -rankJJ = rankJ; + JJ1 = JJ(:,ind1); + [eu,ee2,ee1] = svd( JJ1, 0 ); + condJ= cond(JJ1); + rankJ = rank(JJ); + rankJJ = rankJ; end - + % if hess_flag==0, % rankJJ = rank(JJ'*JJ); -% end +% end ind0 = zeros(1,npar); ind0(ind1) = 1; @@ -96,7 +96,7 @@ else tildaJ = JJ(ind1,ind1)./((deltaJ)*(deltaJ')); McoJ(ind1,1)=(1-1./diag(inv(tildaJ))); rhoM=sqrt(1-McoJ); -% PcoJ=inv(tildaJ); + % PcoJ=inv(tildaJ); PcoJ=NaN(npar,npar); PcoJ(ind1,ind1)=inv(JJ(ind1,ind1)); sd=sqrt(diag(PcoJ)); @@ -130,27 +130,26 @@ jweak=zeros(1,npar); jweak_pair=zeros(npar,npar); if hess_flag==0, -PcoJ = NaN(npar,npar); + PcoJ = NaN(npar,npar); -for ii = 1:size(JJ1,2) - PcoJ(ind1(ii),ind1(ii)) = 1; - for jj = ii+1:size(JJ1,2) - PcoJ(ind1(ii),ind1(jj)) = cosn([JJ1(:,ii),JJ1(:,jj)]); - PcoJ(ind1(jj),ind1(ii)) = PcoJ(ind1(ii),ind1(jj)); + for ii = 1:size(JJ1,2) + PcoJ(ind1(ii),ind1(ii)) = 1; + for jj = ii+1:size(JJ1,2) + PcoJ(ind1(ii),ind1(jj)) = cosn([JJ1(:,ii),JJ1(:,jj)]); + PcoJ(ind1(jj),ind1(ii)) = PcoJ(ind1(ii),ind1(jj)); + end end -end -for j=1:npar - if McoJ(j)>(1-1.e-10) - jweak(j)=1; - [ipair, jpair] = find(PcoJ(j,j+1:end)>(1-1.e-10)); - for jx=1:length(jpair) - jweak_pair(j, jpair(jx)+j)=1; - jweak_pair(jpair(jx)+j, j)=1; + for j=1:npar + if McoJ(j)>(1-1.e-10) + jweak(j)=1; + [ipair, jpair] = find(PcoJ(j,j+1:end)>(1-1.e-10)); + for jx=1:length(jpair) + jweak_pair(j, jpair(jx)+j)=1; + jweak_pair(jpair(jx)+j, j)=1; + end end end end -end jweak_pair=dyn_vech(jweak_pair)'; - diff --git a/matlab/imcforecast.m b/matlab/imcforecast.m index bad87e9812..66841319a8 100644 --- a/matlab/imcforecast.m +++ b/matlab/imcforecast.m @@ -2,29 +2,29 @@ function imcforecast(constrained_paths, constrained_vars, options_cond_fcst) % Computes conditional forecasts. % % INPUTS -% o constrained_paths [double] m*p array, where m is the number of constrained endogenous variables and p is the number of constrained periods. -% o constrained_vars [char] m*x array holding the names of the controlled endogenous variables. +% o constrained_paths [double] m*p array, where m is the number of constrained endogenous variables and p is the number of constrained periods. +% o constrained_vars [char] m*x array holding the names of the controlled endogenous variables. % o options_cond_fcst [structure] containing the options. The fields are: % + replic [integer] scalar, number of monte carlo simulations. % + parameter_set [char] values of the estimated parameters: -% "posterior_mode", -% "posterior_mean", -% "posterior_median", -% "prior_mode" or -% "prior mean". +% "posterior_mode", +% "posterior_mean", +% "posterior_median", +% "prior_mode" or +% "prior mean". % [double] np*1 array, values of the estimated parameters. % + controlled_varexo [char] m*x array, list of controlled exogenous variables. -% + conf_sig [double] scalar in [0,1], probability mass covered by the confidence bands. +% + conf_sig [double] scalar in [0,1], probability mass covered by the confidence bands. % % OUTPUTS % None. -% +% % SPECIAL REQUIREMENTS % This routine has to be called after an estimation statement or an estimated_params block. % % REMARKS % [1] Results are stored in a structure which is saved in a mat file called conditional_forecasts.mat. -% [2] Use the function plot_icforecast to plot the results. +% [2] Use the function plot_icforecast to plot the results. % Copyright (C) 2006-2017 Dynare Team % @@ -119,7 +119,7 @@ if estimated_model data_index = dataset_info.missing.aindex; gend = dataset_.nobs; missing_value = dataset_info.missing.state; - + %store qz_criterium qz_criterium_old=options_.qz_criterium; options_=select_qz_criterium_value(options_); @@ -147,7 +147,7 @@ if estimated_model % add trend to constant for obs_iter=1:length(options_.varobs) j = strmatch(options_.varobs{obs_iter},M_.endo_names,'exact'); - constant(j,:) = constant(j,:)+trend_addition(obs_iter,:); + constant(j,:) = constant(j,:)+trend_addition(obs_iter,:); end trend = constant(oo_.dr.order_var,:); InitState(:,1) = atT(:,end); @@ -225,7 +225,7 @@ jdx = []; for i = 1:n1 idx = [idx ; constrained_vars(i,:)]; -% idx = [idx ; oo_.dr.inv_order_var(constrained_vars(i,:))]; + % idx = [idx ; oo_.dr.inv_order_var(constrained_vars(i,:))]; jdx = [jdx ; strmatch(deblank(options_cond_fcst.controlled_varexo(i,:)),M_.exo_names,'exact')]; end mv = zeros(n1,NumberOfStates); diff --git a/matlab/indnv.m b/matlab/indnv.m index 1df7077865..71b40cd3ed 100644 --- a/matlab/indnv.m +++ b/matlab/indnv.m @@ -40,6 +40,3 @@ for i = 1:size(x,1) a(i) = j; end end - - - diff --git a/matlab/init_plan.m b/matlab/init_plan.m index bc70e361a9..721ba40fb7 100644 --- a/matlab/init_plan.m +++ b/matlab/init_plan.m @@ -1,4 +1,4 @@ -function plan = init_plan(date) +function plan = init_plan(date) % Creates and initializes a new forecast scenario % % INPUTS @@ -25,28 +25,27 @@ function plan = init_plan(date) % % 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_ - plan = struct(); - plan.date = date; - plan.date_str = strings(date); - endo_names_length = size(M_.endo_names,2); - plan.endo_names = deblank(mat2cell(M_.endo_names(1:M_.orig_endo_nbr,:),ones(1,M_.orig_endo_nbr),endo_names_length)); - exo_names_length = size(M_.exo_names,2); - plan.exo_names = deblank(mat2cell(M_.exo_names(1:M_.exo_nbr,:),ones(1,M_.exo_nbr),exo_names_length)); - plan.constrained_vars_ = []; - plan.constrained_paths_ = []; - plan.constrained_date_ = []; - plan.constrained_int_date_ = []; - plan.constrained_str_date_ = []; - plan.constrained_perfect_foresight_ = []; - plan.shock_vars_ = []; - plan.shock_paths_ = []; - plan.shock_date_ = []; - plan.shock_int_date_ = []; - plan.shock_str_date_ = []; - plan.shock_perfect_foresight_ = []; - plan.options_cond_fcst_ = struct(); - plan.options_cond_fcst_.parameter_set = 'calibration'; - plan.options_cond_fcst_.simulation_type = 'deterministic'; - plan.options_cond_fcst_.controlled_varexo = []; - +global M_ +plan = struct(); +plan.date = date; +plan.date_str = strings(date); +endo_names_length = size(M_.endo_names,2); +plan.endo_names = deblank(mat2cell(M_.endo_names(1:M_.orig_endo_nbr,:),ones(1,M_.orig_endo_nbr),endo_names_length)); +exo_names_length = size(M_.exo_names,2); +plan.exo_names = deblank(mat2cell(M_.exo_names(1:M_.exo_nbr,:),ones(1,M_.exo_nbr),exo_names_length)); +plan.constrained_vars_ = []; +plan.constrained_paths_ = []; +plan.constrained_date_ = []; +plan.constrained_int_date_ = []; +plan.constrained_str_date_ = []; +plan.constrained_perfect_foresight_ = []; +plan.shock_vars_ = []; +plan.shock_paths_ = []; +plan.shock_date_ = []; +plan.shock_int_date_ = []; +plan.shock_str_date_ = []; +plan.shock_perfect_foresight_ = []; +plan.options_cond_fcst_ = struct(); +plan.options_cond_fcst_.parameter_set = 'calibration'; +plan.options_cond_fcst_.simulation_type = 'deterministic'; +plan.options_cond_fcst_.controlled_varexo = []; diff --git a/matlab/initial_condition_decomposition.m b/matlab/initial_condition_decomposition.m index af92d65ac8..cee5335a86 100644 --- a/matlab/initial_condition_decomposition.m +++ b/matlab/initial_condition_decomposition.m @@ -4,7 +4,7 @@ function oo_ = initial_condition_decomposition(M_,oo_,options_,varlist,bayestopt % oo_.initval_decomposition. It is a n_var by n_var+2 by nperiods array. The % first n_var columns store the respective endogenous initval contribution, column n+1 % stores the role of the shocks, while column n+2 stores the -% value of the smoothed variables. Variables are stored +% value of the smoothed variables. Variables are stored % in the order of declaration, i.e. M_.endo_names. % % INPUTS @@ -61,9 +61,9 @@ parameter_set = options_.parameter_set; if isempty(parameter_set) if isfield(oo_,'posterior_mean') parameter_set = 'posterior_mean'; - elseif isfield(oo_,'mle_mode') + elseif isfield(oo_,'mle_mode') parameter_set = 'mle_mode'; - elseif isfield(oo_,'posterior') + elseif isfield(oo_,'posterior') parameter_set = 'posterior_mode'; else error(['shock_decomposition: option parameter_set is not specified ' ... @@ -72,61 +72,61 @@ if isempty(parameter_set) end if ~isfield(oo_,'initval_decomposition') -options_.selected_variables_only = 0; %make sure all variables are stored -options_.plot_priors=0; -[oo,junk1,junk2,Smoothed_Variables_deviation_from_mean] = evaluate_smoother(parameter_set,varlist,M_,oo_,options_,bayestopt_,estim_params_); + options_.selected_variables_only = 0; %make sure all variables are stored + options_.plot_priors=0; + [oo,junk1,junk2,Smoothed_Variables_deviation_from_mean] = evaluate_smoother(parameter_set,varlist,M_,oo_,options_,bayestopt_,estim_params_); -% reduced form -dr = oo.dr; + % reduced form + dr = oo.dr; -% data reordering -order_var = dr.order_var; -inv_order_var = dr.inv_order_var; + % data reordering + order_var = dr.order_var; + inv_order_var = dr.inv_order_var; -% coefficients -A = dr.ghx; -B = dr.ghu; + % coefficients + A = dr.ghx; + B = dr.ghu; -% initialization -gend = size(oo.SmoothedShocks.(deblank(M_.exo_names(1,:))),1); %+options_.forecast; -z = zeros(endo_nbr,endo_nbr+2,gend); -z(:,end,:) = Smoothed_Variables_deviation_from_mean; + % initialization + gend = size(oo.SmoothedShocks.(deblank(M_.exo_names(1,:))),1); %+options_.forecast; + z = zeros(endo_nbr,endo_nbr+2,gend); + z(:,end,:) = Smoothed_Variables_deviation_from_mean; -for i=1:endo_nbr - z(i,i,1) = Smoothed_Variables_deviation_from_mean(i,1); -end + for i=1:endo_nbr + z(i,i,1) = Smoothed_Variables_deviation_from_mean(i,1); + end -maximum_lag = M_.maximum_lag; + maximum_lag = M_.maximum_lag; -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:endo_nbr,lags),[1 3 2]); - m = min(i-1,maximum_lag); - tempx = [reshape(tempx,endo_nbr*m,endo_nbr); zeros(endo_nbr*(maximum_lag-i+1),endo_nbr)]; - z(:,1:endo_nbr,i) = A(inv_order_var,:)*tempx(i_state,:); - lags = lags+1; - end - z(:,endo_nbr+1,i) = z(:,endo_nbr+2,i) - sum(z(:,1:endo_nbr,i),2); + 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 -end + if i > 1 + tempx = permute(z(:,1:endo_nbr,lags),[1 3 2]); + m = min(i-1,maximum_lag); + tempx = [reshape(tempx,endo_nbr*m,endo_nbr); zeros(endo_nbr*(maximum_lag-i+1),endo_nbr)]; + z(:,1:endo_nbr,i) = A(inv_order_var,:)*tempx(i_state,:); + lags = lags+1; + end + z(:,endo_nbr+1,i) = z(:,endo_nbr+2,i) - sum(z(:,1:endo_nbr,i),2); + + end -oo_.initval_decomposition = z; + oo_.initval_decomposition = z; end % if ~options_.no_graph.shock_decomposition - oo=oo_; - oo.shock_decomposition = oo_.initval_decomposition; - M_.exo_names = M_.endo_names; - M_.exo_nbr = M_.endo_nbr; - options_.plot_shock_decomp.screen_shocks=1; - options_.plot_shock_decomp.use_shock_groups = ''; - options_.plot_shock_decomp.fig_names='initval'; - plot_shock_decomposition(M_,oo,options_,varlist); +oo=oo_; +oo.shock_decomposition = oo_.initval_decomposition; +M_.exo_names = M_.endo_names; +M_.exo_nbr = M_.endo_nbr; +options_.plot_shock_decomp.screen_shocks=1; +options_.plot_shock_decomp.use_shock_groups = ''; +options_.plot_shock_decomp.fig_names='initval'; +plot_shock_decomposition(M_,oo,options_,varlist); % end \ No newline at end of file diff --git a/matlab/initial_estimation_checks.m b/matlab/initial_estimation_checks.m index 8741eaec0d..7dfc4d9a2a 100644 --- a/matlab/initial_estimation_checks.m +++ b/matlab/initial_estimation_checks.m @@ -54,7 +54,7 @@ if maximum_number_non_missing_observations>length(find(diag(Model.Sigma_e)))+Est end if (any(BayesInfo.pshape >0 ) && DynareOptions.mh_replic) && DynareOptions.mh_nblck<1 - error(['initial_estimation_checks:: Bayesian estimation cannot be conducted with mh_nblocks=0.']) + error(['initial_estimation_checks:: Bayesian estimation cannot be conducted with mh_nblocks=0.']) end old_steady_params=Model.params; %save initial parameters for check if steady state changes param values @@ -69,35 +69,35 @@ if isfield(EstimatedParameters,'param_vals') && ~isempty(EstimatedParameters.par [junk, new_steady_params_2] = evaluate_steady_state(DynareResults.steady_state,Model_par_varied,DynareOptions,DynareResults,DynareOptions.diffuse_filter==0); changed_par_indices=find((old_steady_params(EstimatedParameters.param_vals(:,1))-new_steady_params(EstimatedParameters.param_vals(:,1))) ... - | (Model_par_varied.params(EstimatedParameters.param_vals(:,1))-new_steady_params_2(EstimatedParameters.param_vals(:,1)))); + | (Model_par_varied.params(EstimatedParameters.param_vals(:,1))-new_steady_params_2(EstimatedParameters.param_vals(:,1)))); if ~isempty(changed_par_indices) fprintf('\nThe steady state file internally changed the values of the following estimated parameters:\n') disp(Model.param_names(EstimatedParameters.param_vals(changed_par_indices,1),:)); fprintf('This will override the parameter values drawn from the proposal density and may lead to wrong results.\n') - fprintf('Check whether this is really intended.\n') + fprintf('Check whether this is really intended.\n') warning('The steady state file internally changes the values of the estimated parameters.') end end if any(BayesInfo.pshape) % if Bayesian estimation nvx=EstimatedParameters.nvx; - if nvx && any(BayesInfo.p3(1:nvx)<0) + if nvx && any(BayesInfo.p3(1:nvx)<0) warning('Your prior allows for negative standard deviations for structural shocks. Due to working with variances, Dynare will be able to continue, but it is recommended to change your prior.') end offset=nvx; nvn=EstimatedParameters.nvn; - if nvn && any(BayesInfo.p3(1+offset:offset+nvn)<0) + if nvn && any(BayesInfo.p3(1+offset:offset+nvn)<0) warning('Your prior allows for negative standard deviations for measurement error. Due to working with variances, Dynare will be able to continue, but it is recommended to change your prior.') end offset = nvx+nvn; - ncx=EstimatedParameters.ncx; - if ncx && (any(BayesInfo.p3(1+offset:offset+ncx)<-1) || any(BayesInfo.p4(1+offset:offset+ncx)>1)) + ncx=EstimatedParameters.ncx; + if ncx && (any(BayesInfo.p3(1+offset:offset+ncx)<-1) || any(BayesInfo.p4(1+offset:offset+ncx)>1)) warning('Your prior allows for correlations between structural shocks larger than +-1 and will not integrate to 1 due to truncation. Please change your prior') end offset = nvx+nvn+ncx; - ncn=EstimatedParameters.ncn; - if ncn && (any(BayesInfo.p3(1+offset:offset+ncn)<-1) || any(BayesInfo.p4(1+offset:offset+ncn)>1)) + ncn=EstimatedParameters.ncn; + if ncn && (any(BayesInfo.p3(1+offset:offset+ncn)<-1) || any(BayesInfo.p4(1+offset:offset+ncn)>1)) warning('Your prior allows for correlations between measurement errors larger than +-1 and will not integrate to 1 due to truncation. Please change your prior') end end @@ -142,9 +142,9 @@ if ~isequal(DynareOptions.mode_compute,11) || ... fprintf('initial_estimation_checks:: If you think the latter is the case, you should try with different initial values for the estimated parameters.\n') error('initial_estimation_checks:: The forecast error variance in the multivariate Kalman filter became singular.') end - %reset options + %reset options DynareOptions.use_univariate_filters_if_singularity_is_detected=use_univariate_filters_if_singularity_is_detected_old; -else +else info=0; fval = 0; end @@ -171,8 +171,8 @@ if info(1) > 0 error('Your model has at least one unit root and you are using a nonlinear filter. Please set nonlinear_filter_initialization=3.') end else - disp('Error in computing likelihood for initial parameter values') - print_info(info, DynareOptions.noprint, DynareOptions) + disp('Error in computing likelihood for initial parameter values') + print_info(info, DynareOptions.noprint, DynareOptions) end end diff --git a/matlab/initialize_from_mode.m b/matlab/initialize_from_mode.m index d7c11a9d0d..2e5707158f 100644 --- a/matlab/initialize_from_mode.m +++ b/matlab/initialize_from_mode.m @@ -1,13 +1,13 @@ function estim_params_ = initialize_from_mode(fname,M_,estim_params_) % function estim_params_ = initialize_from_mode(fname,M_,estim_params_) % initialize parameters and initial value of estimated parameters -% from a *_mode.mat file -% +% from a *_mode.mat file +% % INPUTS % fname: mode file name (*.mat file) % M_: sructure of model characteristics % estim_params_: structure of estimated parameters -% +% % OUTPUTS % estim_params: modified structure of estimated parameters % @@ -99,4 +99,3 @@ for i=1:length(parameter_names) end error([name 'doesn''t exist in this model']) end - diff --git a/matlab/initvalf.m b/matlab/initvalf.m index 91c0237060..9d6ae9bc10 100644 --- a/matlab/initvalf.m +++ b/matlab/initvalf.m @@ -1,7 +1,7 @@ function initvalf(fname_) % function initvalf(fname_) % -% Reads an initial path from the 'fname_' file for exogenous and endogenous variables +% Reads an initial path from the 'fname_' file for exogenous and endogenous variables % % INPUTS % fname_: name of the function or file containing the data @@ -58,15 +58,15 @@ if ~exist(fullname) end switch (extension) - case '.m' - eval(basename); - case '.mat' - load(basename); - case { '.xls', '.xlsx' } - [data_,names_v_]=xlsread(fullname); % Octave needs the extension explicitly - series_=0; - otherwise - error(['Unsupported extension for datafile: ' extension]) + case '.m' + eval(basename); + case '.mat' + load(basename); + case { '.xls', '.xlsx' } + [data_,names_v_]=xlsread(fullname); % Octave needs the extension explicitly + series_=0; + otherwise + error(['Unsupported extension for datafile: ' extension]) end options_.initval_file = 1; @@ -79,7 +79,7 @@ for i_=1:size(M_.endo_names,1) if size(x_,2)>size(x_,1) %oo_.endo_simul must be collection of row vectors oo_.endo_simul = [oo_.endo_simul; x_]; else %transpose if column vector - oo_.endo_simul = [oo_.endo_simul; x_']; + oo_.endo_simul = [oo_.endo_simul; x_']; end else k_ = strmatch(deblank(M_.endo_names(i_,:)),names_v_,'exact'); @@ -87,7 +87,7 @@ for i_=1:size(M_.endo_names,1) error(['INITVAL_FILE: ' deblank(M_.endo_names(i_,:)) ' not found']) end x_ = data_(:,k_); - oo_.endo_simul = [oo_.endo_simul; x_']; + oo_.endo_simul = [oo_.endo_simul; x_']; end end @@ -97,7 +97,7 @@ for i_=1:size(M_.exo_names,1) if size(x_,2)>size(x_,1) %oo_.endo_simul must be collection of row vectors oo_.exo_simul = [oo_.exo_simul x_']; else %if column vector - oo_.exo_simul = [oo_.exo_simul x_]; + oo_.exo_simul = [oo_.exo_simul x_]; end else k_ = strmatch(deblank(M_.exo_names(i_,:)),names_v_,'exact'); @@ -105,6 +105,6 @@ for i_=1:size(M_.exo_names,1) error(['INITVAL_FILE: ' deblank(M_.exo_names(i_,:)) ' not found']) end x_ = data_(:,k_); - oo_.exo_simul = [oo_.exo_simul x_]; + oo_.exo_simul = [oo_.exo_simul x_]; end end \ No newline at end of file diff --git a/matlab/interpret_resol_info.m b/matlab/interpret_resol_info.m index de16d47e09..e35dbe6966 100644 --- a/matlab/interpret_resol_info.m +++ b/matlab/interpret_resol_info.m @@ -1,14 +1,14 @@ function message = interpret_resol_info(info) - + % Returns a message describing problem encountered during the resolution of % a model. % -% INPUTS +% INPUTS % - info [struct] Second output argument return by the resol routine % -% OUTPUTS +% OUTPUTS % - message [string] Description of the issue preventing model's resolution. - + % Copyright (C) 2001-2016 Dynare Team % % This file is part of Dynare. diff --git a/matlab/irf.m b/matlab/irf.m index f4be40503a..13c8f36c19 100644 --- a/matlab/irf.m +++ b/matlab/irf.m @@ -2,7 +2,7 @@ function y = irf(dr, e1, long, drop, replic, iorder) % function y = irf(dr, e1, long, drop, replic, iorder) % Computes impulse response functions -% +% % INPUTS % dr: structure of decisions rules for stochastic simulations % e1: exogenous variables value in time 1 after one shock @@ -13,7 +13,7 @@ function y = irf(dr, e1, long, drop, replic, iorder) % % OUTPUTS % y: impulse response matrix -% +% % SPECIAL REQUIREMENTS % none @@ -60,7 +60,7 @@ else for j = 1: replic ex1(:,i_exo_var) = randn(long+drop,nxs)*chol_S; ex2 = ex1; - ex2(drop+1,:) = ex2(drop+1,:)+e1'; + 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)); diff --git a/matlab/isolder.m b/matlab/isolder.m index 091455ad07..534ba54387 100644 --- a/matlab/isolder.m +++ b/matlab/isolder.m @@ -2,12 +2,12 @@ function b = isolder(f, F) % --*-- Unitary tests --*-- % Returns true if f is older than any file in folder (and subfolders) F. % -% INPUTS +% INPUTS % - f [string] file name % - F [string] folder name % -% OUTPUT -% - b [logical] +% OUTPUT +% - b [logical] % Copyright (C) 2015 Dynare Team % @@ -29,9 +29,9 @@ function b = isolder(f, F) % --*-- Unitary tests --*-- if nargin<2 || isempty(F) F = pwd(); end - + b = true; - + files = dir(F); tfile = dir(f); tdate = tfile.datenum; diff --git a/matlab/k_order_pert.m b/matlab/k_order_pert.m index 6de7a7607a..05c56eb37a 100644 --- a/matlab/k_order_pert.m +++ b/matlab/k_order_pert.m @@ -27,45 +27,45 @@ endo_nbr = M.endo_nbr; exo_nbr = M.exo_nbr; nspred = M.nspred; -if order>1 && options.loglinear - error('The loglinear-option currently only works at order 1') +if order>1 && options.loglinear + error('The loglinear-option currently only works at order 1') end if M.maximum_endo_lead == 0 && order>1 - error(['2nd and 3rd order approximation not implemented for purely ' ... - 'backward models']) + error(['2nd and 3rd order approximation not implemented for purely ' ... + 'backward models']) end switch(order) case 1 [err, g_1] = k_order_perturbation(dr,M,options); if err - info(1)=9; - return + info(1)=9; + return end dr.g_1 = g_1; case 2 [err, g_0, g_1, g_2] = k_order_perturbation(dr,M,options); if err - info(1)=9; - return + info(1)=9; + return end dr.g_0 = g_0; dr.g_1 = g_1; dr.g_2 = g_2; case 3 - if options.pruning + if options.pruning [err, g_0, g_1, g_2, g_3, derivs] = k_order_perturbation(dr, ... M,options); if err - info(1)=9; - return + info(1)=9; + return end else [err, g_0, g_1, g_2, g_3] = k_order_perturbation(dr, ... M,options); if err - info(1)=9; - return + info(1)=9; + return end end dr.g_0 = g_0; @@ -119,7 +119,7 @@ else if s1 > s0 ghxx(:,s1*nspred+s0+1) = 2*g_2(:,i); end - elseif s0 < nspred && s1 < nspred+exo_nbr + elseif s0 < nspred && s1 < nspred+exo_nbr ghxu(:,(s0*exo_nbr+s1-nspred+1)) = 2*g_2(:,i); elseif s0 < nspred+exo_nbr && s1 < nspred+exo_nbr ghuu(:,(s0-nspred)*exo_nbr+s1-nspred +1) = 2*g_2(:,i); @@ -132,7 +132,7 @@ else s1 = s1+1; if s1 == nspred+exo_nbr s0 = s0+1; - s1 = s0; + s1 = s0; end end % for loop dr.ghxx = ghxx; @@ -186,7 +186,7 @@ for i=1:n1 m = m + 1; end end -end +end function y = unfold12(x,n1,n2) y = zeros(size(x,1),n1*n2*n2); @@ -203,7 +203,3 @@ for i=1:n1 end end end - - - - diff --git a/matlab/kalman/build_selection_matrix.m b/matlab/kalman/build_selection_matrix.m index f78662ddb0..adec3f3306 100644 --- a/matlab/kalman/build_selection_matrix.m +++ b/matlab/kalman/build_selection_matrix.m @@ -17,7 +17,7 @@ function Z = build_selection_matrix(mf,m,p) % 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/>. +% along with Dynare. If not, see <http://www.gnu.org/licenses/>. Z = zeros(p,m); for i=1:p Z(i,mf(i)) = 1; diff --git a/matlab/kalman/likelihood/computeDLIK.m b/matlab/kalman/likelihood/computeDLIK.m index d30b3f607f..0fc417220c 100644 --- a/matlab/kalman/likelihood/computeDLIK.m +++ b/matlab/kalman/likelihood/computeDLIK.m @@ -22,19 +22,19 @@ function [Da,DP,DLIK,D2a,D2P,Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,P,iF,Da,DY persistent DK DF D2K D2F if notsteady -if Zflag - [DK,DF,DP1] = computeDKalmanZ(T,DT,DOm,P,DP,DH,Z,iF,K); - if nargout>4 - [D2K,D2F,D2P] = computeD2KalmanZ(T,DT,D2T,D2Om,P,DP,D2P,DH,Z,iF,K,DK); - end -else - [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,Z,iF,K); - if nargout>4 - [D2K,D2F,D2P] = computeD2Kalman(T,DT,D2T,D2Om,P,DP,D2P,DH,Z,iF,K,DK); + if Zflag + [DK,DF,DP1] = computeDKalmanZ(T,DT,DOm,P,DP,DH,Z,iF,K); + if nargout>4 + [D2K,D2F,D2P] = computeD2KalmanZ(T,DT,D2T,D2Om,P,DP,D2P,DH,Z,iF,K,DK); + end + else + [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,Z,iF,K); + if nargout>4 + [D2K,D2F,D2P] = computeD2Kalman(T,DT,D2T,D2Om,P,DP,D2P,DH,Z,iF,K,DK); + end end -end -DP=DP1; -clear DP1 + DP=DP1; + clear DP1 else DP=DP; if nargout>4 @@ -47,20 +47,20 @@ Dv=zeros(length(v),k); for ii = 1:k if Zflag Dv(:,ii) = -Z*Da(:,ii) - Z*DYss(:,ii); -% if nargout>4, -% for jj = 1:ii -% D2v(:,jj,ii) = -Z*D2Yss(:,jj,ii) - Z*D2a(:,jj,ii); -% D2v(:,ii,jj) = D2v(:,jj,ii); -% end -% end + % if nargout>4, + % for jj = 1:ii + % D2v(:,jj,ii) = -Z*D2Yss(:,jj,ii) - Z*D2a(:,jj,ii); + % D2v(:,ii,jj) = D2v(:,jj,ii); + % end + % end else Dv(:,ii) = -Da(Z,ii) - DYss(Z,ii); -% if nargout>4, -% for jj = 1:ii -% D2v(:,jj,ii) = -D2Yss(Z,jj,ii) - D2a(Z,jj,ii); -% D2v(:,ii,jj) = D2v(:,jj,ii); -% end -% end + % if nargout>4, + % for jj = 1:ii + % D2v(:,jj,ii) = -D2Yss(Z,jj,ii) - D2a(Z,jj,ii); + % D2v(:,ii,jj) = D2v(:,jj,ii); + % end + % end end end @@ -71,7 +71,7 @@ for ii = 1:k % dai = da(:,:,ii); dKi = DK(:,:,ii); dtmp(:,ii) = Da(:,ii)+dKi*v+K*Dv(:,ii); - + if nargout>4 diFi = -iF*DF(:,:,ii)*iF; for jj = 1:ii @@ -82,9 +82,9 @@ for ii = 1:k d2Kij = D2K(:,:,jj,ii); d2Fij = D2F(:,:,jj,ii); d2iFij = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi; -% dtmpj = Da(:,jj)+dKj*v+K*Dv(:,jj); - -% d2vij = D2v(:,ii,jj); + % dtmpj = Da(:,jj)+dKj*v+K*Dv(:,jj); + + % d2vij = D2v(:,ii,jj); if Zflag d2vij = -Z*D2Yss(:,jj,ii) - Z*D2a(:,jj,ii); else @@ -93,13 +93,13 @@ for ii = 1:k d2tmpij = D2a(:,jj,ii) + d2Kij*v + dKj*Dv(:,ii) + dKi*Dv(:,jj) + K*d2vij; D2a(:,jj,ii) = reshape(D2T(:,jcount),size(T))*tmp + DT(:,:,jj)*dtmp(:,ii) + DT(:,:,ii)*dtmp(:,jj) + T*d2tmpij; D2a(:,ii,jj) = D2a(:,jj,ii); - + if nargout==6 Hesst(ii,jj) = getHesst_ij(v,Dv(:,ii),Dv(:,jj),d2vij,iF,diFi,diFj,d2iFij,dFj,d2Fij); end end end - + Da(:,ii) = DT(:,:,ii)*tmp + T*dtmp(:,ii); DLIK(ii,1) = trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v; end @@ -108,16 +108,16 @@ if nargout==4 % Hesst(ii,jj) = getHesst_ij(v,Dv(:,ii),Dv(:,jj),0,iF,diFi,diFj,0,dFj,0); vecDPmf = reshape(DF,[],k); D2a = 2*Dv'*iF*Dv + (vecDPmf' * kron(iF,iF) * vecDPmf); -% for ii = 1:k -% -% diFi = -iF*DF(:,:,ii)*iF; -% for jj = 1:ii -% dFj = DF(:,:,jj); -% diFj = -iF*DF(:,:,jj)*iF; -% -% Hesst(ii,jj) = getHesst_ij(v*0,Dv(:,ii),Dv(:,jj),v*0,iF,diFi,diFj,0,-dFj,0); -% end -% end + % for ii = 1:k + % + % diFi = -iF*DF(:,:,ii)*iF; + % for jj = 1:ii + % dFj = DF(:,:,jj); + % diFj = -iF*DF(:,:,jj)*iF; + % + % Hesst(ii,jj) = getHesst_ij(v*0,Dv(:,ii),Dv(:,jj),v*0,iF,diFi,diFj,0,-dFj,0); + % end + % end end % end of computeDLIK @@ -168,9 +168,9 @@ end function [d2K,d2S,d2P1] = computeD2Kalman(A,dA,d2A,d2Om,P0,dP0,d2P1,DH,Z,iF,K0,dK0) % computes the second derivatives of the Kalman matrices % note: A=T in main func. - - k = size(dA,3); - tmp = P0-K0*P0(Z,:); + +k = size(dA,3); +tmp = P0-K0*P0(Z,:); [ns,no] = size(K0); % CPC = C*P0*C'; CPC = .5*(CPC+CPC');iF = inv(CPC); @@ -186,14 +186,14 @@ jcount=0; for ii = 1:k dAi = dA(:,:,ii); dFi = dP0(Z,Z,ii); -% d2Omi = d2Om(:,:,ii); + % d2Omi = d2Om(:,:,ii); diFi = -iF*dFi*iF; dKi = dK0(:,:,ii); for jj = 1:ii jcount=jcount+1; dAj = dA(:,:,jj); dFj = dP0(Z,Z,jj); -% d2Omj = d2Om(:,:,jj); + % d2Omj = d2Om(:,:,jj); dFj = dP0(Z,Z,jj); diFj = -iF*dFj*iF; dKj = dK0(:,:,jj); @@ -201,33 +201,33 @@ for ii = 1:k d2Aij = reshape(d2A(:,jcount),[ns ns]); d2Pij = dyn_unvech(d2P1(:,jcount)); d2Omij = dyn_unvech(d2Om(:,jcount)); - - % second order - - d2Fij = d2Pij(Z,Z) ; - -% d2APC = d2Aij*P0*C' + A*d2Pij*C' + A*P0*d2Cij' + dAi*dPj*C' + dAj*dPi*C' + A*dPj*dCi' + A*dPi*dCj' + dAi*P0*dCj' + dAj*P0*dCi'; - d2APC = d2Pij(:,Z); - - d2iF = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi; - - d2Kij= d2Pij(:,Z)*iF + P0(:,Z)*d2iF + dP0(:,Z,jj)*diFi + dP0(:,Z,ii)*diFj; - - d2KCP = d2Kij*P0(Z,:) + K0*d2Pij(Z,:) + dKi*dP0(Z,:,jj) + dKj*dP0(Z,:,ii) ; - - dtmpi = dP0(:,:,ii) - dK0(:,:,ii)*P0(Z,:) - K0*dP0(Z,:,ii); - dtmpj = dP0(:,:,jj) - dK0(:,:,jj)*P0(Z,:) - K0*dP0(Z,:,jj); - d2tmp = d2Pij - d2KCP; - - d2AtmpA = d2Aij*tmp*A' + A*d2tmp*A' + A*tmp*d2Aij' + dAi*dtmpj*A' + dAj*dtmpi*A' + A*dtmpj*dAi' + A*dtmpi*dAj' + dAi*tmp*dAj' + dAj*tmp*dAi'; - - d2K(:,:,ii,jj) = d2Kij; %#ok<NASGU> - d2P1(:,jcount) = dyn_vech(d2AtmpA + d2Omij); %#ok<*NASGU> - d2S(:,:,ii,jj) = d2Fij; - d2K(:,:,jj,ii) = d2Kij; %#ok<NASGU> -% d2P1(:,:,jj,ii) = d2AtmpA + d2Omij; %#ok<*NASGU> - d2S(:,:,jj,ii) = d2Fij; -% d2iS(:,:,ii,jj) = d2iF; + + % second order + + d2Fij = d2Pij(Z,Z) ; + + % d2APC = d2Aij*P0*C' + A*d2Pij*C' + A*P0*d2Cij' + dAi*dPj*C' + dAj*dPi*C' + A*dPj*dCi' + A*dPi*dCj' + dAi*P0*dCj' + dAj*P0*dCi'; + d2APC = d2Pij(:,Z); + + d2iF = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi; + + d2Kij= d2Pij(:,Z)*iF + P0(:,Z)*d2iF + dP0(:,Z,jj)*diFi + dP0(:,Z,ii)*diFj; + + d2KCP = d2Kij*P0(Z,:) + K0*d2Pij(Z,:) + dKi*dP0(Z,:,jj) + dKj*dP0(Z,:,ii) ; + + dtmpi = dP0(:,:,ii) - dK0(:,:,ii)*P0(Z,:) - K0*dP0(Z,:,ii); + dtmpj = dP0(:,:,jj) - dK0(:,:,jj)*P0(Z,:) - K0*dP0(Z,:,jj); + d2tmp = d2Pij - d2KCP; + + d2AtmpA = d2Aij*tmp*A' + A*d2tmp*A' + A*tmp*d2Aij' + dAi*dtmpj*A' + dAj*dtmpi*A' + A*dtmpj*dAi' + A*dtmpi*dAj' + dAi*tmp*dAj' + dAj*tmp*dAi'; + + d2K(:,:,ii,jj) = d2Kij; %#ok<NASGU> + d2P1(:,jcount) = dyn_vech(d2AtmpA + d2Omij); %#ok<*NASGU> + d2S(:,:,ii,jj) = d2Fij; + d2K(:,:,jj,ii) = d2Kij; %#ok<NASGU> + % d2P1(:,:,jj,ii) = d2AtmpA + d2Omij; %#ok<*NASGU> + d2S(:,:,jj,ii) = d2Fij; + % d2iS(:,:,ii,jj) = d2iF; end end @@ -236,9 +236,9 @@ end function [d2K,d2S,d2P1] = computeD2KalmanZ(A,dA,d2A,d2Om,P0,dP0,d2P1,DH,Z,iF,K0,dK0) % computes the second derivatives of the Kalman matrices % note: A=T in main func. - - k = size(dA,3); - tmp = P0-K0*Z*P0(:,:); + +k = size(dA,3); +tmp = P0-K0*Z*P0(:,:); [ns,no] = size(K0); % CPC = C*P0*C'; CPC = .5*(CPC+CPC');iF = inv(CPC); @@ -254,14 +254,14 @@ jcount=0; for ii = 1:k dAi = dA(:,:,ii); dFi = Z*dP0(:,:,ii)*Z; -% d2Omi = d2Om(:,:,ii); + % d2Omi = d2Om(:,:,ii); diFi = -iF*dFi*iF; dKi = dK0(:,:,ii); for jj = 1:ii jcount=jcount+1; dAj = dA(:,:,jj); dFj = Z*dP0(:,:,jj)*Z; -% d2Omj = d2Om(:,:,jj); + % d2Omj = d2Om(:,:,jj); dFj = Z*dP0(:,:,jj)*Z; diFj = -iF*dFj*iF; dKj = dK0(:,:,jj); @@ -269,36 +269,34 @@ for ii = 1:k d2Aij = reshape(d2A(:,jcount),[ns ns]); d2Pij = dyn_unvech(d2P1(:,jcount)); d2Omij = dyn_unvech(d2Om(:,jcount)); - - % second order - - d2Fij = Z*d2Pij(:,:)*Z ; - -% d2APC = d2Aij*P0*C' + A*d2Pij*C' + A*P0*d2Cij' + dAi*dPj*C' + dAj*dPi*C' + A*dPj*dCi' + A*dPi*dCj' + dAi*P0*dCj' + dAj*P0*dCi'; - d2APC = d2Pij(:,:)*Z; - - d2iF = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi; - - d2Kij= d2Pij(:,:)*Z*iF + P0(:,:)*Z*d2iF + dP0(:,:,jj)*Z*diFi + dP0(:,:,ii)*Z*diFj; - - d2KCP = d2Kij*Z*P0(:,:) + K0*Z*d2Pij(:,:) + dKi*Z*dP0(:,:,jj) + dKj*Z*dP0(:,:,ii) ; - - dtmpi = dP0(:,:,ii) - dK0(:,:,ii)*Z*P0(:,:) - K0*Z*dP0(:,:,ii); - dtmpj = dP0(:,:,jj) - dK0(:,:,jj)*Z*P0(:,:) - K0*Z*dP0(:,:,jj); - d2tmp = d2Pij - d2KCP; - - d2AtmpA = d2Aij*tmp*A' + A*d2tmp*A' + A*tmp*d2Aij' + dAi*dtmpj*A' + dAj*dtmpi*A' + A*dtmpj*dAi' + A*dtmpi*dAj' + dAi*tmp*dAj' + dAj*tmp*dAi'; - - d2K(:,:,ii,jj) = d2Kij; %#ok<NASGU> - d2P1(:,jcount) = dyn_vech(d2AtmpA + d2Omij); %#ok<*NASGU> - d2S(:,:,ii,jj) = d2Fij; -% d2iS(:,:,ii,jj) = d2iF; - d2K(:,:,jj,ii) = d2Kij; %#ok<NASGU> -% d2P1(:,:,jj,ii) = d2AtmpA + d2Omij; %#ok<*NASGU> - d2S(:,:,jj,ii) = d2Fij; + + % second order + + d2Fij = Z*d2Pij(:,:)*Z ; + + % d2APC = d2Aij*P0*C' + A*d2Pij*C' + A*P0*d2Cij' + dAi*dPj*C' + dAj*dPi*C' + A*dPj*dCi' + A*dPi*dCj' + dAi*P0*dCj' + dAj*P0*dCi'; + d2APC = d2Pij(:,:)*Z; + + d2iF = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi; + + d2Kij= d2Pij(:,:)*Z*iF + P0(:,:)*Z*d2iF + dP0(:,:,jj)*Z*diFi + dP0(:,:,ii)*Z*diFj; + + d2KCP = d2Kij*Z*P0(:,:) + K0*Z*d2Pij(:,:) + dKi*Z*dP0(:,:,jj) + dKj*Z*dP0(:,:,ii) ; + + dtmpi = dP0(:,:,ii) - dK0(:,:,ii)*Z*P0(:,:) - K0*Z*dP0(:,:,ii); + dtmpj = dP0(:,:,jj) - dK0(:,:,jj)*Z*P0(:,:) - K0*Z*dP0(:,:,jj); + d2tmp = d2Pij - d2KCP; + + d2AtmpA = d2Aij*tmp*A' + A*d2tmp*A' + A*tmp*d2Aij' + dAi*dtmpj*A' + dAj*dtmpi*A' + A*dtmpj*dAi' + A*dtmpi*dAj' + dAi*tmp*dAj' + dAj*tmp*dAi'; + + d2K(:,:,ii,jj) = d2Kij; %#ok<NASGU> + d2P1(:,jcount) = dyn_vech(d2AtmpA + d2Omij); %#ok<*NASGU> + d2S(:,:,ii,jj) = d2Fij; + % d2iS(:,:,ii,jj) = d2iF; + d2K(:,:,jj,ii) = d2Kij; %#ok<NASGU> + % d2P1(:,:,jj,ii) = d2AtmpA + d2Omij; %#ok<*NASGU> + d2S(:,:,jj,ii) = d2Fij; end end % end of computeD2KalmanZ - - diff --git a/matlab/kalman/likelihood/kalman_filter.m b/matlab/kalman/likelihood/kalman_filter.m index 4802a00cf3..441ee85251 100644 --- a/matlab/kalman/likelihood/kalman_filter.m +++ b/matlab/kalman/likelihood/kalman_filter.m @@ -132,7 +132,7 @@ else DLIK = zeros(k,1); % Initialization of the score. Da = zeros(mm,k); % Derivative State vector. dlikk = zeros(smpl,k); - + if Zflag==0 C = zeros(pp,mm); for ii=1:pp, C(ii,Z(ii))=1; end % SELECTION MATRIX IN MEASUREMENT EQ. (FOR WHEN IT IS NOT CONSTANT) @@ -237,7 +237,7 @@ if analytic_derivation dlikk = dlikk/2; if analytic_derivation==2 || asy_hess if asy_hess==0 - Hess = Hess + tril(Hess,-1)'; + Hess = Hess + tril(Hess,-1)'; end Hess = -Hess/2; end diff --git a/matlab/kalman/likelihood/kalman_filter_d.m b/matlab/kalman/likelihood/kalman_filter_d.m index a10cf6f4d2..0877442cfc 100644 --- a/matlab/kalman/likelihood/kalman_filter_d.m +++ b/matlab/kalman/likelihood/kalman_filter_d.m @@ -1,7 +1,7 @@ function [dLIK,dlik,a,Pstar] = kalman_filter_d(Y, start, last, a, Pinf, Pstar, kalman_tol, diffuse_kalman_tol, riccati_tol, presample, T, R, Q, H, Z, mm, pp, rr) % Computes the diffuse likelihood of a state space model. % -% INPUTS +% INPUTS % Y [double] pp*smpl matrix of (detrended) data, where pp is the number of observed variables. % start [integer] scalar, first observation. % last [integer] scalar, last observation. @@ -10,28 +10,28 @@ function [dLIK,dlik,a,Pstar] = kalman_filter_d(Y, start, last, a, Pinf, Pstar, k % Pstar [double] mm*mm matrix used to initialize the covariance matrix of the state vector. % kalman_tol [double] scalar, tolerance parameter (rcond) of F_star. % diffuse_kalman_tol [double] scalar, tolerance parameter (rcond) of Pinf to signify end of diffuse filtering and Finf. -% riccati_tol [double] scalar, tolerance parameter (riccati iteration); +% riccati_tol [double] scalar, tolerance parameter (riccati iteration); % not used in this filter as usually diffuse phase will be left before convergence of filter to steady state. -% presample [integer] scalar, presampling if strictly positive. +% presample [integer] scalar, presampling if strictly positive. % T [double] mm*mm matrix, transition matrix in the state equations. % R [double] mm*rr matrix relating the structural innovations to the state vector. % Q [double] rr*rr covariance matrix of the structural innovations. -% H [double] pp*pp covariance matrix of the measurement errors (if H is equal to zero (scalar) there is no measurement error). +% H [double] pp*pp covariance matrix of the measurement errors (if H is equal to zero (scalar) there is no measurement error). % Z [double] pp*mm matrix, selection matrix or pp linear independent combinations of the state vector. % mm [integer] scalar, number of state variables. % pp [integer] scalar, number of observed variables. -% rr [integer] scalar, number of structural innovations. -% -% OUTPUTS +% rr [integer] scalar, number of structural innovations. +% +% OUTPUTS % LIK [double] scalar, minus loglikelihood % lik [double] smpl*1 vector, log density of each vector of observations. % a [double] mm*1 vector, current estimate of the state vector. -% Pstar [double] mm*mm matrix, covariance matrix of the state vector. -% -% REFERENCES +% Pstar [double] mm*mm matrix, covariance matrix of the state vector. +% +% 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. +% Models", S.J. Koopman and J. Durbin (2003), in Journal of Time Series +% Analysis, vol. 24(1), pp. 85-98. % and % Durbin/Koopman (2012): "Time Series Analysis by State Space Methods", Oxford University Press, % Second Edition, Ch. 5 and 7.2 @@ -69,10 +69,10 @@ while rank(Pinf,diffuse_kalman_tol) && (t<=last) s = t-start+1; v = Y(:,t)-Z*a; %get prediction error v^(0) in (5.13) DK (2012) Finf = Z*Pinf*Z'; % (5.7) in DK (2012) - %do case distinction based on whether F_{\infty,t} has full rank or 0 rank - if rcond(Finf) < diffuse_kalman_tol %F_{\infty,t} = 0 + %do case distinction based on whether F_{\infty,t} has full rank or 0 rank + if rcond(Finf) < diffuse_kalman_tol %F_{\infty,t} = 0 if ~all(abs(Finf(:)) < diffuse_kalman_tol) %rank-deficient but not rank 0 - % The univariate diffuse kalman filter should be used instead. + % The univariate diffuse kalman filter should be used instead. return else %rank of F_{\infty,t} is 0 Fstar = Z*Pstar*Z' + H; % (5.7) in DK (2012) @@ -81,8 +81,8 @@ while rank(Pinf,diffuse_kalman_tol) && (t<=last) % The univariate diffuse kalman filter should be used. return else %rank 0 - %pathological case, discard draw - return + %pathological case, discard draw + return end else iFstar = inv(Fstar); @@ -95,15 +95,15 @@ while rank(Pinf,diffuse_kalman_tol) && (t<=last) end end else %F_{\infty,t} positive definite - %To compare to DK (2012), this block makes use of the following transformation - %Kstar=T^{-1}*K^{(1)}=M_{*}*F^{(1)}+M_{\infty}*F^{(2)} - % =P_{*}*Z'*F^{(1)}+P_{\infty}*Z'*((-1)*(-F_{\infty}^{-1})*F_{*}*(F_{\infty}^{-1})) - % =[P_{*}*Z'-Kinf*F_{*})]*F^{(1)} - %Make use of L^{0}'=(T-K^{(0)}*Z)'=(T-T*M_{\infty}*F^{(1)}*Z)' - % =(T-T*P_{\infty*Z'*F^{(1)}*Z)'=(T-T*Kinf*Z)' - % = (T*(I-*Kinf*Z))'=(I-Z'*Kinf')*T' - %P_{*}=T*P_{\infty}*L^{(1)}+T*P_{*}*L^{(0)}+RQR - % =T*[(P_{\infty}*(-K^{(1)*Z}))+P_{*}*(I-Z'*Kinf')*T'+RQR] + %To compare to DK (2012), this block makes use of the following transformation + %Kstar=T^{-1}*K^{(1)}=M_{*}*F^{(1)}+M_{\infty}*F^{(2)} + % =P_{*}*Z'*F^{(1)}+P_{\infty}*Z'*((-1)*(-F_{\infty}^{-1})*F_{*}*(F_{\infty}^{-1})) + % =[P_{*}*Z'-Kinf*F_{*})]*F^{(1)} + %Make use of L^{0}'=(T-K^{(0)}*Z)'=(T-T*M_{\infty}*F^{(1)}*Z)' + % =(T-T*P_{\infty*Z'*F^{(1)}*Z)'=(T-T*Kinf*Z)' + % = (T*(I-*Kinf*Z))'=(I-Z'*Kinf')*T' + %P_{*}=T*P_{\infty}*L^{(1)}+T*P_{*}*L^{(0)}+RQR + % =T*[(P_{\infty}*(-K^{(1)*Z}))+P_{*}*(I-Z'*Kinf')*T'+RQR] dlik(s)= log(det(Finf)); %set w_t to top case in bottom equation page 172, DK (2012) iFinf = inv(Finf); Kinf = Pinf*Z'*iFinf; %define Kinf=T^{-1}*K_0 with M_{\infty}=Pinf*Z' @@ -117,7 +117,7 @@ while rank(Pinf,diffuse_kalman_tol) && (t<=last) end if t>last - warning(['kalman_filter_d: There isn''t enough information to estimate the initial conditions of the nonstationary variables. The diffuse Kalman filter never left the diffuse stage.']); + warning(['kalman_filter_d: There isn''t enough information to estimate the initial conditions of the nonstationary variables. The diffuse Kalman filter never left the diffuse stage.']); dLIK = NaN; return end diff --git a/matlab/kalman/likelihood/kalman_filter_fast.m b/matlab/kalman/likelihood/kalman_filter_fast.m index f5bb08bae3..db3dec3b75 100644 --- a/matlab/kalman/likelihood/kalman_filter_fast.m +++ b/matlab/kalman/likelihood/kalman_filter_fast.m @@ -152,7 +152,7 @@ while notsteady && t<=last end if rcond(F) < kalman_tol if ~all(abs(F(:))<kalman_tol) - % The univariate diffuse kalman filter should be used. + % The univariate diffuse kalman filter should be used. return else %pathological case, discard draw @@ -199,7 +199,7 @@ if analytic_derivation dlikk = dlikk/2; if analytic_derivation==2 || asy_hess if asy_hess==0 - Hess = Hess + tril(Hess,-1)'; + Hess = Hess + tril(Hess,-1)'; end Hess = -Hess/2; end @@ -210,10 +210,10 @@ if t <= last if analytic_derivation if analytic_derivation==2 [tmp, tmp2] = kalman_filter_ss(Y,t,last,a,T,K,iF,dF,Z,pp,Zflag, ... - analytic_derivation,Da,DT,DYss,D2a,D2T,D2Yss); + analytic_derivation,Da,DT,DYss,D2a,D2T,D2Yss); else [tmp, tmp2] = kalman_filter_ss(Y,t,last,a,T,K,iF,dF,Z,pp,Zflag, ... - analytic_derivation,Da,DT,DYss,asy_hess); + analytic_derivation,Da,DT,DYss,asy_hess); end likk(s+1:end)=tmp2{1}; dlikk(s+1:end,:)=tmp2{2}; diff --git a/matlab/kalman/likelihood/missing_observations_kalman_filter.m b/matlab/kalman/likelihood/missing_observations_kalman_filter.m index 0b0c485330..f1bd40cb59 100644 --- a/matlab/kalman/likelihood/missing_observations_kalman_filter.m +++ b/matlab/kalman/likelihood/missing_observations_kalman_filter.m @@ -5,32 +5,32 @@ function [LIK, lik, a, P] = missing_observations_kalman_filter(data_index,numbe % data_index [cell] 1*smpl cell of column vectors of indices. % number_of_observations [integer] scalar. % no_more_missing_observations [integer] scalar. -% Y [double] pp*smpl matrix of data. +% Y [double] pp*smpl matrix of data. % start [integer] scalar, index of the first observation. % last [integer] scalar, index of the last observation. % a [double] pp*1 vector, initial level of the state vector. % P [double] pp*pp matrix, covariance matrix of the initial state vector. % kalman_tol [double] scalar, tolerance parameter (rcond). -% riccati_tol [double] scalar, tolerance parameter (riccati iteration). +% riccati_tol [double] scalar, tolerance parameter (riccati iteration). % presample [integer] scalar, presampling if strictly positive. % T [double] mm*mm transition matrix of the state equation. -% Q [double] rr*rr covariance matrix of the structural innovations. +% Q [double] rr*rr covariance matrix of the structural innovations. % R [double] mm*rr matrix, mapping structural innovations to state variables. -% H [double] pp*pp (or 1*1 =0 if no measurement error) covariance matrix of the measurement errors. -% Z [integer] pp*1 vector of indices for the observed variables. +% H [double] pp*pp (or 1*1 =0 if no measurement error) covariance matrix of the measurement errors. +% Z [integer] pp*1 vector of indices for the observed variables. % mm [integer] scalar, dimension of the state vector. % pp [integer] scalar, number of observed variables. -% rr [integer] scalar, number of structural innovations. -% -% OUTPUTS +% rr [integer] scalar, number of structural innovations. +% +% OUTPUTS % LIK [double] scalar, MINUS loglikelihood % lik [double] vector, density of observations in each period. % a [double] mm*1 vector, estimated level of the states. -% P [double] mm*mm matrix, covariance matrix of the states. -% +% P [double] mm*mm matrix, covariance matrix of the states. +% % % NOTES -% The vector "lik" is used to evaluate the jacobian of the likelihood. +% The vector "lik" is used to evaluate the jacobian of the likelihood. % Copyright (C) 2004-2017 Dynare Team % diff --git a/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m b/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m index a497d6e53f..c290f17930 100644 --- a/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m +++ b/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m @@ -1,11 +1,11 @@ function [dLIK,dlik,a,Pstar] = missing_observations_kalman_filter_d(data_index,number_of_observations,no_more_missing_observations, ... - Y, start, last, ... - a, Pinf, Pstar, ... - kalman_tol, diffuse_kalman_tol, riccati_tol, presample, ... - T, R, Q, H, Z, mm, pp, rr) + Y, start, last, ... + a, Pinf, Pstar, ... + kalman_tol, diffuse_kalman_tol, riccati_tol, presample, ... + T, R, Q, H, Z, mm, pp, rr) % Computes the diffuse likelihood of a state space model when some observations are missing. % -% INPUTS +% INPUTS % data_index [cell] 1*smpl cell of column vectors of indices. % number_of_observations [integer] scalar. % no_more_missing_observations [integer] scalar. @@ -17,31 +17,31 @@ function [dLIK,dlik,a,Pstar] = missing_observations_kalman_filter_d(data_index,n % Pstar [double] mm*mm matrix used to initialize the covariance matrix of the state vector. % kalman_tol [double] scalar, tolerance parameter (rcond). % riccati_tol [double] scalar, tolerance parameter (riccati iteration). -% presample [integer] scalar, presampling if strictly positive. +% presample [integer] scalar, presampling if strictly positive. % T [double] mm*mm matrix, transition matrix in the state equations. % R [double] mm*rr matrix relating the structural innovations to the state vector. % Q [double] rr*rr covariance matrix of the structural innovations. -% H [double] pp*pp covariance matrix of the measurement errors (if H is equal to zero (scalar) there is no measurement error). +% H [double] pp*pp covariance matrix of the measurement errors (if H is equal to zero (scalar) there is no measurement error). % Z [double] pp*mm matrix, selection matrix or pp linear independant combinations of the state vector. % mm [integer] scalar, number of state variables. % pp [integer] scalar, number of observed variables. -% rr [integer] scalar, number of structural innovations. -% -% OUTPUTS +% rr [integer] scalar, number of structural innovations. +% +% OUTPUTS % dLIK [double] scalar, MINUS loglikelihood % dlik [double] vector, density of observations in each period. % a [double] mm*1 vector, estimated level of the states. -% Pstar [double] mm*mm matrix, covariance matrix of the states. -% +% Pstar [double] mm*mm matrix, covariance matrix of the states. +% % 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. +% Models", S.J. Koopman and J. Durbin (2003), in Journal of Time Series +% Analysis, vol. 24(1), pp. 85-98. % and % Durbin/Koopman (2012): "Time Series Analysis by State Space Methods", Oxford University Press, % Second Edition, Ch. 5 and 7.2 -% +% % Copyright (C) 2004-2016 Dynare Team % % This file is part of Dynare. @@ -87,11 +87,11 @@ while rank(Pinf,diffuse_kalman_tol) && (t<=last) Pinf = T*Pinf*transpose(T); else ZZ = Z(d_index,:); %span selector matrix - v = Y(d_index,t)-ZZ*a; %get prediction error v^(0) in (5.13) DK (2012) + v = Y(d_index,t)-ZZ*a; %get prediction error v^(0) in (5.13) DK (2012) Finf = ZZ*Pinf*ZZ'; % (5.7) in DK (2012) - if rcond(Finf) < diffuse_kalman_tol %F_{\infty,t} = 0 + if rcond(Finf) < diffuse_kalman_tol %F_{\infty,t} = 0 if ~all(abs(Finf(:)) < diffuse_kalman_tol) %rank-deficient but not rank 0 - % The univariate diffuse kalman filter should be used. + % The univariate diffuse kalman filter should be used. return else %rank of F_{\infty,t} is 0 Fstar = ZZ*Pstar*ZZ' + H(d_index,d_index); % (5.7) in DK (2012) @@ -100,7 +100,7 @@ while rank(Pinf,diffuse_kalman_tol) && (t<=last) % The univariate diffuse kalman filter should be used. return else %rank 0 - %pathological case, discard draw + %pathological case, discard draw return end else @@ -129,7 +129,7 @@ while rank(Pinf,diffuse_kalman_tol) && (t<=last) end if t==(last+1) - warning(['kalman_filter_d: There isn''t enough information to estimate the initial conditions of the nonstationary variables. The diffuse Kalman filter never left the diffuse stage.']); + warning(['kalman_filter_d: There isn''t enough information to estimate the initial conditions of the nonstationary variables. The diffuse Kalman filter never left the diffuse stage.']); dLIK = NaN; return end diff --git a/matlab/kalman/likelihood/univariate_computeDLIK.m b/matlab/kalman/likelihood/univariate_computeDLIK.m index 009c0f6357..083fb12db9 100644 --- a/matlab/kalman/likelihood/univariate_computeDLIK.m +++ b/matlab/kalman/likelihood/univariate_computeDLIK.m @@ -47,7 +47,7 @@ if notsteady end end end - + else Dv = -Da(Z,:) - DYss(Z,:); DF = squeeze(DP(Z,Z,:))+DH'; @@ -67,7 +67,7 @@ if notsteady D2K(:,i,j) = D2K(:,i,j) -PZ*D2F(j,i)/F^2 - squeeze(DP(:,Z,i))*DF(j)/F^2 - ... squeeze(DP(:,Z,j))*DF(i)'/F^2 + 2/F^3*PZ*DF(i)'*DF(j); D2K(:,j,i) = D2K(:,i,j); -% D2K = squeeze(D2P(:,Z,:,:))/F; + % D2K = squeeze(D2P(:,Z,:,:))/F; end end end @@ -104,17 +104,17 @@ end DLIK = DF/F + 2*Dv'/F*v - v^2/F^2*DF; if nargout==6 Hesst = D2F/F-1/F^2*(DF*DF') + 2*D2v/F*v + 2*(Dv'*Dv)/F - 2*(DF*Dv)*v/F^2 ... - - v^2/F^2*D2F - 2*v/F^2*(Dv'*DF') + 2*v^2/F^3*(DF*DF'); + - v^2/F^2*D2F - 2*v/F^2*(Dv'*DF') + 2*v^2/F^3*(DF*DF'); elseif nargout==4 D2a = 1/F^2*(DF*DF') + 2*(Dv'*Dv)/F ; -% D2a = -1/F^2*(DF*DF') + 2*(Dv'*Dv)/F + 2*v^2/F^3*(DF*DF') ... -% - 2*(DF*Dv)*v/F^2 - 2*v/F^2*(Dv'*DF'); -% D2a = +2*(Dv'*Dv)/F + (DF' * DF)/F^2; + % D2a = -1/F^2*(DF*DF') + 2*(Dv'*Dv)/F + 2*v^2/F^3*(DF*DF') ... + % - 2*(DF*Dv)*v/F^2 - 2*v/F^2*(Dv'*DF'); + % D2a = +2*(Dv'*Dv)/F + (DF' * DF)/F^2; end Da = Da + DK*v+K*Dv; if nargout>4 - + D2a = D2a + D2K*v; for j=1:k % D2a(:,:,j) = D2a(:,:,j) + DK*Dv(j) + DK(:,j)*Dv + K*D2v(j,:); @@ -123,8 +123,8 @@ if nargout>4 D2a(:,i,j) = D2a(:,j,i); end end - - + + end if notsteady @@ -145,9 +145,9 @@ if notsteady jcount = jcount+1; tmp = dyn_unvech(D2P(:,jcount)); tmp = tmp - (tmp*Z')*K' - (DP(:,:,j)*Z')*DK(:,i)' ... - - (DP(:,:,i)*Z')*DK(:,j)' -PZ*D2K(:,j,i)'; + - (DP(:,:,i)*Z')*DK(:,j)' -PZ*D2K(:,j,i)'; D2P(:,jcount) = dyn_vech(tmp); -% D2P(:,:,i,j) = D2P(:,:,j,i); + % D2P(:,:,i,j) = D2P(:,:,j,i); end end else @@ -160,14 +160,12 @@ if notsteady D2PZ = tmp(:,Z); tmp = tmp - D2PZ*K' - DPZ(:,j)*DK(:,i)'- DPZ(:,i)*DK(:,j)' - PZ*squeeze(D2K(:,j,i))'; D2P(:,jcount) = dyn_vech(tmp); -% D2P(:,:,i,j) = D2P(:,:,j,i); + % D2P(:,:,i,j) = D2P(:,:,j,i); end end - + end end else DP1=DP; end - - diff --git a/matlab/kalman/likelihood/univariate_computeDstate.m b/matlab/kalman/likelihood/univariate_computeDstate.m index c21acd21ba..eecee428eb 100644 --- a/matlab/kalman/likelihood/univariate_computeDstate.m +++ b/matlab/kalman/likelihood/univariate_computeDstate.m @@ -43,14 +43,14 @@ if nargout>2 if notsteady tmp = dyn_unvech(D2P(:,jcount)); tmp = T*tmp*T' +DT(:,:,i)*DP(:,:,j)*T'+T*DP(:,:,j)*DT(:,:,i)' + ... - DT(:,:,j)*DP(:,:,i)*T'+T*DP(:,:,i)*DT(:,:,j)' + ... - DT(:,:,j)*P*DT(:,:,i)'+DT(:,:,i)*P*DT(:,:,j)'+ ... - reshape(D2T(:,jcount),size(T))*P*T'+T*P*reshape(D2T(:,jcount),size(T))' + ... - dyn_unvech(D2Om(:,jcount)); + DT(:,:,j)*DP(:,:,i)*T'+T*DP(:,:,i)*DT(:,:,j)' + ... + DT(:,:,j)*P*DT(:,:,i)'+DT(:,:,i)*P*DT(:,:,j)'+ ... + reshape(D2T(:,jcount),size(T))*P*T'+T*P*reshape(D2T(:,jcount),size(T))' + ... + dyn_unvech(D2Om(:,jcount)); D2P(:,jcount) = dyn_vech(tmp); -% D2P(:,:,i,j) = D2P(:,:,j,i); + % D2P(:,:,i,j) = D2P(:,:,j,i); end end end - + end diff --git a/matlab/kalman/likelihood/univariate_kalman_filter.m b/matlab/kalman/likelihood/univariate_kalman_filter.m index 2e831cc0de..add638a547 100644 --- a/matlab/kalman/likelihood/univariate_kalman_filter.m +++ b/matlab/kalman/likelihood/univariate_kalman_filter.m @@ -37,7 +37,7 @@ function [LIK, lik,a,P] = univariate_kalman_filter(data_index,number_of_observat %! @item Q %! Matrix (@var{rr}*@var{rr}) of doubles, covariance matrix of the structural innovations (noise in the state equation). %! @item R -%! Matrix (@var{mm}*@var{rr}) of doubles, +%! Matrix (@var{mm}*@var{rr}) of doubles, %! @item H %! Vector (@var{pp}) of doubles, diagonal of covariance matrix of the measurement errors (corelation among measurement errors is handled by a model transformation). %! @item Z @@ -76,9 +76,9 @@ function [LIK, lik,a,P] = univariate_kalman_filter(data_index,number_of_observat %! @ref{univariate_kalman_filter_ss} %! @end deftypefn %@eod: -% +% % Algorithm: -% +% % Uses the univariate filter as described in Durbin/Koopman (2012): "Time % Series Analysis by State Space Methods", Oxford University Press, % Second Edition, Ch. 6.4 + 7.2.5 @@ -136,7 +136,7 @@ else DLIK = zeros(k,1); % Initialization of the score. Da = zeros(mm,k); % Derivative State vector. dlik = zeros(smpl,k); - + if Zflag==0 C = zeros(pp,mm); for ii=1:pp, C(ii,Z(ii))=1; end % SELECTION MATRIX IN MEASUREMENT EQ. (FOR WHEN IT IS NOT CONSTANT) @@ -172,13 +172,13 @@ while notsteady && t<=last %loop over t oldP = P(:); for i=1:rows(z) %loop over i if Zflag - prediction_error = Y(d_index(i),t) - z(i,:)*a; % nu_{t,i} in 6.13 in DK (2012) + prediction_error = Y(d_index(i),t) - z(i,:)*a; % nu_{t,i} in 6.13 in DK (2012) PZ = P*z(i,:)'; % Z_{t,i}*P_{t,i}*Z_{t,i}' - Fi = z(i,:)*PZ + H(d_index(i)); % F_{t,i} in 6.13 in DK (2012), relies on H being diagonal + Fi = z(i,:)*PZ + H(d_index(i)); % F_{t,i} in 6.13 in DK (2012), relies on H being diagonal else - prediction_error = Y(d_index(i),t) - a(z(i)); % nu_{t,i} in 6.13 in DK (2012) + prediction_error = Y(d_index(i),t) - a(z(i)); % nu_{t,i} in 6.13 in DK (2012) PZ = P(:,z(i)); % Z_{t,i}*P_{t,i}*Z_{t,i}' - Fi = PZ(z(i)) + H(d_index(i)); % F_{t,i} in 6.13 in DK (2012), relies on H being diagonal + Fi = PZ(z(i)) + H(d_index(i)); % F_{t,i} in 6.13 in DK (2012), relies on H being diagonal end if Fi>kalman_tol Ki = PZ/Fi; %K_{t,i} in 6.13 in DK (2012) @@ -214,7 +214,7 @@ while notsteady && t<=last %loop over t [Da,DP] = univariate_computeDstate(k,a,P,T,Da,DP,DT,DOm,notsteady); end end - a = T*a; %transition according to (6.14) in DK (2012) + a = T*a; %transition according to (6.14) in DK (2012) P = T*P*T' + QQ; %transition according to (6.14) in DK (2012) if t>=no_more_missing_observations notsteady = max(abs(K(:)-oldK))>riccati_tol; @@ -229,7 +229,7 @@ if analytic_derivation DLIK = DLIK/2; dlik = dlik/2; if analytic_derivation==2 || asy_hess -% Hess = (Hess + Hess')/2; + % Hess = (Hess + Hess')/2; Hess = -Hess/2; end end @@ -239,10 +239,10 @@ if t <= last if analytic_derivation if analytic_derivation==2 [tmp, tmp2] = univariate_kalman_filter_ss(Y,t,last,a,P,kalman_tol,T,H,Z,pp,Zflag, ... - analytic_derivation,Da,DT,DYss,DP,DH,D2a,D2T,D2Yss,D2P); + analytic_derivation,Da,DT,DYss,DP,DH,D2a,D2T,D2Yss,D2P); else [tmp, tmp2] = univariate_kalman_filter_ss(Y,t,last,a,P,kalman_tol,T,H,Z,pp,Zflag, ... - analytic_derivation,Da,DT,DYss,DP,DH,asy_hess); + analytic_derivation,Da,DT,DYss,DP,DH,asy_hess); end lik(s+1:end,:)=tmp2{1}; dlik(s+1:end,:)=tmp2{2}; diff --git a/matlab/kalman/likelihood/univariate_kalman_filter_d.m b/matlab/kalman/likelihood/univariate_kalman_filter_d.m index ac121ee338..9a29c49813 100644 --- a/matlab/kalman/likelihood/univariate_kalman_filter_d.m +++ b/matlab/kalman/likelihood/univariate_kalman_filter_d.m @@ -80,9 +80,9 @@ function [dLIK, dlikk, a, Pstar, llik] = univariate_kalman_filter_d(data_index, %! @ref{univariate_kalman_filter_ss} %! @end deftypefn %@eod: -% +% % Algorithm: -% +% % Uses the diffuse univariate filter as described in Durbin/Koopman (2012): "Time % Series Analysis by State Space Methods", Oxford University Press, % Second Edition, Ch. 5, 6.4 + 7.2.5 @@ -125,15 +125,15 @@ while newRank && (t<=last) d_index = data_index{t}; for i=1:length(d_index) Zi = Z(d_index(i),:); - prediction_error = Y(d_index(i),t) - Zi*a; % nu_{t,i} in 6.13 in DK (2012) + prediction_error = Y(d_index(i),t) - Zi*a; % nu_{t,i} in 6.13 in DK (2012) Fstar = Zi*Pstar*Zi' + H(d_index(i)); % F_{*,t} in 5.7 in DK (2012), relies on H being diagonal - Finf = Zi*Pinf*Zi'; % F_{\infty,t} in 5.7 in DK (2012), relies on H being diagonal + Finf = Zi*Pinf*Zi'; % F_{\infty,t} in 5.7 in DK (2012), relies on H being diagonal Kstar = Pstar*Zi'; % Conduct check of rank - % Pinf and Finf are always scaled such that their norm=1: Fstar/Pstar, instead, + % Pinf and Finf are always scaled such that their norm=1: Fstar/Pstar, instead, % depends on the actual values of std errors in the model and can be badly scaled. - % experience is that diffuse_kalman_tol has to be bigger than kalman_tol, to ensure - % exiting the diffuse filter properly, avoiding tests that provide false non-zero rank for Pinf. + % experience is that diffuse_kalman_tol has to be bigger than kalman_tol, to ensure + % exiting the diffuse filter properly, avoiding tests that provide false non-zero rank for Pinf. % Also the test for singularity is better set coarser for Finf than for Fstar for the same reason if Finf>diffuse_kalman_tol && newRank % F_{\infty,t,i} = 0, use upper part of bracket on p. 175 DK (2012) for w_{t,i} Kinf = Pinf*Zi'; @@ -141,7 +141,7 @@ while newRank && (t<=last) a = a + Kinf_Finf*prediction_error; Pstar = Pstar + Kinf*(Kinf_Finf'*(Fstar/Finf)) - Kstar*Kinf_Finf' - Kinf_Finf*Kstar'; Pinf = Pinf - Kinf*Kinf_Finf'; - llik(s,d_index(i)) = log(Finf) + l2pi; + llik(s,d_index(i)) = log(Finf) + l2pi; dlikk(s) = dlikk(s) + llik(s,d_index(i)); elseif Fstar>kalman_tol llik(s,d_index(i)) = log(Fstar) + (prediction_error*prediction_error/Fstar) + l2pi; diff --git a/matlab/kalman/likelihood/univariate_kalman_filter_ss.m b/matlab/kalman/likelihood/univariate_kalman_filter_ss.m index 3801ea90e1..9d8cbff06f 100644 --- a/matlab/kalman/likelihood/univariate_kalman_filter_ss.m +++ b/matlab/kalman/likelihood/univariate_kalman_filter_ss.m @@ -54,7 +54,7 @@ function [LIK,likk,a] = univariate_kalman_filter_ss(Y,start,last,a,P,kalman_tol, %! @sp 1 %! @end deftypefn %@eod: -% +% % Algorithm: See univariate_kalman_filter.m % Copyright (C) 2011-2017 Dynare Team @@ -171,7 +171,7 @@ if analytic_derivation likk = {likk, dlikk}; end if analytic_derivation==2 || asy_hess -% Hess = (Hess + Hess')/2; + % Hess = (Hess + Hess')/2; Hess = -Hess/2; LIK={LIK,DLIK,Hess}; elseif analytic_derivation==1 diff --git a/matlab/kalman/steady_state_kalman_gain.m b/matlab/kalman/steady_state_kalman_gain.m index 460534e1b3..aa9344741f 100644 --- a/matlab/kalman/steady_state_kalman_gain.m +++ b/matlab/kalman/steady_state_kalman_gain.m @@ -1,19 +1,19 @@ function [K,iF,P] = steady_state_kalman_gain(T,R,Q,H,mf) % Given the invariant state space representation of a model, this % function computes the gain matrix and the covariance matrix of the -% state vector at the steady state of the kalman filter. -% -% INPUTS -% T [double] m*m transition matrix of the state vector. +% state vector at the steady state of the kalman filter. +% +% INPUTS +% T [double] m*m transition matrix of the state vector. % R [double] m*q matrix (q is the number of structural innovations). % Q [double] q*q covariance matrix of the structural innovations. % H [double] p*p covariance matrix of the measurement error. % mf [integer] p*1 vector, indices for the observed variables -% -% OUTPUTS +% +% OUTPUTS % K [double] kalman gain matrix. % P [double] covariance matrix of the state vector. -% +% % SPECIAL REQUIREMENTS % Needs a solver for Riccati equations (dare.m) diff --git a/matlab/kalman_transition_matrix.m b/matlab/kalman_transition_matrix.m index 77b3a4d3a7..1b026cfe4c 100644 --- a/matlab/kalman_transition_matrix.m +++ b/matlab/kalman_transition_matrix.m @@ -1,17 +1,17 @@ function [A,B] = kalman_transition_matrix(dr,iv,ic,exo_nbr) %function [A,B] = kalman_transition_matrix(dr,iv,ic,exo_nbr) % Builds the transition equation of the state space representation out of ghx and ghu for Kalman filter -% +% % INPUTS % dr: structure of decisions rules for stochastic simulations % iv: selected variables % ic: state variables position in the transition matrix columns % exo_nbr: number of exogenous variables -% +% % OUTPUTS % A: matrix of predetermined variables effects in linear solution (ghx) % B: matrix of shocks effects in linear solution (ghu) -% +% % SPECIAL REQUIREMENTS % none @@ -41,4 +41,3 @@ A(:,ic) = dr.ghx(iv,:); if nargout>1 B = dr.ghu(iv,:); end - diff --git a/matlab/kernel_density_estimate.m b/matlab/kernel_density_estimate.m index 172097c870..e3e83d5167 100644 --- a/matlab/kernel_density_estimate.m +++ b/matlab/kernel_density_estimate.m @@ -1,27 +1,27 @@ -function [abscissa,f] = kernel_density_estimate(data,number_of_grid_points,number_of_draws,bandwidth,kernel_function) -% Estimates a continuous density. -% +function [abscissa,f] = kernel_density_estimate(data,number_of_grid_points,number_of_draws,bandwidth,kernel_function) +% Estimates a continuous density. +% % INPUTS % data [double] Vector (number_of_draws*1) of draws. % number_of_grid_points [integer] Scalar, number of points where the density is estimated. -% This (positive) integer must be a power of two. +% This (positive) integer must be a power of two. % number_of_draws [integer] Scalar, number of draws. -% bandwidth [double] Real positive scalar. +% bandwidth [double] Real positive scalar. % kernel_function [string] Name of the kernel function: 'gaussian', 'triweight', -% 'uniform', 'triangle', 'epanechnikov', 'quartic', +% 'uniform', 'triangle', 'epanechnikov', 'quartic', % 'triweight' and 'cosinus' % % OUTPUTS % abscissa [double] Vector (number_of_grid_points*1) of values on the abscissa axis. -% f: [double] Vector (number_of_grid_points*1) of values on the ordinate axis, +% f: [double] Vector (number_of_grid_points*1) of values on the ordinate axis, % (density estimates). -% +% % SPECIAL REQUIREMENTS % none. % % REFERENCES % A kernel density estimator is used (see Silverman [1986], "Density estimation for statistics and data analysis") -% The code is adapted from Anders Holtsberg's matlab toolbox (stixbox). +% The code is adapted from Anders Holtsberg's matlab toolbox (stixbox). % % Copyright (C) 2004-2008 Dynare Team @@ -53,19 +53,19 @@ if (abs(test-round(test)) > 1e-12) end %% Kernel specification. -if strcmpi(kernel_function,'gaussian') +if strcmpi(kernel_function,'gaussian') kernel = @(x) inv(sqrt(2*pi))*exp(-0.5*x.^2); -elseif strcmpi(kernel_function,'uniform') - kernel = @(x) 0.5*(abs(x) <= 1); -elseif strcmpi(kernel_function,'triangle') +elseif strcmpi(kernel_function,'uniform') + kernel = @(x) 0.5*(abs(x) <= 1); +elseif strcmpi(kernel_function,'triangle') kernel = @(x) (1-abs(x)).*(abs(x) <= 1); -elseif strcmpi(kernel_function,'epanechnikov') +elseif strcmpi(kernel_function,'epanechnikov') kernel = @(x) 0.75*(1-x.^2).*(abs(x) <= 1); -elseif strcmpi(kernel_function,'quartic') +elseif strcmpi(kernel_function,'quartic') kernel = @(x) 0.9375*((1-x.^2).^2).*(abs(x) <= 1); -elseif strcmpi(kernel_function,'triweight') +elseif strcmpi(kernel_function,'triweight') kernel = @(x) 1.09375*((1-x.^2).^3).*(abs(x) <= 1); -elseif strcmpi(kernel_function,'cosinus') +elseif strcmpi(kernel_function,'cosinus') kernel = @(x) (pi/4)*cos((pi/2)*x).*(abs(x) <= 1); end @@ -73,9 +73,9 @@ end lower_bound = min(data) - (max(data)-min(data))/3; upper_bound = max(data) + (max(data)-min(data))/3; abscissa = linspace(lower_bound,upper_bound,number_of_grid_points)'; -inc = abscissa(2)-abscissa(1); +inc = abscissa(2)-abscissa(1); xi = zeros(number_of_grid_points,1); -xa = (data-lower_bound)/(upper_bound-lower_bound)*number_of_grid_points; +xa = (data-lower_bound)/(upper_bound-lower_bound)*number_of_grid_points; for i = 1:number_of_draws indx = floor(xa(i)); temp = xa(i)-indx; diff --git a/matlab/list_of_parameters_calibrated_as_NaN.m b/matlab/list_of_parameters_calibrated_as_NaN.m index 603a9f2e1f..4911190a52 100644 --- a/matlab/list_of_parameters_calibrated_as_NaN.m +++ b/matlab/list_of_parameters_calibrated_as_NaN.m @@ -1,15 +1,15 @@ function list = list_of_parameters_calibrated_as_NaN(M_) % The name of the function is explicit enough... -% +% % INPUTS % M_ [structure] Description of the (simulated or estimated) model. -% +% % OUTPUTS % list [char] n*p array of characters, each line is the name of parameter without value. -% +% % ALGORITHM % none -% +% % SPECIAL REQUIREMENTS % none diff --git a/matlab/lmmcp/catstruct.m b/matlab/lmmcp/catstruct.m index 014768ad9a..ae40d15318 100644 --- a/matlab/lmmcp/catstruct.m +++ b/matlab/lmmcp/catstruct.m @@ -1,174 +1,171 @@ -function A = catstruct(varargin) -% CATSTRUCT Concatenate or merge structures with different fieldnames -% X = CATSTRUCT(S1,S2,S3,...) merges the structures S1, S2, S3 ... -% into one new structure X. X contains all fields present in the various -% structures. An example: -% -% A.name = 'Me' ; -% B.income = 99999 ; -% X = catstruct(A,B) -% % -> X.name = 'Me' ; -% % X.income = 99999 ; -% -% If a fieldname is not unique among structures (i.e., a fieldname is -% present in more than one structure), only the value from the last -% structure with this field is used. In this case, the fields are -% alphabetically sorted. A warning is issued as well. An axample: -% -% S1.name = 'Me' ; -% S2.age = 20 ; S3.age = 30 ; S4.age = 40 ; -% S5.honest = false ; -% Y = catstruct(S1,S2,S3,S4,S5) % use value from S4 -% -% The inputs can be array of structures. All structures should have the -% same size. An example: -% -% C(1).bb = 1 ; C(2).bb = 2 ; -% D(1).aa = 3 ; D(2).aa = 4 ; -% CD = catstruct(C,D) % CD is a 1x2 structure array with fields bb and aa -% -% The last input can be the string 'sorted'. In this case, -% CATSTRUCT(S1,S2, ..., 'sorted') will sort the fieldnames alphabetically. -% To sort the fieldnames of a structure A, you could use -% CATSTRUCT(A,'sorted') but I recommend ORDERFIELDS for doing that. -% -% When there is nothing to concatenate, the result will be an empty -% struct (0x0 struct array with no fields). -% -% NOTE: To concatenate similar arrays of structs, you can use simple -% concatenation: -% A = dir('*.mat') ; B = dir('*.m') ; C = [A ; B] ; -% -% See also CAT, STRUCT, FIELDNAMES, STRUCT2CELL, ORDERFIELDS - -% for Matlab R13 and up -% version 3.0 (mar 2013) -% Originally downloaded from MATLAB central: -% http://www.mathworks.com/matlabcentral/fileexchange/7842-catstruct - -% Copyright (C) 2005 Jos van der Geest <jos@jasen.nl> -% Copyright (C) 2013 Christophe Gouel -% Copyright (C) 2016 Dynare Team -% -% Redistribution and use in source and binary forms, with or without -% modification, are permitted provided that the following conditions are -% met: -% -% * Redistributions of source code must retain the above copyright -% notice, this list of conditions and the following disclaimer. -% * Redistributions in binary form must reproduce the above copyright -% notice, this list of conditions and the following disclaimer in -% the documentation and/or other materials provided with the distribution -% -% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -% POSSIBILITY OF SUCH DAMAGE. - -% History -% Created in 2005 -% Revisions -% 2.0 (sep 2007) removed bug when dealing with fields containing cell -% arrays (Thanks to Rene Willemink) -% 2.1 (sep 2008) added warning and error identifiers -% 2.2 (oct 2008) fixed error when dealing with empty structs (Thanks to -% Lars Barring) -% 3.0 (mar 2013) fixed problem when the inputs were array of structures -% (thanks to Tor Inge Birkenes for pointing this out). -% Rephrased the help section as well. - -narginchk(1, Inf); -N = nargin ; - -if ~isstruct(varargin{end}) - if isequal(varargin{end},'sorted') - sorted = 1 ; - N = N-1 ; - if N<1 - error('catstruct: wrong number of input arguments') ; - end - else - error('catstruct:InvalidArgument','Last argument should be a structure, or the string "sorted".') ; - end -else - sorted = 0 ; -end - -sz0 = [] ; % used to check that all inputs have the same size - -% used to check for a few trivial cases -NonEmptyInputs = false(N,1) ; -NonEmptyInputsN = 0 ; - -% used to collect the fieldnames and the inputs -FN = cell(N,1) ; -VAL = cell(N,1) ; - -% parse the inputs -for ii=1:N - X = varargin{ii} ; - if ~isstruct(X) - error('catstruct:InvalidArgument',['Argument #' num2str(ii) ' is not a structure.']) ; - end - - if ~isempty(X) - % empty structs are ignored - if ii > 1 && ~isempty(sz0) - if ~isequal(size(X), sz0) - error('catstruct:UnequalSizes','All structures should have the same size.') ; - end - else - sz0 = size(X) ; - end - NonEmptyInputsN = NonEmptyInputsN + 1 ; - NonEmptyInputs(ii) = true ; - FN{ii} = fieldnames(X) ; - VAL{ii} = struct2cell(X) ; - end -end - -if NonEmptyInputsN == 0 - % all structures were empty - A = struct([]) ; -elseif NonEmptyInputsN == 1 - % there was only one non-empty structure - A = varargin{NonEmptyInputs} ; - if sorted - A = orderfields(A) ; - end -else - % there is actually something to concatenate - FN = cat(1,FN{:}) ; - VAL = cat(1,VAL{:}) ; - FN = squeeze(FN) ; - VAL = squeeze(VAL) ; - MatlabVersion = version; - if isoctave || str2double(MatlabVersion(end-5:end-2))<2013 % Equivalent to, but faster than if verLessThan('matlab','8.1') - [UFN,ind] = unique(FN) ; - else - [UFN,ind] = unique(FN,'legacy') ; - end - - if numel(UFN) ~= numel(FN) - warning('catstruct:DuplicatesFound','Fieldnames are not unique between structures.') ; - sorted = 1 ; - end - - if sorted - VAL = VAL(ind,:) ; - FN = FN(ind,:) ; - end - - A = cell2struct(VAL, FN); - A = reshape(A, sz0) ; % reshape into original format -end - - - +function A = catstruct(varargin) +% CATSTRUCT Concatenate or merge structures with different fieldnames +% X = CATSTRUCT(S1,S2,S3,...) merges the structures S1, S2, S3 ... +% into one new structure X. X contains all fields present in the various +% structures. An example: +% +% A.name = 'Me' ; +% B.income = 99999 ; +% X = catstruct(A,B) +% % -> X.name = 'Me' ; +% % X.income = 99999 ; +% +% If a fieldname is not unique among structures (i.e., a fieldname is +% present in more than one structure), only the value from the last +% structure with this field is used. In this case, the fields are +% alphabetically sorted. A warning is issued as well. An axample: +% +% S1.name = 'Me' ; +% S2.age = 20 ; S3.age = 30 ; S4.age = 40 ; +% S5.honest = false ; +% Y = catstruct(S1,S2,S3,S4,S5) % use value from S4 +% +% The inputs can be array of structures. All structures should have the +% same size. An example: +% +% C(1).bb = 1 ; C(2).bb = 2 ; +% D(1).aa = 3 ; D(2).aa = 4 ; +% CD = catstruct(C,D) % CD is a 1x2 structure array with fields bb and aa +% +% The last input can be the string 'sorted'. In this case, +% CATSTRUCT(S1,S2, ..., 'sorted') will sort the fieldnames alphabetically. +% To sort the fieldnames of a structure A, you could use +% CATSTRUCT(A,'sorted') but I recommend ORDERFIELDS for doing that. +% +% When there is nothing to concatenate, the result will be an empty +% struct (0x0 struct array with no fields). +% +% NOTE: To concatenate similar arrays of structs, you can use simple +% concatenation: +% A = dir('*.mat') ; B = dir('*.m') ; C = [A ; B] ; +% +% See also CAT, STRUCT, FIELDNAMES, STRUCT2CELL, ORDERFIELDS + +% for Matlab R13 and up +% version 3.0 (mar 2013) +% Originally downloaded from MATLAB central: +% http://www.mathworks.com/matlabcentral/fileexchange/7842-catstruct + +% Copyright (C) 2005 Jos van der Geest <jos@jasen.nl> +% Copyright (C) 2013 Christophe Gouel +% Copyright (C) 2016 Dynare Team +% +% Redistribution and use in source and binary forms, with or without +% modification, are permitted provided that the following conditions are +% met: +% +% * Redistributions of source code must retain the above copyright +% notice, this list of conditions and the following disclaimer. +% * Redistributions in binary form must reproduce the above copyright +% notice, this list of conditions and the following disclaimer in +% the documentation and/or other materials provided with the distribution +% +% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +% POSSIBILITY OF SUCH DAMAGE. + +% History +% Created in 2005 +% Revisions +% 2.0 (sep 2007) removed bug when dealing with fields containing cell +% arrays (Thanks to Rene Willemink) +% 2.1 (sep 2008) added warning and error identifiers +% 2.2 (oct 2008) fixed error when dealing with empty structs (Thanks to +% Lars Barring) +% 3.0 (mar 2013) fixed problem when the inputs were array of structures +% (thanks to Tor Inge Birkenes for pointing this out). +% Rephrased the help section as well. + +narginchk(1, Inf); +N = nargin ; + +if ~isstruct(varargin{end}) + if isequal(varargin{end},'sorted') + sorted = 1 ; + N = N-1 ; + if N<1 + error('catstruct: wrong number of input arguments') ; + end + else + error('catstruct:InvalidArgument','Last argument should be a structure, or the string "sorted".') ; + end +else + sorted = 0 ; +end + +sz0 = [] ; % used to check that all inputs have the same size + +% used to check for a few trivial cases +NonEmptyInputs = false(N,1) ; +NonEmptyInputsN = 0 ; + +% used to collect the fieldnames and the inputs +FN = cell(N,1) ; +VAL = cell(N,1) ; + +% parse the inputs +for ii=1:N + X = varargin{ii} ; + if ~isstruct(X) + error('catstruct:InvalidArgument',['Argument #' num2str(ii) ' is not a structure.']) ; + end + + if ~isempty(X) + % empty structs are ignored + if ii > 1 && ~isempty(sz0) + if ~isequal(size(X), sz0) + error('catstruct:UnequalSizes','All structures should have the same size.') ; + end + else + sz0 = size(X) ; + end + NonEmptyInputsN = NonEmptyInputsN + 1 ; + NonEmptyInputs(ii) = true ; + FN{ii} = fieldnames(X) ; + VAL{ii} = struct2cell(X) ; + end +end + +if NonEmptyInputsN == 0 + % all structures were empty + A = struct([]) ; +elseif NonEmptyInputsN == 1 + % there was only one non-empty structure + A = varargin{NonEmptyInputs} ; + if sorted + A = orderfields(A) ; + end +else + % there is actually something to concatenate + FN = cat(1,FN{:}) ; + VAL = cat(1,VAL{:}) ; + FN = squeeze(FN) ; + VAL = squeeze(VAL) ; + MatlabVersion = version; + if isoctave || str2double(MatlabVersion(end-5:end-2))<2013 % Equivalent to, but faster than if verLessThan('matlab','8.1') + [UFN,ind] = unique(FN) ; + else + [UFN,ind] = unique(FN,'legacy') ; + end + + if numel(UFN) ~= numel(FN) + warning('catstruct:DuplicatesFound','Fieldnames are not unique between structures.') ; + sorted = 1 ; + end + + if sorted + VAL = VAL(ind,:) ; + FN = FN(ind,:) ; + end + + A = cell2struct(VAL, FN); + A = reshape(A, sz0) ; % reshape into original format +end diff --git a/matlab/lmmcp/dyn_lmmcp_func.m b/matlab/lmmcp/dyn_lmmcp_func.m index 936f98306d..d34b6adb15 100644 --- a/matlab/lmmcp/dyn_lmmcp_func.m +++ b/matlab/lmmcp/dyn_lmmcp_func.m @@ -20,37 +20,36 @@ function [F,A] = dyn_lmmcp_func(x, model_dynamic, Y0, YT, exo_simul, params, ... % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - Y = [Y0; x; YT]; - - F = zeros(periods*ny,1); - if nargout == 2 - A = sparse([],[],[],periods*ny,periods*ny,periods*nnzA); - end +Y = [Y0; x; YT]; - i_rows = 1:ny; - i_cols = find(lead_lag_incidence'); - i_cols_A = i_cols; - - for it = 2:(periods+1) - - [res,jacobian] = model_dynamic(Y(i_cols),exo_simul, params, ... - steady_state,it); - F(i_rows) = res(eq_index); - - if nargout == 2 - if it == 2 - A(i_rows,i_cols_A1) = jacobian(eq_index,i_cols_1); - elseif it == periods+1 - A(i_rows,i_cols_A(i_cols_T)) = jacobian(eq_index,i_cols_T); - else - A(i_rows,i_cols_A) = jacobian(eq_index,i_cols_j); - end - end - - i_rows = i_rows + ny; - i_cols = i_cols + ny; - if nargout == 2 && it > 2 - i_cols_A = i_cols_A + ny; +F = zeros(periods*ny,1); +if nargout == 2 + A = sparse([],[],[],periods*ny,periods*ny,periods*nnzA); +end + +i_rows = 1:ny; +i_cols = find(lead_lag_incidence'); +i_cols_A = i_cols; + +for it = 2:(periods+1) + + [res,jacobian] = model_dynamic(Y(i_cols),exo_simul, params, ... + steady_state,it); + F(i_rows) = res(eq_index); + + if nargout == 2 + if it == 2 + A(i_rows,i_cols_A1) = jacobian(eq_index,i_cols_1); + elseif it == periods+1 + A(i_rows,i_cols_A(i_cols_T)) = jacobian(eq_index,i_cols_T); + else + A(i_rows,i_cols_A) = jacobian(eq_index,i_cols_j); end end + i_rows = i_rows + ny; + i_cols = i_cols + ny; + if nargout == 2 && it > 2 + i_cols_A = i_cols_A + ny; + end +end diff --git a/matlab/lmmcp/get_complementarity_conditions.m b/matlab/lmmcp/get_complementarity_conditions.m index d1ea1771fd..340bd74cb6 100644 --- a/matlab/lmmcp/get_complementarity_conditions.m +++ b/matlab/lmmcp/get_complementarity_conditions.m @@ -2,13 +2,13 @@ function [lb,ub,eq_index] = get_complementarity_conditions(M,ramsey_policy) % [lb,ub,eq_index] = get_complementarity_conditions(M,ramsey_policy) % INPUTS % - M [struct] contains a description of the model. -% - ramsey_policy [boolean] indicator whether a Ramsey problem is considered +% - ramsey_policy [boolean] indicator whether a Ramsey problem is considered % OUTPUTS % - lb [double] endo_nbr*1 array of lower bounds for % endogenous variables % - ub [double] endo_nbr*1 array of upper bounds for % endogenous variables -% - eq_index [struct] endo_nbr*1 index vector describing residual mapping resulting +% - eq_index [struct] endo_nbr*1 index vector describing residual mapping resulting % from complementarity setup used in % perfect_foresight_mcp_problem.m @@ -55,14 +55,14 @@ for i=1:size(etags,1) str = etags{i,3}; kop = strfind(etags{i,3},'<'); if ~isempty(kop) - k = find(strcmp(strtrim(str(1:kop-1)),cellstr(M.endo_names))); %get variable index with restriction - if isempty(k) - error(sprintf(['Complementarity condition %s: variable %s is ' ... - 'not recognized'],etags{i,3},strtrim(str(1:kop-1)))) - end - ub(k) = str2num(str(kop+1:end)); - eq_index(etags{i,1}) = k; - eq_index(k) = etags{i,1}; + k = find(strcmp(strtrim(str(1:kop-1)),cellstr(M.endo_names))); %get variable index with restriction + if isempty(k) + error(sprintf(['Complementarity condition %s: variable %s is ' ... + 'not recognized'],etags{i,3},strtrim(str(1:kop-1)))) + end + ub(k) = str2num(str(kop+1:end)); + eq_index(etags{i,1}) = k; + eq_index(k) = etags{i,1}; else kop = strfind(etags{i,3},'>'); if ~isempty(kop) @@ -81,4 +81,3 @@ for i=1:size(etags,1) end end end - diff --git a/matlab/lmmcp/lmmcp.m b/matlab/lmmcp/lmmcp.m index 1ac1c5e0a4..162e61a865 100644 --- a/matlab/lmmcp/lmmcp.m +++ b/matlab/lmmcp/lmmcp.m @@ -1,625 +1,625 @@ -function [x,FVAL,EXITFLAG,OUTPUT,JACOB] = lmmcp(FUN,x,lb,ub,options,varargin) -% LMMCP solves a mixed complementarity problem. -% -% LMMCP uses a semismooth least squares formulation. The method applies a -% Levenberg-Marquardt/Gauss-Newton algorithm to a least-squares formulation. -% -% X = LMMCP(FUN,X0) tries to solve the system of nonlinear equations F(X)=0 and -% starts at the vector X0. FUN accepts a vector X and return a vector F of equation -% values F evaluated at X and, as second output if required, a matrix J, the -% Jacobian evaluated at X. -% -% X = LMMCP(FUN,X0,LB,UB) solves the mixed complementarity problem of the form: -% LB =X => F(X)>0, -% LB<=X<=UB => F(X)=0, -% X =UB => F(X)<0. -% -% X = LMMCP(FUN,X0,LB,UB,OPTIONS) solves the MCP problem using the options -% defined in the structure OPTIONS. Main fields are -% Display : control the display of iterations, 'none' (default), -% 'iter-detailed' or 'final-detailed' -% Switch from phase I to phase II -% preprocess : activate preprocessor for phase I (default = 1) -% presteps : number of iterations in phase I (default = 20) -% Termination parameters -% MaxIter : Maximum number of iterations (default = 500) -% tmin : safeguard stepsize (default = 1E-12) -% TolFun : Termination tolerance on the function value, a positive -% scalar (default = sqrt(eps)) -% Stepsize parameters -% m : number of previous function values to use in the nonmonotone -% line search rule (default = 10) -% kwatch : maximum number of steps (default = 20 and should not be -% smaller than m) -% watchdog : activate the watchdog strategy (default = 1) -% Ther are other minor parameters. Please see the code for their default values -% and interpretation. -% -% [X,FVAL] = LMMCP(FUN,X0,...) returns the value of the equations FUN at X. -% -% [X,FVAL,EXITFLAG] = LMMCP(FUN,X0,...) returns EXITFLAG that describes the exit -% conditions. Possible values are -% 1 : LMMCP converged to a root -% 0 : Too many iterations -% -1 : -% -% [X,FVAL,EXITFLAG,OUTPUT] = LMMCP(FUN,X0,...) returns the structure OUTPUT that -% contains the number of iterations (OUTPUT.iterations), the value of the merit -% function (OUTPUT.Psix), and the norm of the derivative of the merit function -% (OUTPUT.normDPsix). -% -% [X,FVAL,EXITFLAG,OUTPUT,JACOB] = LMMCP(FUN,X0,...) returns JACOB the Jacobian -% of FUN evaluated at X. -% -% More details of the main program may be found in the following paper: -% -% Christian Kanzow and Stefania Petra: On a semismooth least squares formulation of -% complementarity problems with gap reduction. Optimization Methods and Software -% 19, 2004, pp. 507-525. -% -% In addition, the current implementation uses a preprocessor which is the -% projected Levenberg-Marquardt step from the following preprint: -% -% Christian Kanzow and Stefania Petra: Projected filter trust region methods for a -% semismooth least squares formulation of mixed complementarity -% problems. Optimization Methods and Software -% 22, 2007, pp. 713-735. -% -% A user's guide is also available: -% -% Christian Kanzow and Stefania Petra (2005). -% LMMCP --- A Levenberg-Marquardt-type MATLAB Solver for Mixed Complementarity Problems. -% University of Wuerzburg. -% http://www.mathematik.uni-wuerzburg.de/~kanzow/software/UserGuide.pdf -% -% This is a modification by Christophe Gouel of the original files, which can be -% downloaded from: -% http://www.mathematik.uni-wuerzburg.de/~kanzow/software/LMMCP.zip -% -% Written by Christian Kanzow and Stefania Petra -% Institute of Applied Mathematics and Statistics -% University of Wuerzburg -% Am Hubland -% 97074 Wuerzburg -% GERMANY -% -% e-mail: kanzow@mathematik.uni-wuerzburg.de -% petra@mathematik.uni-wuerzburg.de -% -% Christian Kanzow sent a private message to Dynare Team on July 8, 2014, -% confirming the free software status of lmmcp and granting unlimited -% permission to use, copy, modifiy or redistribute the file. - -% Copyright (C) 2005 Christian Kanzow and Stefania Petra -% Copyright (C) 2013 Christophe Gouel -% Copyright (C) 2014 Dynare Team -% -% Unlimited permission is granted to everyone to use, copy, modify or -% distribute this software. - -%% Initialization -defaultopt = struct(... - 'beta', 0.55,... - 'Big', 1e10,... - 'delta', 5,... - 'deltamin', 1,... - 'Display', 'none',... - 'epsilon1', 1e-6,... - 'eta', 0.95,... - 'kwatch', 20,... - 'lambda1', 0.1,... - 'm', 10,... - 'MaxIter', 500,... - 'null', 1e-10,... - 'preprocess', 1,... - 'presteps', 20,... - 'sigma', 1e-4,... - 'sigma1', 0.5,... - 'sigma2', 2,... - 'tmin', 1e-12,... - 'TolFun', sqrt(eps),... - 'watchdog', 1); - -if nargin < 4 - ub = inf(size(x)); - if nargin < 3 - lb = -inf(size(x)); - end -end - -if nargin < 5 || isempty(options) || ~isstruct(options) - options = defaultopt; -else - warning('off','catstruct:DuplicatesFound') - options = catstruct(defaultopt,options); -end - -warning('off','MATLAB:rankDeficientMatrix') - -switch options.Display - case {'off','none'} - verbosity = 0; - case {'iter','iter-detailed'} - verbosity = 2; - case {'final','final-detailed'} - verbosity = 1; - otherwise - verbosity = 0; -end - -% parameter settings -eps1 = options.epsilon1; -eps2 = 0.5*options.TolFun^2; -null = options.null; -Big = options.Big; - -% maximal number of iterations -kmax = options.MaxIter; - -% choice of lambda -lambda1 = options.lambda1; -lambda2 = 1-lambda1; - -% steplength parameters -beta = options.beta; -sigma = options.sigma; -tmin = options.tmin; - -% parameters watchdog and nonmonotone line search; redefined later -m = options.m; -kwatch = options.kwatch; -watchdog = options.watchdog; % 1=watchdog strategy active, otherwise not - -% parameters for preprocessor -preprocess = options.preprocess; % 1=preprocessor used, otherwise not -presteps = options.presteps; % maximum number of preprocessing steps - -% trust-region parameters for preprocessor -delta = options.delta; -deltamin = options.deltamin; -sigma1 = options.sigma1; -sigma2 = options.sigma2; -eta = options.eta; - -% initializations -k = 0; -k_main = 0; - -% compute a feasible starting point by projection -x = max(lb,min(x,ub)); - -n = length(x); -OUTPUT.Dim = n; - -% definition of index sets I_l, I_u and I_lu -Indexset = zeros(n,1); -I_l = lb>-Big & ub>Big; -I_u = lb<-Big & ub<Big; -I_lu = lb>-Big & ub<Big; -Indexset(I_l) = 1; -Indexset(I_u) = 2; -Indexset(I_lu) = 3; - -% function evaluations -[Fx,DFx] = feval(FUN,x,varargin{:}); - -% choice of NCP-function and corresponding evaluations -Phix = Phi(x,Fx,lb,ub,lambda1,lambda2,n,Indexset); -normPhix = norm(Phix); -Psix = 0.5*(Phix'*Phix); -DPhix = DPhi(x,Fx,DFx,lb,ub,lambda1,lambda2,n,Indexset); -DPsix = DPhix'*Phix; -normDPsix = norm(DPsix); - -% save initial values -x0 = x; -Phix0 = Phix; -Psix0 = Psix; -DPhix0 = DPhix; -DPsix0 = DPsix; -normDPsix0 = normDPsix; - -% watchdog strategy -aux = zeros(m,1); -aux(1) = Psix; -MaxPsi = Psix; - -if watchdog==1 - kbest = k; - xbest = x; - Phibest = Phix; - Psibest = Psix; - DPhibest = DPhix; - DPsibest = DPsix; - normDPsibest = normDPsix; -end - -% initial output -if verbosity > 1 - fprintf(' k Psi(x) || DPsi(x) || stepsize\n'); - disp('====================================================================') - disp('********************* Output at starting point *********************') - fprintf('%4.0f %24.5e %24.5e\n',k,Psix,normDPsix); -end - -%% Preprocessor using local method - -if preprocess==1 - - if verbosity > 1 - disp('************************** Preprocessor ****************************') - end - - normpLM=1; - while (k < presteps) && (Psix > eps2) && (normpLM>null) - k = k+1; - - % choice of Levenberg-Marquardt parameter, note that we do not use - % the condition estimator for large-scale problems, although this - % may cause numerical problems in some examples - - i = false; - mu = 0; - if n<100 - i = true; - mu = 1e-16; - if condest(DPhix'*DPhix)>1e25 - mu = 1e-6/(k+1); - end - end - if i - pLM = [DPhix; sqrt(mu)*speye(n)]\[-Phix; zeros(n,1)]; - else - pLM = -DPhix\Phix; - end - normpLM = norm(pLM); - - % compute the projected Levenberg-Marquard step onto box Xk - lbnew = max(min(lb-x,0),-delta); - ubnew = min(max(ub-x,0),delta); - d = max(lbnew,min(pLM,ubnew)); - xnew = x+d; - - % function evaluations etc. - [Fxnew,DFxnew] = feval(FUN,xnew,varargin{:}); - Phixnew = Phi(xnew,Fxnew,lb,ub,lambda1,lambda2,n,Indexset); - Psixnew = 0.5*(Phixnew'*Phixnew); - normPhixnew = norm(Phixnew); - - % update of delta - if normPhixnew<=eta*normPhix - delta = max(deltamin,sigma2*delta); - elseif normPhixnew>5*eta*normPhix - delta = max(deltamin,sigma1*delta); - end - - % update - x = xnew; - Fx = Fxnew; - DFx = DFxnew; - Phix = Phixnew; - Psix = Psixnew; - normPhix = normPhixnew; - DPhix = DPhi(x,Fx,DFx,lb,ub,lambda1,lambda2,n,Indexset); - DPsix = DPhix'*Phix; - normDPsix = norm(DPsix,inf); - - % output at each iteration - t=1; - if verbosity > 1 - fprintf('%4.0f %24.5e %24.5e %11.7g\n',k,Psix,normDPsix,t); - end - end -end - -% terminate program or redefine current iterate as original initial point -if preprocess==1 && Psix<eps2 - if verbosity > 0 - fprintf('Psix = %1.4e\nnormDPsix = %1.4e\n',Psix,normDPsix); - disp('Approximate solution found.') - end - EXITFLAG = 1; - FVAL = Fx; - OUTPUT.iterations = k; - OUTPUT.Psix = Psix; - OUTPUT.normDPsix = normDPsix; - JACOB = DFx; - return -elseif preprocess==1 && Psix>=eps2 - x=x0; - Phix=Phix0; - Psix=Psix0; - DPhix=DPhix0; - DPsix=DPsix0; - if verbosity > 1 - disp('******************** Restart with initial point ********************') - fprintf('%4.0f %24.5e %24.5e\n',k_main,Psix0,normDPsix0); - end -end - -%% Main algorithm - -if verbosity > 1 - disp('************************** Main program ****************************') -end - -while (k < kmax) && (Psix > eps2) - - % choice of Levenberg-Marquardt parameter, note that we do not use - % the condition estimator for large-scale problems, although this - % may cause numerical problems in some examples - - i = false; - if n<100 - i = true; - mu = 1e-16; - if condest(DPhix'*DPhix)>1e25 - mu = 1e-1/(k+1); - end - end - - % compute a Levenberg-Marquard direction - - if i - d = [DPhix; sqrt(mu)*speye(n)]\[-Phix; zeros(n,1)]; - else - d = -DPhix\Phix; - end - - % computation of steplength t using the nonmonotone Armijo-rule - % starting with the 6-th iteration - - % computation of steplength t using the monotone Armijo-rule if - % d is a 'good' descent direction or k<=5 - - t = 1; - xnew = x+d; - Fxnew = feval(FUN,xnew,varargin{:}); - Phixnew = Phi(xnew,Fxnew,lb,ub,lambda1,lambda2,n,Indexset); - Psixnew = 0.5*(Phixnew'*Phixnew); - const = sigma*DPsix'*d; - - while (Psixnew > MaxPsi + const*t) && (t > tmin) - t = t*beta; - xnew = x+t*d; - Fxnew = feval(FUN,xnew,varargin{:}); - Phixnew = Phi(xnew,Fxnew,lb,ub,lambda1,lambda2,n,Indexset); - Psixnew = 0.5*(Phixnew'*Phixnew); - end - - % updatings - x = xnew; - Fx = Fxnew; - Phix = Phixnew; - Psix = Psixnew; - [junk,DFx] = feval(FUN,x,varargin{:}); - DPhix = DPhi(x,Fx,DFx,lb,ub,lambda1,lambda2,n,Indexset); - DPsix = DPhix'*Phix; - normDPsix = norm(DPsix); - k = k+1; - k_main = k_main+1; - - if k_main<=5 - aux(mod(k_main,m)+1) = Psix; - MaxPsi = Psix; - else - aux(mod(k_main,m)+1) = Psix; - MaxPsi = max(aux); - end - - % updatings for the watchdog strategy - if watchdog ==1 - if Psix<Psibest - kbest = k; - xbest = x; - Phibest = Phix; - Psibest = Psix; - DPhibest = DPhix; - DPsibest = DPsix; - normDPsibest = normDPsix; - elseif k-kbest>kwatch - x=xbest; - Phix=Phibest; - Psix=Psibest; - DPhix=DPhibest; - DPsix=DPsibest; - normDPsix=normDPsibest; - MaxPsi=Psix; - end - end - - if verbosity > 1 - % output at each iteration - fprintf('%4.0f %24.5e %24.5e %11.7g\n',k,Psix,normDPsix,t); - end -end - -%% Final output -if Psix<=eps2 - EXITFLAG = 1; - if verbosity > 0, disp('Approximate solution found.'); end -elseif k>=kmax - EXITFLAG = 0; - if verbosity > 0, disp('Maximum iteration number reached.'); end -elseif normDPsix<=eps1 - EXITFLAG = -1; % Provisoire - if verbosity > 0, disp('Approximate stationary point found.'); end -else - EXITFLAG = -1; % Provisoire - if verbosity > 0, disp('No solution found.'); end -end - -FVAL = Fx; -OUTPUT.iterations = k; -OUTPUT.Psix = Psix; -OUTPUT.normDPsix = normDPsix; -JACOB = DFx; - -%% Subfunctions - -function y = Phi(x,Fx,lb,ub,lambda1,lambda2,n,Indexset) -%% PHI - -y = zeros(2*n,1); -phi_u = sqrt((ub-x).^2+Fx.^2)-ub+x+Fx; -LZ = false(n,1); % logical zero - -I0 = Indexset==0; -y(I0) = -lambda1*Fx(I0); -y([LZ; I0]) = -lambda2*Fx(I0); - -I1 = Indexset==1; -y(I1) = lambda1*(-x(I1)+lb(I1)-Fx(I1)+sqrt((x(I1)-lb(I1)).^2+Fx(I1).^2)); -y([LZ; I1]) = lambda2*max(0,x(I1)-lb(I1)).*max(0,Fx(I1)); - -I2 = Indexset==2; -y(I2) = -lambda1*phi_u(I2); -y([LZ; I2]) = lambda2*max(0,ub(I2)-x(I2)).*max(0,-Fx(I2)); - -I3 = Indexset==3; -y(I3) = lambda1*(sqrt((x(I3)-lb(I3)).^2+phi_u(I3).^2)-x(I3)+lb(I3)-phi_u(I3)); -y([LZ; I3]) = lambda2*(max(0,x(I3)-lb(I3)).*max(0,Fx(I3))+max(0,ub(I3)-x(I3)).*max(0,-Fx(I3))); - - -function H = DPhi(x,Fx,DFx,lb,ub,lambda1,lambda2,n,Indexset) -%% DPHI evaluates an element of the C-subdifferential of operator Phi - -null = 1e-8; -beta_l = zeros(n,1); -beta_u = zeros(n,1); -alpha_l = zeros(n,1); -alpha_u = zeros(n,1); - - -z = zeros(n,1); -H2 = sparse(n,n); - -I = abs(x-lb)<=null & abs(Fx)<=null; -beta_l(I) = 1; -z(I) = 1; - -I = abs(ub-x)<=null & abs(Fx)<=null; -beta_u(I) = 1; -z(I) = 1; - -I = x-lb>=-null & Fx>=-null; -alpha_l(I) = 1; - -I = ub-x>=-null & Fx<=null; -alpha_u(I) = 1; - -Da = zeros(n,1); -Db = zeros(n,1); - -I = 1:n; - -I0 = Indexset==0; -Da(I0) = 0; -Db(I0) = -1; -H2(I0,:) = -DFx(I0,:); - -I1 = Indexset==1; -denom1 = zeros(n,1); -denom2 = zeros(n,1); -if any(I1) - denom1(I1) = max(null,sqrt((x(I1)-lb(I1)).^2+Fx(I1).^2)); - denom2(I1) = max(null,sqrt(z(I1).^2+(DFx(I1,:)*z).^2)); -end - -I1b = Indexset==1 & beta_l==0; -Da(I1b) = (x(I1b)-lb(I1b))./denom1(I1b)-1; -Db(I1b) = Fx(I1b)./denom1(I1b)-1; -I1b = Indexset==1 & beta_l~=0; -if any(I1b) - Da(I1b) = z(I1b)./denom2(I1b)-1; - Db(I1b) = (DFx(I1b,:)*z)./denom2(I1b)-1; -end - -I1a = I(Indexset==1 & alpha_l==1); -if any(I1a) - H2(I1a,:) = spdiags(x(I1a)-lb(I1a), 0, length(I1a), length(I1a))*DFx(I1a,:) +... - sparse(1:length(I1a),I1a,Fx(I1a),length(I1a),n,length(I1a)); -end - -I2 = Indexset==2; -denom1 = zeros(n,1); -denom2 = zeros(n,1); -if any(I2) - denom1(I2) = max(null,sqrt((ub(I2)-x(I2)).^2+Fx(I2).^2)); - denom2(I2) = max(null,sqrt(z(I2).^2+(DFx(I2,:)*z).^2)); -end - -I2b = Indexset==2 & beta_u==0; -Da(I2b) = (ub(I2b)-x(I2b))./denom1(I2b)-1; -Db(I2b) = -Fx(I2b)./denom1(I2b)-1; -I2b = Indexset==2 & beta_u~=0; -if any(I2b) - Da(I2b) = -z(I2b)./denom2(I2b)-1; - Db(I2b) = -(DFx(I2b,:)*z)./denom2(I2b)-1; -end - -I2a = I(Indexset==2 & alpha_u==1); -if any(I2a) - H2(I2a,:) = bsxfun(@times,x(I2a)-ub(I2a),DFx(I2a,:))+... - sparse(1:length(I2a),I2a,Fx(I2a),length(I2a),n,length(I2a)); -end - -I3 = Indexset==3; -phi = zeros(n,1); -ai = zeros(n,1); -bi = zeros(n,1); -ci = zeros(n,1); -di = zeros(n,1); -denom1 = zeros(n,1); -denom2 = zeros(n,1); -denom3 = zeros(n,1); -denom4 = zeros(n,1); -if any(I3) - phi(I3) = -ub(I3)+x(I3)+Fx(I3)+sqrt((ub(I3)-x(I3)).^2+Fx(I3).^2); - denom1(I3) = max(null,sqrt((x(I3)-lb(I3)).^2+phi(I3).^2)); - denom2(I3) = max(null,sqrt(z(I3).^2+(DFx(I3,:)*z).^2)); - denom3(I3) = max(null,sqrt((ub(I3)-x(I3)).^2+Fx(I3).^2)); - denom4(I3) = max(null,sqrt(z(I3).^2)); -end - -I3bu = Indexset==3 & beta_u==0; -ci(I3bu) = (x(I3bu)-ub(I3bu))./denom3(I3bu)+1; -di(I3bu) = Fx(I3bu)./denom3(I3bu)+1; -I3bu = Indexset==3 & beta_u~=0; -if any(I3bu) - ci(I3bu) = 1+z(I3bu)./denom2(I3bu); - di(I3bu) = 1+(DFx(I3bu,:)*z)./denom2(I3bu); -end - -I3bl = Indexset==3 & beta_l==0; -ai(I3bl) = (x(I3bl)-lb(I3bl))./denom1(I3bl)-1; -bi(I3bl) = phi(I3bl)./denom1(I3bl)-1; -I3bl = Indexset==3 & beta_l~=0; -if any(I3bl) - ai(I3bl) = z(I3bl)./denom4(I3bl)-1; - bi(I3bl) = (ci(I3bl).*z(I3bl)+(di(I3bl,ones(1,n)).*DFx(I3bl,:))*z)./denom4(I3bl)-1; -end - -Da(I3) = ai(I3)+bi(I3).*ci(I3); -Db(I3) = bi(I3).*di(I3); - -I3a = I(Indexset==3 & alpha_l==1 & alpha_u==1); -if any(I3a) - H2(I3a,:) = bsxfun(@times,-lb(I3a)-ub(I3a)+2*x(I3a),DFx(I3a,:))+... - 2*sparse(1:length(I3a),I3a,Fx(I3a),length(I3a),n,length(I3a)); -end -I3a = I(Indexset==3 & alpha_l==1 & alpha_u~=1); -if any(I3a) - H2(I3a,:) = bsxfun(@times,x(I3a)-lb(I3a),DFx(I3a,:))+... - sparse(1:length(I3a),I3a,Fx(I3a),length(I3a),n,length(I3a)); -end -I3a = I(Indexset==3 & alpha_l~=1 & alpha_u==1); -if any(I3a) - H2(I3a,:) = bsxfun(@times,x(I3a)-ub(I3a),DFx(I3a,:))+... - sparse(1:length(I3a),I3a,Fx(I3a),length(I3a),n,length(I3a)); -end - -H1 = spdiags(Db,0,length(Db),length(Db))*DFx; -H1 = H1 + spdiags(Da, 0, length(Da), length(Da)); - -H = [lambda1*H1; lambda2*H2]; +function [x,FVAL,EXITFLAG,OUTPUT,JACOB] = lmmcp(FUN,x,lb,ub,options,varargin) +% LMMCP solves a mixed complementarity problem. +% +% LMMCP uses a semismooth least squares formulation. The method applies a +% Levenberg-Marquardt/Gauss-Newton algorithm to a least-squares formulation. +% +% X = LMMCP(FUN,X0) tries to solve the system of nonlinear equations F(X)=0 and +% starts at the vector X0. FUN accepts a vector X and return a vector F of equation +% values F evaluated at X and, as second output if required, a matrix J, the +% Jacobian evaluated at X. +% +% X = LMMCP(FUN,X0,LB,UB) solves the mixed complementarity problem of the form: +% LB =X => F(X)>0, +% LB<=X<=UB => F(X)=0, +% X =UB => F(X)<0. +% +% X = LMMCP(FUN,X0,LB,UB,OPTIONS) solves the MCP problem using the options +% defined in the structure OPTIONS. Main fields are +% Display : control the display of iterations, 'none' (default), +% 'iter-detailed' or 'final-detailed' +% Switch from phase I to phase II +% preprocess : activate preprocessor for phase I (default = 1) +% presteps : number of iterations in phase I (default = 20) +% Termination parameters +% MaxIter : Maximum number of iterations (default = 500) +% tmin : safeguard stepsize (default = 1E-12) +% TolFun : Termination tolerance on the function value, a positive +% scalar (default = sqrt(eps)) +% Stepsize parameters +% m : number of previous function values to use in the nonmonotone +% line search rule (default = 10) +% kwatch : maximum number of steps (default = 20 and should not be +% smaller than m) +% watchdog : activate the watchdog strategy (default = 1) +% Ther are other minor parameters. Please see the code for their default values +% and interpretation. +% +% [X,FVAL] = LMMCP(FUN,X0,...) returns the value of the equations FUN at X. +% +% [X,FVAL,EXITFLAG] = LMMCP(FUN,X0,...) returns EXITFLAG that describes the exit +% conditions. Possible values are +% 1 : LMMCP converged to a root +% 0 : Too many iterations +% -1 : +% +% [X,FVAL,EXITFLAG,OUTPUT] = LMMCP(FUN,X0,...) returns the structure OUTPUT that +% contains the number of iterations (OUTPUT.iterations), the value of the merit +% function (OUTPUT.Psix), and the norm of the derivative of the merit function +% (OUTPUT.normDPsix). +% +% [X,FVAL,EXITFLAG,OUTPUT,JACOB] = LMMCP(FUN,X0,...) returns JACOB the Jacobian +% of FUN evaluated at X. +% +% More details of the main program may be found in the following paper: +% +% Christian Kanzow and Stefania Petra: On a semismooth least squares formulation of +% complementarity problems with gap reduction. Optimization Methods and Software +% 19, 2004, pp. 507-525. +% +% In addition, the current implementation uses a preprocessor which is the +% projected Levenberg-Marquardt step from the following preprint: +% +% Christian Kanzow and Stefania Petra: Projected filter trust region methods for a +% semismooth least squares formulation of mixed complementarity +% problems. Optimization Methods and Software +% 22, 2007, pp. 713-735. +% +% A user's guide is also available: +% +% Christian Kanzow and Stefania Petra (2005). +% LMMCP --- A Levenberg-Marquardt-type MATLAB Solver for Mixed Complementarity Problems. +% University of Wuerzburg. +% http://www.mathematik.uni-wuerzburg.de/~kanzow/software/UserGuide.pdf +% +% This is a modification by Christophe Gouel of the original files, which can be +% downloaded from: +% http://www.mathematik.uni-wuerzburg.de/~kanzow/software/LMMCP.zip +% +% Written by Christian Kanzow and Stefania Petra +% Institute of Applied Mathematics and Statistics +% University of Wuerzburg +% Am Hubland +% 97074 Wuerzburg +% GERMANY +% +% e-mail: kanzow@mathematik.uni-wuerzburg.de +% petra@mathematik.uni-wuerzburg.de +% +% Christian Kanzow sent a private message to Dynare Team on July 8, 2014, +% confirming the free software status of lmmcp and granting unlimited +% permission to use, copy, modifiy or redistribute the file. + +% Copyright (C) 2005 Christian Kanzow and Stefania Petra +% Copyright (C) 2013 Christophe Gouel +% Copyright (C) 2014 Dynare Team +% +% Unlimited permission is granted to everyone to use, copy, modify or +% distribute this software. + +%% Initialization +defaultopt = struct(... + 'beta', 0.55,... + 'Big', 1e10,... + 'delta', 5,... + 'deltamin', 1,... + 'Display', 'none',... + 'epsilon1', 1e-6,... + 'eta', 0.95,... + 'kwatch', 20,... + 'lambda1', 0.1,... + 'm', 10,... + 'MaxIter', 500,... + 'null', 1e-10,... + 'preprocess', 1,... + 'presteps', 20,... + 'sigma', 1e-4,... + 'sigma1', 0.5,... + 'sigma2', 2,... + 'tmin', 1e-12,... + 'TolFun', sqrt(eps),... + 'watchdog', 1); + +if nargin < 4 + ub = inf(size(x)); + if nargin < 3 + lb = -inf(size(x)); + end +end + +if nargin < 5 || isempty(options) || ~isstruct(options) + options = defaultopt; +else + warning('off','catstruct:DuplicatesFound') + options = catstruct(defaultopt,options); +end + +warning('off','MATLAB:rankDeficientMatrix') + +switch options.Display + case {'off','none'} + verbosity = 0; + case {'iter','iter-detailed'} + verbosity = 2; + case {'final','final-detailed'} + verbosity = 1; + otherwise + verbosity = 0; +end + +% parameter settings +eps1 = options.epsilon1; +eps2 = 0.5*options.TolFun^2; +null = options.null; +Big = options.Big; + +% maximal number of iterations +kmax = options.MaxIter; + +% choice of lambda +lambda1 = options.lambda1; +lambda2 = 1-lambda1; + +% steplength parameters +beta = options.beta; +sigma = options.sigma; +tmin = options.tmin; + +% parameters watchdog and nonmonotone line search; redefined later +m = options.m; +kwatch = options.kwatch; +watchdog = options.watchdog; % 1=watchdog strategy active, otherwise not + +% parameters for preprocessor +preprocess = options.preprocess; % 1=preprocessor used, otherwise not +presteps = options.presteps; % maximum number of preprocessing steps + +% trust-region parameters for preprocessor +delta = options.delta; +deltamin = options.deltamin; +sigma1 = options.sigma1; +sigma2 = options.sigma2; +eta = options.eta; + +% initializations +k = 0; +k_main = 0; + +% compute a feasible starting point by projection +x = max(lb,min(x,ub)); + +n = length(x); +OUTPUT.Dim = n; + +% definition of index sets I_l, I_u and I_lu +Indexset = zeros(n,1); +I_l = lb>-Big & ub>Big; +I_u = lb<-Big & ub<Big; +I_lu = lb>-Big & ub<Big; +Indexset(I_l) = 1; +Indexset(I_u) = 2; +Indexset(I_lu) = 3; + +% function evaluations +[Fx,DFx] = feval(FUN,x,varargin{:}); + +% choice of NCP-function and corresponding evaluations +Phix = Phi(x,Fx,lb,ub,lambda1,lambda2,n,Indexset); +normPhix = norm(Phix); +Psix = 0.5*(Phix'*Phix); +DPhix = DPhi(x,Fx,DFx,lb,ub,lambda1,lambda2,n,Indexset); +DPsix = DPhix'*Phix; +normDPsix = norm(DPsix); + +% save initial values +x0 = x; +Phix0 = Phix; +Psix0 = Psix; +DPhix0 = DPhix; +DPsix0 = DPsix; +normDPsix0 = normDPsix; + +% watchdog strategy +aux = zeros(m,1); +aux(1) = Psix; +MaxPsi = Psix; + +if watchdog==1 + kbest = k; + xbest = x; + Phibest = Phix; + Psibest = Psix; + DPhibest = DPhix; + DPsibest = DPsix; + normDPsibest = normDPsix; +end + +% initial output +if verbosity > 1 + fprintf(' k Psi(x) || DPsi(x) || stepsize\n'); + disp('====================================================================') + disp('********************* Output at starting point *********************') + fprintf('%4.0f %24.5e %24.5e\n',k,Psix,normDPsix); +end + +%% Preprocessor using local method + +if preprocess==1 + + if verbosity > 1 + disp('************************** Preprocessor ****************************') + end + + normpLM=1; + while (k < presteps) && (Psix > eps2) && (normpLM>null) + k = k+1; + + % choice of Levenberg-Marquardt parameter, note that we do not use + % the condition estimator for large-scale problems, although this + % may cause numerical problems in some examples + + i = false; + mu = 0; + if n<100 + i = true; + mu = 1e-16; + if condest(DPhix'*DPhix)>1e25 + mu = 1e-6/(k+1); + end + end + if i + pLM = [DPhix; sqrt(mu)*speye(n)]\[-Phix; zeros(n,1)]; + else + pLM = -DPhix\Phix; + end + normpLM = norm(pLM); + + % compute the projected Levenberg-Marquard step onto box Xk + lbnew = max(min(lb-x,0),-delta); + ubnew = min(max(ub-x,0),delta); + d = max(lbnew,min(pLM,ubnew)); + xnew = x+d; + + % function evaluations etc. + [Fxnew,DFxnew] = feval(FUN,xnew,varargin{:}); + Phixnew = Phi(xnew,Fxnew,lb,ub,lambda1,lambda2,n,Indexset); + Psixnew = 0.5*(Phixnew'*Phixnew); + normPhixnew = norm(Phixnew); + + % update of delta + if normPhixnew<=eta*normPhix + delta = max(deltamin,sigma2*delta); + elseif normPhixnew>5*eta*normPhix + delta = max(deltamin,sigma1*delta); + end + + % update + x = xnew; + Fx = Fxnew; + DFx = DFxnew; + Phix = Phixnew; + Psix = Psixnew; + normPhix = normPhixnew; + DPhix = DPhi(x,Fx,DFx,lb,ub,lambda1,lambda2,n,Indexset); + DPsix = DPhix'*Phix; + normDPsix = norm(DPsix,inf); + + % output at each iteration + t=1; + if verbosity > 1 + fprintf('%4.0f %24.5e %24.5e %11.7g\n',k,Psix,normDPsix,t); + end + end +end + +% terminate program or redefine current iterate as original initial point +if preprocess==1 && Psix<eps2 + if verbosity > 0 + fprintf('Psix = %1.4e\nnormDPsix = %1.4e\n',Psix,normDPsix); + disp('Approximate solution found.') + end + EXITFLAG = 1; + FVAL = Fx; + OUTPUT.iterations = k; + OUTPUT.Psix = Psix; + OUTPUT.normDPsix = normDPsix; + JACOB = DFx; + return +elseif preprocess==1 && Psix>=eps2 + x=x0; + Phix=Phix0; + Psix=Psix0; + DPhix=DPhix0; + DPsix=DPsix0; + if verbosity > 1 + disp('******************** Restart with initial point ********************') + fprintf('%4.0f %24.5e %24.5e\n',k_main,Psix0,normDPsix0); + end +end + +%% Main algorithm + +if verbosity > 1 + disp('************************** Main program ****************************') +end + +while (k < kmax) && (Psix > eps2) + + % choice of Levenberg-Marquardt parameter, note that we do not use + % the condition estimator for large-scale problems, although this + % may cause numerical problems in some examples + + i = false; + if n<100 + i = true; + mu = 1e-16; + if condest(DPhix'*DPhix)>1e25 + mu = 1e-1/(k+1); + end + end + + % compute a Levenberg-Marquard direction + + if i + d = [DPhix; sqrt(mu)*speye(n)]\[-Phix; zeros(n,1)]; + else + d = -DPhix\Phix; + end + + % computation of steplength t using the nonmonotone Armijo-rule + % starting with the 6-th iteration + + % computation of steplength t using the monotone Armijo-rule if + % d is a 'good' descent direction or k<=5 + + t = 1; + xnew = x+d; + Fxnew = feval(FUN,xnew,varargin{:}); + Phixnew = Phi(xnew,Fxnew,lb,ub,lambda1,lambda2,n,Indexset); + Psixnew = 0.5*(Phixnew'*Phixnew); + const = sigma*DPsix'*d; + + while (Psixnew > MaxPsi + const*t) && (t > tmin) + t = t*beta; + xnew = x+t*d; + Fxnew = feval(FUN,xnew,varargin{:}); + Phixnew = Phi(xnew,Fxnew,lb,ub,lambda1,lambda2,n,Indexset); + Psixnew = 0.5*(Phixnew'*Phixnew); + end + + % updatings + x = xnew; + Fx = Fxnew; + Phix = Phixnew; + Psix = Psixnew; + [junk,DFx] = feval(FUN,x,varargin{:}); + DPhix = DPhi(x,Fx,DFx,lb,ub,lambda1,lambda2,n,Indexset); + DPsix = DPhix'*Phix; + normDPsix = norm(DPsix); + k = k+1; + k_main = k_main+1; + + if k_main<=5 + aux(mod(k_main,m)+1) = Psix; + MaxPsi = Psix; + else + aux(mod(k_main,m)+1) = Psix; + MaxPsi = max(aux); + end + + % updatings for the watchdog strategy + if watchdog ==1 + if Psix<Psibest + kbest = k; + xbest = x; + Phibest = Phix; + Psibest = Psix; + DPhibest = DPhix; + DPsibest = DPsix; + normDPsibest = normDPsix; + elseif k-kbest>kwatch + x=xbest; + Phix=Phibest; + Psix=Psibest; + DPhix=DPhibest; + DPsix=DPsibest; + normDPsix=normDPsibest; + MaxPsi=Psix; + end + end + + if verbosity > 1 + % output at each iteration + fprintf('%4.0f %24.5e %24.5e %11.7g\n',k,Psix,normDPsix,t); + end +end + +%% Final output +if Psix<=eps2 + EXITFLAG = 1; + if verbosity > 0, disp('Approximate solution found.'); end +elseif k>=kmax + EXITFLAG = 0; + if verbosity > 0, disp('Maximum iteration number reached.'); end +elseif normDPsix<=eps1 + EXITFLAG = -1; % Provisoire + if verbosity > 0, disp('Approximate stationary point found.'); end +else + EXITFLAG = -1; % Provisoire + if verbosity > 0, disp('No solution found.'); end +end + +FVAL = Fx; +OUTPUT.iterations = k; +OUTPUT.Psix = Psix; +OUTPUT.normDPsix = normDPsix; +JACOB = DFx; + +%% Subfunctions + +function y = Phi(x,Fx,lb,ub,lambda1,lambda2,n,Indexset) +%% PHI + +y = zeros(2*n,1); +phi_u = sqrt((ub-x).^2+Fx.^2)-ub+x+Fx; +LZ = false(n,1); % logical zero + +I0 = Indexset==0; +y(I0) = -lambda1*Fx(I0); +y([LZ; I0]) = -lambda2*Fx(I0); + +I1 = Indexset==1; +y(I1) = lambda1*(-x(I1)+lb(I1)-Fx(I1)+sqrt((x(I1)-lb(I1)).^2+Fx(I1).^2)); +y([LZ; I1]) = lambda2*max(0,x(I1)-lb(I1)).*max(0,Fx(I1)); + +I2 = Indexset==2; +y(I2) = -lambda1*phi_u(I2); +y([LZ; I2]) = lambda2*max(0,ub(I2)-x(I2)).*max(0,-Fx(I2)); + +I3 = Indexset==3; +y(I3) = lambda1*(sqrt((x(I3)-lb(I3)).^2+phi_u(I3).^2)-x(I3)+lb(I3)-phi_u(I3)); +y([LZ; I3]) = lambda2*(max(0,x(I3)-lb(I3)).*max(0,Fx(I3))+max(0,ub(I3)-x(I3)).*max(0,-Fx(I3))); + + +function H = DPhi(x,Fx,DFx,lb,ub,lambda1,lambda2,n,Indexset) +%% DPHI evaluates an element of the C-subdifferential of operator Phi + +null = 1e-8; +beta_l = zeros(n,1); +beta_u = zeros(n,1); +alpha_l = zeros(n,1); +alpha_u = zeros(n,1); + + +z = zeros(n,1); +H2 = sparse(n,n); + +I = abs(x-lb)<=null & abs(Fx)<=null; +beta_l(I) = 1; +z(I) = 1; + +I = abs(ub-x)<=null & abs(Fx)<=null; +beta_u(I) = 1; +z(I) = 1; + +I = x-lb>=-null & Fx>=-null; +alpha_l(I) = 1; + +I = ub-x>=-null & Fx<=null; +alpha_u(I) = 1; + +Da = zeros(n,1); +Db = zeros(n,1); + +I = 1:n; + +I0 = Indexset==0; +Da(I0) = 0; +Db(I0) = -1; +H2(I0,:) = -DFx(I0,:); + +I1 = Indexset==1; +denom1 = zeros(n,1); +denom2 = zeros(n,1); +if any(I1) + denom1(I1) = max(null,sqrt((x(I1)-lb(I1)).^2+Fx(I1).^2)); + denom2(I1) = max(null,sqrt(z(I1).^2+(DFx(I1,:)*z).^2)); +end + +I1b = Indexset==1 & beta_l==0; +Da(I1b) = (x(I1b)-lb(I1b))./denom1(I1b)-1; +Db(I1b) = Fx(I1b)./denom1(I1b)-1; +I1b = Indexset==1 & beta_l~=0; +if any(I1b) + Da(I1b) = z(I1b)./denom2(I1b)-1; + Db(I1b) = (DFx(I1b,:)*z)./denom2(I1b)-1; +end + +I1a = I(Indexset==1 & alpha_l==1); +if any(I1a) + H2(I1a,:) = spdiags(x(I1a)-lb(I1a), 0, length(I1a), length(I1a))*DFx(I1a,:) +... + sparse(1:length(I1a),I1a,Fx(I1a),length(I1a),n,length(I1a)); +end + +I2 = Indexset==2; +denom1 = zeros(n,1); +denom2 = zeros(n,1); +if any(I2) + denom1(I2) = max(null,sqrt((ub(I2)-x(I2)).^2+Fx(I2).^2)); + denom2(I2) = max(null,sqrt(z(I2).^2+(DFx(I2,:)*z).^2)); +end + +I2b = Indexset==2 & beta_u==0; +Da(I2b) = (ub(I2b)-x(I2b))./denom1(I2b)-1; +Db(I2b) = -Fx(I2b)./denom1(I2b)-1; +I2b = Indexset==2 & beta_u~=0; +if any(I2b) + Da(I2b) = -z(I2b)./denom2(I2b)-1; + Db(I2b) = -(DFx(I2b,:)*z)./denom2(I2b)-1; +end + +I2a = I(Indexset==2 & alpha_u==1); +if any(I2a) + H2(I2a,:) = bsxfun(@times,x(I2a)-ub(I2a),DFx(I2a,:))+... + sparse(1:length(I2a),I2a,Fx(I2a),length(I2a),n,length(I2a)); +end + +I3 = Indexset==3; +phi = zeros(n,1); +ai = zeros(n,1); +bi = zeros(n,1); +ci = zeros(n,1); +di = zeros(n,1); +denom1 = zeros(n,1); +denom2 = zeros(n,1); +denom3 = zeros(n,1); +denom4 = zeros(n,1); +if any(I3) + phi(I3) = -ub(I3)+x(I3)+Fx(I3)+sqrt((ub(I3)-x(I3)).^2+Fx(I3).^2); + denom1(I3) = max(null,sqrt((x(I3)-lb(I3)).^2+phi(I3).^2)); + denom2(I3) = max(null,sqrt(z(I3).^2+(DFx(I3,:)*z).^2)); + denom3(I3) = max(null,sqrt((ub(I3)-x(I3)).^2+Fx(I3).^2)); + denom4(I3) = max(null,sqrt(z(I3).^2)); +end + +I3bu = Indexset==3 & beta_u==0; +ci(I3bu) = (x(I3bu)-ub(I3bu))./denom3(I3bu)+1; +di(I3bu) = Fx(I3bu)./denom3(I3bu)+1; +I3bu = Indexset==3 & beta_u~=0; +if any(I3bu) + ci(I3bu) = 1+z(I3bu)./denom2(I3bu); + di(I3bu) = 1+(DFx(I3bu,:)*z)./denom2(I3bu); +end + +I3bl = Indexset==3 & beta_l==0; +ai(I3bl) = (x(I3bl)-lb(I3bl))./denom1(I3bl)-1; +bi(I3bl) = phi(I3bl)./denom1(I3bl)-1; +I3bl = Indexset==3 & beta_l~=0; +if any(I3bl) + ai(I3bl) = z(I3bl)./denom4(I3bl)-1; + bi(I3bl) = (ci(I3bl).*z(I3bl)+(di(I3bl,ones(1,n)).*DFx(I3bl,:))*z)./denom4(I3bl)-1; +end + +Da(I3) = ai(I3)+bi(I3).*ci(I3); +Db(I3) = bi(I3).*di(I3); + +I3a = I(Indexset==3 & alpha_l==1 & alpha_u==1); +if any(I3a) + H2(I3a,:) = bsxfun(@times,-lb(I3a)-ub(I3a)+2*x(I3a),DFx(I3a,:))+... + 2*sparse(1:length(I3a),I3a,Fx(I3a),length(I3a),n,length(I3a)); +end +I3a = I(Indexset==3 & alpha_l==1 & alpha_u~=1); +if any(I3a) + H2(I3a,:) = bsxfun(@times,x(I3a)-lb(I3a),DFx(I3a,:))+... + sparse(1:length(I3a),I3a,Fx(I3a),length(I3a),n,length(I3a)); +end +I3a = I(Indexset==3 & alpha_l~=1 & alpha_u==1); +if any(I3a) + H2(I3a,:) = bsxfun(@times,x(I3a)-ub(I3a),DFx(I3a,:))+... + sparse(1:length(I3a),I3a,Fx(I3a),length(I3a),n,length(I3a)); +end + +H1 = spdiags(Db,0,length(Db),length(Db))*DFx; +H1 = H1 + spdiags(Da, 0, length(Da), length(Da)); + +H = [lambda1*H1; lambda2*H2]; diff --git a/matlab/lnsrch1.m b/matlab/lnsrch1.m index 36e9f3afb5..09b128b918 100644 --- a/matlab/lnsrch1.m +++ b/matlab/lnsrch1.m @@ -20,7 +20,7 @@ function [x,f,fvec,check]=lnsrch1(xold, fold, g, p, stpmax, func, j1, j2, tolx, % fvec: residuals vector % check=1: problem of the looping which continues indefinitely % -% +% % SPECIAL REQUIREMENTS % none @@ -48,7 +48,7 @@ x = xold; nn = length(j2); summ = sqrt(p'*p); -if ~isfinite(summ) +if ~isfinite(summ) if ~isequal(func,@perfect_foresight_problem) eq_number_string=[]; for ii=1:length(j1)-1 @@ -61,13 +61,13 @@ if ~isfinite(summ) var_string=[var_string, deblank(Model.endo_names(j2(ii),:)), ', ']; end var_string=[var_string, deblank(Model.endo_names(j2(end),:))]; - fprintf('\nAn infinite element was encountered when trying to solve equation(s) %s \n',eq_number_string) + fprintf('\nAn infinite element was encountered when trying to solve equation(s) %s \n',eq_number_string) fprintf('with respect to the variable(s): %s.\n',var_string) fprintf('The values of the endogenous variables when the problem was encountered were:\n') for ii=1:length(xold) fprintf('%-s % 8.4g \n',Model.endo_names(ii,:),xold(ii)); end - skipline(); + skipline(); end error(['Some element of Newton direction isn''t finite. Jacobian maybe' ... ' singular or there is a problem with initial values']) diff --git a/matlab/lnsrch1_wrapper_one_boundary.m b/matlab/lnsrch1_wrapper_one_boundary.m index 2248510468..5aca3de3da 100644 --- a/matlab/lnsrch1_wrapper_one_boundary.m +++ b/matlab/lnsrch1_wrapper_one_boundary.m @@ -12,14 +12,14 @@ function r = lnsrch1_wrapper_one_boundary(ya, y_index, fname, y, x, params, stea % x [matrix] All the exogenous variables of the model % params [vector] All the parameters of the model % OUTPUTS -% r [vector] The residuals of the current block -% +% r [vector] The residuals of the current block +% % ALGORITHM % none. -% +% % SPECIAL REQUIREMENTS % none. -% +% % Copyright (C) 2009-2011 Dynare Team % diff --git a/matlab/lnsrch1_wrapper_two_boundaries.m b/matlab/lnsrch1_wrapper_two_boundaries.m index 3b55ca7035..75a9771cc1 100644 --- a/matlab/lnsrch1_wrapper_two_boundaries.m +++ b/matlab/lnsrch1_wrapper_two_boundaries.m @@ -17,14 +17,14 @@ function ra = lnsrch1_wrapper_two_boundaries(ya, fname, y, y_index, x, ... % y_size [int] The number of endogenous variables % in the current block % OUTPUTS -% ra [vector] The residuals of the current block -% +% ra [vector] The residuals of the current block +% % ALGORITHM % none. -% +% % SPECIAL REQUIREMENTS % none. -% +% % Copyright (C) 2009-2015 Dynare Team % diff --git a/matlab/load_first_mh_history_file.m b/matlab/load_first_mh_history_file.m index 3177fafe45..67bd70a1c5 100644 --- a/matlab/load_first_mh_history_file.m +++ b/matlab/load_first_mh_history_file.m @@ -1,7 +1,7 @@ function info = load_first_mh_history_file(MetropolisFolder, ModelName) % This routine requires that the MCMC draws were obtained with a dynare version greater than 4.3.3. - + % Copyright (C) 2013 Dynare Team % % This file is part of Dynare. diff --git a/matlab/load_last_mh_history_file.m b/matlab/load_last_mh_history_file.m index 92bf059dbb..e22fb61528 100644 --- a/matlab/load_last_mh_history_file.m +++ b/matlab/load_last_mh_history_file.m @@ -4,9 +4,9 @@ function info = load_last_mh_history_file(MetropolisFolder, ModelName) % Inputs: % MetropolisFolder [char] Name of the metropolis subfolder % ModelName [char] Name of the mod-file -% Outputs: +% Outputs: % info [struct] structure storing the MH history -% +% % Notes: The record structure is written to the caller workspace via an % assignin statement. @@ -37,7 +37,7 @@ mh_history_files = dir([BaseName '_mh_history_*.mat']); % Consistency with older versions of Dynare. if isequal(length(mh_history_files),0) if exist([BaseName '_mh_history.mat']) - format_mh_history_file = 1; % old Dynare format + format_mh_history_file = 1; % old Dynare format else error(['Estimation::load_mh_file: I cannot find any mh-history file in ' MetropolisFolder '!']) end @@ -63,7 +63,7 @@ else load([BaseName '_mh_history_' num2str(length(mh_history_files)-1) '.mat']); % add fields that have later been introduced if ~isfield(record,'MCMCConcludedSuccessfully') - record.MCMCConcludedSuccessfully = NaN; % This information is forever lost... + record.MCMCConcludedSuccessfully = NaN; % This information is forever lost... end if ~isfield(record,'MAX_nruns') record.MAX_nruns=NaN(size(record.MhDraws,1),1); % This information is forever lost... diff --git a/matlab/load_m_file_data_legacy.m b/matlab/load_m_file_data_legacy.m index 5a4cdecb90..9d4b8e34c8 100644 --- a/matlab/load_m_file_data_legacy.m +++ b/matlab/load_m_file_data_legacy.m @@ -81,82 +81,82 @@ o2WysrOISH = dseries(eval(sprintf(VbO4y7zOlh, U7ORsJ0vy3{:})), [], U7ORsJ0vy3); return %@test:1 - % Write a data file - fid = fopen('example.m','w'); - fwriten(fid, 'a = randn(100,1);'); - fwriten(fid, 'b = randn(100,1);'); - fwriten(fid, 'c = transpose(randn(100,1));'); - fwriten(fid, 'd = randn(100,1);'); - fwriten(fid, 'e = randn(100,2);'); - fwriten(fid, ' '); - fwriten(fid, 'f = NaN(100,1);'); - fwriten(fid, 'for i=1:100'); - fwriten(fid, ' f(i) = log(rand());') - fwriten(fid, 'end'); - fclose(fid); - % Define a set of variables to be loaded. - listofvariablestobeloaded = {'b', 'a'}; - % Test if we can load the data. - try - data = load_m_file_data_legacy('example.m', listofvariablestobeloaded); - delete example.m - t(1) = 1; - catch - t(1) = 0; - end - T = all(t); +% Write a data file +fid = fopen('example.m','w'); +fwriten(fid, 'a = randn(100,1);'); +fwriten(fid, 'b = randn(100,1);'); +fwriten(fid, 'c = transpose(randn(100,1));'); +fwriten(fid, 'd = randn(100,1);'); +fwriten(fid, 'e = randn(100,2);'); +fwriten(fid, ' '); +fwriten(fid, 'f = NaN(100,1);'); +fwriten(fid, 'for i=1:100'); +fwriten(fid, ' f(i) = log(rand());') +fwriten(fid, 'end'); +fclose(fid); +% Define a set of variables to be loaded. +listofvariablestobeloaded = {'b', 'a'}; +% Test if we can load the data. +try + data = load_m_file_data_legacy('example.m', listofvariablestobeloaded); + delete example.m + t(1) = 1; +catch + t(1) = 0; +end +T = all(t); %@eof:1 %@test:2 - % Write a data file - fid = fopen('example.m','w'); - fwriten(fid, 'a = randn(100,1);'); - fwriten(fid, 'b = randn(100,1);'); - fwriten(fid, 'c = transpose(randn(100,1));'); - fwriten(fid, 'd = randn(100,1);'); - fwriten(fid, 'e = randn(100,2);'); - fwriten(fid, ' '); - fwriten(fid, 'f = NaN(100,1);'); - fwriten(fid, 'for i=1:100'); - fwriten(fid, ' f(i) = log(rand());') - fwriten(fid, 'end'); - fclose(fid); - % Define a set of variables to be loaded. - listofvariablestobeloaded = {'e', 'a'}; - % Test if we can load the data. - try - data = load_m_file_data_legacy('example.m', listofvariablestobeloaded); - delete example.m - t(1) = 0; - catch - t(1) = 1; - end - T = all(t); +% Write a data file +fid = fopen('example.m','w'); +fwriten(fid, 'a = randn(100,1);'); +fwriten(fid, 'b = randn(100,1);'); +fwriten(fid, 'c = transpose(randn(100,1));'); +fwriten(fid, 'd = randn(100,1);'); +fwriten(fid, 'e = randn(100,2);'); +fwriten(fid, ' '); +fwriten(fid, 'f = NaN(100,1);'); +fwriten(fid, 'for i=1:100'); +fwriten(fid, ' f(i) = log(rand());') +fwriten(fid, 'end'); +fclose(fid); +% Define a set of variables to be loaded. +listofvariablestobeloaded = {'e', 'a'}; +% Test if we can load the data. +try + data = load_m_file_data_legacy('example.m', listofvariablestobeloaded); + delete example.m + t(1) = 0; +catch + t(1) = 1; +end +T = all(t); %@eof:2 %@test:3 - % Write a data file - fid = fopen('example.m','w'); - fwriten(fid, 'a = randn(100,1);'); - fwriten(fid, 'b = randn(100,1);'); - fwriten(fid, 'c = transpose(randn(100,1));'); - fwriten(fid, 'd = randn(100,1);'); - fwriten(fid, 'e = randn(100,2);'); - fwriten(fid, ' '); - fwriten(fid, 'f = NaN(100,1);'); - fwriten(fid, 'for i=1:100'); - fwriten(fid, ' f(i) = log(rand());') - fwriten(fid, 'end'); - fclose(fid); - % Define a set of variables to be loaded. - listofvariablestobeloaded = {'c', 'a'}; - % Test if we can load the data. - try - data = load_m_file_data_legacy('example.m', listofvariablestobeloaded); - delete example.m - t(1) = 1; - catch - t(1) = 0; - end - T = all(t); +% Write a data file +fid = fopen('example.m','w'); +fwriten(fid, 'a = randn(100,1);'); +fwriten(fid, 'b = randn(100,1);'); +fwriten(fid, 'c = transpose(randn(100,1));'); +fwriten(fid, 'd = randn(100,1);'); +fwriten(fid, 'e = randn(100,2);'); +fwriten(fid, ' '); +fwriten(fid, 'f = NaN(100,1);'); +fwriten(fid, 'for i=1:100'); +fwriten(fid, ' f(i) = log(rand());') +fwriten(fid, 'end'); +fclose(fid); +% Define a set of variables to be loaded. +listofvariablestobeloaded = {'c', 'a'}; +% Test if we can load the data. +try + data = load_m_file_data_legacy('example.m', listofvariablestobeloaded); + delete example.m + t(1) = 1; +catch + t(1) = 0; +end +T = all(t); %@eof:3 diff --git a/matlab/load_mat_file_data_legacy.m b/matlab/load_mat_file_data_legacy.m index bf8f342b1d..356c572370 100644 --- a/matlab/load_mat_file_data_legacy.m +++ b/matlab/load_mat_file_data_legacy.m @@ -27,14 +27,14 @@ if ~all(ismember(varobs',names)) for ii=2:size(missing_variables,1) disp_string=[disp_string,', ',missing_variables{ii,:}]; end - error('makedataset: The variable(s) %s listed in varobs are not contained in the dataset %s',disp_string); -else + error('makedataset: The variable(s) %s listed in varobs are not contained in the dataset %s',disp_string); +else data_mat=[]; for var_iter=1:length(varobs) try - data_mat=[data_mat vec(data_file.(varobs{1,var_iter}))]; + data_mat=[data_mat vec(data_file.(varobs{1,var_iter}))]; catch - error('makedataset: The variable %s does not have dimensions conformable with the previous one',varobs{1,var_iter}); + error('makedataset: The variable %s does not have dimensions conformable with the previous one',varobs{1,var_iter}); end end end diff --git a/matlab/lpdfgam.m b/matlab/lpdfgam.m index c98addbb79..7dbcf2579e 100644 --- a/matlab/lpdfgam.m +++ b/matlab/lpdfgam.m @@ -1,15 +1,15 @@ function [ldens,Dldens,D2ldens] = lpdfgam(x,a,b) % Evaluates the logged GAMMA PDF at x. % -% INPUTS +% INPUTS % x [double] m*n matrix of locations, % a [double] m*n matrix or scalar, First GAMMA distribution parameters (shape), % b [double] m*n matrix or scalar, Second GAMMA distribution parameters (scale), % % OUTPUTS % ldens [double] m*n matrix of logged GAMMA densities evaluated at x. -% -% +% +% % SPECIAL REQUIREMENTS % none @@ -41,7 +41,7 @@ end -if nargout >1 +if nargout >1 if length(a)==1 Dldens(idx) = (a-1)./(x(idx)) - ones(length(idx),1)/b ; else diff --git a/matlab/lpdfgbeta.m b/matlab/lpdfgbeta.m index bcb3c17371..6f0dd0fd87 100644 --- a/matlab/lpdfgbeta.m +++ b/matlab/lpdfgbeta.m @@ -1,16 +1,16 @@ function [ldens,Dldens,D2ldens] = lpdfgbeta(x,a,b,aa,bb) -% Evaluates the logged BETA PDF at x. +% Evaluates the logged BETA PDF at x. % -% INPUTS +% INPUTS % x [double] m*n matrix of loactions, -% a [double] m*n matrix of First BETA distribution parameters, -% b [double] m*n matrix of Second BETA distribution parameters, -% aa [double] m*n matrix of lower bounds for (generalized) distribution, +% a [double] m*n matrix of First BETA distribution parameters, +% b [double] m*n matrix of Second BETA distribution parameters, +% aa [double] m*n matrix of lower bounds for (generalized) distribution, % bb [double] m*n matrix of upper bounds for (generalized) distribution % -% OUTPUTS +% OUTPUTS % ldens [double] m*n matrix of logged (generalized) BETA densities. -% +% % SPECIAL REQUIREMENTS % none @@ -41,7 +41,7 @@ else end -if nargout >1 +if nargout >1 if length(a)==1 Dldens(idx) = (a-1)./(x(idx)-aa) - (b-1)./(bb-x(idx)) ; else @@ -50,7 +50,7 @@ if nargout >1 end -if nargout == 3 +if nargout == 3 if length(a)==1 D2ldens(idx) = -(a-1)./(x(idx)-aa).^2 - (b-1)./(bb-x(idx)).^2 ; else diff --git a/matlab/lpdfig1.m b/matlab/lpdfig1.m index 5aeb05f90c..11fd33b363 100644 --- a/matlab/lpdfig1.m +++ b/matlab/lpdfig1.m @@ -1,15 +1,15 @@ function [ldens,Dldens,D2ldens] = lpdfig1(x,s,nu) % Evaluates the logged INVERSE-GAMMA-1 PDF at x. % -% X ~ IG1(s,nu) if X = sqrt(Y) where Y ~ IG2(s,nu) and Y = inv(Z) with Z ~ G(nu/2,2/s) (Gamma distribution) +% X ~ IG1(s,nu) if X = sqrt(Y) where Y ~ IG2(s,nu) and Y = inv(Z) with Z ~ G(nu/2,2/s) (Gamma distribution) % % See L. Bauwens, M. Lubrano and J-F. Richard [1999, appendix A] for more details. % % -% INPUTS +% INPUTS % x [double] m*n matrix of locations, -% s [double] m*n matrix or scalar, First INVERSE-GAMMA-1 distribution parameters, -% nu [double] m*n matrix or scalar, Second INVERSE-GAMMA-1 distribution parameters. +% s [double] m*n matrix or scalar, First INVERSE-GAMMA-1 distribution parameters, +% nu [double] m*n matrix or scalar, Second INVERSE-GAMMA-1 distribution parameters. % % OUTPUTS % ldens [double] m*n matrix of logged INVERSE-GAMMA-1 densities evaluated at x. @@ -35,7 +35,7 @@ function [ldens,Dldens,D2ldens] = lpdfig1(x,s,nu) % along with Dynare. If not, see <http://www.gnu.org/licenses/>. ldens = -Inf( size(x) ) ; -idx = find( x>0 ) ; +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)) ; @@ -43,7 +43,7 @@ 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 -if nargout >1 +if nargout >1 if length(s)==1 Dldens(idx) = - (nu+1)./(x(idx)) + s./(x(idx).^3) ; else @@ -51,11 +51,10 @@ if nargout >1 end end -if nargout == 3 +if nargout == 3 if length(s)==1 D2ldens(idx) = (nu+1)./(x(idx).^2) - 3*s(idx)./(x(idx).^4) ; else D2ldens(idx) = (nu(idx)+1)./(x(idx).^2) - 3*s(idx)./(x(idx).^4) ; end end - diff --git a/matlab/lpdfig2.m b/matlab/lpdfig2.m index 00de3abb12..3f534fb05e 100644 --- a/matlab/lpdfig2.m +++ b/matlab/lpdfig2.m @@ -1,15 +1,15 @@ function [ldens,Dldens,D2ldens] = lpdfig2(x,s,nu) % Evaluates the logged INVERSE-GAMMA-2 PDF at x. % -% X ~ IG2(s,nu) if X = inv(Z) where Z ~ G(nu/2,2/s) (Gamma distribution) +% X ~ IG2(s,nu) if X = inv(Z) where Z ~ G(nu/2,2/s) (Gamma distribution) % % See L. Bauwens, M. Lubrano and J-F. Richard [1999, appendix A] for more details. % % -% INPUTS +% INPUTS % x [double] m*n matrix of locations, -% s [double] m*n matrix or scalar, First INVERSE-GAMMA-2 distribution parameters, -% nu [double] m*n matrix or scalar, Second INVERSE-GAMMA-2 distribution parameters. +% s [double] m*n matrix or scalar, First INVERSE-GAMMA-2 distribution parameters, +% nu [double] m*n matrix or scalar, Second INVERSE-GAMMA-2 distribution parameters. % % OUTPUTS % ldens [double] m*n matrix of logged INVERSE-GAMMA-2 densities evaluated at x. @@ -35,7 +35,7 @@ function [ldens,Dldens,D2ldens] = lpdfig2(x,s,nu) % along with Dynare. If not, see <http://www.gnu.org/licenses/>. ldens = -Inf( size(x) ) ; -idx = find( x>0 ) ; +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); @@ -43,7 +43,7 @@ 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 -if nargout >1 +if nargout >1 if length(s)==1 Dldens(idx) = - .5*(nu+2)./(x(idx)) + .5*s./x(idx).^2; else @@ -51,7 +51,7 @@ if nargout >1 end end -if nargout == 3 +if nargout == 3 if length(s)==1 D2ldens(idx) = .5*(nu+2)./(x(idx)).^2 - s./x(idx).^3; else diff --git a/matlab/lpdfnorm.m b/matlab/lpdfnorm.m index bb9da98d8e..fff678da91 100644 --- a/matlab/lpdfnorm.m +++ b/matlab/lpdfnorm.m @@ -1,15 +1,15 @@ function [ldens,Dldens,D2ldens] = lpdfnorm(x,a,b) % Evaluates the logged UNIVARIATE GAUSSIAN PDF at x. % -% INPUTS +% INPUTS % x [double] m*n matrix of locations, -% a [double] m*n matrix or scalar, First GAUSSIAN distribution parameters (expectation) -% b [double] m*n matrix or scalar, Second GAUSSIAN distribution parameters (standard deviation). +% a [double] m*n matrix or scalar, First GAUSSIAN distribution parameters (expectation) +% b [double] m*n matrix or scalar, Second GAUSSIAN distribution parameters (standard deviation). % -% OUTPUTS +% OUTPUTS % ldens [double] m*n matrix of logged GAUSSIAN densities evaluated at x. -% -% +% +% % SPECIAL REQUIREMENTS % none @@ -34,10 +34,10 @@ if nargin<3, b=1; end if nargin<2, a=0; end ldens = -log(b) -.5*log(2*pi) - .5*((x-a)./b).*((x-a)./b) ; -if nargout >1 +if nargout >1 Dldens = - (1./b).*((x-a)./b) ; end -if nargout == 3 +if nargout == 3 D2ldens = - (1./b).^2 ; end \ No newline at end of file diff --git a/matlab/lyapunov_solver.m b/matlab/lyapunov_solver.m index 2be9e3a282..98d782cdf3 100644 --- a/matlab/lyapunov_solver.m +++ b/matlab/lyapunov_solver.m @@ -1,14 +1,14 @@ function P=lyapunov_solver(T,R,Q,DynareOptions) % --*-- Unitary tests --*-- % function P=lyapunov_solver(T,R,Q,DynareOptions) % Solves the Lyapunov equation P-T*P*T' = R*Q*R' arising in a state-space -% system, where P is the variance of the states +% system, where P is the variance of the states % % Inputs % T [double] n*n matrix. % R [double] n*m matrix. % Q [double] m*m matrix. % DynareOptions [structure] Dynare options -% +% % Outputs % P [double] n*n matrix. % @@ -20,7 +20,7 @@ function P=lyapunov_solver(T,R,Q,DynareOptions) % --*-- Unitary tests --*-- % DynareOptions.lyapunov_db == 1 % doubling algorithm % DynareOptions.lyapunov_srs == 1 -% Square-root solver for discrete-time Lyapunov equations (requires Matlab System Control toolbox +% Square-root solver for discrete-time Lyapunov equations (requires Matlab System Control toolbox % or Octave control package) % Copyright (C) 2016-2017 Dynare Team @@ -60,7 +60,7 @@ elseif DynareOptions.lyapunov_srs == 1 end chol_Q = R*chol(Q,'lower'); R_P = dlyapchol(T,chol_Q); - P = R_P' * R_P; + P = R_P' * R_P; else P = lyapunov_symm(T,R*Q*R',DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold, [], DynareOptions.debug); end @@ -81,7 +81,7 @@ end %$ tmp2=randn(m_small,m_small); %$ Q_small=tmp2*tmp2'; %$ R_small=randn(n_small,m_small); -%$ +%$ %$ n_large=9; %$ m_large=11; %$ T_large=randn(n_large,n_large); @@ -89,7 +89,7 @@ end %$ tmp2=randn(m_large,m_large); %$ Q_large=tmp2*tmp2'; %$ R_large=randn(n_large,m_large); -%$ +%$ %$ % DynareOptions.lyapunov_fp == 1 %$ options_.lyapunov_fp = 1; %$ try diff --git a/matlab/lyapunov_symm.m b/matlab/lyapunov_symm.m index 92f66d4e11..53eaf9e4c1 100644 --- a/matlab/lyapunov_symm.m +++ b/matlab/lyapunov_symm.m @@ -1,22 +1,22 @@ function [x,u] = lyapunov_symm(a,b,lyapunov_fixed_point_tol,qz_criterium,lyapunov_complex_threshold,method,debug) % --*-- Unitary tests --*-- % 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] unit root threshold for eigenvalues % lyapunov_fixed_point_tol [double] convergence criteria for fixed_point algorithm. % 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 +% 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. % method=3 fixed point method % 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 +% u: [double] Schur vectors associated with unit roots % % ALGORITHM % Uses reordered Schur decomposition (Bartels-Stewart algorithm) @@ -74,7 +74,7 @@ if method == 3 X_old = X; X = a * X * at + b; evol = max(sum(abs(X - X_old))); %norm_1 - %evol = max(sum(abs(X - X_old)')); %norm_inf + %evol = max(sum(abs(X - X_old)')); %norm_inf it_fp = it_fp + 1; end if debug @@ -110,7 +110,7 @@ end if method<2 [U,T] = schur(a); e1 = abs(ordeig(T)) > 2-qz_criterium; - k = sum(e1); % Number of unit roots. + k = sum(e1); % Number of unit roots. n = length(e1)-k; % Number of stationary variables. if k > 0 % Selects stable roots diff --git a/matlab/marginal_density.m b/matlab/marginal_density.m index da9c450434..e5683da2c1 100644 --- a/matlab/marginal_density.m +++ b/matlab/marginal_density.m @@ -64,7 +64,7 @@ end % save the posterior mean and the inverse of the covariance matrix % (usefull if the user wants to perform some computations using -% the posterior mean instead of the posterior mode ==> ). +% the posterior mean instead of the posterior mode ==> ). parameter_names = bayestopt_.name; save([M_.fname '_mean.mat'],'xparam1','hh','parameter_names','SIGMA'); @@ -106,7 +106,7 @@ while check_coverage disp('Estimation::marginal density: The support of the weighting density function is not large enough...') disp('Estimation::marginal density: I increase the variance of this distribution.') increase = 1.2*increase; - linee = 0; + linee = 0; else disp('Estimation::marginal density: Let me try again.') increase = 1.2*increase; @@ -114,9 +114,9 @@ while check_coverage if increase > 20 check_coverage = 0; clear invSIGMA detSIGMA increase; - disp('Estimation::marginal density: There''s probably a problem with the modified harmonic mean estimator.') + disp('Estimation::marginal density: There''s probably a problem with the modified harmonic mean estimator.') end - end + end else check_coverage = 0; clear invSIGMA detSIGMA increase; @@ -130,17 +130,17 @@ return function oo_=fill_mh_mode(xparam1,stdh,M_,options_,estim_params_,bayestopt_,oo_, field_name) %function oo_=fill_mh_mode(xparam1,stdh,M_,options_,estim_params_,bayestopt_,oo_, field_name) -% -% INPUTS +% +% INPUTS % o xparam1 [double] (p*1) vector of estimate parameters. % o stdh [double] (p*1) vector of estimate parameters. -% o M_ Matlab's structure describing the Model (initialized by dynare, see @ref{M_}). +% o M_ Matlab's structure describing the Model (initialized by dynare, see @ref{M_}). % o estim_params_ Matlab's structure describing the estimated_parameters (initialized by dynare, see @ref{estim_params_}). % o options_ Matlab's structure describing the options (initialized by dynare, see @ref{options_}). % o bayestopt_ Matlab's structure describing the priors (initialized by dynare, see @ref{bayesopt_}). % o oo_ Matlab's structure gathering the results (initialized by dynare, see @ref{oo_}). -% -% OUTPUTS +% +% OUTPUTS % o oo_ Matlab's structure gathering the results % % SPECIAL REQUIREMENTS @@ -172,8 +172,8 @@ if nvx eval(['oo_.' field_name '_std_at_mode.shocks_std.' name ' = stdh(ip);']); ip = ip+1; end - end - if nvn +end +if nvn ip = nvx+1; for i=1:nvn name = options_.varobs{estim_params_.nvn_observable_correspondence(i,1)}; @@ -181,7 +181,7 @@ if nvx eval(['oo_.' field_name '_std_at_mode.measurement_errors_std.' name ' = stdh(ip);']); ip = ip+1; end - end +end if ncx ip = nvx+nvn+1; diff --git a/matlab/matlab_ver_less_than.m b/matlab/matlab_ver_less_than.m index 53dd8d7ef5..1b4b808768 100644 --- a/matlab/matlab_ver_less_than.m +++ b/matlab/matlab_ver_less_than.m @@ -8,7 +8,7 @@ function r = matlab_ver_less_than(verstr) % % INPUTS % verstr: a string of the format 'x.y' or 'x.y.z' -% +% % OUTPUTS % r: 0 or 1 % diff --git a/matlab/maximize_prior_density.m b/matlab/maximize_prior_density.m index 72df861a47..2c9fc4de9d 100644 --- a/matlab/maximize_prior_density.m +++ b/matlab/maximize_prior_density.m @@ -1,16 +1,16 @@ function [xparams,lpd,hessian_mat] = ... maximize_prior_density(iparams, prior_shape, prior_hyperparameter_1, prior_hyperparameter_2, prior_inf_bound, prior_sup_bound,DynareOptions,DynareModel,BayesInfo,EstimatedParams,DynareResults) % Maximizes the logged prior density using Chris Sims' optimization routine. -% -% INPUTS +% +% INPUTS % iparams [double] vector of initial parameters. % prior_shape [integer] vector specifying prior densities shapes. % prior_hyperparameter_1 [double] vector, first hyperparameter. % prior_hyperparameter_2 [double] vector, second hyperparameter. % prior_inf_bound [double] vector, prior's lower bound. -% prior_sup_bound [double] vector, prior's upper bound. +% prior_sup_bound [double] vector, prior's upper bound. % -% OUTPUTS +% OUTPUTS % xparams [double] vector, prior mode. % lpd [double] scalar, value of the logged prior density at the mode. % hessian_mat [double] matrix, Hessian matrix at the prior mode. diff --git a/matlab/mcforecast3.m b/matlab/mcforecast3.m index e2fb7de8a6..a01dbe8d57 100644 --- a/matlab/mcforecast3.m +++ b/matlab/mcforecast3.m @@ -2,7 +2,7 @@ function [forcs, e]= mcforecast3(cL,H,mcValue,shocks,forcs,T,R,mv,mu) % forcs = mcforecast3(cL,H,mcValue,shocks,forcs,T,R,mv,mu) % Computes the shock values for constrained forecasts necessary to keep % endogenous variables at their constrained paths -% +% % INPUTS % o cL [scalar] number of controlled periods % o H [scalar] number of forecast periods @@ -14,7 +14,7 @@ function [forcs, e]= mcforecast3(cL,H,mcValue,shocks,forcs,T,R,mv,mu) % o mv [n_controlled_exo by n_endovars boolean] indicator vector selecting constrained endogenous variables % o mu [n_controlled_vars by nexo boolean] indicator vector % selecting controlled exogenous variables -% +% % Algorithm: % Relies on state-space form: % y_t=T*y_{t-1}+R*shocks(:,t) @@ -30,7 +30,7 @@ function [forcs, e]= mcforecast3(cL,H,mcValue,shocks,forcs,T,R,mv,mu) % After obtaining the shocks, and for uncontrolled periods, the state-space representation % y_t=T*y_{t-1}+R*shocks(:,t) % is used for forecasting -% +% % Copyright (C) 2006-2015 Dynare Team % % This file is part of Dynare. diff --git a/matlab/mcompare.m b/matlab/mcompare.m index 9bf0f1713f..a43d54cf91 100644 --- a/matlab/mcompare.m +++ b/matlab/mcompare.m @@ -1,7 +1,7 @@ function mcompare(s1,s2) -% MCOMPARE : MCOMPARE ( [ 'file1' ; 'file2' ] , [ 'var1' ; 'var2' ...] ) +% MCOMPARE : MCOMPARE ( [ 'file1' ; 'file2' ] , [ 'var1' ; 'var2' ...] ) % This optional command plots the relative differences between -% two different simulations for a list of variables. One plot +% two different simulations for a list of variables. One plot % is drawn for each variable. The trajectories must have been % previously saved by the instruction DYNASAVE. The simulation % in file1 serves as the base simulation and the ploted quantity diff --git a/matlab/mcp_func.m b/matlab/mcp_func.m index 424b9203f9..f0af5189da 100644 --- a/matlab/mcp_func.m +++ b/matlab/mcp_func.m @@ -1,12 +1,12 @@ function [res,fjac,domer] = mcp_func(x,jacflag) % function [res,fjac,domer] = mcp_func(x,jacflag) % wrapper function for mixed complementarity problem when using PATH -% -% INPUTS +% +% INPUTS % - x [double] N*T array, paths for the endogenous variables (initial guess). % - jacflag [scalar] indicator whether Jacobian is requested % -% OUTPUTS +% OUTPUTS % - res [double] (N*T)*1 array, residuals of the stacked problem % - fjac [double] (N*T)*(N*T) array, Jacobian of the stacked problem % - domer [scalar] errorflag that is 1 if solution is not real diff --git a/matlab/metropolis_draw.m b/matlab/metropolis_draw.m index 783d2215a7..94c4212783 100644 --- a/matlab/metropolis_draw.m +++ b/matlab/metropolis_draw.m @@ -1,12 +1,12 @@ function [xparams, logpost, options_]=metropolis_draw(init,options_,estim_params_,M_) -% function [xparams, logpost]=metropolis_draw(init) +% function [xparams, logpost]=metropolis_draw(init) % Builds draws from metropolis % % INPUTS: -% init: scalar equal to -% 1: first call to store the required information -% on files, lines, and chains to be read -% in persistent variables to make them available +% init: scalar equal to +% 1: first call to store the required information +% on files, lines, and chains to be read +% in persistent variables to make them available % for future calls % 0: load a parameter draw % Additional Inputs required for initialization @@ -19,7 +19,7 @@ function [xparams, logpost, options_]=metropolis_draw(init,options_,estim_params % if init==1: error flaog % logpost: log of posterior density % options_: [structure] Matlab's structure describing the options (initialized by dynare, see @ref{options_}). -% +% % SPECIAL REQUIREMENTS % % Requires CutSample to be run before in order to set up mh_history-file @@ -61,9 +61,9 @@ if init %load mh_history-file with info on what to load load_last_mh_history_file(MetropolisFolder, FileName); FirstMhFile = record.KeepedDraws.FirstMhFile; - FirstLine = record.KeepedDraws.FirstLine; - TotalNumberOfMhFiles = sum(record.MhDraws(:,2)); - LastMhFile = TotalNumberOfMhFiles; + 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); %number of parameters plus posterior plus ? @@ -82,16 +82,16 @@ if init end return else %not initialization, return one draw - %get random draw from random chain + %get random draw from random chain ChainNumber = ceil(rand*mh_nblck); DrawNumber = ceil(rand*NumberOfDraws); if DrawNumber <= MAX_nruns-FirstLine+1 %draw in first file, needs to account for first line MhFilNumber = FirstMhFile; MhLine = FirstLine+DrawNumber-1; - else %draw in other file + else %draw in other file DrawNumber = DrawNumber-(MAX_nruns-FirstLine+1); - MhFilNumber = FirstMhFile+ceil(DrawNumber/MAX_nruns); + MhFilNumber = FirstMhFile+ceil(DrawNumber/MAX_nruns); MhLine = DrawNumber-(MhFilNumber-FirstMhFile-1)*MAX_nruns; end %load parameters and posterior diff --git a/matlab/metropolis_hastings_initialization.m b/matlab/metropolis_hastings_initialization.m index f62cf70233..e9d97a0ea2 100644 --- a/matlab/metropolis_hastings_initialization.m +++ b/matlab/metropolis_hastings_initialization.m @@ -3,13 +3,13 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa % function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npar, NumberOfBlocks, nruns, NewFile, MAX_nruns, d ] = ... % metropolis_hastings_initialization(TargetFun, xparam1, vv, mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_) % Metropolis-Hastings initialization. -% -% INPUTS +% +% INPUTS % o TargetFun [char] string specifying the name of the objective % function (posterior kernel). % o xparam1 [double] (p*1) vector of parameters to be estimated (initial values). % o vv [double] (p*p) matrix, posterior covariance matrix (at the mode). -% o mh_bounds [double] (p*2) matrix defining lower and upper bounds for the parameters. +% o mh_bounds [double] (p*2) matrix defining lower and upper bounds for the parameters. % o dataset_ data structure % o dataset_info dataset info structure % o options_ options structure @@ -17,17 +17,17 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa % o estim_params_ estimated parameters structure % o bayestopt_ estimation options structure % o oo_ outputs structure -% -% OUTPUTS +% +% OUTPUTS % o ix2 [double] (NumberOfBlocks*npar) vector of starting points for different chains % o ilogpo2 [double] (NumberOfBlocks*1) vector of initial posterior values for different chains % o ModelName [string] name of the mod-file % o MetropolisFolder [string] path to the Metropolis subfolder -% o FirstBlock [scalar] number of the first MH chain to be run (not equal to 1 in case of recovery) -% o FirstLine [double] (NumberOfBlocks*1) vector of first draw in each chain (not equal to 1 in case of recovery) +% o FirstBlock [scalar] number of the first MH chain to be run (not equal to 1 in case of recovery) +% o FirstLine [double] (NumberOfBlocks*1) vector of first draw in each chain (not equal to 1 in case of recovery) % o npar [scalar] number of parameters estimated -% o NumberOfBlocks [scalar] Number of MCM chains requested -% o nruns [double] (NumberOfBlocks*1) number of draws in each chain +% o NumberOfBlocks [scalar] Number of MCM chains requested +% o nruns [double] (NumberOfBlocks*1) number of draws in each chain % o NewFile [scalar] (NumberOfBlocks*1) vector storing the number % of the first MH-file to created for each chain when saving additional % draws @@ -57,7 +57,7 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa %Initialize outputs ix2 = []; ilogpo2 = []; -ModelName = []; +ModelName = []; MetropolisFolder = []; FirstBlock = []; FirstLine = []; @@ -124,7 +124,7 @@ if ~options_.load_mh_file && ~options_.mh_recover trial = 1; while validate == 0 && trial <= 10 candidate = rand_multivariate_normal( transpose(xparam1), d * options_.mh_init_scale, npar); - if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub) + if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub) ix2(j,:) = candidate; ilogpo2(j) = - feval(TargetFun,ix2(j,:)',dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_); if ~isfinite(ilogpo2(j)) % if returned log-density is @@ -167,7 +167,7 @@ if ~options_.load_mh_file && ~options_.mh_recover else% Case 2: one chain (we start from the posterior mode) fprintf(fidlog,[' Initial values of the parameters:\n']); candidate = transpose(xparam1(:));% - if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub) + if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub) ix2 = candidate; ilogpo2 = - feval(TargetFun,ix2',dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_); disp('Estimation::mcmc: Initialization at the posterior mode.') @@ -281,7 +281,7 @@ elseif options_.load_mh_file && ~options_.mh_recover NumberOfDrawsWrittenInThePastLastFile = MAX_nruns - LastLineNumber; NumberOfDrawsToBeSaved = nruns(1) - NumberOfDrawsWrittenInThePastLastFile; AnticipatedNumberOfFiles = ceil(NumberOfDrawsToBeSaved/MAX_nruns); - AnticipatedNumberOfLinesInTheLastFile = NumberOfDrawsToBeSaved - (AnticipatedNumberOfFiles-1)*MAX_nruns; + AnticipatedNumberOfLinesInTheLastFile = NumberOfDrawsToBeSaved - (AnticipatedNumberOfFiles-1)*MAX_nruns; record.LastFileNumber = LastFileNumber + AnticipatedNumberOfFiles; record.LastLineNumber = AnticipatedNumberOfLinesInTheLastFile; record.MhDraws(end,1) = nruns(1); @@ -300,15 +300,15 @@ elseif options_.mh_recover load_last_mh_history_file(MetropolisFolder, ModelName); NumberOfBlocks = record.Nblck;% Number of "parallel" mcmc chains. options_.mh_nblck = NumberOfBlocks; - + %% check consistency of options if record.MhDraws(end,1)~=options_.mh_replic fprintf('\nEstimation::mcmc: You cannot specify a different mh_replic than in the chain you are trying to recover\n') fprintf('Estimation::mcmc: I am resetting mh_replic to %u\n',record.MhDraws(end,1)) options_.mh_replic=record.MhDraws(end,1); nruns = ones(NumberOfBlocks,1)*options_.mh_replic; - end - + end + if ~isnan(record.MAX_nruns(end,1)) %field exists if record.MAX_nruns(end,1)~=MAX_nruns fprintf('\nEstimation::mcmc: You cannot specify a different MaxNumberOfBytes than in the chain you are trying to recover\n') @@ -335,9 +335,9 @@ elseif options_.mh_recover if OldMhExists LastLineNumberInThePreviousMh = record.MhDraws(end-1,3);% Number of lines in the last mh files of the previous session. LastFileNumberInThePreviousMh = sum(record.MhDraws(1:end-1,2),1);% Number of mh files in the the previous sessions. - %Test if the last mh files of the previous session were not full yet - if LastLineNumberInThePreviousMh < MAX_nruns%not full - %store starting point if whole chain needs to be redone + %Test if the last mh files of the previous session were not full yet + if LastLineNumberInThePreviousMh < MAX_nruns%not full + %store starting point if whole chain needs to be redone NewFile = ones(NumberOfBlocks,1)*LastFileNumberInThePreviousMh; FirstLine = ones(NumberOfBlocks,1)*(LastLineNumberInThePreviousMh+1); LastFileFullIndicator=0; @@ -354,9 +354,9 @@ elseif options_.mh_recover FirstLine = ones(NumberOfBlocks,1); LastFileFullIndicator=1; end - + %% Now find out what exactly needs to be redone - % 1. Check if really something needs to be done + % 1. Check if really something needs to be done % How many mh files should we have ? ExpectedNumberOfMhFilesPerBlock = sum(record.MhDraws(:,2),1); ExpectedNumberOfMhFiles = ExpectedNumberOfMhFilesPerBlock*NumberOfBlocks; @@ -366,7 +366,7 @@ elseif options_.mh_recover % Quit if no crashed mcmc chain can be found as there are as many files as expected if (TotalNumberOfMhFiles==ExpectedNumberOfMhFiles) disp('Estimation::mcmc: It appears that you don''t need to use the mh_recover option!') - disp(' You have to edit the mod file and remove the mh_recover option') + disp(' You have to edit the mod file and remove the mh_recover option') disp(' in the estimation command') error('Estimation::mcmc: mh_recover option not required!') end @@ -389,15 +389,15 @@ elseif options_.mh_recover end FirstBlock = FirstBlock+1; end - - %% 3. Overwrite default settings for + + %% 3. Overwrite default settings for % How many mh-files are saved in this block? NumberOfSavedMhFilesInTheCrashedBlck = NumberOfMhFilesPerBlock(FirstBlock); ExistingDrawsInLastMCFile=0; %initialize: no MCMC draws of current MCMC are in file from last run - % Check whether last present file is a file included in the last MCMC run - if ~LastFileFullIndicator + % Check whether last present file is a file included in the last MCMC run + if ~LastFileFullIndicator if NumberOfSavedMhFilesInTheCrashedBlck==NewFile(FirstBlock) %only that last file exists, but no files from current MCMC - loaded_results=load([BaseName '_mh' int2str(NewFile(FirstBlock)) '_blck' int2str(FirstBlock) '.mat']); + loaded_results=load([BaseName '_mh' int2str(NewFile(FirstBlock)) '_blck' int2str(FirstBlock) '.mat']); %check whether that last file was filled if size(loaded_results.x2,1)==MAX_nruns %file is full NewFile(FirstBlock)=NewFile(FirstBlock)+1; %set first file to be created to next one @@ -407,20 +407,20 @@ elseif options_.mh_recover ExistingDrawsInLastMCFile=0; end end - elseif LastFileFullIndicator + elseif LastFileFullIndicator ExistingDrawsInLastMCFile=0; if NumberOfSavedMhFilesInTheCrashedBlck==NewFile(FirstBlock) %only the last file exists, but no files from current MCMC NewFile(FirstBlock)=NewFile(FirstBlock)+1; %set first file to be created to next one end end -% % Correct the number of saved mh files if the crashed Metropolis was not the first session (so -% % that NumberOfSavedMhFilesInTheCrashedBlck is the number of saved mh files in the crashed chain -% % of the current session). -% if OldMhExists -% NumberOfSavedMhFilesInTheCrashedBlck = NumberOfSavedMhFilesInTheCrashedBlck - LastFileNumberInThePreviousMh; -% end -% NumberOfSavedMhFiles = NumberOfSavedMhFilesInTheCrashedBlck+LastFileNumberInThePreviousMh; - + % % Correct the number of saved mh files if the crashed Metropolis was not the first session (so + % % that NumberOfSavedMhFilesInTheCrashedBlck is the number of saved mh files in the crashed chain + % % of the current session). + % if OldMhExists + % NumberOfSavedMhFilesInTheCrashedBlck = NumberOfSavedMhFilesInTheCrashedBlck - LastFileNumberInThePreviousMh; + % end + % NumberOfSavedMhFiles = NumberOfSavedMhFilesInTheCrashedBlck+LastFileNumberInThePreviousMh; + % Correct initial conditions. if NumberOfSavedMhFilesInTheCrashedBlck<ExpectedNumberOfMhFilesPerBlock loaded_results=load([BaseName '_mh' int2str(NumberOfSavedMhFilesInTheCrashedBlck) '_blck' int2str(FirstBlock) '.mat']); diff --git a/matlab/metropolis_run_analysis.m b/matlab/metropolis_run_analysis.m index 99b589c820..aa4ec29a3e 100644 --- a/matlab/metropolis_run_analysis.m +++ b/matlab/metropolis_run_analysis.m @@ -1,12 +1,12 @@ function metropolis_run_analysis(M,basetopt,j) %function metropolis_run_analysis(M) % analizes Metropolis runs -% +% % INPUTS % M: (struct) Model structure % basetopt: (struct) Estimated parameters structure % j: (int) Index of estimated paramter -% +% % OUTPUTS % none % @@ -39,7 +39,7 @@ params = []; blck = 1; for i=1:record.LastFileNumber fname = [M.fname '/metropolis/' M.fname '_mh' int2str(i) '_blck' ... - int2str(blck) '.mat']; + int2str(blck) '.mat']; if exist(fname,'file') o=load(fname); logPost = [logPost; o.logpo2]; diff --git a/matlab/mex/k_order_perturbation.m b/matlab/mex/k_order_perturbation.m index 53359a9cf5..7c10d0efdf 100644 --- a/matlab/mex/k_order_perturbation.m +++ b/matlab/mex/k_order_perturbation.m @@ -37,7 +37,7 @@ % The Taylor coefficient (1/6) is % included. Inside the tensor, the variables are in % dr.order_var order of state endogenous variables -% and shocks +% and shocks % derivs struct contains the original derivatives of the % decision function (ghx, ghu, ghxx, ghxu, ghuu, % ghs2, ghxxx, ghxxu, ghxuu,ghuuu, ghxss, ghuss), diff --git a/matlab/mex/qmc_sequence.m b/matlab/mex/qmc_sequence.m index e540569994..1b93492731 100644 --- a/matlab/mex/qmc_sequence.m +++ b/matlab/mex/qmc_sequence.m @@ -16,7 +16,7 @@ %! @sp 1 %! @table @ @samp %! @item @var{t}=0 -%! Uniform numbers in a n-dimensional (unit by default) hypercube +%! Uniform numbers in a n-dimensional (unit by default) hypercube %! @item @var{t}=1 %! Gaussian numbers %! @item @var{t}=2 @@ -125,7 +125,7 @@ %$ %$ [draws1, S] = qmc_sequence(d,s,0,n,[0 , 2; -1, 2]); %$ [draws2, Q] = qmc_sequence(d,s,0,n); -%$ +%$ %$ draws3 = draws2; %$ draws3(1,:) = 2*draws2(1,:); %$ draws3(2,:) = 3*draws2(2,:)-1; diff --git a/matlab/mh_autocorrelation_function.m b/matlab/mh_autocorrelation_function.m index b14178def4..377de19786 100644 --- a/matlab/mh_autocorrelation_function.m +++ b/matlab/mh_autocorrelation_function.m @@ -1,9 +1,9 @@ function mh_autocorrelation_function(options_,M_,estim_params_,type,blck,name1,name2) % This function plots the autocorrelation of the sampled draws in the % posterior distribution. -% % -% INPUTS +% +% INPUTS % % options_ [structure] Dynare structure. % M_ [structure] Dynare structure (related to model definition). @@ -11,11 +11,11 @@ function mh_autocorrelation_function(options_,M_,estim_params_,type,blck,name1,n % type [string] 'DeepParameter', 'MeasurementError' (for measurement equation error) or 'StructuralShock' (for structural shock). % blck [integer] Number of the mh chain. % name1 [string] Object name. -% name2 [string] Object name. -% -% OUTPUTS +% name2 [string] Object name. +% +% OUTPUTS % None -% +% % SPECIAL REQUIREMENTS % Copyright (C) 2003-2017 Dynare Team @@ -36,7 +36,7 @@ function mh_autocorrelation_function(options_,M_,estim_params_,type,blck,name1,n % along with Dynare. If not, see <http://www.gnu.org/licenses/>. % Cet the column index: -if nargin<7 +if nargin<7 column = name2index(options_, M_, estim_params_, type, name1); else column = name2index(options_, M_, estim_params_, type, name1, name2); @@ -88,7 +88,7 @@ else end if options_.mh_nblck>1 - FigureName = [ FigureName , ' (block number' int2str(blck) ').']; + FigureName = [ FigureName , ' (block number' int2str(blck) ').']; end hh=dyn_figure(options_.nodisplay,'Name',FigureName); diff --git a/matlab/mh_optimal_bandwidth.m b/matlab/mh_optimal_bandwidth.m index c9296ad623..7d1858285d 100644 --- a/matlab/mh_optimal_bandwidth.m +++ b/matlab/mh_optimal_bandwidth.m @@ -1,28 +1,28 @@ -function optimal_bandwidth = mh_optimal_bandwidth(data,number_of_draws,bandwidth,kernel_function) +function optimal_bandwidth = mh_optimal_bandwidth(data,number_of_draws,bandwidth,kernel_function) % This function gives the optimal bandwidth parameter of a kernel estimator -% used to estimate a posterior univariate density from realisations of a -% Metropolis-Hastings algorithm. +% used to estimate a posterior univariate density from realisations of a +% Metropolis-Hastings algorithm. % % INPUTS: % data [double] Vector (number_of_draws*1) of draws. % number_of_draws [integer] Scalar, number of draws. -% bandwidth [integer] Scalar equal to 0,-1 or -2. +% bandwidth [integer] Scalar equal to 0,-1 or -2. % bandwidth = 0 => Silverman [1986] rule of thumb. % bandwidth = -1 => Sheather and Jones [1991]. -% bandwidth = -2 => Local bandwith parameters. +% bandwidth = -2 => Local bandwith parameters. % kernel_function [string] Name of the kernel function: 'gaussian', 'triweight', -% 'uniform', 'triangle', 'epanechnikov', 'quartic', +% 'uniform', 'triangle', 'epanechnikov', 'quartic', % 'triweight' and 'cosinus' % % OUTPUTS: % optimal_bandwidth: [double] Scalar or vector, optimal window width. -% +% % SPECIAL REQUIREMENTS: % none. % % REFERENCES: -% [1] M. Skoeld and G.O. Roberts [2003], "Density estimation for the Metropolis-Hastings algorithm". -% [2] Silverman [1986], "Density estimation for statistics and data analysis". +% [1] M. Skoeld and G.O. Roberts [2003], "Density estimation for the Metropolis-Hastings algorithm". +% [2] Silverman [1986], "Density estimation for statistics and data analysis". % Copyright (C) 2004-2017 Dynare Team % @@ -53,30 +53,30 @@ if strcmpi(kernel_function,'gaussian') k6 = @(x)inv(sqrt(2*pi))*(-15*exp(-0.5*x.^2)+45*(x.^2).*exp(-0.5*x.^2)-15*(x.^4).*exp(-0.5*x.^2)+(x.^6).*exp(-0.5*x.^2)); mu02 = inv(2*sqrt(pi)); mu21 = 1; -elseif strcmpi(kernel_function,'uniform') +elseif strcmpi(kernel_function,'uniform') k = @(x)0.5*(abs(x) <= 1); mu02 = 0.5; mu21 = 1/3; -elseif strcmpi(kernel_function,'triangle') +elseif strcmpi(kernel_function,'triangle') k = @(x)(1-abs(x)).*(abs(x) <= 1); mu02 = 2/3; mu21 = 1/6; -elseif strcmpi(kernel_function,'epanechnikov') +elseif strcmpi(kernel_function,'epanechnikov') k = @(x)0.75*(1-x.^2).*(abs(x) <= 1); mu02 = 3/5; mu21 = 1/5; -elseif strcmpi(kernel_function,'quartic') +elseif strcmpi(kernel_function,'quartic') k = @(x)0.9375*((1-x.^2).^2).*(abs(x) <= 1); mu02 = 15/21; mu21 = 1/7; -elseif strcmpi(kernel_function,'triweight') +elseif strcmpi(kernel_function,'triweight') k = @(x)1.09375*((1-x.^2).^3).*(abs(x) <= 1); k2 = @(x)(105/4*(1-x.^2).*x.^2-105/16*(1-x.^2).^2).*(abs(x) <= 1); k4 = @(x)(-1575/4*x.^2+315/4).*(abs(x) <= 1); k6 = @(x)(-1575/2).*(abs(x) <= 1); mu02 = 350/429; mu21 = 1/9; -elseif strcmpi(kernel_function,'cosinus') +elseif strcmpi(kernel_function,'cosinus') k = @(x)(pi/4)*cos((pi/2)*x).*(abs(x) <= 1); k2 = @(x)(-1/16*cos(pi*x/2)*pi^3).*(abs(x) <= 1); k4 = @(x)(1/64*cos(pi*x/2)*pi^5).*(abs(x) <= 1); @@ -101,20 +101,20 @@ sigma = std(data); if bandwidth == 0 % Rule of thumb bandwidth parameter (Silverman [1986]. h = 2*sigma*(sqrt(pi)*mu02/(12*(mu21^2)*number_of_draws))^(1/5); 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') || ... +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.']); - end + end Itilda4 = 8*7*6*5/(((2*sigma)^9)*sqrt(pi)); g3 = abs(2*correction*k6(0)/(mu21*Itilda4*number_of_draws))^(1/9); Ihat3 = 0; for i=1:number_of_draws Ihat3 = Ihat3 + sum(k6((data(i,1)-data)/g3)); - end + end Ihat3 = - Ihat3/((number_of_draws^2)*g3^7); g2 = abs(2*correction*k4(0)/(mu21*Ihat3*number_of_draws))^(1/7); Ihat2 = 0; @@ -122,12 +122,12 @@ elseif bandwidth == -1 % Sheather and Jones [1991] plug-in estimation of the opt Ihat2 = Ihat2 + sum(k4((data(i)-data)/g2)); end Ihat2 = Ihat2/((number_of_draws^2)*g2^5); - h = (correction*mu02/(number_of_draws*Ihat2*mu21^2))^(1/5); % equation (22) in Skold and Roberts [2003]. -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') || ... + h = (correction*mu02/(number_of_draws*Ihat2*mu21^2))^(1/5); % equation (22) in Skold and Roberts [2003]. +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') error(['I can''t compute the optimal bandwidth with this kernel...' ... 'Try the gaussian, triweight or cosinus kernels.']); @@ -137,7 +137,7 @@ elseif bandwidth == -2 % Bump killing... I compute local bandwith parameters j = i; while j<= n && (data(j,1)-data(i,1))<2*eps j = j+1; - end + end T(i) = (j-i); correction = correction + 2*T(i) - 1; end @@ -153,9 +153,9 @@ elseif bandwidth == -2 % Bump killing... I compute local bandwith parameters Ihat2 = 0; for i=1:number_of_draws Ihat2 = Ihat2 + sum(k4((data(i)-data)/g2)); - end + end Ihat2 = Ihat2/((number_of_draws^2)*g2^5); - h = ((2*T-1)*mu02/(number_of_draws*Ihat2*mu21^2)).^(1/5); % h is a column vector (local banwidth parameters). + h = ((2*T-1)*mu02/(number_of_draws*Ihat2*mu21^2)).^(1/5); % h is a column vector (local banwidth parameters). else disp('mh_optimal_bandwidth:: '); error('Parameter bandwidth must be equal to 0, -1 or -2.'); diff --git a/matlab/minus_logged_prior_density.m b/matlab/minus_logged_prior_density.m index 38662541e1..c36fbe2a81 100644 --- a/matlab/minus_logged_prior_density.m +++ b/matlab/minus_logged_prior_density.m @@ -1,15 +1,15 @@ function [fval,info,exit_flag,fake_1,fake_2] = minus_logged_prior_density(xparams,pshape,p6,p7,p3,p4,DynareOptions,DynareModel,EstimatedParams,DynareResults) % Evaluates minus the logged prior density. -% -% INPUTS +% +% INPUTS % xparams [double] vector of parameters. % pshape [integer] vector specifying prior densities shapes. % p6 [double] vector, first hyperparameter. % p7 [double] vector, second hyperparameter. % p3 [double] vector, prior's lower bound. -% p4 [double] vector, prior's upper bound. +% p4 [double] vector, prior's upper bound. % -% OUTPUTS +% OUTPUTS % f [double] value of minus the logged prior density. % info [double] vector: second entry stores penalty, first entry the error code. % @@ -128,8 +128,8 @@ M_ = set_all_parameters(xparams,EstimatedParams,DynareModel); % Return, with endogenous penalty when possible, if dynare_resolve issues an error code (defined in resol). if info(1) if info(1) == 3 || info(1) == 4 || info(1) == 5 || info(1)==6 ||info(1) == 19 ... - info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ... - info(1) == 81 || info(1) == 84 || info(1) == 85 + info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ... + info(1) == 81 || info(1) == 84 || info(1) == 85 %meaningful second entry of output that can be used fval = Inf; info(4) = info(2); @@ -138,7 +138,7 @@ if info(1) else fval = Inf; info(4) = 0.1; - exit_flag = 0; + exit_flag = 0; return end end diff --git a/matlab/missing/corrcoef/corrcoef.m b/matlab/missing/corrcoef/corrcoef.m index e997518ac9..722d969c0b 100644 --- a/matlab/missing/corrcoef/corrcoef.m +++ b/matlab/missing/corrcoef/corrcoef.m @@ -25,28 +25,28 @@ function [R,sig,ci1,ci2,nan_sig] = corrcoef(X,Y,varargin) % This replaces RANKCORR.M % % [...] = CORRCOEF(..., param1, value1, param2, value2, ... ); -% param value -% 'Mode' type of correlation -% 'Pearson','parametric' -% 'Spearman' -% 'rank' -% 'rows' how do deal with missing values encoded as NaN's. -% 'complete': remove all rows with at least one NaN -% 'pairwise': [default] -% 'alpha' 0.01 : significance level to compute confidence interval +% param value +% 'Mode' type of correlation +% 'Pearson','parametric' +% 'Spearman' +% 'rank' +% 'rows' how do deal with missing values encoded as NaN's. +% 'complete': remove all rows with at least one NaN +% 'pairwise': [default] +% 'alpha' 0.01 : significance level to compute confidence interval % % [R,p,ci1,ci2,nansig] = CORRCOEF(...); % R is the correlation matrix -% R(i,j) is the correlation coefficient r between X(:,i) and Y(:,j) +% R(i,j) is the correlation coefficient r between X(:,i) and Y(:,j) % p gives the significance of R -% It tests the null hypothesis that the product moment correlation coefficient is zero +% It tests the null hypothesis that the product moment correlation coefficient is zero % using Student's t-test on the statistic t = r*sqrt(N-2)/sqrt(1-r^2) % where N is the number of samples (Statistics, M. Spiegel, Schaum series). % p > alpha: do not reject the Null hypothesis: 'R is zero'. % p < alpha: The alternative hypothesis 'R is larger than zero' is true with probability (1-alpha). -% ci1 lower (1-alpha) confidence interval -% ci2 upper (1-alpha) confidence interval -% If no alpha is provided, the default alpha is 0.01. This can be changed with function flag_implicit_significance. +% ci1 lower (1-alpha) confidence interval +% ci2 upper (1-alpha) confidence interval +% If no alpha is provided, the default alpha is 0.01. This can be changed with function flag_implicit_significance. % nan_sig p-value whether H0: 'NaN''s are not correlated' could be correct % if nan_sig < alpha, H1 ('NaNs are correlated') is very likely. % @@ -65,7 +65,7 @@ function [R,sig,ci1,ci2,nan_sig] = corrcoef(X,Y,varargin) % Further recommandation related to the correlation coefficient: % + LOOK AT THE SCATTERPLOTS to make sure that the relationship is linear % + Correlation is not causation because -% it is not clear which parameter is 'cause' and which is 'effect' and +% it is not clear which parameter is 'cause' and which is 'effect' and % the observed correlation between two variables might be due to the action of other, unobserved variables. % % see also: SUMSKIPNAN, COVM, COV, COR, SPEARMAN, RANKCORR, RANKS, @@ -124,54 +124,54 @@ function [R,sig,ci1,ci2,nan_sig] = corrcoef(X,Y,varargin) global FLAG_NANS_OCCURED; -NARG = nargout; % needed because nargout is not reentrant in Octave, and corrcoef is recursive +NARG = nargout; % needed because nargout is not reentrant in Octave, and corrcoef is recursive mode = []; if nargin==1 - Y = []; - Mode='Pearson'; + Y = []; + Mode='Pearson'; elseif nargin==0 - fprintf(2,'Error CORRCOEF: Missing argument(s)\n'); + fprintf(2,'Error CORRCOEF: Missing argument(s)\n'); elseif nargin>1 - if ischar(Y) - varg = [Y,varargin]; - Y=[]; - else - varg = varargin; - end + if ischar(Y) + varg = [Y,varargin]; + Y=[]; + else + varg = varargin; + end - if length(varg)<1 - Mode = 'Pearson'; - elseif length(varg)==1 - Mode = varg{1}; - else - for k = 2:2:length(varg) - mode = setfield(mode,lower(varg{k-1}),varg{k}); - end - if isfield(mode,'mode') - Mode = mode.mode; - end + if length(varg)<1 + Mode = 'Pearson'; + elseif length(varg)==1 + Mode = varg{1}; + else + for k = 2:2:length(varg) + mode = setfield(mode,lower(varg{k-1}),varg{k}); + end + if isfield(mode,'mode') + Mode = mode.mode; end + end end if isempty(Mode), Mode='pearson'; end Mode=[Mode,' ']; -FLAG_WARNING = warning; % save warning status +FLAG_WARNING = warning; % save warning status warning('off'); [r1,c1]=size(X); if ~isempty(Y) - [r2,c2]=size(Y); - if r1~=r2 - fprintf(2,'Error CORRCOEF: X and Y must have the same number of observations (rows).\n'); - return - end - NN = real(~isnan(X)')*real(~isnan(Y)); + [r2,c2]=size(Y); + if r1~=r2 + fprintf(2,'Error CORRCOEF: X and Y must have the same number of observations (rows).\n'); + return + end + NN = real(~isnan(X)')*real(~isnan(Y)); else - [r2,c2]=size(X); - NN = real(~isnan(X)')*real(~isnan(X)); + [r2,c2]=size(X); + NN = real(~isnan(X)')*real(~isnan(X)); end %%%%% generate combinations using indices for pairwise calculation of the correlation @@ -196,117 +196,117 @@ if YESNAN end end if isempty(Y) - IX = ones(c1)-diag(ones(c1,1)); - [jx, jy ] = find(IX); - [jxo,jyo] = find(IX); + IX = ones(c1)-diag(ones(c1,1)); + [jx, jy ] = find(IX); + [jxo,jyo] = find(IX); R = eye(c1); else - IX = sparse([],[],[],c1+c2,c1+c2,c1*c2); - IX(1:c1,c1+(1:c2)) = 1; - [jx,jy] = find(IX); + IX = sparse([],[],[],c1+c2,c1+c2,c1*c2); + IX(1:c1,c1+(1:c2)) = 1; + [jx,jy] = find(IX); - IX = ones(c1,c2); - [jxo,jyo] = find(IX); + IX = ones(c1,c2); + [jxo,jyo] = find(IX); R = zeros(c1,c2); end if strcmp(lower(Mode(1:7)),'pearson') - % see http://mathworld.wolfram.com/CorrelationCoefficient.html + % see http://mathworld.wolfram.com/CorrelationCoefficient.html if ~YESNAN - [S,N,SSQ] = sumskipnan(X,1); - if ~isempty(Y) - [S2,N2,SSQ2] = sumskipnan(Y,1); - CC = X'*Y; - M1 = S./N; - M2 = S2./N2; - cc = CC./NN - M1'*M2; - R = cc./sqrt((SSQ./N-M1.*M1)'*(SSQ2./N2-M2.*M2)); - else - CC = X'*X; - M = S./N; - cc = CC./NN - M'*M; - v = SSQ./N - M.*M; %max(N-1,0); - R = cc./sqrt(v'*v); - end + [S,N,SSQ] = sumskipnan(X,1); + if ~isempty(Y) + [S2,N2,SSQ2] = sumskipnan(Y,1); + CC = X'*Y; + M1 = S./N; + M2 = S2./N2; + cc = CC./NN - M1'*M2; + R = cc./sqrt((SSQ./N-M1.*M1)'*(SSQ2./N2-M2.*M2)); else - if ~isempty(Y) - X = [X,Y]; - end - for k = 1:length(jx) - %ik = ~any(isnan(X(:,[jx(k),jy(k)])),2); - ik = ~isnan(X(:,jx(k))) & ~isnan(X(:,jy(k))); - [s,n,s2] = sumskipnan(X(ik,[jx(k),jy(k)]),1); - v = (s2-s.*s./n)./n; - cc = X(ik,jx(k))'*X(ik,jy(k)); - cc = cc/n(1) - prod(s./n); - %r(k) = cc./sqrt(prod(v)); - R(jxo(k),jyo(k)) = cc./sqrt(prod(v)); - end + CC = X'*X; + M = S./N; + cc = CC./NN - M'*M; + v = SSQ./N - M.*M; %max(N-1,0); + R = cc./sqrt(v'*v); + end + else + if ~isempty(Y) + X = [X,Y]; + end + for k = 1:length(jx) + %ik = ~any(isnan(X(:,[jx(k),jy(k)])),2); + ik = ~isnan(X(:,jx(k))) & ~isnan(X(:,jy(k))); + [s,n,s2] = sumskipnan(X(ik,[jx(k),jy(k)]),1); + v = (s2-s.*s./n)./n; + cc = X(ik,jx(k))'*X(ik,jy(k)); + cc = cc/n(1) - prod(s./n); + %r(k) = cc./sqrt(prod(v)); + R(jxo(k),jyo(k)) = cc./sqrt(prod(v)); + end end elseif strcmp(lower(Mode(1:4)),'rank') - % see [ 6] http://mathworld.wolfram.com/SpearmanRankCorrelationCoefficient.html + % see [ 6] http://mathworld.wolfram.com/SpearmanRankCorrelationCoefficient.html if ~YESNAN - if isempty(Y) - R = corrcoef(ranks(X)); - else - R = corrcoef(ranks(X),ranks(Y)); - end + if isempty(Y) + R = corrcoef(ranks(X)); else - if ~isempty(Y) - X = [X,Y]; - end - for k = 1:length(jx) - %ik = ~any(isnan(X(:,[jx(k),jy(k)])),2); - ik = ~isnan(X(:,jx(k))) & ~isnan(X(:,jy(k))); - il = ranks(X(ik,[jx(k),jy(k)])); - R(jxo(k),jyo(k)) = corrcoef(il(:,1),il(:,2)); - end + R = corrcoef(ranks(X),ranks(Y)); + end + else + if ~isempty(Y) + X = [X,Y]; + end + for k = 1:length(jx) + %ik = ~any(isnan(X(:,[jx(k),jy(k)])),2); + ik = ~isnan(X(:,jx(k))) & ~isnan(X(:,jy(k))); + il = ranks(X(ik,[jx(k),jy(k)])); + R(jxo(k),jyo(k)) = corrcoef(il(:,1),il(:,2)); + end X = ranks(X); end elseif strcmp(lower(Mode(1:8)),'spearman') - % see [ 6] http://mathworld.wolfram.com/SpearmanRankCorrelationCoefficient.html - if ~isempty(Y) - X = [X,Y]; - end + % see [ 6] http://mathworld.wolfram.com/SpearmanRankCorrelationCoefficient.html + if ~isempty(Y) + X = [X,Y]; + end - n = repmat(nan,c1,c2); + n = repmat(nan,c1,c2); - if ~YESNAN - iy = ranks(X); % calculates ranks; + if ~YESNAN + iy = ranks(X); % calculates ranks; - for k = 1:length(jx) - [R(jxo(k),jyo(k)),n(jxo(k),jyo(k))] = sumskipnan((iy(:,jx(k)) - iy(:,jy(k))).^2); % NN is the number of non-missing values - end - else - for k = 1:length(jx) - %ik = ~any(isnan(X(:,[jx(k),jy(k)])),2); - ik = ~isnan(X(:,jx(k))) & ~isnan(X(:,jy(k))); - il = ranks(X(ik,[jx(k),jy(k)])); - % NN is the number of non-missing values - [R(jxo(k),jyo(k)),n(jxo(k),jyo(k))] = sumskipnan((il(:,1) - il(:,2)).^2); - end - X = ranks(X); + for k = 1:length(jx) + [R(jxo(k),jyo(k)),n(jxo(k),jyo(k))] = sumskipnan((iy(:,jx(k)) - iy(:,jy(k))).^2); % NN is the number of non-missing values end - R = 1 - 6 * R ./ (n.*(n.*n-1)); + else + for k = 1:length(jx) + %ik = ~any(isnan(X(:,[jx(k),jy(k)])),2); + ik = ~isnan(X(:,jx(k))) & ~isnan(X(:,jy(k))); + il = ranks(X(ik,[jx(k),jy(k)])); + % NN is the number of non-missing values + [R(jxo(k),jyo(k)),n(jxo(k),jyo(k))] = sumskipnan((il(:,1) - il(:,2)).^2); + end + X = ranks(X); + end + R = 1 - 6 * R ./ (n.*(n.*n-1)); elseif strcmp(lower(Mode(1:7)),'partial') - fprintf(2,'Error CORRCOEF: use PARTCORRCOEF \n',Mode); + fprintf(2,'Error CORRCOEF: use PARTCORRCOEF \n',Mode); - return + return elseif strcmp(lower(Mode(1:7)),'kendall') - fprintf(2,'Error CORRCOEF: mode ''%s'' not implemented yet.\n',Mode); + fprintf(2,'Error CORRCOEF: mode ''%s'' not implemented yet.\n',Mode); - return + return else - fprintf(2,'Error CORRCOEF: unknown mode ''%s''\n',Mode); + fprintf(2,'Error CORRCOEF: unknown mode ''%s''\n',Mode); end if (NARG<2) - warning(FLAG_WARNING); % restore warning status - return + warning(FLAG_WARNING); % restore warning status + return end @@ -314,7 +314,7 @@ end if isfield(mode,'alpha') alpha = mode.alpha; elseif exist('flag_implicit_significance','file') - alpha = flag_implicit_significance; + alpha = flag_implicit_significance; else alpha = 0.01; end @@ -324,36 +324,36 @@ end % SIGNIFICANCE TEST R(isnan(R))=0; tmp = 1 - R.*R; -tmp(tmp<0) = 0; % prevent tmp<0 i.e. imag(t)~=0 +tmp(tmp<0) = 0; % prevent tmp<0 i.e. imag(t)~=0 t = R.*sqrt(max(NN-2,0)./tmp); if exist('t_cdf','file') - sig = t_cdf(t,NN-2); + sig = t_cdf(t,NN-2); elseif exist('tcdf','file')>1 - sig = tcdf(t,NN-2); + sig = tcdf(t,NN-2); else - fprintf('CORRCOEF: significance test not completed because of missing TCDF-function\n') - sig = repmat(nan,size(R)); + fprintf('CORRCOEF: significance test not completed because of missing TCDF-function\n') + sig = repmat(nan,size(R)); end sig = 2 * min(sig,1 - sig); if NARG<3 warning(FLAG_WARNING); % restore warning status - return + return end tmp = R; -%tmp(ix1 | ix2) = nan; % avoid division-by-zero warning +%tmp(ix1 | ix2) = nan; % avoid division-by-zero warning z = log((1+tmp)./(1-tmp))/2; % Fisher transformation [21] -%sz = 1./sqrt(NN-3); % standard error of z -sz = sqrt(2)*erfinv(1-alpha)./sqrt(NN-3); % confidence interval for alpha of z + %sz = 1./sqrt(NN-3); % standard error of z +sz = sqrt(2)*erfinv(1-alpha)./sqrt(NN-3); % confidence interval for alpha of z ci1 = tanh(z-sz); ci2 = tanh(z+sz); -%ci1(isnan(ci1))=R(isnan(ci1)); % in case of isnan(ci), the interval limits are exactly the R value +%ci1(isnan(ci1))=R(isnan(ci1)); % in case of isnan(ci), the interval limits are exactly the R value %ci2(isnan(ci2))=R(isnan(ci2)); if (NARG<5) || ~YESNAN @@ -371,16 +371,15 @@ nan_sig(isnan(nan_R)) = nan; nan_R(isnan(nan_R)) = 0; if 0, any(nan_sig(:) < alpha) - tmp = nan_sig(:); % Hack to skip NaN's in MIN(X) - min_sig = min(tmp(~isnan(tmp))); % Necessary, because Octave returns NaN rather than min(X) for min(NaN,X) - fprintf(1,'CORRCOFF Warning: Missing Values (i.e. NaNs) are not independent of data (p-value=%f)\n', min_sig); - fprintf(1,' Its recommended to remove all samples (i.e. rows) with any missing value (NaN).\n'); - fprintf(1,' The null-hypotheses (NaNs are uncorrelated) is rejected for the following parameter pair(s).\n'); - [ix,iy] = find(nan_sig < alpha); - disp([ix,iy]) + tmp = nan_sig(:); % Hack to skip NaN's in MIN(X) + min_sig = min(tmp(~isnan(tmp))); % Necessary, because Octave returns NaN rather than min(X) for min(NaN,X) + fprintf(1,'CORRCOFF Warning: Missing Values (i.e. NaNs) are not independent of data (p-value=%f)\n', min_sig); + fprintf(1,' Its recommended to remove all samples (i.e. rows) with any missing value (NaN).\n'); + fprintf(1,' The null-hypotheses (NaNs are uncorrelated) is rejected for the following parameter pair(s).\n'); + [ix,iy] = find(nan_sig < alpha); + disp([ix,iy]) end %%%%% ----- end of independence check ------ warning(FLAG_WARNING); % restore warning status - diff --git a/matlab/missing/corrcoef/flag_implicit_skip_nan.m b/matlab/missing/corrcoef/flag_implicit_skip_nan.m index c86580d566..12795f5291 100644 --- a/matlab/missing/corrcoef/flag_implicit_skip_nan.m +++ b/matlab/missing/corrcoef/flag_implicit_skip_nan.m @@ -1,6 +1,6 @@ function FLAG = flag_implicit_skip_nan(i) % FLAG_IMPLICIT_SKIP_NAN sets and gets default mode for handling NaNs -% 1 skips NaN's (the default mode if no mode is set) +% 1 skips NaN's (the default mode if no mode is set) % 0 NaNs are propagated; input NaN's give NaN's at the output % % FLAG = flag_implicit_skip_nan() @@ -9,15 +9,15 @@ function FLAG = flag_implicit_skip_nan(i) % flag_implicit_skip_nan(FLAG) % sets mode % % prevFLAG = flag_implicit_skip_nan(nextFLAG) -% gets previous set FLAG and sets FLAG for the future +% gets previous set FLAG and sets FLAG for the future % flag_implicit_skip_nan(prevFLAG) -% resets FLAG to previous mode +% resets FLAG to previous mode % % It is used in: -% SUMSKIPNAN, MEDIAN, QUANTILES, TRIMEAN +% SUMSKIPNAN, MEDIAN, QUANTILES, TRIMEAN % and affects many other functions like: -% CENTER, KURTOSIS, MAD, MEAN, MOMENT, RMS, SEM, SKEWNESS, -% STATISTIC, STD, VAR, ZSCORE etc. +% CENTER, KURTOSIS, MAD, MEAN, MOMENT, RMS, SEM, SKEWNESS, +% STATISTIC, STD, VAR, ZSCORE etc. % % The mode is stored in the global variable FLAG_implicit_skip_nan % It is recommended to use flag_implicit_skip_nan(1) as default and @@ -40,7 +40,7 @@ function FLAG = flag_implicit_skip_nan(i) % along with this program; if not, write to the Free Software % Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -% $Id: flag_implicit_skip_nan.m 8351 2011-06-24 17:35:07Z carandraug $ +% $Id: flag_implicit_skip_nan.m 8351 2011-06-24 17:35:07Z carandraug $ % Copyright (C) 2001-2003,2009 by Alois Schloegl <alois.schloegl@gmail.com> % Copyright (C) 2014 Dynare Team % This function is part of the NaN-toolbox @@ -49,7 +49,7 @@ function FLAG = flag_implicit_skip_nan(i) persistent FLAG_implicit_skip_nan; -%% if strcmp(version,'3.6'), FLAG_implicit_skip_nan=(1==1); end; %% hack for the use with Freemat3.6 +%% if strcmp(version,'3.6'), FLAG_implicit_skip_nan=(1==1); end; %% hack for the use with Freemat3.6 %%% set DEFAULT value of FLAG if isempty(FLAG_implicit_skip_nan) @@ -63,4 +63,3 @@ if nargin>0 warning('flag_implicit_skipnan(0): You are warned!!! You have turned off skipping NaN in sumskipnan. This is not recommended. Make sure you really know what you do.') end end - diff --git a/matlab/missing/corrcoef/sumskipnan.m b/matlab/missing/corrcoef/sumskipnan.m index 1c53fee6d4..cdff175d39 100644 --- a/matlab/missing/corrcoef/sumskipnan.m +++ b/matlab/missing/corrcoef/sumskipnan.m @@ -13,13 +13,13 @@ function [o,count,SSQ] = sumskipnan(x, DIM, W) % [Y,N,SSQ] = sumskipnan(x [,DIM]) % [...] = sumskipnan(x, DIM, W) % -% x input data -% DIM dimension (default: []) -% empty DIM sets DIM to first non singleton dimension -% W weight vector for weighted sum, numel(W) must fit size(x,DIM) -% Y resulting sum -% N number of valid (not missing) elements -% SSQ sum of squares +% x input data +% DIM dimension (default: []) +% empty DIM sets DIM to first non singleton dimension +% W weight vector for weighted sum, numel(W) must fit size(x,DIM) +% Y resulting sum +% N number of valid (not missing) elements +% SSQ sum of squares % % the function FLAG_NANS_OCCURED() returns whether any value in x % is a not-a-number (NaN) @@ -47,7 +47,7 @@ function [o,count,SSQ] = sumskipnan(x, DIM, W) % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. -% $Id: sumskipnan.m 9033 2011-11-08 20:58:07Z schloegl $ +% $Id: sumskipnan.m 9033 2011-11-08 20:58:07Z schloegl $ % Copyright (C) 2000-2005,2009,2011 by Alois Schloegl <alois.schloegl@gmail.com> % Copyright (C) 2014 Dynare Team % This function is part of the NaN-toolbox @@ -57,10 +57,10 @@ function [o,count,SSQ] = sumskipnan(x, DIM, W) global FLAG_NANS_OCCURED; if nargin<2 - DIM = []; + DIM = []; end if nargin<3 - W = []; + W = []; end % an efficient implementation in C of the following lines @@ -73,14 +73,14 @@ end % if ~isnan(i(k)) % { o += x(k); % count += 1; -% tmp = x(k)*x(k) -% o2 += tmp; -% o3 += tmp.*tmp; +% tmp = x(k)*x(k) +% o2 += tmp; +% o3 += tmp.*tmp; % }; if isempty(DIM) - DIM = find(size(x)>1,1); - if isempty(DIM), DIM = 1; end + DIM = find(size(x)>1,1); + if isempty(DIM), DIM = 1; end end if (DIM<1), DIM = 1; end %% Hack, because min([])=0 for FreeMat v3.5 @@ -169,7 +169,7 @@ end % count non-NaN's %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargout>1 - count = sum(x==x,DIM); + count = sum(x==x,DIM); FLAG_NANS_OCCURED = any(count(:)<size(x,DIM)); end @@ -180,8 +180,8 @@ x(x~=x) = 0; o = sum(x,DIM); if nargout>2 - x = real(x).^2 + imag(x).^2; - SSQ = sum(x,DIM); + x = real(x).^2 + imag(x).^2; + SSQ = sum(x,DIM); end %!assert(sumskipnan([1,2],1),[1,2]) @@ -189,6 +189,3 @@ end %!assert(sumskipnan([1,NaN],2),1) %!assert(sumskipnan([nan,1,4,5]),10) %!assert(sumskipnan([nan,1,4,5]',1,[3;2;1;0]),6) - - - diff --git a/matlab/missing/corrcoef/tcdf.m b/matlab/missing/corrcoef/tcdf.m index 1901c4f7d1..38c8379ed6 100644 --- a/matlab/missing/corrcoef/tcdf.m +++ b/matlab/missing/corrcoef/tcdf.m @@ -11,8 +11,8 @@ function p = tcdf(x,n) % Reference(s): -% $Id: tcdf.m 9033 2011-11-08 20:58:07Z schloegl $ -% Copyright (C) 2000-2003,2009 by Alois Schloegl <alois.schloegl@gmail.com> +% $Id: tcdf.m 9033 2011-11-08 20:58:07Z schloegl $ +% Copyright (C) 2000-2003,2009 by Alois Schloegl <alois.schloegl@gmail.com> % Copyright (C) 2014 Dynare Team % This is part of the NaN-toolbox. For more details see % http://pub.ist.ac.at/~schloegl/matlab/NaN/ diff --git a/matlab/missing/ilu/ilu.m b/matlab/missing/ilu/ilu.m index 4b4fe23382..0b8f8df737 100644 --- a/matlab/missing/ilu/ilu.m +++ b/matlab/missing/ilu/ilu.m @@ -18,20 +18,20 @@ function [L, U, P] = ilu(A, setup) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if nargout ~= 2 - error('Only two output arguments supported') - end - if nargin ~= 2 - error('Only two input arguments supported') - end +if nargout ~= 2 + error('Only two output arguments supported') +end +if nargin ~= 2 + error('Only two input arguments supported') +end + +if isfield(setup, 'milu') + if setup.milu == 'off' + setup.milu = 0; + else + error(['Unsupported milu: ' setup.milu ]) + end +end - if isfield(setup, 'milu') - if setup.milu == 'off' - setup.milu = 0; - else - error(['Unsupported milu: ' setup.milu ]) - end - end - - [L, U] = luinc(A, setup); +[L, U] = luinc(A, setup); end diff --git a/matlab/missing/issquare/issquare.m b/matlab/missing/issquare/issquare.m index 4d4eb2b572..dfbfe89259 100644 --- a/matlab/missing/issquare/issquare.m +++ b/matlab/missing/issquare/issquare.m @@ -46,7 +46,7 @@ function i = issquare(A) d = size(A); if (length(d)==2) && (d(1)==d(2)) - i = d(1); + i = d(1); else - i = 0; + i = 0; end diff --git a/matlab/missing/stats/betacdf.m b/matlab/missing/stats/betacdf.m index 2ba7cc53eb..b15913fbb1 100644 --- a/matlab/missing/stats/betacdf.m +++ b/matlab/missing/stats/betacdf.m @@ -61,4 +61,3 @@ if (any (k)) end end - diff --git a/matlab/missing/stats/betarnd.m b/matlab/missing/stats/betarnd.m index f27fca4413..02c9e5ad73 100644 --- a/matlab/missing/stats/betarnd.m +++ b/matlab/missing/stats/betarnd.m @@ -1,16 +1,16 @@ function rnd = betarnd(a, b) % This function produces independent random variates from the Beta distribution. % -% INPUTS +% INPUTS % a [double] n*1 vector of positive parameters. % b [double] n*1 vector of positive parameters. % -% OUTPUT +% OUTPUT % rnd [double] n*1 vector of independent variates from the beta(a,b) distribution. -% rnd(i) is beta distributed with variance a(i)/(a(i)+b(i)) and -% variance a(i)b(i)/(a(i)+b(i))^2/(a(i)+b(i)+1). -% -% ALGORITHMS +% rnd(i) is beta distributed with variance a(i)/(a(i)+b(i)) and +% variance a(i)b(i)/(a(i)+b(i))^2/(a(i)+b(i)+1). +% +% ALGORITHMS % Described and Devroye (1986, chapter 9). % Copyright (C) 2008-2009 Dynare Team diff --git a/matlab/missing/stats/corr.m b/matlab/missing/stats/corr.m index 4f3ebfb7bf..6b5d35cbbd 100644 --- a/matlab/missing/stats/corr.m +++ b/matlab/missing/stats/corr.m @@ -25,7 +25,7 @@ function retval = corr(x, y) % --*-- Unitary tests --*-- %! the correlation between the columns of @var{x}. %! @end deftypefn %@eod: -% +% % Notes: - the original Octave code has been rewritten to avoid calling cov, since % there is a long-standing incompatiblity between Matlab's cov and Octave's cov % (see https://savannah.gnu.org/bugs/?40751) @@ -63,12 +63,12 @@ end % Input validation if (nargin==1 && ~(isnumeric (x) || islogical (x))) || ... - (nargin==2 && ~(isnumeric (x) || islogical (x) || isnumeric (y) || islogical (y))) + (nargin==2 && ~(isnumeric (x) || islogical (x) || isnumeric (y) || islogical (y))) error ('corr: X and Y must be numeric matrices or vectors'); end if (nargin==1 && ~ismatrix(x)) || (nargin==2 && (~ismatrix(y) || ~ismatrix(x))) -error ('corr: X and Y must be 2-D matrices or vectors'); + error ('corr: X and Y must be 2-D matrices or vectors'); end if (nargin == 2) @@ -82,13 +82,13 @@ if isscalar(x) if nargin==1 retval = NaN; else - retval = NaN(size(y)); + retval = NaN(size(y)); end return end if nargin==2 && isscalar(y) - retval = NaN(size(x')); + retval = NaN(size(x')); return end diff --git a/matlab/missing/stats/exprnd.m b/matlab/missing/stats/exprnd.m index 65855db6e3..6fc088b777 100644 --- a/matlab/missing/stats/exprnd.m +++ b/matlab/missing/stats/exprnd.m @@ -2,20 +2,20 @@ function rnd = exprnd(a) % Random samples from the exponential distribution with expectation a % and variance a^2. % -% INPUTS +% INPUTS % a [double] m*n matrix of positive parameters % -% OUTPUT +% OUTPUT % rnd [double] m*n matrix, independent draws from the exponential -% distribution rnd(j,j) has expectation a(i,j) and -% variance a(i,j)^2. +% distribution rnd(j,j) has expectation a(i,j) and +% variance a(i,j)^2. % -% ALGORITHM +% ALGORITHM % Inverse transform sampling. % % SPECIAL REQUIREMENTS % None. -% +% % Copyright (C) 2009 Dynare Team % diff --git a/matlab/missing/stats/gamrnd.m b/matlab/missing/stats/gamrnd.m index b75b7868fd..06caff7f00 100644 --- a/matlab/missing/stats/gamrnd.m +++ b/matlab/missing/stats/gamrnd.m @@ -1,16 +1,16 @@ function rnd = gamrnd(a,b,method) % This function produces independent random variates from the Gamma distribution. % -% INPUTS +% INPUTS % a [double] n*1 vector of positive parameters. -% b [double] n*1 vector of positive parameters. +% b [double] n*1 vector of positive parameters. % method [string] 'BawensLubranoRichard' or anything else (see below). % -% OUTPUT +% OUTPUT % rnd [double] n*1 vector of independent variates from the gamma(a,b) distribution. % rnd(i) is gamma distributed with mean a(i)b(i) and variance a(i)b(i)^2. -% -% ALGORITHMS +% +% ALGORITHMS % Described in Bauwens, Lubrano and Richard (1999, page 316) and Devroye (1986, chapter 9). % Copyright (C) 2006-2011 Dynare Team @@ -39,13 +39,13 @@ 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' + 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 + % 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 else @@ -96,7 +96,7 @@ if number_of_double_a if strcmpi(method,'BauwensLubranoRichard') % Algorithm given in Bauwens, Lubrano & Richard (1999) page 316. rnd(double_idx) = knuth_algorithm(a(double_idx),b(double_idx)); - else% Algorithm given in Devroye (1986, chapter 9) + else% Algorithm given in Devroye (1986, chapter 9) small_idx = find(a(double_idx)<1); big_idx = find(a(double_idx)>1); number_of_small_a = length(small_idx); @@ -180,7 +180,7 @@ end gamma_variates = exprnd(ones(nn,1)).*X./(X+Y); -function gamma_variates = berman_algorithm(a,b) +function gamma_variates = berman_algorithm(a,b) nn = length(a); mm = nn; aa = 1./a ; @@ -206,7 +206,7 @@ Z = gamrnd(2*ones(nn,1),ones(nn,1)); gamma_variates = Z.*X.*b ; -function gamma_variates = ahrens_dieter_algorithm(a,b) +function gamma_variates = ahrens_dieter_algorithm(a,b) nn = length(a); mm = nn; bb = (exp(1)+a)/exp(1); @@ -246,7 +246,7 @@ end gamma_variates = X.*b ; -function gamma_variates = best_1983_algorithm(a,b) +function gamma_variates = best_1983_algorithm(a,b) nn = length(a); mm = nn; tt = .07 + .75*sqrt(1-a); diff --git a/matlab/missing/stats/quantile.m b/matlab/missing/stats/quantile.m index ec7dbfa64f..2c0c683f92 100644 --- a/matlab/missing/stats/quantile.m +++ b/matlab/missing/stats/quantile.m @@ -8,18 +8,18 @@ function [q,N] = quantile(X, p, dim, method, weights) % --*-- Unitary tests --*- % a matrix, the i-th row of Q contains the P(i)-th quantiles of each % column of X. For N-D arrays, QUANTILE2 operates along the first % non-singleton dimension. -% +% % Q = QUANTILE2(X,P,DIM) calculates quantiles along dimension DIM. The % DIM'th dimension of Q has length LENGTH(P). -% +% % Q = QUANTILE2(X,P,DIM,METHOD) calculates quantiles using one of the % methods described in http://en.wikipedia.org/wiki/Quantile. The method % are designated 'R-1'...'R-9'; the default is R-8 as described in % http://bit.ly/1kX4NcT, whereas Matlab uses 'R-5'. -% +% % Q = QUANTILE2(X,P,[],METHOD) uses the specified METHOD, but calculates % quantiles along the first non-singleton dimension. -% +% % Q = QUANTILE2(X,P,[],METHOD,WEIGHTS) and QUANTILE2(X,P,[],[],WEIGHTS) % uses the array WEIGHTS to weight the values in X when calculating % quantiles. If no weighting is specified, the method determines the @@ -33,12 +33,12 @@ function [q,N] = quantile(X, p, dim, method, weights) % --*-- Unitary tests --*- % equal, then the weighted and unweighted index (and correpsonding % quantile) are identical. The default method R-8 is used if METHOD is % specified as an empty array ([]). -% +% % [Q,N] = QUANTILE2(...) returns an array that is the same size as Q such % that N(i) is the number of points used to calculate Q(i). -% +% % Further reading -% +% % Hyndman, R.J.; Fan, Y. (November 1996). "Sample Quantiles in % Statistical Packages". The American Statistician 50 (4): 361-365. % Frigge, Michael; Hoaglin, David C.; Iglewicz, Boris (February 1989). @@ -47,8 +47,8 @@ function [q,N] = quantile(X, p, dim, method, weights) % --*-- Unitary tests --*- % Original file downloaded from: % http://fr.mathworks.com/matlabcentral/fileexchange/46555-quantile-calculation -% -% Copyright (C) 2014-2016 University of Surrey (Christopher Hummersone) +% +% Copyright (C) 2014-2016 University of Surrey (Christopher Hummersone) % Copyright (C) 2016 Dynare Team % % This file is part of Dynare. @@ -205,34 +205,34 @@ if numel(p)==numel(q) end function cumweights = accumulateWeights(weights, ind, n, N) - % ACCUMULATEWEIGHTS accumulate the weights - wSorted = weights(ind,n); % sort weights - wSorted = wSorted*N/sum(wSorted); % normalize weights to sum to N - cumweights = cumsum(wSorted); % cumulative weights +% ACCUMULATEWEIGHTS accumulate the weights +wSorted = weights(ind,n); % sort weights +wSorted = wSorted*N/sum(wSorted); % normalize weights to sum to N +cumweights = cumsum(wSorted); % cumulative weights function hw = weightedIndex(huw, cumweights) - % WEIGHTEDINDEX calculate index from cumulative weights - ii = find(sign(cumweights-huw)<0,1,'last'); - jj = find(sign(cumweights-huw)>0,1,'first'); - if isempty(ii) || isempty(jj) - hw = huw; - else - hw = ii + (huw-cumweights(ii))/(cumweights(jj)-cumweights(ii)); % weighted index - end +% WEIGHTEDINDEX calculate index from cumulative weights +ii = find(sign(cumweights-huw)<0,1,'last'); +jj = find(sign(cumweights-huw)>0,1,'first'); +if isempty(ii) || isempty(jj) + hw = huw; +else + hw = ii + (huw-cumweights(ii))/(cumweights(jj)-cumweights(ii)); % weighted index +end function y = isint(x) - % ISINT check if input is whole number - y = x==round(x); +% ISINT check if input is whole number +y = x==round(x); function y = rearrange(x,order,shape) - %REARRANGE reshape and permute to make target dim column - y = permute(x,order); - y = reshape(y,shape); +%REARRANGE reshape and permute to make target dim column +y = permute(x,order); +y = reshape(y,shape); function y = irearrange(x,order,shape) - %IREARRANGE reshape and permute to original size - y = reshape(x,shape); - y = ipermute(y,order); +%IREARRANGE reshape and permute to original size +y = reshape(x,shape); +y = ipermute(y,order); %@test:1 diff --git a/matlab/missing/stats/stdnormal_inv.m b/matlab/missing/stats/stdnormal_inv.m index bc52845a56..44cdebe1ff 100644 --- a/matlab/missing/stats/stdnormal_inv.m +++ b/matlab/missing/stats/stdnormal_inv.m @@ -34,4 +34,3 @@ end inv = sqrt (2) * erfinv (2 * x - 1); end - diff --git a/matlab/missing/stats/wblcdf.m b/matlab/missing/stats/wblcdf.m index 14b0fc8e8f..701abe964e 100644 --- a/matlab/missing/stats/wblcdf.m +++ b/matlab/missing/stats/wblcdf.m @@ -2,13 +2,13 @@ function p = wblcdf(x, scale, shape) % --*-- Unitary tests --*-- % Cumulative distribution function for the Weibull distribution. % -% INPUTS +% INPUTS % - x [double] Positive real scalar. % - scale [double] Positive hyperparameter. % - shape [double] Positive hyperparameter. % -% OUTPUTS -% - p [double] Positive scalar between +% OUTPUTS +% - p [double] Positive scalar between % Copyright (C) 2015 Dynare Team % @@ -58,7 +58,7 @@ if isinf(x) return end -% Evaluate the CDF. +% Evaluate the CDF. p = 1-exp(-(x/scale)^shape); @@ -146,4 +146,3 @@ p = 1-exp(-(x/scale)^shape); %$ end %$ T = all(t); %@eof:4 - diff --git a/matlab/missing/stats/wblinv.m b/matlab/missing/stats/wblinv.m index 42d83ffe94..363d518019 100644 --- a/matlab/missing/stats/wblinv.m +++ b/matlab/missing/stats/wblinv.m @@ -2,12 +2,12 @@ function t = wblinv(proba, scale, shape) % --*-- Unitary tests --*-- % Inverse cumulative distribution function. % -% INPUTS +% INPUTS % - proba [double] Probability, scalar between 0 and 1. % - scale [double] Positive hyperparameter. % - shape [double] Positive hyperparameter. % -% OUTPUTS +% OUTPUTS % - t [double] scalar such that P(X<=t)=proba % Copyright (C) 2015-2017 Dynare Team @@ -156,7 +156,7 @@ t = exp(log(scale)+log(-log(1-proba))/shape); %$ [s, abs(p-s)] %$ end %$ if isoctave -%$ t(k) = abs(p-s)<1e-10; +%$ t(k) = abs(p-s)<1e-10; %$ else %$ t(k) = abs(p-s)<1e-12; %$ end @@ -165,4 +165,3 @@ t = exp(log(scale)+log(-log(1-proba))/shape); %$ end %$ T = all(t); %@eof:4 - diff --git a/matlab/missing/stats/wblrnd.m b/matlab/missing/stats/wblrnd.m index 2f55bc8b77..ca31efa50c 100644 --- a/matlab/missing/stats/wblrnd.m +++ b/matlab/missing/stats/wblrnd.m @@ -1,11 +1,11 @@ function rnd = wblrnd(a, b) % This function produces independent random variates from the Weibull distribution. % -% INPUTS +% INPUTS % a [double] m*n matrix of positive parameters (scale). % b [double] m*n matrix of positive parameters (shape). % -% OUTPUT +% OUTPUT % rnd [double] m*n matrix of independent variates from the beta(a,b) distribution. % Copyright (C) 2015 Dynare Team diff --git a/matlab/missing/struct2array/struct2array.m b/matlab/missing/struct2array/struct2array.m index b1c1370dd3..92aaab35fe 100644 --- a/matlab/missing/struct2array/struct2array.m +++ b/matlab/missing/struct2array/struct2array.m @@ -1,9 +1,9 @@ function a = struct2array(s) -% INPUTS +% INPUTS % - s [struct] with N fields, field i contains a n_i*m_i array of doubles. % -% OUPUTS +% OUPUTS % - a [double] column vector with sum(n_i*m_i, i=1,...,N) elements. % Copyright (C) 2017 Dynare Team diff --git a/matlab/missing/vec/vec.m b/matlab/missing/vec/vec.m index 225c5f9ec1..8565f86a4e 100644 --- a/matlab/missing/vec/vec.m +++ b/matlab/missing/vec/vec.m @@ -1,10 +1,10 @@ function Vector = vec(Matrix) % This function implements the vec operator. -% -% INPUTS +% +% INPUTS % Matrix [double] a squared n*n matrix. -% -% OUTPUTS +% +% OUTPUTS % Vector [double] a n*n vector. % Copyright (C) 2009 Dynare Team diff --git a/matlab/missing_DiffuseKalmanSmootherH1_Z.m b/matlab/missing_DiffuseKalmanSmootherH1_Z.m index a19d3fff63..5950f03d28 100644 --- a/matlab/missing_DiffuseKalmanSmootherH1_Z.m +++ b/matlab/missing_DiffuseKalmanSmootherH1_Z.m @@ -5,10 +5,10 @@ function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,decomp,V] = missing_DiffuseK % % INPUTS % T: mm*mm matrix -% Z: pp*mm matrix +% Z: pp*mm matrix % R: mm*rr matrix % Q: rr*rr matrix -% H: pp*pp matrix variance of measurement errors +% 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 @@ -22,7 +22,7 @@ function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,decomp,V] = missing_DiffuseK % decomp_flag if true, compute filter decomposition % state_uncertainty_flag if true, compute uncertainty about smoothed % state estimate -% +% % OUTPUTS % alphahat: smoothed variables (a_{t|T}) % epsilonhat:smoothed measurement errors @@ -36,16 +36,16 @@ function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,decomp,V] = missing_DiffuseK % matrices (meaningless for periods 1:d) % decomp: decomposition of the effect of shocks on filtered values % V: 3D array of state uncertainty matrices -% +% % Notes: % Outputs are stored in decision-rule order, i.e. to get variables in order of declaration % as in M_.endo_names, ones needs code along the lines of: % variables_declaration_order(dr.order_var,:) = alphahat -% +% % 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). +% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series +% Analysis, vol. 24(1), pp. 85-98). % Durbin/Koopman (2012): "Time Series Analysis by State Space Methods", Oxford University Press, % Second Edition, Ch. 5 @@ -70,7 +70,7 @@ function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,decomp,V] = missing_DiffuseK % 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 +% it is assured that P is symmetric d = 0; decomp = []; @@ -92,9 +92,9 @@ Lstar = zeros(mm,mm,smpl); Kstar = zeros(mm,pp,smpl); Kinf = zeros(mm,pp,smpl); P = zeros(mm,mm,smpl+1); -Pstar = zeros(spstar(1),spstar(2),smpl+1); +Pstar = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1; -Pinf = zeros(spinf(1),spinf(2),smpl+1); +Pinf = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1; rr = size(Q,1); QQ = R*Q*transpose(R); @@ -127,9 +127,9 @@ while rank(Pinf(:,:,t+1),diffuse_kalman_tol) && t<smpl ZZ = Z(di,:); %span selector matrix v(di,t)= Y(di,t) - ZZ*a(:,t); %get prediction error v^(0) in (5.13) DK (2012) Finf = ZZ*Pinf(:,:,t)*ZZ'; % (5.7) in DK (2012) - if rcond(Finf) < diffuse_kalman_tol %F_{\infty,t} = 0 + if rcond(Finf) < diffuse_kalman_tol %F_{\infty,t} = 0 if ~all(abs(Finf(:)) < diffuse_kalman_tol) %rank-deficient but not rank 0 - % The univariate diffuse kalman filter should be used. + % The univariate diffuse kalman filter should be used. alphahat = Inf; return else %rank of F_{\infty,t} is 0 @@ -200,13 +200,13 @@ while notsteady && t<smpl if any(diag(F)<kalman_tol) || rcond(F./(sig*sig')) < kalman_tol alphahat = Inf; return - end + end iF(di,di,t) = inv(F./(sig*sig'))./(sig*sig'); 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)*L(:,:,t)' + QQ; + P(:,:,t+1) = T*P(:,:,t)*L(:,:,t)' + QQ; end a(:,t+1) = T*atilde(:,t); Pf = P(:,:,t); @@ -267,8 +267,8 @@ while t>d+1 end end if d %diffuse periods - % initialize r_d^(0) and r_d^(1) as below DK (2012), eq. 5.23 - r0 = zeros(mm,d+1); + % initialize r_d^(0) and r_d^(1) as below DK (2012), eq. 5.23 + r0 = zeros(mm,d+1); r0(:,d+1) = r(:,d+1); %set r0_{d}, i.e. shifted by one period r1 = zeros(mm,d+1); %set r1_{d}, i.e. shifted by one period if state_uncertainty_flag @@ -284,7 +284,7 @@ if d %diffuse periods if ~Finf_singular(1,t) r0(:,t) = Linf(:,:,t)'*r0(:,t+1); % DK (2012), eq. 5.21 where L^(0) is named Linf r1(:,t) = Z(di,:)'*(iFinf(di,di,t)*v(di,t)-Kstar(:,di,t)'*T'*r0(:,t+1)) ... - + Linf(:,:,t)'*r1(:,t+1); % DK (2012), eq. 5.21, noting that i) F^(1)=(F^Inf)^(-1)(see 5.10), ii) where L^(0) is named Linf, and iii) Kstar=T^{-1}*K^(1) + + Linf(:,:,t)'*r1(:,t+1); % DK (2012), eq. 5.21, noting that i) F^(1)=(F^Inf)^(-1)(see 5.10), ii) where L^(0) is named Linf, and iii) Kstar=T^{-1}*K^(1) if state_uncertainty_flag L_1=(-T*Kstar(:,di,t)*Z(di,:)); % noting that Kstar=T^{-1}*K^(1) N(:,:,t)=Linf(:,:,t)'*N(:,:,t+1)*Linf(:,:,t); % DK (2012), eq. 5.19, noting that L^(0) is named Linf @@ -301,7 +301,7 @@ if d %diffuse periods r1(:,t) = T'*r1(:,t+1); % DK (2003), eq. (14) if state_uncertainty_flag N(:,:,t)=Z(di,:)'*iFstar(di,di,t)*Z(di,:)... - +Lstar(:,:,t)'*N(:,:,t+1)*Lstar(:,:,t); % DK (2003), eq. (14) + +Lstar(:,:,t)'*N(:,:,t+1)*Lstar(:,:,t); % DK (2003), eq. (14) N_1(:,:,t)=T'*N_1(:,:,t+1)*Lstar(:,:,t); % DK (2003), eq. (14) N_2(:,:,t)=T'*N_2(:,:,t+1)*T'; % DK (2003), eq. (14) end @@ -311,9 +311,9 @@ if d %diffuse periods etahat(:,t) = QRt*r0(:,t); % DK (2012), p. 135 if state_uncertainty_flag V(:,:,t)=Pstar(:,:,t)-Pstar(:,:,t)*N(:,:,t)*Pstar(:,:,t)... - -(Pinf(:,:,t)*N_1(:,:,t)*Pstar(:,:,t))'... - - Pinf(:,:,t)*N_1(:,:,t)*Pstar(:,:,t)... - - Pinf(:,:,t)*N_2(:,:,t)*Pinf(:,:,t); % DK (2012), eq. 5.30 + -(Pinf(:,:,t)*N_1(:,:,t)*Pstar(:,:,t))'... + - Pinf(:,:,t)*N_1(:,:,t)*Pstar(:,:,t)... + - Pinf(:,:,t)*N_2(:,:,t)*Pinf(:,:,t); % DK (2012), eq. 5.30 end end end diff --git a/matlab/missing_DiffuseKalmanSmootherH3_Z.m b/matlab/missing_DiffuseKalmanSmootherH3_Z.m index 463d7f1aae..de40741fcf 100644 --- a/matlab/missing_DiffuseKalmanSmootherH3_Z.m +++ b/matlab/missing_DiffuseKalmanSmootherH3_Z.m @@ -43,18 +43,18 @@ function [alphahat,epsilonhat,etahat,a,P,aK,PK,decomp,V] = missing_DiffuseKalman % variables_declaration_order(dr.order_var,:) = alphahat % % Algorithm: -% +% % Uses the univariate filter as described in Durbin/Koopman (2012): "Time % Series Analysis by State Space Methods", Oxford University Press, % Second Edition, Ch. 6.4 + 7.2.5 -% and +% and % Koopman/Durbin (2000): "Fast Filtering and Smoothing for Multivariatze State Space % Models", in Journal of Time Series Analysis, vol. 21(3), pp. 281-296. % % 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. +% Models", S.J. Koopman and J. Durbin (2003), in Journal of Time Series +% Analysis, vol. 24(1), pp. 85-98. % Copyright (C) 2004-2017 Dynare Team % @@ -78,10 +78,10 @@ function [alphahat,epsilonhat,etahat,a,P,aK,PK,decomp,V] = missing_DiffuseKalman % New input argument nk: max order of predictions in aK -if size(H,2)>1 +if size(H,2)>1 error('missing_DiffuseKalmanSmootherH3_Z:: H is not a vector. This must not happens') end - + d = 0; decomp = []; spinf = size(Pinf1); @@ -100,9 +100,9 @@ Kinf = zeros(spstar(1),pp,smpl); P = zeros(mm,mm,smpl+1); P1 = P; PK = zeros(nk,mm,mm,smpl+nk); -Pstar = zeros(spstar(1),spstar(2),smpl); +Pstar = zeros(spstar(1),spstar(2),smpl); Pstar(:,:,1) = Pstar1; -Pinf = zeros(spinf(1),spinf(2),smpl); +Pinf = zeros(spinf(1),spinf(2),smpl); Pinf(:,:,1) = Pinf1; Pstar1 = Pstar; Pinf1 = Pinf; @@ -135,13 +135,13 @@ while newRank && t < smpl di = data_index{t}'; for i=di Zi = Z(i,:); - v(i,t) = Y(i,t)-Zi*a(:,t); % nu_{t,i} in 6.13 in DK (2012) + v(i,t) = Y(i,t)-Zi*a(:,t); % nu_{t,i} in 6.13 in DK (2012) Fstar(i,t) = Zi*Pstar(:,:,t)*Zi' +H(i); % F_{*,t} in 5.7 in DK (2012), relies on H being diagonal Finf(i,t) = Zi*Pinf(:,:,t)*Zi'; % F_{\infty,t} in 5.7 in DK (2012) Kstar(:,i,t) = Pstar(:,:,t)*Zi'; % KD (2000), eq. (15) if Finf(i,t) > diffuse_kalman_tol && newRank % F_{\infty,t,i} = 0, use upper part of bracket on p. 175 DK (2012) for w_{t,i} icc=icc+1; - Kinf(:,i,t) = Pinf(:,:,t)*Zi'; % KD (2000), eq. (15) + Kinf(:,i,t) = Pinf(:,:,t)*Zi'; % KD (2000), eq. (15) Kinf_Finf = Kinf(:,i,t)/Finf(i,t); a(:,t) = a(:,t) + Kinf_Finf*v(i,t); % KD (2000), eq. (16) Pstar(:,:,t) = Pstar(:,:,t) + ... @@ -149,14 +149,14 @@ while newRank && t < smpl Kstar(:,i,t)*Kinf_Finf' - ... Kinf_Finf*Kstar(:,i,t)'; % KD (2000), eq. (16) Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*Kinf(:,i,t)'/Finf(i,t); % KD (2000), eq. (16) - elseif Fstar(i,t) > kalman_tol + elseif Fstar(i,t) > kalman_tol a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t); % KD (2000), eq. (17) Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*Kstar(:,i,t)'/Fstar(i,t); % KD (2000), eq. (17) - % Pinf is passed through unaltered, see eq. (17) of - % Koopman/Durbin (2000) + % Pinf is passed through unaltered, see eq. (17) of + % Koopman/Durbin (2000) else % do nothing as a_{t,i+1}=a_{t,i} and P_{t,i+1}=P_{t,i}, see - % p. 157, DK (2012) + % p. 157, DK (2012) end end if newRank @@ -164,12 +164,12 @@ while newRank && t < smpl oldRank = rank(Z*Pinf(:,:,t)*Z',diffuse_kalman_tol); else oldRank = rank(Pinf(:,:,t),diffuse_kalman_tol); - end + end else oldRank = 0; end a1(:,t+1) = T*a(:,t); - aK(1,:,t+1) = a1(:,t+1); + aK(1,:,t+1) = a1(:,t+1); for jnk=2:nk aK(jnk,:,t+jnk) = T*dynare_squeeze(aK(jnk-1,:,t+jnk-1)); end @@ -183,7 +183,7 @@ while newRank && t < smpl end end if oldRank ~= newRank - disp('univariate_diffuse_kalman_filter:: T does influence the rank of Pinf!') + disp('univariate_diffuse_kalman_filter:: T does influence the rank of Pinf!') end end @@ -206,7 +206,7 @@ while notsteady && t<smpl for i=di Zi = Z(i,:); v(i,t) = Y(i,t) - Zi*a(:,t); % nu_{t,i} in 6.13 in DK (2012) - Fi(i,t) = Zi*P(:,:,t)*Zi' + H(i); % F_{t,i} in 6.13 in DK (2012), relies on H being diagonal + Fi(i,t) = Zi*P(:,:,t)*Zi' + H(i); % F_{t,i} in 6.13 in DK (2012), relies on H being diagonal Ki(:,i,t) = P(:,:,t)*Zi'; % K_{t,i}*F_(i,t) in 6.13 in DK (2012) if Fi(i,t) > kalman_tol a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t); %filtering according to (6.13) in DK (2012) @@ -216,18 +216,18 @@ while notsteady && t<smpl % p. 157, DK (2012) end end - a1(:,t+1) = T*a(:,t); %transition according to (6.14) in DK (2012) + a1(:,t+1) = T*a(:,t); %transition according to (6.14) in DK (2012) Pf = P(:,:,t); - aK(1,:,t+1) = a1(:,t+1); + aK(1,:,t+1) = a1(:,t+1); for jnk=1:nk Pf = T*Pf*T' + QQ; PK(jnk,:,:,t+jnk) = Pf; if jnk>1 - aK(jnk,:,t+jnk) = T*dynare_squeeze(aK(jnk-1,:,t+jnk-1)); + aK(jnk,:,t+jnk) = T*dynare_squeeze(aK(jnk-1,:,t+jnk-1)); end end - P(:,:,t+1) = T*P(:,:,t)*T' + QQ; %transition according to (6.14) in DK (2012) - % notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<kalman_tol); + P(:,:,t+1) = T*P(:,:,t)*T' + QQ; %transition according to (6.14) in DK (2012) + % notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<kalman_tol); end % $$$ P_s=tril(P(:,:,t))+tril(P(:,:,t),-1)'; % $$$ P1_s=tril(P1(:,:,t))+tril(P1(:,:,t),-1)'; @@ -279,18 +279,18 @@ while t > d+1 end end end - r(:,t) = ri; % DK (2012), below 6.15, r_{t-1}=r_{t,0} + r(:,t) = ri; % DK (2012), below 6.15, r_{t-1}=r_{t,0} alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t); etahat(:,t) = QRt*r(:,t); - ri = T'*ri; % KD (2003), eq. (23), equation for r_{t-1,p_{t-1}} + ri = T'*ri; % KD (2003), eq. (23), equation for r_{t-1,p_{t-1}} if state_uncertainty_flag - N(:,:,t) = Ni; % DK (2012), below 6.15, N_{t-1}=N_{t,0} + N(:,:,t) = Ni; % DK (2012), below 6.15, N_{t-1}=N_{t,0} V(:,:,t) = P1(:,:,t)-P1(:,:,t)*N(:,:,t)*P1(:,:,t); % KD (2000), eq. (7) with N_{t-1} stored in N(:,:,t) - Ni = T'*Ni*T; % KD (2000), eq. (23), equation for N_{t-1,p_{t-1}} + Ni = T'*Ni*T; % KD (2000), eq. (23), equation for N_{t-1,p_{t-1}} end end if d - r0 = zeros(mm,d); + r0 = zeros(mm,d); r0(:,d) = ri; r1 = zeros(mm,d); if state_uncertainty_flag @@ -304,10 +304,10 @@ if d di = flipud(data_index{t})'; for i = di if Finf(i,t) > diffuse_kalman_tol - % recursions need to be from highest to lowest term in order to not + % recursions need to be from highest to lowest term in order to not % overwrite lower terms still needed in this step Linf = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t); - L0 = (Kinf(:,i,t)*(Fstar(i,t)/Finf(i,t))-Kstar(:,i,t))*Z(i,:)/Finf(i,t); + L0 = (Kinf(:,i,t)*(Fstar(i,t)/Finf(i,t))-Kstar(:,i,t))*Z(i,:)/Finf(i,t); r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ... L0'*r0(:,t) + ... Linf'*r1(:,t); % KD (2000), eq. (25) for r_1 @@ -335,9 +335,9 @@ if d etahat(:,t) = QRt*r(:,t); % KD (2000), eq. (27) if state_uncertainty_flag V(:,:,t)=Pstar(:,:,t)-Pstar(:,:,t)*N_0(:,:,t)*Pstar(:,:,t)... - -(Pinf(:,:,t)*N_1(:,:,t)*Pstar(:,:,t))'... - - Pinf(:,:,t)*N_1(:,:,t)*Pstar(:,:,t)... - - Pinf(:,:,t)*N_2(:,:,t)*Pinf(:,:,t); % DK (2012), eq. 5.30 + -(Pinf(:,:,t)*N_1(:,:,t)*Pstar(:,:,t))'... + - Pinf(:,:,t)*N_1(:,:,t)*Pstar(:,:,t)... + - Pinf(:,:,t)*N_2(:,:,t)*Pinf(:,:,t); % DK (2012), eq. 5.30 end if t > 1 r0(:,t-1) = T'*r0(:,t); % KD (2000), below eq. (25) r_{t-1,p_{t-1}}=T'*r_{t,0} @@ -362,11 +362,11 @@ if decomp_flag ri_d = Z(i,:)'/Fi(i,t)*v(i,t)+ri_d-Ki(:,i,t)'*ri_d/Fi(i,t)*Z(i,:)'; end end - + % calculate eta_tm1t eta_tm1t = QRt*ri_d; % calculate decomposition - Ttok = eye(mm,mm); + Ttok = eye(mm,mm); AAA = P1(:,:,t)*Z'*ZRQinv*Z*R; for h = 1:nk BBB = Ttok*AAA; @@ -382,6 +382,6 @@ epsilonhat = Y - Z*alphahat; if (d==smpl) - warning(['missing_DiffuseKalmanSmootherH3_Z:: There isn''t enough information to estimate the initial conditions of the nonstationary variables']); + warning(['missing_DiffuseKalmanSmootherH3_Z:: There isn''t enough information to estimate the initial conditions of the nonstationary variables']); return end diff --git a/matlab/mode_check.m b/matlab/mode_check.m index ac4497249e..2df26ff0c5 100644 --- a/matlab/mode_check.m +++ b/matlab/mode_check.m @@ -121,7 +121,7 @@ for plt = 1:nbplt elseif isequal(x(kk),BoundsInfo.ub(kk)) binding_upper_bound=1; bound_value=BoundsInfo.ub(kk); - end + end if DynareOptions.mode_check.symmetric_plots && ~binding_lower_bound && ~binding_upper_bound if l2<(1+ll)*x(kk) %test whether upper bound is too small due to prior binding l1 = x(kk) - (l2-x(kk)); %adjust lower bound to become closer @@ -203,7 +203,7 @@ for plt = 1:nbplt end end if TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format))) - fclose(fidTeX); + fclose(fidTeX); end OutputDirectoryName = CheckPath('modecheck',Model.dname); diff --git a/matlab/model_comparison.m b/matlab/model_comparison.m index cafa90a681..81afdf768c 100644 --- a/matlab/model_comparison.m +++ b/matlab/model_comparison.m @@ -5,9 +5,9 @@ function oo = model_comparison(ModelNames,ModelPriors,oo,options_,fname) % % INPUTS % ModelNames [string] m*1 cell array of string. -% ModelPriors [double] m*1 vector of prior probabilities +% ModelPriors [double] m*1 vector of prior probabilities % oo [struct] Dynare results structure -% options_ [struct] Dynare options structure +% options_ [struct] Dynare options structure % fname [string] name of the current mod-file % % OUTPUTS @@ -61,14 +61,14 @@ if isfield(options_,'mc_marginal_density') type = options_.mc_marginal_density; if strcmp(type,'laplace') || strcmp(type,'Laplace') type = 'LaplaceApproximation'; - title = 'Model Comparison (based on Laplace approximation)'; - elseif strcmp(type,'modifiedharmonicmean') || strcmp(type,'ModifiedHarmonicMean') + title = 'Model Comparison (based on Laplace approximation)'; + elseif strcmp(type,'modifiedharmonicmean') || strcmp(type,'ModifiedHarmonicMean') type = 'ModifiedHarmonicMean'; - title = 'Model Comparison (based on Modified Harmonic Mean Estimator)'; + title = 'Model Comparison (based on Modified Harmonic Mean Estimator)'; end else type = 'LaplaceApproximation'; - title = 'Model Comparison (based on Laplace approximation)'; + title = 'Model Comparison (based on Laplace approximation)'; end % Get the estimated logged marginal densities. @@ -87,7 +87,7 @@ for i=1:NumberOfModels end end try - eval(['MarginalLogDensity(i) = mstruct.oo_.MarginalDensity.' type ';']) + eval(['MarginalLogDensity(i) = mstruct.oo_.MarginalDensity.' type ';']) catch if strcmpi(type,'LaplaceApproximation') if isfield(mstruct.oo_,'mle_mode') @@ -119,13 +119,13 @@ if prior_flag labels = char('Priors','Log Marginal Density','Bayes Ratio', ... 'Posterior Model Probability'); field_labels={'Prior','Log_Marginal_Density','Bayes_Ratio', ... - 'Posterior_Model_Probability'}; + 'Posterior_Model_Probability'}; values = [ModelPriors';MarginalLogDensity';exp(lmpd-lmpd(1))'; ... elmpd'/sum(elmpd)]; else labels = char('Priors','Log Marginal Density','Bayes Ratio','Posterior Odds Ratio', ... 'Posterior Model Probability'); - field_labels={'Prior','Log_Marginal_Density','Bayes_Ratio','Posterior_Odds_Ratio','Posterior_Model_Probability'}; + field_labels={'Prior','Log_Marginal_Density','Bayes_Ratio','Posterior_Odds_Ratio','Posterior_Model_Probability'}; values = [ModelPriors';MarginalLogDensity'; exp(MarginalLogDensity-MarginalLogDensity(1))'; ... exp(lmpd-lmpd(1))'; elmpd'/sum(elmpd)]; end @@ -148,7 +148,7 @@ if options_.TeX for ii=1:size(labels,1) labels_tex=strvcat(labels_tex,strrep(labels(ii,:),' ', '\ ')); end - + dyn_latex_table(M_temp,options_,title,['model_comparison',type],headers_tex,labels_tex,values,0,16,6); end diff --git a/matlab/model_diagnostics.m b/matlab/model_diagnostics.m index 8725f1cdd4..6734291150 100644 --- a/matlab/model_diagnostics.m +++ b/matlab/model_diagnostics.m @@ -1,20 +1,20 @@ function model_diagnostics(M,options,oo) % function model_diagnostics(M,options,oo) -% computes various diagnostics on the model +% computes various diagnostics on the model % INPUTS -% M [matlab structure] Definition of the model. +% M [matlab structure] Definition of the model. % options [matlab structure] Global options. -% oo [matlab structure] Results -% +% oo [matlab structure] Results +% % OUTPUTS % none -% +% % ALGORITHM % ... -% +% % SPECIAL REQUIREMENTS % none. -% +% % Copyright (C) 1996-2017 Dynare Team % @@ -108,7 +108,7 @@ for b=1:nb if options.bytecode if nb == 1 [chk, res, jacob] = bytecode(dr.ys, exo, M.params, dr.ys, 1, exo, ... - 'evaluate', 'static'); + 'evaluate', 'static'); else [chk, res, jacob] = bytecode(dr.ys, exo, M.params, dr.ys, 1, exo, ... 'evaluate', 'static',['block=' ... @@ -173,8 +173,8 @@ for b=1:nb end end end - -if singularity_problem + +if singularity_problem try options_check=options; options_check.noprint=1; @@ -205,29 +205,29 @@ if ~options.block if options.order == 1 if (options.bytecode) [chck, junk, loc_dr] = bytecode('dynamic','evaluate', z,exo_simul, ... - M.params, dr.ys, 1); + M.params, dr.ys, 1); jacobia_ = [loc_dr.g1 loc_dr.g1_x loc_dr.g1_xd]; else [junk,jacobia_] = feval([M.fname '_dynamic'],z(iyr0),exo_simul, ... - M.params, dr.ys, it_); + M.params, dr.ys, it_); end elseif options.order >= 2 if (options.bytecode) [chck, junk, loc_dr] = bytecode('dynamic','evaluate', z,exo_simul, ... - M.params, dr.ys, 1); + M.params, dr.ys, 1); jacobia_ = [loc_dr.g1 loc_dr.g1_x]; else [junk,jacobia_,hessian1] = feval([M.fname '_dynamic'],z(iyr0),... - exo_simul, ... - M.params, dr.ys, it_); + exo_simul, ... + M.params, dr.ys, it_); end 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)); + size(jacobia_, 1), size(jacobia_, 2)*size(jacobia_, 2)); end end - + if any(any(isinf(jacobia_) | isnan(jacobia_))) problem_dummy=1; [infrow,infcol]=find(isinf(jacobia_) | isnan(jacobia_)); @@ -245,7 +245,7 @@ if ~options.block problem_dummy=1; fprintf('\nMODEL_DIAGNOSTICS: The Hessian of the dynamic model contains Inf or NaN.\n') end - end + end else fprintf('\nMODEL_DIAGNOSTICS: This command currently does not support the block option for checking.\n') fprintf('\nMODEL_DIAGNOSTICS: the dynamic model. You may want to disable it for doing model_diagnostics. Skipping this part.\n') @@ -254,4 +254,3 @@ end if problem_dummy==0 fprintf('MODEL_DIAGNOSTICS: No obvious problems with this mod-file were detected.\n') end - diff --git a/matlab/model_info.m b/matlab/model_info.m index 2a55376ba6..e277792253 100644 --- a/matlab/model_info.m +++ b/matlab/model_info.m @@ -30,14 +30,14 @@ else incidence = 0; end if static_ - fprintf(' Informations about %s (static model)\n',M_.fname); - block_structre_str = 'block_structure_stat'; - nb_leadlag = 1; - else - fprintf(' Informations about %s (dynamic model)\n',M_.fname); - block_structre_str = 'block_structure'; - nb_leadlag = 3; - end + fprintf(' Informations about %s (static model)\n',M_.fname); + block_structre_str = 'block_structure_stat'; + nb_leadlag = 1; +else + fprintf(' Informations about %s (dynamic model)\n',M_.fname); + block_structre_str = 'block_structure'; + nb_leadlag = 3; +end if(isfield(M_,block_structre_str)) if static_ block_structure = M_.block_structure_stat; @@ -108,7 +108,7 @@ if(isfield(M_,block_structre_str)) fprintf('\n\n'); end end - + %printing the gross incidence matrix IM_star = char([kron(ones(M_.endo_nbr, M_.endo_nbr-1), double(blanks(3))) double(blanks(M_.endo_nbr)')]); for i = 1:nb_leadlag @@ -136,7 +136,7 @@ if(isfield(M_,block_structre_str)) fprintf('\n Gross incidence matrix\n'); fprintf(' =======================\n'); disp([topp; bott]); - + %printing the reordered incidence matrix IM_star_reordered = char([kron(ones(M_.endo_nbr, M_.endo_nbr-1), double(blanks(3))) double(blanks(M_.endo_nbr)')]); eq(block_structure.equation_reordered) = seq; @@ -179,7 +179,7 @@ if(isfield(M_,block_structre_str)) end end fprintf('1: non nul element, X: non nul element related to a state variable\n'); - + cur_block = 1; i_last = 0; block = {}; @@ -201,17 +201,17 @@ if(isfield(M_,block_structre_str)) end if past_block ~= cur_block for j = 1:i-1 - IM_star_reordered(j, 3 * (i - 1) - 1) = '|'; + IM_star_reordered(j, 3 * (i - 1) - 1) = '|'; end end end - + bott = [int2str(block_structure.equation_reordered') blanks(M_.endo_nbr)' blanks(M_.endo_nbr)' IM_star_reordered]; fprintf('\n Reordered incidence matrix\n'); fprintf(' ==========================\n'); disp([topp; bott]); fprintf('1: non nul element, X: non nul element related to a state variable\n'); - end + end else fprintf('There is no block decomposition of the model.\nUse ''block'' model''s option.\n'); end @@ -256,6 +256,3 @@ for i=1:n s = [s '|']; end ret = s; - - - diff --git a/matlab/model_inversion.m b/matlab/model_inversion.m index 6c873c6550..4d01412f98 100644 --- a/matlab/model_inversion.m +++ b/matlab/model_inversion.m @@ -1,19 +1,19 @@ function [endogenousvariables, exogenousvariables] = model_inversion(constraints, ... - exogenousvariables, ... - initialconditions, DynareModel, DynareOptions, DynareOutput) + exogenousvariables, ... + initialconditions, DynareModel, DynareOptions, DynareOutput) -% INPUTS +% INPUTS % - constraints [dseries] with N constrained endogenous variables from t1 to t2. % - exogenousvariables [dseries] with Q exogenous variables. % - initialconditions [dseries] with M endogenous variables starting before t1 (M initialcond must contain at least the state variables). % - DynareModel [struct] M_, Dynare global structure containing informations related to the model. % - DynareOptions [struct] options_, Dynare global structure containing all the options. % -% OUTPUTS -% - endogenous [dseries] +% OUTPUTS +% - endogenous [dseries] % - exogenous [dseries] % -% REMARKS +% REMARKS % Copyright (C) 2017 Dynare Team % @@ -52,7 +52,7 @@ if ~isstruct(DynareModel) error('model_inversion: Last input argument must be structures (M_)!') end -% Set range where the endogenous variables are constrained. +% Set range where the endogenous variables are constrained. crange = constraints.dates; % Check that the number of instruments match the number of constrained endogenous variables. diff --git a/matlab/moment_function.m b/matlab/moment_function.m index 9ebe62e7b0..fb42db9e88 100644 --- a/matlab/moment_function.m +++ b/matlab/moment_function.m @@ -3,12 +3,12 @@ function [g,grad,hess,flag] = moment_function(xparams,sample_moments,dataset,opt % ). % % INPUTS: -% xparams [double] p*1 vector of estimated parameters. +% xparams [double] p*1 vector of estimated parameters. % sample_moments [double] n*1 vector of sample moments (n>=p). % options [ ] Structure defining options for SMM. % parallel [ ] Structure defining the parallel mode settings (optional). % -% OUTPUTS: +% OUTPUTS: % g [double] n*1 vector, the gap between simulated and sample moments. % flag [intger] empty matrix. % @@ -30,7 +30,7 @@ function [g,grad,hess,flag] = moment_function(xparams,sample_moments,dataset,opt % 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/>. +% along with Dynare. If not, see <http://www.gnu.org/licenses/>. global M_ options_ persistent mainStream mainState @@ -106,7 +106,7 @@ else% parallel mode. end end for j=1:parallel(i).number_of_jobs - if (strcmpi(hostname,machine) && j>1) || ~strcmpi(hostname,machine) + if (strcmpi(hostname,machine) && j>1) || ~strcmpi(hostname,machine) job_number = job_number + 1; unix(['ssh -A ' parallel(i).login '@' machine ' ./call_matlab_session.sh job' int2str(job_number) '.m &']); end @@ -117,7 +117,7 @@ else% parallel mode. eval('job1;') tElapsedMasterJob = etime(clock, tStartMasterJob); TimeLimit = tElapsedMasterJob*1.2; - % Master waits for the slaves' output... + % Master waits for the slaves' output... tStart = clock; tElapsed = 0; while tElapsed<TimeLimit @@ -132,7 +132,7 @@ else% parallel mode. simulated_moments = load(['./intermediary_results_from_master_and_slaves/simulated_moments_slave_' int2str(i) '.dat'],'-ascii'); tmp = tmp + simulated_moments; end - simulated_moments = tmp / job_number; + simulated_moments = tmp / job_number; catch flag = 0; return diff --git a/matlab/moments.m b/matlab/moments.m index f295336aa3..ac5ed4f27a 100644 --- a/matlab/moments.m +++ b/matlab/moments.m @@ -1,7 +1,7 @@ function m = moments(X,order) % Returns the central sample moment of X specified by the positive integer order. % -% Note that the cross moments are only computed if order=2, in this case the +% Note that the cross moments are only computed if order=2, in this case the % output is a matrix. % % INPUTS diff --git a/matlab/ms-sbvar/clean_files_for_second_type_of_mex.m b/matlab/ms-sbvar/clean_files_for_second_type_of_mex.m index d29b532bfa..5f6d7d43cd 100644 --- a/matlab/ms-sbvar/clean_files_for_second_type_of_mex.m +++ b/matlab/ms-sbvar/clean_files_for_second_type_of_mex.m @@ -34,12 +34,12 @@ if ~strcmp(tagtouse, options_.ms.output_file_tag) end switch type - case 'irf' - clean_ms_irf_files(tagtouse); - case 'forecast' - clean_ms_forecast_files(tagtouse); - case 'variance_decomposition' - clean_ms_variance_decomposition_files(tagtouse); - otherwise - error('clean_files_for_second_type_of_mex: should not arrive here'); + case 'irf' + clean_ms_irf_files(tagtouse); + case 'forecast' + clean_ms_forecast_files(tagtouse); + case 'variance_decomposition' + clean_ms_variance_decomposition_files(tagtouse); + otherwise + error('clean_files_for_second_type_of_mex: should not arrive here'); end diff --git a/matlab/ms-sbvar/dyn_save_graph.m b/matlab/ms-sbvar/dyn_save_graph.m index cc8906cd13..91782d71fe 100644 --- a/matlab/ms-sbvar/dyn_save_graph.m +++ b/matlab/ms-sbvar/dyn_save_graph.m @@ -9,7 +9,7 @@ function dyn_save_graph(dirname,graph_name,graph_formats,TeX,names,texnames,capt % % OUTPUTS % none -% +% % SPECIAL REQUIREMENTS % none % @@ -30,40 +30,40 @@ function dyn_save_graph(dirname,graph_name,graph_formats,TeX,names,texnames,capt % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - create_dir(dirname); - graph_name = [dirname filesep regexprep(graph_name,' ','_')]; - if nargin <= 2 - TeX = 0; - elseif nargin <= 4 - names = {}; - texnames = {}; - elseif nargin <= 6 - caption = ''; - end - - if graph_formats.eps || TeX - print([ graph_name '.eps' ],'-depsc2'); - end - if graph_formats.pdf && ~isoctave - print(graph_name,'-dpdf'); - end - if graph_formats.fig && ~isoctave - print(graph_name,'-dfig'); +create_dir(dirname); +graph_name = [dirname filesep regexprep(graph_name,' ','_')]; +if nargin <= 2 + TeX = 0; +elseif nargin <= 4 + names = {}; + texnames = {}; +elseif nargin <= 6 + caption = ''; +end + +if graph_formats.eps || TeX + print([ graph_name '.eps' ],'-depsc2'); +end +if graph_formats.pdf && ~isoctave + print(graph_name,'-dpdf'); +end +if graph_formats.fig && ~isoctave + print(graph_name,'-dfig'); +end + +if TeX + fh = fopen([graph_name '.tex'],'w'); + for i=1:length(names) + fprintf(fh,'\\psfrag{%s}[1][][0.5][0]{%s}\n',names{i},texnames{i}); end - - if TeX - fh = fopen([graph_name '.tex'],'w'); - for i=1:length(names) - fprintf(fh,'\\psfrag{%s}[1][][0.5][0]{%s}\n',names{i},texnames{i}); - end - fprintf(fh,'\\centering \n'); - fprintf(fh,'\\includegraphics[width=0.8\\textwidth]{%s}\n',graph_name); - if caption - fprintf(fh,'\\caption{%s}',caption); - end - fprintf(fh,'\\label{Fig:%s}\n',graph_name); - fprintf(fh,'\\end{figure}\n'); - fprintf(fh,'\n'); - fprintf(fh,'%% End of TeX file.\n'); - fclose(fh); + fprintf(fh,'\\centering \n'); + fprintf(fh,'\\includegraphics[width=0.8\\textwidth]{%s}\n',graph_name); + if caption + fprintf(fh,'\\caption{%s}',caption); end + fprintf(fh,'\\label{Fig:%s}\n',graph_name); + fprintf(fh,'\\end{figure}\n'); + fprintf(fh,'\n'); + fprintf(fh,'%% End of TeX file.\n'); + fclose(fh); +end diff --git a/matlab/ms-sbvar/identification/exclusions.m b/matlab/ms-sbvar/identification/exclusions.m index 938fd92b41..c695124a81 100644 --- a/matlab/ms-sbvar/identification/exclusions.m +++ b/matlab/ms-sbvar/identification/exclusions.m @@ -47,25 +47,25 @@ np = zeros(nvar,1); k = nlags*nvar+1; for n=1:nvar - Qi{n} = zeros(nvar,nvar); - sQ = size(Qi1{n}); - if all(sQ) > 0 - Qi{n}(1:sQ(1),1:sQ(2)) = Qi1{n}; - end - Ri{n} = zeros(k,k); - sR = size(Ri1{n}); - if all(sR) > 0 - Ri{n}(1:sR(1),1:sR(2)) = Ri1{n}; - end + Qi{n} = zeros(nvar,nvar); + sQ = size(Qi1{n}); + if all(sQ) > 0 + Qi{n}(1:sQ(1),1:sQ(2)) = Qi1{n}; + end + Ri{n} = zeros(k,k); + sR = size(Ri1{n}); + if all(sR) > 0 + Ri{n}(1:sR(1),1:sR(2)) = Ri1{n}; + end - if options_ms.constants_exclusion + if options_ms.constants_exclusion Ri{n}(sR(1)+1,k) = 1; - end + end - Ui{n} = null(Qi{n}); - Vi{n} = null(Ri{n}); - n0(n) = size(Ui{n},2); - np(n) = size(Vi{n},2); + Ui{n} = null(Qi{n}); + Vi{n} = null(Ri{n}); + n0(n) = size(Ui{n},2); + np(n) = size(Vi{n},2); end ixmC0Pres = NaN; \ No newline at end of file diff --git a/matlab/ms-sbvar/identification/lower_cholesky.m b/matlab/ms-sbvar/identification/lower_cholesky.m index 2af96ca9b7..3085e09ddc 100644 --- a/matlab/ms-sbvar/identification/lower_cholesky.m +++ b/matlab/ms-sbvar/identification/lower_cholesky.m @@ -41,11 +41,11 @@ Vi = cell(nvar,1); n0 = zeros(nvar,1); np = zeros(nvar,1); if (nargin==2) - nexo = 1; + nexo = 1; elseif (nargin==3) - indxC0Pres = 0; + indxC0Pres = 0; end -k = lags*nvar+nexo; +k = lags*nvar+nexo; Qi = zeros(nvar,nvar,nvar); Ri = zeros(k,k,nvar); @@ -61,11 +61,11 @@ if options_ms.constants_exclusion end end -for n=1:nvar - Ui{n} = null(Qi(:,:,n)); - Vi{n} = null(Ri(:,:,n)); - n0(n) = size(Ui{n},2); - np(n) = size(Vi{n},2); +for n=1:nvar + Ui{n} = null(Qi(:,:,n)); + Vi{n} = null(Ri(:,:,n)); + n0(n) = size(Ui{n},2); + np(n) = size(Vi{n},2); end ixmC0Pres = NaN; \ No newline at end of file diff --git a/matlab/ms-sbvar/identification/upper_cholesky.m b/matlab/ms-sbvar/identification/upper_cholesky.m index 7f4d2027c5..dbdd19c400 100644 --- a/matlab/ms-sbvar/identification/upper_cholesky.m +++ b/matlab/ms-sbvar/identification/upper_cholesky.m @@ -42,9 +42,9 @@ n0 = zeros(nvar,1); np = zeros(nvar,1); if (nargin==2) - nexo = 1; + nexo = 1; elseif (nargin==3) - indxC0Pres = 0; + indxC0Pres = 0; end k = lags*nvar+nexo; @@ -52,8 +52,8 @@ Qi = zeros(nvar,nvar,nvar); Ri = zeros(k,k,nvar); for ii=2:nvar - Qi(ii-1,ii-1,ii)=1; - Qi(:,:,ii)=Qi(:,:,ii)+Qi(:,:,ii-1); + Qi(ii-1,ii-1,ii)=1; + Qi(:,:,ii)=Qi(:,:,ii)+Qi(:,:,ii-1); end if options_ms.constants_exclusion @@ -62,11 +62,11 @@ if options_ms.constants_exclusion end end -for n=1:nvar - Ui{n} = null(Qi(:,:,n)); - Vi{n} = null(Ri(:,:,n)); - n0(n) = size(Ui{n},2); - np(n) = size(Vi{n},2); +for n=1:nvar + Ui{n} = null(Qi(:,:,n)); + Vi{n} = null(Ri(:,:,n)); + n0(n) = size(Ui{n},2); + np(n) = size(Vi{n},2); end ixmC0Pres = NaN; \ No newline at end of file diff --git a/matlab/ms-sbvar/ms_estimation.m b/matlab/ms-sbvar/ms_estimation.m index 6d5eec32d7..67b8c34fc5 100644 --- a/matlab/ms-sbvar/ms_estimation.m +++ b/matlab/ms-sbvar/ms_estimation.m @@ -45,7 +45,7 @@ else exist(['matlab_' options_.ms.file_tag '.prn'],'file') ~= 2 || ... exist([options_.ms.file_tag '_markov_file.dat'],'file') ~= 2 error(['You must run ms_estimation without no_create_init as '... - 'you are missing an initialization file it needs.']); + 'you are missing an initialization file it needs.']); end if ~strcmp(options_.ms.file_tag, options_.ms.output_file_tag) clean_ms_estimation_files(options_.ms.output_file_tag); diff --git a/matlab/ms-sbvar/ms_forecast.m b/matlab/ms-sbvar/ms_forecast.m index 55030c9021..e8ed8be20c 100644 --- a/matlab/ms-sbvar/ms_forecast.m +++ b/matlab/ms-sbvar/ms_forecast.m @@ -89,30 +89,30 @@ if options_.ms.regimes for regime_i=1:n_regimes forecast_title = ['Forecast, Regimes ' num2str(regime_i)]; forecast_data = load([forecastdir filesep 'forecasts_percentiles_regime_' ... - num2str(regime_i-1) '_' options_.ms.output_file_tag ... - '.out'], '-ascii'); + num2str(regime_i-1) '_' options_.ms.output_file_tag ... + '.out'], '-ascii'); forecast_data = reshape_ascii_forecast_data(M_.endo_nbr, ... - percentiles_size, options_.ms.horizon, forecast_data); + percentiles_size, options_.ms.horizon, forecast_data); save([forecastdir filesep 'forecast_regime_' num2str(regime_i-1) '.mat'], ... - 'forecast_data'); + 'forecast_data'); plot_ms_forecast(M_, options_, forecast_data, forecast_title); end else if options_.ms.regime forecast_data = load([forecastdir filesep 'forecasts_percentiles_regime_' ... - num2str(options_.ms.regime-1) '_' options_.ms.output_file_tag ... - '.out'], '-ascii'); + num2str(options_.ms.regime-1) '_' options_.ms.output_file_tag ... + '.out'], '-ascii'); forecast_title = ['Forecast, Regime ' num2str(options_.ms.regime)]; save_filename = ['forecast_regime_' num2str(options_.ms.regime-1) '.mat']; else forecast_data = load([forecastdir filesep 'forecasts_percentiles_' ... - options_.ms.output_file_tag '.out'], '-ascii'); + options_.ms.output_file_tag '.out'], '-ascii'); forecast_title = 'Forecast'; save_filename = 'forecast.mat'; end forecast_data = reshape_ascii_forecast_data(M_.endo_nbr, ... - percentiles_size, options_.ms.horizon, forecast_data); + percentiles_size, options_.ms.horizon, forecast_data); save([forecastdir filesep save_filename], 'forecast_data'); plot_ms_forecast(M_, options_, forecast_data, forecast_title); end diff --git a/matlab/ms-sbvar/ms_irf.m b/matlab/ms-sbvar/ms_irf.m index 32718aa29c..9b13aaa5e1 100644 --- a/matlab/ms-sbvar/ms_irf.m +++ b/matlab/ms-sbvar/ms_irf.m @@ -91,34 +91,34 @@ if options_.ms.regimes for regime_i=1:n_regimes irf_title = ['Impulse Responses, Regime ' num2str(regime_i)]; irf_data = load([irfdir filesep 'ir_percentiles_regime_' ... - num2str(regime_i-1) '_' options_.ms.output_file_tag ... - '.out'], '-ascii'); + num2str(regime_i-1) '_' options_.ms.output_file_tag ... + '.out'], '-ascii'); irf_data = reshape_ascii_irf_data(M_.endo_nbr, percentiles_size, ... - options_.ms.horizon, irf_data); + options_.ms.horizon, irf_data); save([irfdir filesep 'irf_regime_' num2str(regime_i-1) '.mat'], 'irf_data'); plot_ms_irf(M_, options_, irf_data, irf_title, varlist); end else if options_.ms.regime irf_data = load([irfdir filesep 'ir_percentiles_regime_' ... - num2str(options_.ms.regime-1) '_' options_.ms.output_file_tag ... - '.out'], '-ascii'); + num2str(options_.ms.regime-1) '_' options_.ms.output_file_tag ... + '.out'], '-ascii'); irf_title = ['Impulse Response, Regime ' num2str(options_.ms.regime)]; save_filename = ['irf_regime_' num2str(options_.ms.regime-1) '.mat']; elseif options_.ms.filtered_probabilities irf_data = load([irfdir filesep 'ir_percentiles_filtered_' ... - options_.ms.output_file_tag '.out'], '-ascii'); + options_.ms.output_file_tag '.out'], '-ascii'); irf_title = 'Impulse Response Filtered'; save_filename = 'irf.mat'; else irf_data = load([irfdir filesep 'ir_percentiles_ergodic_' ... - options_.ms.output_file_tag '.out'], '-ascii'); + options_.ms.output_file_tag '.out'], '-ascii'); irf_title = 'Impulse Response Ergodic'; save_filename = 'irf.mat'; end irf_data = reshape_ascii_irf_data(M_.endo_nbr, percentiles_size, ... - options_.ms.horizon, irf_data); + options_.ms.horizon, irf_data); save([irfdir filesep save_filename], 'irf_data'); plot_ms_irf(M_, options_, irf_data, irf_title, varlist); end diff --git a/matlab/ms-sbvar/ms_mardd.m b/matlab/ms-sbvar/ms_mardd.m index 7ca2f304aa..090c69127c 100644 --- a/matlab/ms-sbvar/ms_mardd.m +++ b/matlab/ms-sbvar/ms_mardd.m @@ -25,26 +25,26 @@ function ms_mardd(options_) msstart2 % start the program in which everyhting is initialized through msstart2.m if ~options_.ms.indxestima - warning(' ') - disp('You must set IxEstima=1 in msstart to run this program') - disp('Press ctrl-c to abort now') - pause + warning(' ') + disp('You must set IxEstima=1 in msstart to run this program') + disp('Press ctrl-c to abort now') + pause end A0xhat = zeros(size(A0hat)); Apxhat = zeros(size(Aphat)); if (0) - %Robustness check to see if the same result is obtained with the purterbation of the parameters. - for k=1:nvar - bk = Uiconst{k}'*A0hat(:,k); - gk = Viconst{k}'*Aphat(:,k); - A0xhat(:,k) = Uiconst{k}*(bk + 5.2*randn(size(bk))); % Perturbing the posterior estimate. - Apxhat(:,k) = Viconst{k}*(gk + 5.2*randn(size(gk))); % Perturbing the posterior estimate. - end + %Robustness check to see if the same result is obtained with the purterbation of the parameters. + for k=1:nvar + bk = Uiconst{k}'*A0hat(:,k); + gk = Viconst{k}'*Aphat(:,k); + A0xhat(:,k) = Uiconst{k}*(bk + 5.2*randn(size(bk))); % Perturbing the posterior estimate. + Apxhat(:,k) = Viconst{k}*(gk + 5.2*randn(size(gk))); % Perturbing the posterior estimate. + end else - %At the posterior estimate. - A0xhat = A0hat; % ML estimate of A0 - Apxhat = Aphat; % ML estimate of A+ + %At the posterior estimate. + A0xhat = A0hat; % ML estimate of A0 + Apxhat = Aphat; % ML estimate of A+ end %--- Rename variables. YatYa = yty; @@ -59,40 +59,40 @@ XatXa = xtx; vlog_a0p = 0; Yexpt=0; % exponential term for Y in p(Y|A0,A+) at some point such as the peak Apexpt=0.0; % 0.0 because we have chosen posterior estimate of A+ as A+*. Exponential term for A+ conditional on A0 and Y -%======= Computing the log prior pdf of a0a+ and the exponential term for Y in p(Y|A0,A+). + %======= Computing the log prior pdf of a0a+ and the exponential term for Y in p(Y|A0,A+). for k=1:nvar - a0k = A0xhat(:,k); % meaningful parameters in the kth equation. - apk = Apxhat(:,k); % meaningful parameters in the kth equation. - - %--- Prior settings. - S0bar = H0invtld{k}; %See Claim 2 on p.69b. - Spbar = Hpinvtld{k}; - bk = Uiconst{k}'*a0k; % free parameters in the kth equation. - gk = Viconst{k}'*apk; % free parameters in the kth equation. - gbark = Ptld{k}*bk; % bar: prior - - %--- The exponential term for Y in p(Y|A0,A+) - Yexpt = Yexpt - 0.5*(a0k'*YatYa*a0k - 2*apk'*XatYa*a0k + apk'*XatXa*apk); - %--- The log prior pdf. - vlog_a0p = vlog_a0p - 0.5*(size(Uiconst{k},2)+size(Viconst{k},2))*log(2*pi) + 0.5*log(abs(det(S0bar))) + ... - 0.5*log(abs(det(Spbar))) - 0.5*(bk'*S0bar*bk+(gk-gbark)'*Spbar*(gk-gbark)); - %--- For p(A+|Y,a0) only. - tmpd = gk - Pmat{k}*bk; - Apexpt = Apexpt - 0.5*tmpd'*(Hpinv{k}*tmpd); + a0k = A0xhat(:,k); % meaningful parameters in the kth equation. + apk = Apxhat(:,k); % meaningful parameters in the kth equation. + + %--- Prior settings. + S0bar = H0invtld{k}; %See Claim 2 on p.69b. + Spbar = Hpinvtld{k}; + bk = Uiconst{k}'*a0k; % free parameters in the kth equation. + gk = Viconst{k}'*apk; % free parameters in the kth equation. + gbark = Ptld{k}*bk; % bar: prior + + %--- The exponential term for Y in p(Y|A0,A+) + Yexpt = Yexpt - 0.5*(a0k'*YatYa*a0k - 2*apk'*XatYa*a0k + apk'*XatXa*apk); + %--- The log prior pdf. + vlog_a0p = vlog_a0p - 0.5*(size(Uiconst{k},2)+size(Viconst{k},2))*log(2*pi) + 0.5*log(abs(det(S0bar))) + ... + 0.5*log(abs(det(Spbar))) - 0.5*(bk'*S0bar*bk+(gk-gbark)'*Spbar*(gk-gbark)); + %--- For p(A+|Y,a0) only. + tmpd = gk - Pmat{k}*bk; + Apexpt = Apexpt - 0.5*tmpd'*(Hpinv{k}*tmpd); end vlog_a0p %--------- The log value of p(Y|A0,A+) at some point such as the peak. ---------- %--------- Note that logMarLHres is the same as vlog_Y_a, just to double check. ---------- vlog_Y_a = -0.5*nvar*fss*log(2*pi) + fss*log(abs(det(A0xhat))) + Yexpt - % a: given a0 and a+ +% a: given a0 and a+ logMarLHres = 0; % Initialize log of the marginal likelihood (restricted or constant parameters). for ki=1:fss %ndobs+1:fss % Forward recursion to get the marginal likelihood. See F on p.19 and pp. 48-49. - %---- Restricted log marginal likelihood function (constant parameters). - [A0l,A0u] = lu(A0xhat); - ada = sum(log(abs(diag(A0u)))); % log|A0| - termexp = y(ki,:)*A0xhat - phi(ki,:)*Apxhat; % 1-by-nvar - logMarLHres = logMarLHres - (0.5*nvar)*log(2*pi) + ada - 0.5*termexp*termexp'; % log value + %---- Restricted log marginal likelihood function (constant parameters). + [A0l,A0u] = lu(A0xhat); + ada = sum(log(abs(diag(A0u)))); % log|A0| + termexp = y(ki,:)*A0xhat - phi(ki,:)*Apxhat; % 1-by-nvar + logMarLHres = logMarLHres - (0.5*nvar)*log(2*pi) + ada - 0.5*termexp*termexp'; % log value end logMarLHres @@ -101,8 +101,8 @@ logMarLHres totparsp = 0.0; tmpd = 0.0; for k=1:nvar - totparsp = totparsp + size(Viconst{k},2); - tmpd = tmpd + 0.5*log(abs(det(Hpinv{k}))); + totparsp = totparsp + size(Viconst{k},2); + tmpd = tmpd + 0.5*log(abs(det(Hpinv{k}))); end vlog_ap_Ya0 = -0.5*totparsp*log(2*pi) + tmpd + Apexpt; @@ -117,65 +117,65 @@ vlog_ap_Ya0 = -0.5*totparsp*log(2*pi) + tmpd + Apexpt; [Tinv,UT] = fn_gibbsrvar_setup(H0inv, Uiconst, Hpinv, Pmat, Viconst, nvar, fss); % vlog_a0_Yao = zeros(nvar,1); - % the log value of p(a0k|Y,ao) where ao: other a's at some point such as the peak of ONLY some a0's +% the log value of p(a0k|Y,ao) where ao: other a's at some point such as the peak of ONLY some a0's vlog=zeros(ndraws2,1); for k=1:nvar - bk = Uiconst{k}'*A0xhat(:,k); - indx_ks=[k:nvar]; % the columns that exclude 1-(k-1)th columns - A0gbs0 = A0hat; % starting at some point such as the peak - nk = n0(k); - - if k<nvar - %--------- The 1st set of draws to be tossed away. ------------------ - for draws = 1:ndraws1 - if ~mod(draws,nbuffer) - skipline() - disp(sprintf('The %dth column or equation in A0 with %d 1st tossed-away draws in Gibbs',k,draws)) - end - A0gbs1 = fn_gibbsrvar(A0gbs0,UT,nvar,fss,n0,indx_ks); - A0gbs0=A0gbs1; % repeat the Gibbs sampling - end - - - %--------- The 2nd set of draws to be used. ------------------ - for draws = 1:ndraws2 - if ~mod(draws,nbuffer) - skipline() - disp(sprintf('The %dth column or equation in A0 with %d usable draws in Gibbs',k,draws)) - end - [A0gbs1, Wcell] = fn_gibbsrvar(A0gbs0,UT,nvar,fss,n0,indx_ks); - %------ See p.71, Forecast (II). - %------ Computing p(a0_k|Y,a_others) at some point such as the peak along the dimensions of indx_ks. - Vk = Tinv{k}\Wcell{k}; %V_k on p.71 of Forecast (II). - gbeta = Vk\bk; % inv(V_k)*b_k on p.71 of Forecast (II) where alpha_k = b_k in our notation. - [Vtq,Vtr]=qr(Vk',0); %To get inv(V_k)'*inv(V_k) in (*) on p.71 of Forecast (II). - % - vlog(draws) = 0.5*(fss+nk)*log(fss)-log(abs(det(Vk)))-0.5*(nk-1)*log(2*pi)-... - 0.5*(fss+1)*log(2)-gammaln(0.5*(fss+1))+fss*log(abs(gbeta(1)))-... - 0.5*fss*bk'*(Vtr\(Vtr'\bk)); - - A0gbs0=A0gbs1; % repeat the Gibbs sampling - end - vlogm=max(vlog); - qlog=vlog-vlogm; - vlogxhat=vlogm-log(ndraws2)+log(sum(exp(qlog))); - vlog_a0_Yao(k) = vlogxhat; - % The log value of p(a0_k|Y,a_others) where a_others: other a's at some point such as the peak of ONLY some a0's - else - skipline() - disp(sprintf('The last(6th) column or equation in A0 with no Gibbs draws')) - [A0gbs1, Wcell] = fn_gibbsrvar(A0gbs0,UT,nvar,fss,n0,indx_ks) - %------ See p.71, Forecast (II). - %------ Computing p(a0_k|Y,a_others) at some point such as the peak along the dimensions of indx_ks. - Vk = Tinv{k}\Wcell{k}; %V_k on p.71 of Forecast (II). - gbeta = Vk\bk; % inv(V_k)*b_k on p.71 of Forecast (II) where alpha_k = b_k in our notation. - [Vtq,Vtr]=qr(Vk',0); %To get inv(V_k)'*inv(V_k) in (*) on p.71 of Forecast (II). - % - vloglast = 0.5*(fss+nk)*log(fss)-log(abs(det(Vk)))-0.5*(nk-1)*log(2*pi)-... - 0.5*(fss+1)*log(2)-gammaln(0.5*(fss+1))+fss*log(abs(gbeta(1)))-... - 0.5*fss*bk'*(Vtr\(Vtr'\bk)); - vlog_a0_Yao(k) = vloglast; - end + bk = Uiconst{k}'*A0xhat(:,k); + indx_ks=[k:nvar]; % the columns that exclude 1-(k-1)th columns + A0gbs0 = A0hat; % starting at some point such as the peak + nk = n0(k); + + if k<nvar + %--------- The 1st set of draws to be tossed away. ------------------ + for draws = 1:ndraws1 + if ~mod(draws,nbuffer) + skipline() + disp(sprintf('The %dth column or equation in A0 with %d 1st tossed-away draws in Gibbs',k,draws)) + end + A0gbs1 = fn_gibbsrvar(A0gbs0,UT,nvar,fss,n0,indx_ks); + A0gbs0=A0gbs1; % repeat the Gibbs sampling + end + + + %--------- The 2nd set of draws to be used. ------------------ + for draws = 1:ndraws2 + if ~mod(draws,nbuffer) + skipline() + disp(sprintf('The %dth column or equation in A0 with %d usable draws in Gibbs',k,draws)) + end + [A0gbs1, Wcell] = fn_gibbsrvar(A0gbs0,UT,nvar,fss,n0,indx_ks); + %------ See p.71, Forecast (II). + %------ Computing p(a0_k|Y,a_others) at some point such as the peak along the dimensions of indx_ks. + Vk = Tinv{k}\Wcell{k}; %V_k on p.71 of Forecast (II). + gbeta = Vk\bk; % inv(V_k)*b_k on p.71 of Forecast (II) where alpha_k = b_k in our notation. + [Vtq,Vtr]=qr(Vk',0); %To get inv(V_k)'*inv(V_k) in (*) on p.71 of Forecast (II). + % + vlog(draws) = 0.5*(fss+nk)*log(fss)-log(abs(det(Vk)))-0.5*(nk-1)*log(2*pi)-... + 0.5*(fss+1)*log(2)-gammaln(0.5*(fss+1))+fss*log(abs(gbeta(1)))-... + 0.5*fss*bk'*(Vtr\(Vtr'\bk)); + + A0gbs0=A0gbs1; % repeat the Gibbs sampling + end + vlogm=max(vlog); + qlog=vlog-vlogm; + vlogxhat=vlogm-log(ndraws2)+log(sum(exp(qlog))); + vlog_a0_Yao(k) = vlogxhat; + % The log value of p(a0_k|Y,a_others) where a_others: other a's at some point such as the peak of ONLY some a0's + else + skipline() + disp(sprintf('The last(6th) column or equation in A0 with no Gibbs draws')) + [A0gbs1, Wcell] = fn_gibbsrvar(A0gbs0,UT,nvar,fss,n0,indx_ks) + %------ See p.71, Forecast (II). + %------ Computing p(a0_k|Y,a_others) at some point such as the peak along the dimensions of indx_ks. + Vk = Tinv{k}\Wcell{k}; %V_k on p.71 of Forecast (II). + gbeta = Vk\bk; % inv(V_k)*b_k on p.71 of Forecast (II) where alpha_k = b_k in our notation. + [Vtq,Vtr]=qr(Vk',0); %To get inv(V_k)'*inv(V_k) in (*) on p.71 of Forecast (II). + % + vloglast = 0.5*(fss+nk)*log(fss)-log(abs(det(Vk)))-0.5*(nk-1)*log(2*pi)-... + 0.5*(fss+1)*log(2)-gammaln(0.5*(fss+1))+fss*log(abs(gbeta(1)))-... + 0.5*fss*bk'*(Vtr\(Vtr'\bk)); + vlog_a0_Yao(k) = vloglast; + end end ndraws2 diff --git a/matlab/ms-sbvar/ms_sbvar_setup.m b/matlab/ms-sbvar/ms_sbvar_setup.m index 93b4170357..2bdefad15c 100644 --- a/matlab/ms-sbvar/ms_sbvar_setup.m +++ b/matlab/ms-sbvar/ms_sbvar_setup.m @@ -29,7 +29,7 @@ function ms_sbvar_setup(options_) % along with Dynare. If not, see <http://www.gnu.org/licenses/>. options_.data = read_variables(options_.datafile, ... - options_.varobs, [], options_.xls_sheet, options_.xls_range); + options_.varobs, [], options_.xls_sheet, options_.xls_range); [options_.ms.final_year,options_.ms.final_subperiod] = check_datafile_years_assigned(options_); if options_.ms.upper_cholesky @@ -243,10 +243,10 @@ if indxPrior else [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] = fn_rnrprior(nvar,q_m,options_.ms.nlags,xdgel,mu); end - + %*** Combines asymmetric prior with linear restrictions [Ptld,H0invtld,Hpinvtld] = fn_rlrprior(Ui,Vi,Pi,H0multi,Hpmulti,nvar); - + %*** Obtains the posterior matrices for estimation and inference [Pmat,H0inv,Hpinv] = fn_rlrpostr(xtx,xty,yty,Ptld,H0invtld,Hpinvtld,Ui,Vi); else @@ -258,7 +258,7 @@ if Rform %*** Obtain the ML estimate A0hatinv = chol(H0inv{1}/fss); % upper triangular but lower triangular choleski A0hat=inv(A0hatinv); - + Aphat = Pmat{1}*A0hat; else %*** Obtain the ML estimate @@ -271,16 +271,16 @@ else [fhat,xhat,grad,Hhat,itct,fcount,retcodehat] = csminwel('fn_a0freefun',x,H0,'fn_a0freegrad',crit,nit,Ui,nvar,n0,fss,H0inv); A0hat = fn_tran_b2a(xhat,Ui,nvar,n0); - + xhat = fn_tran_a2b(A0hat,Ui,nvar,n0); [Aphat,ghat] = fn_gfmean(xhat,Pmat,Vi,nvar,ncoef,n0,np); if indxC0Pres Fhatur0P = Fhat; % ur: unrestriced across A0 and A+ for ki = 1:size(ixmC0Pres,1) % loop through the number of equations in which - % cross-A0-A+ restrictions occur. See St. Louis Note p.5. + % cross-A0-A+ restrictions occur. See St. Louis Note p.5. ixeq = ixmC0Pres{ki}(1,1); % index for the jth equation in consideration. Lit = Vi{ixeq}(ixmC0Pres{ki}(:,2),:); % transposed restriction matrix Li - % V_j(i,:) in f_j(i) = V_j(i,:)*g_j + % V_j(i,:) in f_j(i) = V_j(i,:)*g_j ci = ixmC0Pres{ki}(:,4) .* A0hat(ixmC0Pres{ki}(:,3),ixeq); % s * a_j(h) in the restriction f_j(i) = s * a_j(h). LtH = Lit/Hpinv{ixeq}; diff --git a/matlab/ms-sbvar/ms_variance_decomposition.m b/matlab/ms-sbvar/ms_variance_decomposition.m index 553488acd1..83e270171a 100644 --- a/matlab/ms-sbvar/ms_variance_decomposition.m +++ b/matlab/ms-sbvar/ms_variance_decomposition.m @@ -85,7 +85,7 @@ if options_.ms.regime || options_.ms.regimes outfile = [outfile 'regime_']; if options_.ms.regime outfile = [outfile num2str(options_.ms.regime-1) ... - '_' options_.ms.output_file_tag '.out']; + '_' options_.ms.output_file_tag '.out']; end elseif options_.ms.filtered_probabilities outfile = [outfile 'filtered_' options_.ms.output_file_tag '.out']; @@ -103,7 +103,7 @@ if options_.ms.regimes for regime_i=1:n_regimes vd_title = ['Variance Decomposition, Regime ' num2str(regime_i)]; vd_data = load([outfile num2str(regime_i-1) '_' ... - options_.ms.output_file_tag '.out'], '-ascii'); + options_.ms.output_file_tag '.out'], '-ascii'); vd_data = reshape_ascii_variance_decomposition_data( ... M_.endo_nbr, percentiles_size, options_.ms.horizon, vd_data); save([vddir filesep 'variance_decomposition_regime_' num2str(regime_i-1) '.mat'], 'vd_data'); diff --git a/matlab/ms-sbvar/ms_write_markov_file.m b/matlab/ms-sbvar/ms_write_markov_file.m index 322a0fbf56..b35409cf0a 100644 --- a/matlab/ms-sbvar/ms_write_markov_file.m +++ b/matlab/ms-sbvar/ms_write_markov_file.m @@ -27,136 +27,136 @@ function ms_write_markov_file(fname, options) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - n_chains = length(options.ms.ms_chain); - nvars = length(options.varobs); - - fh = fopen(fname,'w'); - %/******************************************************************************/ - %/********************* Markov State Variable Information **********************/ - %/******************************************************************************/ - - fprintf(fh,'//== Markov State Variables with Simple Restrictions ==//\n\n'); - - - %//This number is NOT used but read in. - fprintf(fh,'//== Number Observations ==//\n'); - fprintf(fh,'0\n\n'); - - fprintf(fh,'//== Number independent state variables ==//\n'); - fprintf(fh,'%d\n\n',n_chains); +n_chains = length(options.ms.ms_chain); +nvars = length(options.varobs); - for i_chain = 1:n_chains +fh = fopen(fname,'w'); +%/******************************************************************************/ +%/********************* Markov State Variable Information **********************/ +%/******************************************************************************/ - %//=====================================================// - %//== state_variable[i] (1 <= i <= n_state_variables) ==// - %//=====================================================// - fprintf(fh,'//== Number of states for state_variable[%d] ==//\n', ... - i_chain); - n_states = length(options.ms.ms_chain(i_chain).regime); - fprintf(fh,'%d\n\n',n_states); - - %//== 03/15/06: DW TVBVAR code reads the data below and overwrite the prior data read somewhere else if any. - %//== Each column contains the parameters for a Dirichlet prior on the corresponding - %//== column of the transition matrix. Each element must be positive. For each column, - %//== the relative size of the prior elements determine the relative size of the elements - %//== of the transition matrix and overall larger sizes implies a tighter prior. - fprintf(fh,['//== Transition matrix prior for state_variable[%d] ==//\n'], ... - i_chain); - Alpha = ones(n_states,n_states); - for i_state = 1:n_states - p = 1-1/options.ms.ms_chain(i_chain).regime(i_state).duration; - Alpha(i_state,i_state) = p*(n_states-1)/(1-p); - fprintf(fh,'%22.16f',Alpha(i_state,:)); - fprintf(fh,'\n'); +fprintf(fh,'//== Markov State Variables with Simple Restrictions ==//\n\n'); + + +%//This number is NOT used but read in. +fprintf(fh,'//== Number Observations ==//\n'); +fprintf(fh,'0\n\n'); + +fprintf(fh,'//== Number independent state variables ==//\n'); +fprintf(fh,'%d\n\n',n_chains); + +for i_chain = 1:n_chains + + %//=====================================================// + %//== state_variable[i] (1 <= i <= n_state_variables) ==// + %//=====================================================// + fprintf(fh,'//== Number of states for state_variable[%d] ==//\n', ... + i_chain); + n_states = length(options.ms.ms_chain(i_chain).regime); + fprintf(fh,'%d\n\n',n_states); + + %//== 03/15/06: DW TVBVAR code reads the data below and overwrite the prior data read somewhere else if any. + %//== Each column contains the parameters for a Dirichlet prior on the corresponding + %//== column of the transition matrix. Each element must be positive. For each column, + %//== the relative size of the prior elements determine the relative size of the elements + %//== of the transition matrix and overall larger sizes implies a tighter prior. + fprintf(fh,['//== Transition matrix prior for state_variable[%d] ==//\n'], ... + i_chain); + Alpha = ones(n_states,n_states); + for i_state = 1:n_states + p = 1-1/options.ms.ms_chain(i_chain).regime(i_state).duration; + Alpha(i_state,i_state) = p*(n_states-1)/(1-p); + fprintf(fh,'%22.16f',Alpha(i_state,:)); + fprintf(fh,'\n'); + end + + fprintf(fh,['\n//== Dirichlet dimensions for state_variable[%d] ' ... + '==//\n'],i_chain); + % fprintf(fh,'%d ',repmat(n_states,1,n_states)); + fprintf(fh,'%d ',repmat(2,1,n_states)); + fprintf(fh,'\n\n'); + + %//== The jth restriction matrix is n_states-by-free[j]. Each row of the restriction + %//== matrix has exactly one non-zero entry and the sum of each column must be one. + fprintf(fh,['//== Column restrictions for state_variable[%d] ' ... + '==//\n'],i_chain); + for i_state = 1:n_states + if i_state == 1 + M = eye(n_states,2); + elseif i_state == n_states + M = [zeros(n_states-2,2); eye(2)]; + else + M = zeros(n_states,2); + M(i_state+[-1 1],1) = ones(2,1)/2; + M(i_state,2) = 1; + disp(M) end - - fprintf(fh,['\n//== Dirichlet dimensions for state_variable[%d] ' ... - '==//\n'],i_chain); - % fprintf(fh,'%d ',repmat(n_states,1,n_states)); - fprintf(fh,'%d ',repmat(2,1,n_states)); - fprintf(fh,'\n\n'); - - %//== The jth restriction matrix is n_states-by-free[j]. Each row of the restriction - %//== matrix has exactly one non-zero entry and the sum of each column must be one. - fprintf(fh,['//== Column restrictions for state_variable[%d] ' ... - '==//\n'],i_chain); - for i_state = 1:n_states - if i_state == 1 - M = eye(n_states,2); - elseif i_state == n_states - M = [zeros(n_states-2,2); eye(2)]; - else - M = zeros(n_states,2); - M(i_state+[-1 1],1) = ones(2,1)/2; - M(i_state,2) = 1; - disp(M) - end - for j_state = 1:n_states - fprintf(fh,'%f ',M(j_state,:)); - fprintf(fh,'\n'); - end + for j_state = 1:n_states + fprintf(fh,'%f ',M(j_state,:)); fprintf(fh,'\n'); end + fprintf(fh,'\n'); end +end + +%/******************************************************************************/ +%/******************************* VAR Parameters *******************************/ +%/******************************************************************************/ +%//NOT read +fprintf(fh,'//== Number Variables ==//\n'); +fprintf(fh,'%d\n\n',nvars); + +%//NOT read +fprintf(fh,'//== Number Lags ==//\n'); +fprintf(fh,'%d\n\n',options.ms.nlags); + +%//NOT read +fprintf(fh,'//== Exogenous Variables ==//\n'); +fprintf(fh,'1\n\n'); + + +%//== nvar x n_state_variables matrix. In the jth row, a non-zero value implies that +%this state variable controls the jth column of A0 and Aplus +fprintf(fh,['//== Controlling states variables for coefficients ==//\' ... + 'n']); - %/******************************************************************************/ - %/******************************* VAR Parameters *******************************/ - %/******************************************************************************/ - %//NOT read - fprintf(fh,'//== Number Variables ==//\n'); - fprintf(fh,'%d\n\n',nvars); - - %//NOT read - fprintf(fh,'//== Number Lags ==//\n'); - fprintf(fh,'%d\n\n',options.ms.nlags); - - %//NOT read - fprintf(fh,'//== Exogenous Variables ==//\n'); - fprintf(fh,'1\n\n'); - - - %//== nvar x n_state_variables matrix. In the jth row, a non-zero value implies that - %this state variable controls the jth column of A0 and Aplus - fprintf(fh,['//== Controlling states variables for coefficients ==//\' ... - 'n']); - - for i_var = 1:nvars - for i_chain = 1:n_chains - if ~isfield(options.ms.ms_chain(i_chain),'svar_coefficients') ... - || isempty(options.ms.ms_chain(i_chain).svar_coefficients) - i_equations = 0; - else - i_equations = ... - options.ms.ms_chain(i_chain).svar_coefficients.equations; - end - if strcmp(i_equations,'ALL') || any(i_equations == i_var) - fprintf(fh,'%d ',1); - else - fprintf(fh,'%d ',0); - end +for i_var = 1:nvars + for i_chain = 1:n_chains + if ~isfield(options.ms.ms_chain(i_chain),'svar_coefficients') ... + || isempty(options.ms.ms_chain(i_chain).svar_coefficients) + i_equations = 0; + else + i_equations = ... + options.ms.ms_chain(i_chain).svar_coefficients.equations; + end + if strcmp(i_equations,'ALL') || any(i_equations == i_var) + fprintf(fh,'%d ',1); + else + fprintf(fh,'%d ',0); end - fprintf(fh,'\n'); end + fprintf(fh,'\n'); +end - %//== nvar x n_state_variables matrix. In the jth row, a non-zero value implies that - %this state variable controls the jth diagonal element of Xi - fprintf(fh,'\n//== Controlling states variables for variance ==//\n'); - for i_var = 1:nvars - for i_chain = 1:n_chains - if ~isfield(options.ms.ms_chain(i_chain),'svar_variances') ... - || isempty(options.ms.ms_chain(i_chain).svar_variances) - i_equations = 0; - else - i_equations = ... - options.ms.ms_chain(i_chain).svar_variances.equations; - end - if strcmp(i_equations,'ALL') || any(i_equations == i_var) - fprintf(fh,'%d ',1); - else - fprintf(fh,'%d ',0); - end +%//== nvar x n_state_variables matrix. In the jth row, a non-zero value implies that +%this state variable controls the jth diagonal element of Xi +fprintf(fh,'\n//== Controlling states variables for variance ==//\n'); +for i_var = 1:nvars + for i_chain = 1:n_chains + if ~isfield(options.ms.ms_chain(i_chain),'svar_variances') ... + || isempty(options.ms.ms_chain(i_chain).svar_variances) + i_equations = 0; + else + i_equations = ... + options.ms.ms_chain(i_chain).svar_variances.equations; + end + if strcmp(i_equations,'ALL') || any(i_equations == i_var) + fprintf(fh,'%d ',1); + else + fprintf(fh,'%d ',0); end - fprintf(fh,'\n'); end + fprintf(fh,'\n'); +end - fclose(fh); +fclose(fh); diff --git a/matlab/ms-sbvar/ms_write_mhm_input.m b/matlab/ms-sbvar/ms_write_mhm_input.m index 57854d59ae..1edd4b4a2d 100644 --- a/matlab/ms-sbvar/ms_write_mhm_input.m +++ b/matlab/ms-sbvar/ms_write_mhm_input.m @@ -28,41 +28,41 @@ function ms_write_mhm_input(fname, options_ms) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - fh = fopen(fname,'w'); +fh = fopen(fname,'w'); - fprintf(fh,'/**********************************************************\n'); - fprintf(fh,' *** This input file is read by swzmsbvar_mhm_1 and swzmsbvar_mhm_1.exe only, NOT by swzmsbvar_printdraws.exe.\n'); - fprintf(fh,' ***\n'); - fprintf(fh,' **********************************************************/\n'); +fprintf(fh,'/**********************************************************\n'); +fprintf(fh,' *** This input file is read by swzmsbvar_mhm_1 and swzmsbvar_mhm_1.exe only, NOT by swzmsbvar_printdraws.exe.\n'); +fprintf(fh,' ***\n'); +fprintf(fh,' **********************************************************/\n'); - fprintf(fh,'\n\n//------------- 1st set of posterior draws to find optimal scales for Metropolis (30000). ---------------\n'); - fprintf(fh,'//== number draws for first burn-in ==// //For determining the Metropolis scales only.\n'); - fprintf(fh,'%d\n\n',options_ms.draws_nbr_burn_in_1); +fprintf(fh,'\n\n//------------- 1st set of posterior draws to find optimal scales for Metropolis (30000). ---------------\n'); +fprintf(fh,'//== number draws for first burn-in ==// //For determining the Metropolis scales only.\n'); +fprintf(fh,'%d\n\n',options_ms.draws_nbr_burn_in_1); - fprintf(fh,'//------------- MCMC burn-in draws once the Metropolis scales (previous stage) are fixed. --------------\n'); - fprintf(fh,'//------------- 2nd set of standard burn-in posterior draws to throw away the initial draws (10000). ---------------\n'); - fprintf(fh,'//== number draws for second burn-in ==//\n'); - fprintf(fh,'%d\n\n',options_ms.draws_nbr_burn_in_2); +fprintf(fh,'//------------- MCMC burn-in draws once the Metropolis scales (previous stage) are fixed. --------------\n'); +fprintf(fh,'//------------- 2nd set of standard burn-in posterior draws to throw away the initial draws (10000). ---------------\n'); +fprintf(fh,'//== number draws for second burn-in ==//\n'); +fprintf(fh,'%d\n\n',options_ms.draws_nbr_burn_in_2); - fprintf(fh,'//--------------- 1st set of posterior draws to compute the mean and variance for the weighting function in the MHM (200000) ----------------\n'); - fprintf(fh,'//== number draws to estimate mean and variance ==//\n'); - fprintf(fh,'%d\n\n',options_ms.draws_nbr_mean_var_estimate); +fprintf(fh,'//--------------- 1st set of posterior draws to compute the mean and variance for the weighting function in the MHM (200000) ----------------\n'); +fprintf(fh,'//== number draws to estimate mean and variance ==//\n'); +fprintf(fh,'%d\n\n',options_ms.draws_nbr_mean_var_estimate); - fprintf(fh,'//--------------- Only applied to mhm_2 process: total number of MCMC draws = thinning factor * 2nd set of saved posterior draws ----------------\n'); - fprintf(fh,'//== thinning factor for modified harmonic mean process ==//\n'); - fprintf(fh,'%d\n\n',options_ms.thinning_factor); +fprintf(fh,'//--------------- Only applied to mhm_2 process: total number of MCMC draws = thinning factor * 2nd set of saved posterior draws ----------------\n'); +fprintf(fh,'//== thinning factor for modified harmonic mean process ==//\n'); +fprintf(fh,'%d\n\n',options_ms.thinning_factor); - fprintf(fh,'//--------------- 2nd set of saved posterior draws from MHM_2 (second stage): saved draws AFTER thinning (1000000) ----------------\n'); - fprintf(fh,'//== number draws for modified harmonic mean process ==//\n'); - fprintf(fh,'%d\n\n',options_ms.draws_nbr_modified_harmonic_mean); +fprintf(fh,'//--------------- 2nd set of saved posterior draws from MHM_2 (second stage): saved draws AFTER thinning (1000000) ----------------\n'); +fprintf(fh,'//== number draws for modified harmonic mean process ==//\n'); +fprintf(fh,'%d\n\n',options_ms.draws_nbr_modified_harmonic_mean); - fprintf(fh,'//------- 1st stage: computing all three tightness factors for Dirichlet. ---------\n'); - fprintf(fh,'//------- 2nd stage: hard-code the second scale factor (in principle, we can do all three). ---------\n'); - fprintf(fh,'//------- It seems that Dan''s code only use the first element of the following scales. The scale applies to the Dirichlet''s hyperparameter alpha for the diagonal of the transition matrix in the weighting function. Note that the weighting function for the transition matrix parameters is Dirichlet. ---------\n'); - - fprintf(fh,'//== scale values for Dirichlet distribution ==//\n'); - fprintf(fh,'3\n\n'); - fprintf(fh,'%f ',options_ms.dirichlet_scale); - fprintf(fh,'\n'); - fclose(fh); \ No newline at end of file +fprintf(fh,'//------- 1st stage: computing all three tightness factors for Dirichlet. ---------\n'); +fprintf(fh,'//------- 2nd stage: hard-code the second scale factor (in principle, we can do all three). ---------\n'); +fprintf(fh,'//------- It seems that Dan''s code only use the first element of the following scales. The scale applies to the Dirichlet''s hyperparameter alpha for the diagonal of the transition matrix in the weighting function. Note that the weighting function for the transition matrix parameters is Dirichlet. ---------\n'); + +fprintf(fh,'//== scale values for Dirichlet distribution ==//\n'); +fprintf(fh,'3\n\n'); +fprintf(fh,'%f ',options_ms.dirichlet_scale); +fprintf(fh,'\n'); +fclose(fh); \ No newline at end of file diff --git a/matlab/ms-sbvar/msstart2.m b/matlab/ms-sbvar/msstart2.m index 284f6eaeea..95491d5af1 100644 --- a/matlab/ms-sbvar/msstart2.m +++ b/matlab/ms-sbvar/msstart2.m @@ -45,17 +45,17 @@ msstart_setup %options_.ms.Indxcol = [1:nvar]; % a vector of random columns in which MC draws are made. % %options_.ms.indxparr = 1; % 1: parameters random; 0: no randomness in parameters - % Note, when 0, there is no effect from the values of options_.ms.IndxAp, options_.ms.Aband, etc. +% Note, when 0, there is no effect from the values of options_.ms.IndxAp, options_.ms.Aband, etc. %options_.ms.indxovr = 0; % 1: distributions for other variables of interest; 0: no distribution. - % Example: joint distribution of a(1) and a(2). Only for specific purposes +% Example: joint distribution of a(1) and a(2). Only for specific purposes %options_.ms.Aband = 1; % 1: error bands with only A0 and A+ random. %options_.ms.IndxAp = 1; % 1: generate draws of A+; 0: no such draws. - % Note: when options_.ms.IndxAp=0, there is no effect from the values of options_.ms.options_.ms.options_.ms.options_.ms.indximf, IndxFore, - % or options_.ms.apband. +% Note: when options_.ms.IndxAp=0, there is no effect from the values of options_.ms.options_.ms.options_.ms.options_.ms.indximf, IndxFore, +% or options_.ms.apband. %options_.ms.apband = 1; % 1: error bands for A+; 0: no error bands for A+. %*** The following (impulse responses and forecasts) is used only if options_.ms.IndxAp=1 %options_.ms.indximf = 1; % 1: generate draws of impulse responses; 0: no such draws (thus no effect - % from options_.ms.imfband) +% from options_.ms.imfband) %options_.ms.imfband = 1; % 1: error bands for impulse responses; 0: no error bands %options_.ms.indxfore = 0; % 1: generate draws of forecasts; 0: no such draws (thus no effect from options_.ms.foreband) %options_.ms.foreband = 0; % 1: error bands for out-of-sample forecasts; 0: no error bands @@ -64,23 +64,23 @@ msstart_setup rnum = nvar; % number of rows in the graph cnum = 1; % number of columns in the graph if rnum*cnum<nvar - warning('rnum*cnum must be at least as large as nvar') - disp('Hit any key to continue, or ctrl-c to abort') - pause + warning('rnum*cnum must be at least as large as nvar') + disp('Hit any key to continue, or ctrl-c to abort') + pause end %options_.ms.indxgimfhat = 1; % 1: plot ML impulse responses; 0: no plot %options_.ms.indxestima = 1; %1: ML estimation; 0: no estimation and data only % IndxNmlr = [1 0 0 0 0 0]; % imported by nmlzvar.m - % Index for which normalization rule to choose - % Only one of the elments in IndxNmlr can be non-zero - % IndxNmlr(1): ML A distance rule (supposed to be the best) - % IndxNmlr(2): ML Ahat distance rule (to approximate IndxNmlr(1)) - % IndxNmlr(3): ML Euclidean distance rule (not invariant to scale) - % IndxNmlr(4): Positive diagonal rule - % IndxNmlr(5): Positive inv(A) diagonal rule (if ~IndxNmlr(5), no need for A0inu, - % so let A0inu=[]) - % IndxNmlr(6): Assigned postive rule (such as off-diagonal elements). Added 1/3/00 + % Index for which normalization rule to choose + % Only one of the elments in IndxNmlr can be non-zero + % IndxNmlr(1): ML A distance rule (supposed to be the best) + % IndxNmlr(2): ML Ahat distance rule (to approximate IndxNmlr(1)) + % IndxNmlr(3): ML Euclidean distance rule (not invariant to scale) + % IndxNmlr(4): Positive diagonal rule + % IndxNmlr(5): Positive inv(A) diagonal rule (if ~IndxNmlr(5), no need for A0inu, + % so let A0inu=[]) + % IndxNmlr(6): Assigned postive rule (such as off-diagonal elements). Added 1/3/00 %%%%---------------------------------------- @@ -90,7 +90,7 @@ IndxNmlr = [1 0 0 0 0 0]; % imported by nmlzvar.m nconstr1=nfqm; % number of the 1st set of constraints nconstr2=options_.forecast ; % number of the 2nd set of constraints nconstr=nconstr1+nconstr2; % q: 4 years -- 4*12 months. - % When 0, no conditions directly on variables <<>> + % When 0, no conditions directly on variables <<>> nconstr=0 ; %6*nconstr1; options_.ms.eq_ms = []; % location of MS equation; if [], all shocks PorR = [4*ones(nconstr1,1);2*ones(nconstr1,1);3*ones(nconstr1,1)]; % the variable conditioned. 1: Pcm; 3: FFR; 4: CPI @@ -102,32 +102,32 @@ PorR = [PorR;1*ones(nconstr1,1);5*ones(nconstr1,1);6*ones(nconstr1,1)]; % Conditions directly on future shocks % %options_.ms.cms = 0 % 1: condition on ms shocks; 0: disable this and "fidcnderr.m" gives - % unconditional forecasts if nconstr = 0 as well; <<>> +% unconditional forecasts if nconstr = 0 as well; <<>> %options_.ms.ncms = 0; % number of the stance of policy; 0 if no tightening or loosening %options_.ms.eq_cms = 1; % location of MS shocks options_.ms.tlindx = 1*ones(1,options_.ms.ncms); % 1-by-options_.ms.ncms vector; 1: tightening; 0: loosen options_.ms.tlnumber = [0.5 0.5 0 0]; %94:4 % [2 2 1.5 1.5]; %79:9 %[1.5 1.5 1 1]; 90:9 - % 1-by-options_.ms.ncms vector; cut-off point for MS shocks + % 1-by-options_.ms.ncms vector; cut-off point for MS shocks TLmean = zeros(1,options_.ms.ncms); - % unconditional, i.e., 0 mean, for the final report in the paper +% unconditional, i.e., 0 mean, for the final report in the paper if options_.ms.cms - options_.ms.eq_ms = []; - % At least at this point, it makes no sense to have DLS type of options_.ms.eq_ms; 10/12/98 - if all(isfinite(options_.ms.tlnumber)) - for k=1:options_.ms.ncms - TLmean(k) = lcnmean(options_.ms.tlnumber(k),options_.ms.tlindx(k)); - % shock mean magnitude. 1: tight; 0: loose - % Never used for any subsequent computation but - % simply used for the final report in the paper. - %options_.ms.tlnumber(k) = fzero('lcutoff',0,[],[],TLmean(k)) - % get an idea about the cutoff point given TLmean instead - - end - end + options_.ms.eq_ms = []; + % At least at this point, it makes no sense to have DLS type of options_.ms.eq_ms; 10/12/98 + if all(isfinite(options_.ms.tlnumber)) + for k=1:options_.ms.ncms + TLmean(k) = lcnmean(options_.ms.tlnumber(k),options_.ms.tlindx(k)); + % shock mean magnitude. 1: tight; 0: loose + % Never used for any subsequent computation but + % simply used for the final report in the paper. + %options_.ms.tlnumber(k) = fzero('lcutoff',0,[],[],TLmean(k)) + % get an idea about the cutoff point given TLmean instead + + end + end else - options_.ms.ncms = 0; % only for the use of the graph by msprobg.m - options_.ms.tlnumber = NaN*ones(1,options_.ms.ncms); - % -infinity, only for the use of the graph by msprobg.m + options_.ms.ncms = 0; % only for the use of the graph by msprobg.m + options_.ms.tlnumber = NaN*ones(1,options_.ms.ncms); + % -infinity, only for the use of the graph by msprobg.m end @@ -135,22 +135,22 @@ end % Soft conditions on variables % %cnum = 0 % # of band condtions; when 0, disable this option - % Note (different from "fidencon") that each condition corres. to variable +% Note (different from "fidencon") that each condition corres. to variable %options_.ms.banact = 1; % 1: use infor on actual; 0: preset without infor on actual if cnum - banindx = cell(cnum,1); % index for each variable or conditon - banstp = cell(cnum,1); % steps: annual in general - banvar = zeros(cnum,1); % varables: annual in general - banval = cell(cnum,1); % band value (each variable occupy a cell) - badval{1} = zeros(length(banstp{1}),2); % 2: lower or higher bound - - banstp{1} = 1:4; % 3 or 4 years - banvar(1) = 3; % 3: FFR; 5: CPI - if ~options_.ms.banact - for i=1:length(banstp{1}) - banval{1}(i,:) = [5.0 10.0]; - end - end + banindx = cell(cnum,1); % index for each variable or conditon + banstp = cell(cnum,1); % steps: annual in general + banvar = zeros(cnum,1); % varables: annual in general + banval = cell(cnum,1); % band value (each variable occupy a cell) + badval{1} = zeros(length(banstp{1}),2); % 2: lower or higher bound + + banstp{1} = 1:4; % 3 or 4 years + banvar(1) = 3; % 3: FFR; 5: CPI + if ~options_.ms.banact + for i=1:length(banstp{1}) + banval{1}(i,:) = [5.0 10.0]; + end + end end % pause(1) @@ -171,60 +171,60 @@ pause(1) %(1)-------------------------------------- % if (options_.ms.freq==12) - nStart=(yrStart-options_.ms.initial_year )*12+qmStart-options_.ms.initial_subperiod ; % positive number of months at the start - nEnd=(yrEnd-options_.ms.final_year )*12+qmEnd-options_.ms.final_subperiod ; % negative number of months towards end + nStart=(yrStart-options_.ms.initial_year )*12+qmStart-options_.ms.initial_subperiod ; % positive number of months at the start + nEnd=(yrEnd-options_.ms.final_year )*12+qmEnd-options_.ms.final_subperiod ; % negative number of months towards end elseif (options_.ms.freq==4) - nStart=(yrStart-options_.ms.initial_year )*4+qmStart-options_.ms.initial_subperiod ; % positive number of months at the start - nEnd=(yrEnd-options_.ms.final_year )*4+qmEnd-options_.ms.final_subperiod ; % negative number of months towards end + nStart=(yrStart-options_.ms.initial_year )*4+qmStart-options_.ms.initial_subperiod ; % positive number of months at the start + nEnd=(yrEnd-options_.ms.final_year )*4+qmEnd-options_.ms.final_subperiod ; % negative number of months towards end elseif (options_.ms.freq==1) - nStart=(yrStart-options_.ms.initial_year )*1+qmStart-options_.ms.initial_subperiod ; % positive number of months at the start - nEnd=(yrEnd-options_.ms.final_year )*1+qmEnd-options_.ms.final_subperiod ; % negative number of months towards end + nStart=(yrStart-options_.ms.initial_year )*1+qmStart-options_.ms.initial_subperiod ; % positive number of months at the start + nEnd=(yrEnd-options_.ms.final_year )*1+qmEnd-options_.ms.final_subperiod ; % negative number of months towards end else - error('Error: this code is only good for monthly/quarterly/yearly data!!!') - return + error('Error: this code is only good for monthly/quarterly/yearly data!!!') + return end % if nEnd>0 || nStart<0 - disp('Warning: this particular sample consider is out of bounds of the data!!!') - return + disp('Warning: this particular sample consider is out of bounds of the data!!!') + return end %*** Note, both xdgel and xdata have the same start with the specific sample xdgel=options_.data(nStart+1:nData+nEnd,options_.ms.vlist); - % gel: general options_.data within sample (nSample) +% gel: general options_.data within sample (nSample) if ~(nSample==size(xdgel,1)) - warning('The sample size (including options_.ms.nlags ) and data are incompatible') - disp('Check to make sure nSample and size(xdgel,1) are the same') - return + warning('The sample size (including options_.ms.nlags ) and data are incompatible') + disp('Check to make sure nSample and size(xdgel,1) are the same') + return end % baddata = find(isnan(xdgel)); if ~isempty(baddata) - warning('Some data for this selected sample are actually unavailable.') - disp('Hit any key to continue, or ctrl-c to abort') - pause + warning('Some data for this selected sample are actually unavailable.') + disp('Hit any key to continue, or ctrl-c to abort') + pause end % if options_.ms.initial_subperiod ==1 - yrB = options_.ms.initial_year ; qmB = options_.ms.initial_subperiod ; + yrB = options_.ms.initial_year ; qmB = options_.ms.initial_subperiod ; else - yrB = options_.ms.initial_year +1; qmB = 1; + yrB = options_.ms.initial_year +1; qmB = 1; end yrF = options_.ms.final_year ; qmF = options_.ms.final_subperiod ; [Mdate,tmp] = fn_calyrqm(options_.ms.freq,[options_.ms.initial_year options_.ms.initial_subperiod ],[options_.ms.final_year options_.ms.final_subperiod ]); xdatae=[Mdate options_.data(1:nData,options_.ms.vlist)]; - % beyond sample into forecast horizon until the end of the data options_.ms.final_year :options_.ms.final_subperiod - % Note: may contain NaN data. So must be careful about its use +% beyond sample into forecast horizon until the end of the data options_.ms.final_year :options_.ms.final_subperiod +% Note: may contain NaN data. So must be careful about its use %=========== Obtain prior-period, period-to-last period, and annual growth rates [yactyrge,yactyre,yactqmyge,yactqmge,yactqme] = fn_datana(xdatae,options_.ms.freq,options_.ms.log_var,options_.ms.percent_var,[yrB qmB],[yrF qmF]); qdates = zeros(size(yactqmyge,1),1); for ki=1:length(qdates) - qdates(ki) = yactqmyge(1,1) + (yactqmyge(1,2)+ki-2)/options_.ms.freq; + qdates(ki) = yactqmyge(1,1) + (yactqmyge(1,2)+ki-2)/options_.ms.freq; end for ki=1:nvar - figure - plot(qdates, yactqmyge(:,2+ki)/100) - xlabel(options_.ms.varlist{ki}) + figure + plot(qdates, yactqmyge(:,2+ki)/100) + xlabel(options_.ms.varlist{ki}) end save outactqmygdata.prn yactqmyge -ascii @@ -236,11 +236,11 @@ spstr1 = 'disp([sprintf('; spstr2 = '%4.0f %2.0f'; yactyrget=yactyrge'; for ki=1:length(options_.ms.vlist) - if ki==length(options_.ms.vlist) - spstr2 = [spstr2 ' %8.3f\n']; - else - spstr2 = [spstr2 ' %8.3f']; - end + if ki==length(options_.ms.vlist) + spstr2 = [spstr2 ' %8.3f\n']; + else + spstr2 = [spstr2 ' %8.3f']; + end end spstr = [spstr1 'spstr2' ', yactyrget)])']; eval(spstr) @@ -251,11 +251,11 @@ fid = fopen('outyrqm.prn','w'); fpstr1 = 'fprintf(fid,'; fpstr2 = '%4.0f %2.0f'; for ki=1:nvar - if ki==nvar - fpstr2 = [fpstr2 ' %8.3f\n']; - else - fpstr2 = [fpstr2 ' %8.3f']; - end + if ki==nvar + fpstr2 = [fpstr2 ' %8.3f\n']; + else + fpstr2 = [fpstr2 ' %8.3f']; + end end fpstr = [fpstr1 'fpstr2' ', yactyrget);']; eval(fpstr) @@ -264,479 +264,479 @@ fclose(fid); if options_.ms.indxestima - %(2)---------------------------------------------------------------------------- - % Estimation - % ML forecast and impulse responses - % Hard or soft conditions for conditional forecasts - %(2)---------------------------------------------------------------------------- - % - %* Arranged data information, WITHOUT dummy obs when 0 after mu is used. See fn_rnrprior_covres_dobs.m for using the dummy - % observations as part of an explicit prior. - [xtx,xty,yty,fss,phi,y,ncoef,xr,Bh] = fn_dataxy(nvar,options_.ms.nlags ,xdgel,mu,0,nexo); - if qmStart+options_.ms.nlags -options_.ms.dummy_obs >0 - qmStartEsti = rem(qmStart+options_.ms.nlags -options_.ms.dummy_obs ,options_.ms.freq); % dummy observations are included in the sample. - if (~qmStartEsti) - qmStartEsti = options_.ms.freq; - end - yrStartEsti = yrStart + floor((qmStart+options_.ms.nlags -options_.ms.dummy_obs )/(options_.ms.freq+0.01)); + %(2)---------------------------------------------------------------------------- + % Estimation + % ML forecast and impulse responses + % Hard or soft conditions for conditional forecasts + %(2)---------------------------------------------------------------------------- + % + %* Arranged data information, WITHOUT dummy obs when 0 after mu is used. See fn_rnrprior_covres_dobs.m for using the dummy + % observations as part of an explicit prior. + [xtx,xty,yty,fss,phi,y,ncoef,xr,Bh] = fn_dataxy(nvar,options_.ms.nlags ,xdgel,mu,0,nexo); + if qmStart+options_.ms.nlags -options_.ms.dummy_obs >0 + qmStartEsti = rem(qmStart+options_.ms.nlags -options_.ms.dummy_obs ,options_.ms.freq); % dummy observations are included in the sample. + if (~qmStartEsti) + qmStartEsti = options_.ms.freq; + end + yrStartEsti = yrStart + floor((qmStart+options_.ms.nlags -options_.ms.dummy_obs )/(options_.ms.freq+0.01)); % + 0.01 (or any number < 1) is used so that qmStart+options_.ms.nlags -options_.ms.dummy_obs ==?*options_.ms.freq doesn't give us an extra year forward. - else - qmStartEsti = options_.ms.freq + rem(qmStart+options_.ms.nlags -options_.ms.dummy_obs ,options_.ms.freq); % dummy observations are included in the sample. - if (qmStart+options_.ms.nlags -options_.ms.dummy_obs ==0) - yrStartEsti = yrStart - 1; % one year back. - else - yrStartEsti = yrStart + floor((qmStart+options_.ms.nlags -options_.ms.dummy_obs )/(options_.ms.freq-0.01)); - % - 0.01 (or any number < 1) is used so that qmStart+options_.ms.nlags -options_.ms.dummy_obs ==-?*options_.ms.freq give us an extra year back. - end - end - dateswd = fn_dataext([yrStartEsti qmStartEsti],[yrEnd qmEnd],xdatae(:,[1:2])); % dates with dummies - phie = [dateswd phi]; - ye = [dateswd y]; - - %* Obtain linear restrictions - [Uiconst,Viconst,n0,np,ixmC0Pres] = feval(options_.ms.restriction_fname,nvar,nexo,options_.ms ); - if min(n0)==0 - skipline() - warning('A0: restrictions in dlrprior.m give no free parameter in one of equations') - disp('Press ctrl-c to abort') - pause - elseif min(np)==0 - skipline() - warning('Ap: Restrictions in dlrprior.m give no free parameter in one of equations') - disp('Press ctrl-c to abort') - pause - end - - if options_.ms.contemp_reduced_form - Uiconst=cell(nvar,1); Viconst=cell(ncoef,1); - for kj=1:nvar - Uiconst{kj} = eye(nvar); Viconst{kj} = eye(ncoef); - end - end - - if options_.ms.bayesian_prior - %*** Obtains asymmetric prior (with no linear restrictions) with dummy observations as part of an explicit prior (i.e, - % reflected in Hpmulti and Hpinvmulti). See Forecast II, pp.69a-69b for details. - if 1 % Liquidity effect prior on both MS and MD equations. - [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] = fn_rnrprior_covres_dobs(nvar,options_.ms.freq,options_.ms.nlags ,xdgel,mu,indxDummy,hpmsmd,indxmsmdeqn); - else - [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] = fn_rnrprior(nvar,options_.ms.freq,options_.ms.nlags ,xdgel,mu); - end - - %*** Combines asymmetric prior with linear restrictions - [Ptld,H0invtld,Hpinvtld] = fn_rlrprior(Uiconst,Viconst,Pi,H0multi,Hpmulti,nvar); - - %*** Obtains the posterior matrices for estimation and inference - [Pmat,H0inv,Hpinv] = fn_rlrpostr(xtx,xty,yty,Ptld,H0invtld,Hpinvtld,Uiconst,Viconst); - - if options_.ms.contemp_reduced_form - %*** Obtain the ML estimate - A0hatinv = chol(H0inv{1}/fss); % upper triangular but lower triangular choleski - A0hat=inv(A0hatinv); - a0indx = find(A0hat); - else - %*** Obtain the ML estimate - % load idenml - x = 10*rand(sum(n0),1); - H0 = eye(sum(n0)); - crit = 1.0e-9; - nit = 10000; - % - [fhat,xhat,grad,Hhat,itct,fcount,retcodehat] = ... - csminwel('fn_a0freefun',x,H0,'fn_a0freegrad',crit,nit,Uiconst,nvar,n0,fss,H0inv); - - A0hat = fn_tran_b2a(xhat,Uiconst,nvar,n0) - A0hatinv = inv(A0hat); - fhat - xhat - grad - itct - fcount - retcodehat - save outm.mat xhat A0hat A0hatinv grad fhat itct itct fcount retcodehat - end - else - %*** Obtain the posterior matrices for estimation and inference - [Pmat,H0inv,Hpinv] = fn_dlrpostr(xtx,xty,yty,Uiconst,Viconst); - - if options_.ms.contemp_reduced_form - %*** Obtain the ML estimate - A0hatinv = chol(H0inv{1}/fss); % upper triangular but lower triangular choleski - A0hat=inv(A0hatinv); - a0indx = find(A0hat); - else - %*** Obtain the ML estimate - % load idenml - x = 10*rand(sum(n0),1); - H0 = eye(sum(n0)); - crit = 1.0e-9; - nit = 10000; - % - [fhat,xhat,grad,Hhat,itct,fcount,retcodehat] = ... - csminwel('fn_a0freefun',x,H0,'fn_a0freegrad',crit,nit,Uiconst,nvar,n0,fss,H0inv); - - A0hat = fn_tran_b2a(xhat,Uiconst,nvar,n0) - A0hatinv = inv(A0hat); - fhat - xhat - grad - itct - fcount - retcodehat - save outm.mat xhat A0hat A0hatinv grad fhat itct itct fcount retcodehat - end - end - - %**** impulse responses - swish = A0hatinv; % each column corresponds to an equation - if options_.ms.contemp_reduced_form - xhat = A0hat(a0indx); - Bhat=Pmat{1}; - Fhat = Bhat*A0hat - ghat = NaN; - else - xhat = fn_tran_a2b(A0hat,Uiconst,nvar,n0); - [Fhat,ghat] = fn_gfmean(xhat,Pmat,Viconst,nvar,ncoef,n0,np); - if options_.ms.cross_restrictions - Fhatur0P = Fhat; % ur: unrestriced across A0 and A+ - for ki = 1:size(ixmC0Pres,1) % loop through the number of equations in which - % cross-A0-A+ restrictions occur. See St. Louis Note p.5. - ixeq = ixmC0Pres{ki}(1,1); % index for the jth equation in consideration. - Lit = Viconst{ixeq}(ixmC0Pres{ki}(:,2),:); % transposed restriction matrix Li - % V_j(i,:) in f_j(i) = V_j(i,:)*g_j - ci = ixmC0Pres{ki}(:,4) .* A0hat(ixmC0Pres{ki}(:,3),ixeq); - % s * a_j(h) in the restriction f_j(i) = s * a_j(h). - LtH = Lit/Hpinv{ixeq}; - HLV = LtH'/(LtH*Lit'); - gihat = Viconst{ixeq}'*Fhatur0P(:,ixeq); - Fhat(:,ixeq) = Viconst{ixeq}*(gihat + HLV*(ci-Lit*gihat)); - end - end - Fhat - Bhat = Fhat/A0hat; % ncoef-by-nvar reduced form lagged parameters. - end - nn = [nvar options_.ms.nlags imstp]; - imfhat = fn_impulse(Bhat,swish,nn); % in the form that is congenial to RATS - imf3hat=reshape(imfhat,size(imfhat,1),nvar,nvar); - % imf3: row--steps, column--nvar responses, 3rd dimension--nvar shocks - imf3shat=permute(imf3hat,[1 3 2]); - % imf3s: permuted so that row--steps, column--nvar shocks, - % 3rd dimension--nvar responses - % Note: reshape(imf3s(1,:,:),nvar,nvar) = A0in (columns -- equations) - if options_.ms.indxgimfhat - figure - end - scaleout = fn_imcgraph(imfhat,nvar,imstp,xlab,ylab,options_.ms.indxgimfhat); - imfstd = max(abs(scaleout)'); % row: nvar (largest number); used for standard deviations - - % - % %**** save stds. of both data and impulse responses in idfile1 - % temp = [std(yactqmyge(:,3:end)); std(yactyrge(:,3:end)); imfstd]; %<<>> - % save idenyimstd.prn temp -ascii % export forecast and impulse response to the file "idenyimstd.prn", 3-by-nvar - % % - % %**** save stds. of both data and impulse responses in idfile1 - % temp = [std(yactqmyge(:,3:end)); std(yactyrge(:,3:end)); imfstd]; %<<>> - % save idenyimstd.prn temp -ascii % export forecast and impulse response to the file "idenyimstd.prn", 3-by-nvar - % if options_.ms.indxparr - % idfile1='idenyimstd'; - % end - - %===================================== - % Now, out-of-sample forecasts. Note: Hm1t does not change with A0. - %===================================== - % - % * updating the last row of X (phi) with the current (last row of) y. - tcwx = nvar*options_.ms.nlags ; % total coefficeint without exogenous variables - phil = phi(size(phi,1),:); - phil(nvar+1:tcwx) = phil(1:tcwx-nvar); - phil(1:nvar) = y(end,:); - %*** exogenous variables excluding constant terms - if (nexo>1) - Xexoe = fn_dataext([yrEnd qmEnd],[yrEnd qmEnd],xdatae(:,[1:2 2+nvar+1:2+nvar+nexo-1])); - phil(1,tcwx+1:tcwx+nexo-1) = Xexoe(1,3:end); - end - % - %*** ML unconditional point forecast - nn = [nvar options_.ms.nlags nfqm]; - if nexo<2 - yforehat = fn_forecast(Bhat,phil,nn); % nfqm-by-nvar, in log - else - Xfexoe = fn_dataext(fdates(1,:),fdates(numel(fdates),:),xdatae(:,[1:2 2+nvar+1:2+nvar+nexo-1])); - %Xfexoe = fn_dataext(fdates(1,:),fdates(end,:),xdatae(:,[1:2 2+nvar+1:2+nvar+nexo-1])); - yforehat = fn_forecast(Bhat,phil,nn,nexo,Xfexoe(:,3:end)); % nfqm-by-nvar, in log - end - yforehate = [fdates yforehat]; - % - yact1e = fn_dataext([yrEnd-nayr 1],[yrEnd qmEnd],xdatae(:,1:nvar+2)); - if options_.ms.real_pseudo_forecast - %yact2e = fn_dataext([yrEnd-nayr 1],E2yrqm,xdatae); - yact2e = fn_dataext([yrEnd-nayr 1],[fdates(end,1) options_.ms.freq],xdatae(:,1:nvar+2)); - else - yact2e=yact1e; - end - yafhate = [yact1e; yforehate]; % actual and forecast - % - %===== Converted to mg, qg, and calendar yg - % - [yafyrghate,yafyrhate,yafqmyghate] = fn_datana(yafhate,options_.ms.freq,options_.ms.log_var(1:nlogeno),options_.ms.percent_var(1:npereno)); - % actual and forecast growth rates - [yact2yrge,yact2yre,yact2qmyge] = fn_datana(yact2e,options_.ms.freq,options_.ms.log_var(1:nlogeno),options_.ms.percent_var(1:npereno)); - % only actual growth rates - yafyrghate - if options_.ms.indxgforhat - keyindx = [1:nvar]; - conlab=['unconditional']; - - figure - yafyrghate(:,3:end) = yafyrghate(:,3:end)/100; - yact2yrge(:,3:end) = yact2yrge(:,3:end)/100; - fn_foregraph(yafyrghate,yact2yrge,keyindx,rnum,cnum,options_.ms.freq,ylab,forelabel,conlab) - end - - %------------------------------------------------- - % Setup for point conditional forecast - % ML Conditional Forecast - %------------------------------------------------- - % - %% See Zha's note "Forecast (1)" p. 5, RATS manual (some errors in RATS), etc. - % - %% Some notations: y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n. - %% Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse - %% response at t=1, C at t=2, etc. The row of inv(A0) or C is - %% all responses to one shock. - %% Let r be q-by-1 (such as r(1) = r(t+1) - %% = y(t+1) (constrained) - y(t+1) (forecast)). - %% Use impulse responses to find out R (k-by-q) where k=nvar*nsteps - %% where nsteps the largest constrained step. The key of the program - %% is to creat R using impulse responses - %% Optimal solution for shock e where R'*e=r and e is k-by-1 is - %% e = R*inv(R'*R)*r. - % - - if (nconstr > 0) - %*** initializing - stepcon=cell(nconstr,1); % initializing, value y conditioned - valuecon=zeros(nconstr,1); % initializing, value y conditioned - varcon=zeros(nconstr,1); % initializing, endogous variables conditioned - varcon(:)=PorR; % 1: Pcm; 3: FFR; 5: CPI - - % - for i=1:nconstr - if i<=nconstr1 - stepcon{i}=i; % FFR - elseif i<=2*nconstr1 - stepcon{i}=i-nconstr1; % FFR - elseif i<=3*nconstr1 - stepcon{i}=i-2*nconstr1; % FFR - elseif i<=4*nconstr1 - stepcon{i}=i-3*nconstr1; % FFR - elseif i<=5*nconstr1 - stepcon{i}=i-4*nconstr1; % FFR - elseif i<=6*nconstr1 - stepcon{i}=i-5*nconstr1; % FFR - end - end - -% for i=1:nconstr -% stepcon{i}=i; % FFR -% end - -% bend=12; -% stepcon{1}=[1:bend]'; % average over -% stepcon{nconstr1+1}=[1:options_.ms.freq-qmSub]'; % average over the remaing months in 1st forecast year -% stepcon{nconstr1+2}=[options_.ms.freq-qmSub+1:options_.ms.freq-qmSub+12]'; % average over 12 months next year -% stepcon{nconstr1+3}=[options_.ms.freq-qmSub+13:options_.ms.freq-qmSub+24]'; % average over 12 months. 3rd year -% stepcon{nconstr1+4}=[options_.ms.freq-qmSub+25:options_.ms.freq-qmSub+36]'; % average over 12 months. 4th year - -% %**** avearage condition over, say, options_.ms.freq periods -% if qmEnd==options_.ms.freq -% stepcon{1}=[1:options_.ms.freq]'; % average over the remaing periods in 1st forecast year -% else -% stepcon{1}=[1:options_.ms.freq-qmEnd]'; % average over the remaing periods in 1st forecast year -% end -% for kj=2:nconstr -% stepcon{kj}=[length(stepcon{kj-1})+1:length(stepcon{kj-1})+options_.ms.freq]'; % average over 12 months next year -% end - - if options_.ms.real_pseudo_forecast -% %*** conditions in every period -% for i=1:nconstr -% valuecon(i) = yact(actup+i,varcon(i)); -% %valuecon(i) = mean( yact(actup+1:actup+bend,varcon(i)) ); -% %valuecon(i) = 0.060; % 95:01 -% %valuecon(i) = (0.0475+0.055)/2; % 94:10 -% end - -% %*** average condtions over,say, options_.ms.freq periods. -% for i=nconstr1+1:nconstr1+nconstr2 -% i=1; -% valuecon(nconstr1+i) = ( ( mean(ylast12Cal(:,varcon(nconstr1+i)),1) + ... -% log(1+yactCalyg(yAg-yFg+i,varcon(nconstr1+i))/100) )*options_.ms.freq - ... -% yCal_1(:,varcon(nconstr1+i)) ) ./ length(stepcon{nconstr1+i}); -% % the same as unconditional "yactCalyg" 1st calendar year -% i=2; -% valuecon(nconstr1+i) = mean(ylast12Cal(:,varcon(nconstr1+i))) + ... -% log(1+yactCalyg(yAg-yFg+1,varcon(nconstr1+i))/100) ... -% + log(1+yactCalyg(yAg-yFg+i,varcon(nconstr1+i))/100); -% % the same as actual "yactCalgy" 2nd calendar year -% i=3; -% valuecon(nconstr1+i) = valuecon(nconstr1+i-1) + ... -% log(1+yactCalyg(yAg-yFg+i,varcon(nconstr1+i))/100); -% % the same as actual "yactCalgy" 3rd calendar year -% %i=4; -% %valuecon(nconstr1+i) = valuecon(nconstr1+i-1) + ... -% % log(1+yactCalyg(yAg-yFg+i,varcon(nconstr1+i))/100); -% % the same as actual "yactCalgy" 4th calendar year -% end - - %*** conditions in every period - vpntM = fn_dataext(E1yrqm, E2yrqm,xdatae); % point value matrix with dates - % vaveM = fn_dataext([yrEnd+1 0],[yrEnd+options_.forecast 0],yact2yre); % average value matrix with dates - for i=1:nconstr + else + qmStartEsti = options_.ms.freq + rem(qmStart+options_.ms.nlags -options_.ms.dummy_obs ,options_.ms.freq); % dummy observations are included in the sample. + if (qmStart+options_.ms.nlags -options_.ms.dummy_obs ==0) + yrStartEsti = yrStart - 1; % one year back. + else + yrStartEsti = yrStart + floor((qmStart+options_.ms.nlags -options_.ms.dummy_obs )/(options_.ms.freq-0.01)); + % - 0.01 (or any number < 1) is used so that qmStart+options_.ms.nlags -options_.ms.dummy_obs ==-?*options_.ms.freq give us an extra year back. + end + end + dateswd = fn_dataext([yrStartEsti qmStartEsti],[yrEnd qmEnd],xdatae(:,[1:2])); % dates with dummies + phie = [dateswd phi]; + ye = [dateswd y]; + + %* Obtain linear restrictions + [Uiconst,Viconst,n0,np,ixmC0Pres] = feval(options_.ms.restriction_fname,nvar,nexo,options_.ms ); + if min(n0)==0 + skipline() + warning('A0: restrictions in dlrprior.m give no free parameter in one of equations') + disp('Press ctrl-c to abort') + pause + elseif min(np)==0 + skipline() + warning('Ap: Restrictions in dlrprior.m give no free parameter in one of equations') + disp('Press ctrl-c to abort') + pause + end + + if options_.ms.contemp_reduced_form + Uiconst=cell(nvar,1); Viconst=cell(ncoef,1); + for kj=1:nvar + Uiconst{kj} = eye(nvar); Viconst{kj} = eye(ncoef); + end + end + + if options_.ms.bayesian_prior + %*** Obtains asymmetric prior (with no linear restrictions) with dummy observations as part of an explicit prior (i.e, + % reflected in Hpmulti and Hpinvmulti). See Forecast II, pp.69a-69b for details. + if 1 % Liquidity effect prior on both MS and MD equations. + [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] = fn_rnrprior_covres_dobs(nvar,options_.ms.freq,options_.ms.nlags ,xdgel,mu,indxDummy,hpmsmd,indxmsmdeqn); + else + [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] = fn_rnrprior(nvar,options_.ms.freq,options_.ms.nlags ,xdgel,mu); + end + + %*** Combines asymmetric prior with linear restrictions + [Ptld,H0invtld,Hpinvtld] = fn_rlrprior(Uiconst,Viconst,Pi,H0multi,Hpmulti,nvar); + + %*** Obtains the posterior matrices for estimation and inference + [Pmat,H0inv,Hpinv] = fn_rlrpostr(xtx,xty,yty,Ptld,H0invtld,Hpinvtld,Uiconst,Viconst); + + if options_.ms.contemp_reduced_form + %*** Obtain the ML estimate + A0hatinv = chol(H0inv{1}/fss); % upper triangular but lower triangular choleski + A0hat=inv(A0hatinv); + a0indx = find(A0hat); + else + %*** Obtain the ML estimate + % load idenml + x = 10*rand(sum(n0),1); + H0 = eye(sum(n0)); + crit = 1.0e-9; + nit = 10000; + % + [fhat,xhat,grad,Hhat,itct,fcount,retcodehat] = ... + csminwel('fn_a0freefun',x,H0,'fn_a0freegrad',crit,nit,Uiconst,nvar,n0,fss,H0inv); + + A0hat = fn_tran_b2a(xhat,Uiconst,nvar,n0) + A0hatinv = inv(A0hat); + fhat + xhat + grad + itct + fcount + retcodehat + save outm.mat xhat A0hat A0hatinv grad fhat itct itct fcount retcodehat + end + else + %*** Obtain the posterior matrices for estimation and inference + [Pmat,H0inv,Hpinv] = fn_dlrpostr(xtx,xty,yty,Uiconst,Viconst); + + if options_.ms.contemp_reduced_form + %*** Obtain the ML estimate + A0hatinv = chol(H0inv{1}/fss); % upper triangular but lower triangular choleski + A0hat=inv(A0hatinv); + a0indx = find(A0hat); + else + %*** Obtain the ML estimate + % load idenml + x = 10*rand(sum(n0),1); + H0 = eye(sum(n0)); + crit = 1.0e-9; + nit = 10000; + % + [fhat,xhat,grad,Hhat,itct,fcount,retcodehat] = ... + csminwel('fn_a0freefun',x,H0,'fn_a0freegrad',crit,nit,Uiconst,nvar,n0,fss,H0inv); + + A0hat = fn_tran_b2a(xhat,Uiconst,nvar,n0) + A0hatinv = inv(A0hat); + fhat + xhat + grad + itct + fcount + retcodehat + save outm.mat xhat A0hat A0hatinv grad fhat itct itct fcount retcodehat + end + end + + %**** impulse responses + swish = A0hatinv; % each column corresponds to an equation + if options_.ms.contemp_reduced_form + xhat = A0hat(a0indx); + Bhat=Pmat{1}; + Fhat = Bhat*A0hat + ghat = NaN; + else + xhat = fn_tran_a2b(A0hat,Uiconst,nvar,n0); + [Fhat,ghat] = fn_gfmean(xhat,Pmat,Viconst,nvar,ncoef,n0,np); + if options_.ms.cross_restrictions + Fhatur0P = Fhat; % ur: unrestriced across A0 and A+ + for ki = 1:size(ixmC0Pres,1) % loop through the number of equations in which + % cross-A0-A+ restrictions occur. See St. Louis Note p.5. + ixeq = ixmC0Pres{ki}(1,1); % index for the jth equation in consideration. + Lit = Viconst{ixeq}(ixmC0Pres{ki}(:,2),:); % transposed restriction matrix Li + % V_j(i,:) in f_j(i) = V_j(i,:)*g_j + ci = ixmC0Pres{ki}(:,4) .* A0hat(ixmC0Pres{ki}(:,3),ixeq); + % s * a_j(h) in the restriction f_j(i) = s * a_j(h). + LtH = Lit/Hpinv{ixeq}; + HLV = LtH'/(LtH*Lit'); + gihat = Viconst{ixeq}'*Fhatur0P(:,ixeq); + Fhat(:,ixeq) = Viconst{ixeq}*(gihat + HLV*(ci-Lit*gihat)); + end + end + Fhat + Bhat = Fhat/A0hat; % ncoef-by-nvar reduced form lagged parameters. + end + nn = [nvar options_.ms.nlags imstp]; + imfhat = fn_impulse(Bhat,swish,nn); % in the form that is congenial to RATS + imf3hat=reshape(imfhat,size(imfhat,1),nvar,nvar); + % imf3: row--steps, column--nvar responses, 3rd dimension--nvar shocks + imf3shat=permute(imf3hat,[1 3 2]); + % imf3s: permuted so that row--steps, column--nvar shocks, + % 3rd dimension--nvar responses + % Note: reshape(imf3s(1,:,:),nvar,nvar) = A0in (columns -- equations) + if options_.ms.indxgimfhat + figure + end + scaleout = fn_imcgraph(imfhat,nvar,imstp,xlab,ylab,options_.ms.indxgimfhat); + imfstd = max(abs(scaleout)'); % row: nvar (largest number); used for standard deviations + + % + % %**** save stds. of both data and impulse responses in idfile1 + % temp = [std(yactqmyge(:,3:end)); std(yactyrge(:,3:end)); imfstd]; %<<>> + % save idenyimstd.prn temp -ascii % export forecast and impulse response to the file "idenyimstd.prn", 3-by-nvar + % % + % %**** save stds. of both data and impulse responses in idfile1 + % temp = [std(yactqmyge(:,3:end)); std(yactyrge(:,3:end)); imfstd]; %<<>> + % save idenyimstd.prn temp -ascii % export forecast and impulse response to the file "idenyimstd.prn", 3-by-nvar + % if options_.ms.indxparr + % idfile1='idenyimstd'; + % end + + %===================================== + % Now, out-of-sample forecasts. Note: Hm1t does not change with A0. + %===================================== + % + % * updating the last row of X (phi) with the current (last row of) y. + tcwx = nvar*options_.ms.nlags ; % total coefficeint without exogenous variables + phil = phi(size(phi,1),:); + phil(nvar+1:tcwx) = phil(1:tcwx-nvar); + phil(1:nvar) = y(end,:); + %*** exogenous variables excluding constant terms + if (nexo>1) + Xexoe = fn_dataext([yrEnd qmEnd],[yrEnd qmEnd],xdatae(:,[1:2 2+nvar+1:2+nvar+nexo-1])); + phil(1,tcwx+1:tcwx+nexo-1) = Xexoe(1,3:end); + end + % + %*** ML unconditional point forecast + nn = [nvar options_.ms.nlags nfqm]; + if nexo<2 + yforehat = fn_forecast(Bhat,phil,nn); % nfqm-by-nvar, in log + else + Xfexoe = fn_dataext(fdates(1,:),fdates(numel(fdates),:),xdatae(:,[1:2 2+nvar+1:2+nvar+nexo-1])); + %Xfexoe = fn_dataext(fdates(1,:),fdates(end,:),xdatae(:,[1:2 2+nvar+1:2+nvar+nexo-1])); + yforehat = fn_forecast(Bhat,phil,nn,nexo,Xfexoe(:,3:end)); % nfqm-by-nvar, in log + end + yforehate = [fdates yforehat]; + % + yact1e = fn_dataext([yrEnd-nayr 1],[yrEnd qmEnd],xdatae(:,1:nvar+2)); + if options_.ms.real_pseudo_forecast + %yact2e = fn_dataext([yrEnd-nayr 1],E2yrqm,xdatae); + yact2e = fn_dataext([yrEnd-nayr 1],[fdates(end,1) options_.ms.freq],xdatae(:,1:nvar+2)); + else + yact2e=yact1e; + end + yafhate = [yact1e; yforehate]; % actual and forecast + % + %===== Converted to mg, qg, and calendar yg + % + [yafyrghate,yafyrhate,yafqmyghate] = fn_datana(yafhate,options_.ms.freq,options_.ms.log_var(1:nlogeno),options_.ms.percent_var(1:npereno)); + % actual and forecast growth rates + [yact2yrge,yact2yre,yact2qmyge] = fn_datana(yact2e,options_.ms.freq,options_.ms.log_var(1:nlogeno),options_.ms.percent_var(1:npereno)); + % only actual growth rates + yafyrghate + if options_.ms.indxgforhat + keyindx = [1:nvar]; + conlab=['unconditional']; + + figure + yafyrghate(:,3:end) = yafyrghate(:,3:end)/100; + yact2yrge(:,3:end) = yact2yrge(:,3:end)/100; + fn_foregraph(yafyrghate,yact2yrge,keyindx,rnum,cnum,options_.ms.freq,ylab,forelabel,conlab) + end + + %------------------------------------------------- + % Setup for point conditional forecast + % ML Conditional Forecast + %------------------------------------------------- + % + %% See Zha's note "Forecast (1)" p. 5, RATS manual (some errors in RATS), etc. + % + %% Some notations: y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n. + %% Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse + %% response at t=1, C at t=2, etc. The row of inv(A0) or C is + %% all responses to one shock. + %% Let r be q-by-1 (such as r(1) = r(t+1) + %% = y(t+1) (constrained) - y(t+1) (forecast)). + %% Use impulse responses to find out R (k-by-q) where k=nvar*nsteps + %% where nsteps the largest constrained step. The key of the program + %% is to creat R using impulse responses + %% Optimal solution for shock e where R'*e=r and e is k-by-1 is + %% e = R*inv(R'*R)*r. + % + + if (nconstr > 0) + %*** initializing + stepcon=cell(nconstr,1); % initializing, value y conditioned + valuecon=zeros(nconstr,1); % initializing, value y conditioned + varcon=zeros(nconstr,1); % initializing, endogous variables conditioned + varcon(:)=PorR; % 1: Pcm; 3: FFR; 5: CPI + + % + for i=1:nconstr if i<=nconstr1 - valuecon(i) = vpntM(i,2+varcon(i)); % 2: first 2 elements are dates + stepcon{i}=i; % FFR elseif i<=2*nconstr1 - valuecon(i) = vpntM(i-nconstr1,2+varcon(i)); + stepcon{i}=i-nconstr1; % FFR elseif i<=3*nconstr1 - valuecon(i) = vpntM(i-2*nconstr1,2+varcon(i)); + stepcon{i}=i-2*nconstr1; % FFR elseif i<=4*nconstr1 - valuecon(i) = vpntM(i-3*nconstr1,2+varcon(i)); + stepcon{i}=i-3*nconstr1; % FFR elseif i<=5*nconstr1 - valuecon(i) = vpntM(i-4*nconstr1,2+varcon(i)); + stepcon{i}=i-4*nconstr1; % FFR elseif i<=6*nconstr1 - valuecon(i) = vpntM(i-5*nconstr1,2+varcon(i)); + stepcon{i}=i-5*nconstr1; % FFR end - end - -% %*** average condtions over,say, options_.ms.freq periods. -% if qmEnd==options_.ms.freq -% vaveM = fn_dataext([yrEnd+1 0],[yrEnd+options_.forecast 0],yact2yre); % average value matrix with dates -% valuecon(1) = vaveM(1,2+varcon(1)); % 2: first 2 elements are dates -% else -% vaveM = fn_dataext([yrEnd 0],[yrEnd+options_.forecast 0],yact2yre); % average value matrix with dates -% yactrem = fn_dataext([yrEnd qmEnd+1],[yrEnd options_.ms.freq],xdatae); -% valuecon(1) = sum(yactrem(:,2+varcon(1)),1)/length(stepcon{1}); -% % 2: first 2 elements are dates -% end -% for kj=2:nconstr -% valuecon(kj) = vaveM(kj,2+varcon(kj)); % 2: first 2 elements are dates -% end - else - vpntM = dataext([yrEnd qmEnd+1],[yrEnd qmEnd+2],xdatae); % point value matrix with dates - for i=1:nconstr - if i<=nconstr1 - valuecon(i) = vpntM(i,2+varcon(i)); % 2: first 2 elements are dates; Poil - elseif i<=2*nconstr1 - valuecon(i) = vpntM(i-nconstr1,2+varcon(i)); % 2: first 2 elements are dates; M2 - elseif i<=3*nconstr1 - valuecon(i) = vpntM(i-2*nconstr1,2+varcon(i)); % 2: first 2 elements are dates; FFR - elseif i<=4*nconstr1 - valuecon(i) = vpntM(i-3*nconstr1,2+varcon(i)); % 2: first 2 elements are dates; CPI - elseif i<=5*nconstr1 - valuecon(i) = vpntM(i-4*nconstr1,2+varcon(i)); % 2: first 2 elements are dates; U - elseif i<=5*nconstr1+nconstr2 - valuecon(i)=xdata(end,5)+(i-5*nconstr1)*log(1.001)/options_.ms.freq; %CPI - elseif i<=5*nconstr1+2*nconstr2 - valuecon(i)=0.0725; %FFR - else - valuecon(i)=xdata(end,6)+(i-5*nconstr1-2*nconstr2)*0.01/nfqm; %U + end + + % for i=1:nconstr + % stepcon{i}=i; % FFR + % end + + % bend=12; + % stepcon{1}=[1:bend]'; % average over + % stepcon{nconstr1+1}=[1:options_.ms.freq-qmSub]'; % average over the remaing months in 1st forecast year + % stepcon{nconstr1+2}=[options_.ms.freq-qmSub+1:options_.ms.freq-qmSub+12]'; % average over 12 months next year + % stepcon{nconstr1+3}=[options_.ms.freq-qmSub+13:options_.ms.freq-qmSub+24]'; % average over 12 months. 3rd year + % stepcon{nconstr1+4}=[options_.ms.freq-qmSub+25:options_.ms.freq-qmSub+36]'; % average over 12 months. 4th year + + % %**** avearage condition over, say, options_.ms.freq periods + % if qmEnd==options_.ms.freq + % stepcon{1}=[1:options_.ms.freq]'; % average over the remaing periods in 1st forecast year + % else + % stepcon{1}=[1:options_.ms.freq-qmEnd]'; % average over the remaing periods in 1st forecast year + % end + % for kj=2:nconstr + % stepcon{kj}=[length(stepcon{kj-1})+1:length(stepcon{kj-1})+options_.ms.freq]'; % average over 12 months next year + % end + + if options_.ms.real_pseudo_forecast + % %*** conditions in every period + % for i=1:nconstr + % valuecon(i) = yact(actup+i,varcon(i)); + % %valuecon(i) = mean( yact(actup+1:actup+bend,varcon(i)) ); + % %valuecon(i) = 0.060; % 95:01 + % %valuecon(i) = (0.0475+0.055)/2; % 94:10 + % end + + % %*** average condtions over,say, options_.ms.freq periods. + % for i=nconstr1+1:nconstr1+nconstr2 + % i=1; + % valuecon(nconstr1+i) = ( ( mean(ylast12Cal(:,varcon(nconstr1+i)),1) + ... + % log(1+yactCalyg(yAg-yFg+i,varcon(nconstr1+i))/100) )*options_.ms.freq - ... + % yCal_1(:,varcon(nconstr1+i)) ) ./ length(stepcon{nconstr1+i}); + % % the same as unconditional "yactCalyg" 1st calendar year + % i=2; + % valuecon(nconstr1+i) = mean(ylast12Cal(:,varcon(nconstr1+i))) + ... + % log(1+yactCalyg(yAg-yFg+1,varcon(nconstr1+i))/100) ... + % + log(1+yactCalyg(yAg-yFg+i,varcon(nconstr1+i))/100); + % % the same as actual "yactCalgy" 2nd calendar year + % i=3; + % valuecon(nconstr1+i) = valuecon(nconstr1+i-1) + ... + % log(1+yactCalyg(yAg-yFg+i,varcon(nconstr1+i))/100); + % % the same as actual "yactCalgy" 3rd calendar year + % %i=4; + % %valuecon(nconstr1+i) = valuecon(nconstr1+i-1) + ... + % % log(1+yactCalyg(yAg-yFg+i,varcon(nconstr1+i))/100); + % % the same as actual "yactCalgy" 4th calendar year + % end + + %*** conditions in every period + vpntM = fn_dataext(E1yrqm, E2yrqm,xdatae); % point value matrix with dates + % vaveM = fn_dataext([yrEnd+1 0],[yrEnd+options_.forecast 0],yact2yre); % average value matrix with dates + for i=1:nconstr + if i<=nconstr1 + valuecon(i) = vpntM(i,2+varcon(i)); % 2: first 2 elements are dates + elseif i<=2*nconstr1 + valuecon(i) = vpntM(i-nconstr1,2+varcon(i)); + elseif i<=3*nconstr1 + valuecon(i) = vpntM(i-2*nconstr1,2+varcon(i)); + elseif i<=4*nconstr1 + valuecon(i) = vpntM(i-3*nconstr1,2+varcon(i)); + elseif i<=5*nconstr1 + valuecon(i) = vpntM(i-4*nconstr1,2+varcon(i)); + elseif i<=6*nconstr1 + valuecon(i) = vpntM(i-5*nconstr1,2+varcon(i)); + end + end + + % %*** average condtions over,say, options_.ms.freq periods. + % if qmEnd==options_.ms.freq + % vaveM = fn_dataext([yrEnd+1 0],[yrEnd+options_.forecast 0],yact2yre); % average value matrix with dates + % valuecon(1) = vaveM(1,2+varcon(1)); % 2: first 2 elements are dates + % else + % vaveM = fn_dataext([yrEnd 0],[yrEnd+options_.forecast 0],yact2yre); % average value matrix with dates + % yactrem = fn_dataext([yrEnd qmEnd+1],[yrEnd options_.ms.freq],xdatae); + % valuecon(1) = sum(yactrem(:,2+varcon(1)),1)/length(stepcon{1}); + % % 2: first 2 elements are dates + % end + % for kj=2:nconstr + % valuecon(kj) = vaveM(kj,2+varcon(kj)); % 2: first 2 elements are dates + % end + else + vpntM = dataext([yrEnd qmEnd+1],[yrEnd qmEnd+2],xdatae); % point value matrix with dates + for i=1:nconstr + if i<=nconstr1 + valuecon(i) = vpntM(i,2+varcon(i)); % 2: first 2 elements are dates; Poil + elseif i<=2*nconstr1 + valuecon(i) = vpntM(i-nconstr1,2+varcon(i)); % 2: first 2 elements are dates; M2 + elseif i<=3*nconstr1 + valuecon(i) = vpntM(i-2*nconstr1,2+varcon(i)); % 2: first 2 elements are dates; FFR + elseif i<=4*nconstr1 + valuecon(i) = vpntM(i-3*nconstr1,2+varcon(i)); % 2: first 2 elements are dates; CPI + elseif i<=5*nconstr1 + valuecon(i) = vpntM(i-4*nconstr1,2+varcon(i)); % 2: first 2 elements are dates; U + elseif i<=5*nconstr1+nconstr2 + valuecon(i)=xdata(end,5)+(i-5*nconstr1)*log(1.001)/options_.ms.freq; %CPI + elseif i<=5*nconstr1+2*nconstr2 + valuecon(i)=0.0725; %FFR + else + valuecon(i)=xdata(end,6)+(i-5*nconstr1-2*nconstr2)*0.01/nfqm; %U + end + end + %valuecon(i) = 0.060; % 95:01 + end + else + valuecon = []; + stepcon = []; + varcon = []; + end + + nstepsm = 0; % initializing, the maximum step in all constraints + for i=1:nconstr + nstepsm = max([nstepsm max(stepcon{i})]); + end + + if cnum + if options_.ms.real_pseudo_forecast && options_.ms.banact + for i=1:length(banstp{1}) + banval{1}(1:length(banstp{1}),1) = ... + yactCalyg(yAg-yFg+1:yAg-yFg+length(banstp{1}),banvar(1)) - 2; + banval{1}(1:length(banstp{1}),2) = ... + yactCalyg(yAg-yFg+1:yAg-yFg+length(banstp{1}),banvar(1)) + 2; end - end - %valuecon(i) = 0.060; % 95:01 - end - else - valuecon = []; - stepcon = []; - varcon = []; - end - - nstepsm = 0; % initializing, the maximum step in all constraints - for i=1:nconstr - nstepsm = max([nstepsm max(stepcon{i})]); - end - - if cnum - if options_.ms.real_pseudo_forecast && options_.ms.banact - for i=1:length(banstp{1}) - banval{1}(1:length(banstp{1}),1) = ... - yactCalyg(yAg-yFg+1:yAg-yFg+length(banstp{1}),banvar(1)) - 2; - banval{1}(1:length(banstp{1}),2) = ... - yactCalyg(yAg-yFg+1:yAg-yFg+length(banstp{1}),banvar(1)) + 2; - end - end - end - - - %=================================================== - % ML conditional forecast - %=================================================== - %/* - [ychat,Estr,rcon] = fn_fcstidcnd(valuecon,stepcon,varcon,nstepsm,... - nconstr,options_.ms.eq_ms,nvar,options_.ms.nlags ,phil,0,0,yforehat,imf3shat,A0hat,Bhat,... - nfqm,options_.ms.tlindx,options_.ms.tlnumber,options_.ms.ncms,options_.ms.eq_cms); - ychate = [fdates ychat]; - yachate = [yact1e; ychate]; % actual and condtional forecast - %===== Converted to mg, qg, and calendar yg - [yacyrghate,yacyrhate,yacqmyghate] = fn_datana(yachate,options_.ms.freq,options_.ms.log_var(1:nlogeno),options_.ms.percent_var(1:npereno)); - % actual and conditional forecast growth rates - if options_.ms.indxgdls && nconstr - keyindx = [1:nvar]; - % conlab=['conditional on' ylab{PorR(1)}]; - conlab=['v-conditions']; - - figure - fn_foregraph(yafyrghate,yact2yrge,keyindx,rnum,cnum,options_.ms.freq,ylab,forelabel,conlab) - end - - if options_.ms.ncsk - Estr = zeros(nfqm,nvar); - Estr(1:2,:) = [ - -2.1838 -1.5779 0.53064 -0.099425 -0.69269 -1.0391 - 1.9407 3.3138 -0.10563 -0.55457 -0.68772 1.3534 - ]; - Estr(3:6,3) = [0.5*ones(1,4)]'; % MD shocks - - Estr(3:10,2) = [1.5 1.5 1.5*ones(1,6)]'; % MS shocks - - %Estr(3:6,6) = 1*ones(4,1); % U shocks - %Estr(8:11,4) = 1*ones(4,1); % y shocks - - %Estr(3:10,2) = [2.5 2.5 1.5*ones(1,6)]'; % MS shocks alone - - nn = [nvar options_.ms.noptions_.ms.nlags nfqm]; - ycEhat = forefixe(A0hat,Bhat,phil,nn,Estr); - ycEhate = [fdates ycEhat]; - yacEhate = [yact1e; ycEhate]; % actual and condtional forecast - %===== Converted to mg, qg, and calendar yg - [yacEyrghate,yacEyrhate,yacEqmyghate] = datana(yacEhate,options_.ms.freq,options_.ms.log_var(1:nlogeno),options_.ms.percent_var(1:npereno)); - % actual and conditional forecast growth rates - disp([sprintf('%4.0f %2.0f %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f\n',yacEyrghate')]) - - if 1 - keyindx = [1:nvar]; - % conlab=['conditional on' ylab{PorR(1)}]; - conlab=['shock-conditions']; - - figure - gyrfore(yacEyrghate,yact2yrge,keyindx,rnum,cnum,ylab,forelabel,conlab) - end - end - - %----------------------------------------------------------- - % Compute structural shocks for the whole sample period excluding dummy observations. - %----------------------------------------------------------- - ywod = y(options_.ms.dummy_obs +1:end,:); % without dummy observations - phiwod=phi(options_.ms.dummy_obs +1:end,:); % without dummy observations - eplhat=ywod*A0hat-phiwod*Fhat; - qmStartWod = mod(qmStart+options_.ms.nlags ,options_.ms.freq); - if (~qmStartWod) - qmStartWod = options_.ms.freq; - end - yrStartWod = yrStart + floor((qmStart+options_.ms.nlags -1)/options_.ms.freq); - dateswod = fn_dataext([yrStartWod qmStartWod],[yrEnd qmEnd],xdatae(:,[1:2])); - eplhate = [dateswod eplhat]; - - Aphat = Fhat; + end + end + + + %=================================================== + % ML conditional forecast + %=================================================== + %/* + [ychat,Estr,rcon] = fn_fcstidcnd(valuecon,stepcon,varcon,nstepsm,... + nconstr,options_.ms.eq_ms,nvar,options_.ms.nlags ,phil,0,0,yforehat,imf3shat,A0hat,Bhat,... + nfqm,options_.ms.tlindx,options_.ms.tlnumber,options_.ms.ncms,options_.ms.eq_cms); + ychate = [fdates ychat]; + yachate = [yact1e; ychate]; % actual and condtional forecast + %===== Converted to mg, qg, and calendar yg + [yacyrghate,yacyrhate,yacqmyghate] = fn_datana(yachate,options_.ms.freq,options_.ms.log_var(1:nlogeno),options_.ms.percent_var(1:npereno)); + % actual and conditional forecast growth rates + if options_.ms.indxgdls && nconstr + keyindx = [1:nvar]; + % conlab=['conditional on' ylab{PorR(1)}]; + conlab=['v-conditions']; + + figure + fn_foregraph(yafyrghate,yact2yrge,keyindx,rnum,cnum,options_.ms.freq,ylab,forelabel,conlab) + end + + if options_.ms.ncsk + Estr = zeros(nfqm,nvar); + Estr(1:2,:) = [ + -2.1838 -1.5779 0.53064 -0.099425 -0.69269 -1.0391 + 1.9407 3.3138 -0.10563 -0.55457 -0.68772 1.3534 + ]; + Estr(3:6,3) = [0.5*ones(1,4)]'; % MD shocks + + Estr(3:10,2) = [1.5 1.5 1.5*ones(1,6)]'; % MS shocks + + %Estr(3:6,6) = 1*ones(4,1); % U shocks + %Estr(8:11,4) = 1*ones(4,1); % y shocks + + %Estr(3:10,2) = [2.5 2.5 1.5*ones(1,6)]'; % MS shocks alone + + nn = [nvar options_.ms.noptions_.ms.nlags nfqm]; + ycEhat = forefixe(A0hat,Bhat,phil,nn,Estr); + ycEhate = [fdates ycEhat]; + yacEhate = [yact1e; ycEhate]; % actual and condtional forecast + %===== Converted to mg, qg, and calendar yg + [yacEyrghate,yacEyrhate,yacEqmyghate] = datana(yacEhate,options_.ms.freq,options_.ms.log_var(1:nlogeno),options_.ms.percent_var(1:npereno)); + % actual and conditional forecast growth rates + disp([sprintf('%4.0f %2.0f %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f\n',yacEyrghate')]) + + if 1 + keyindx = [1:nvar]; + % conlab=['conditional on' ylab{PorR(1)}]; + conlab=['shock-conditions']; + + figure + gyrfore(yacEyrghate,yact2yrge,keyindx,rnum,cnum,ylab,forelabel,conlab) + end + end + + %----------------------------------------------------------- + % Compute structural shocks for the whole sample period excluding dummy observations. + %----------------------------------------------------------- + ywod = y(options_.ms.dummy_obs +1:end,:); % without dummy observations + phiwod=phi(options_.ms.dummy_obs +1:end,:); % without dummy observations + eplhat=ywod*A0hat-phiwod*Fhat; + qmStartWod = mod(qmStart+options_.ms.nlags ,options_.ms.freq); + if (~qmStartWod) + qmStartWod = options_.ms.freq; + end + yrStartWod = yrStart + floor((qmStart+options_.ms.nlags -1)/options_.ms.freq); + dateswod = fn_dataext([yrStartWod qmStartWod],[yrEnd qmEnd],xdatae(:,[1:2])); + eplhate = [dateswod eplhat]; + + Aphat = Fhat; end %---------------------------------------- @@ -745,11 +745,11 @@ end % from different idfile's. %---------------------------------------- % -%if ~options_.ms.contemp_reduced_form +%if ~options_.ms.contemp_reduced_form % SpHR=A0in'*A0in; %end %% -%if ~isnan(SpHR) && ~options_.ms.contemp_reduced_form +%if ~isnan(SpHR) && ~options_.ms.contemp_reduced_form % warning(' ') % disp('Make sure you run the program with options_.ms.contemp_reduced_form =1 first.') % disp('Otherwise, the following test results such as Schwartz are incorrect.') diff --git a/matlab/ms-sbvar/msstart_setup.m b/matlab/ms-sbvar/msstart_setup.m index 79c8024d40..88c307fe80 100644 --- a/matlab/ms-sbvar/msstart_setup.m +++ b/matlab/ms-sbvar/msstart_setup.m @@ -26,14 +26,14 @@ % Exordium I %=========================================== format short g % format -% -%options_.ms.freq = 4; % quarters or months -%options_.ms.initial_year=1959; % beginning of the year -%options_.ms.initial_subperiod=1; % begining of the quarter or month -%options_.ms.final_year=2005; % final year -%options_.ms.final_subperiod=4; % final month or quarter + % + %options_.ms.freq = 4; % quarters or months + %options_.ms.initial_year=1959; % beginning of the year + %options_.ms.initial_subperiod=1; % begining of the quarter or month + %options_.ms.final_year=2005; % final year + %options_.ms.final_subperiod=4; % final month or quarter nData=(options_.ms.final_year-options_.ms.initial_year)*options_.ms.freq + (options_.ms.final_subperiod-options_.ms.initial_subperiod+1); - % total number of the available data -- this is all you have +% total number of the available data -- this is all you have %*** Load data and series %load datainf_argen.prn % the default name for the variable is "options_.ms.data". @@ -61,19 +61,19 @@ nvar = length(options_.varobs); % number of endogenous variables nlogeno = length(options_.ms.log_var); % number of endogenous variables in options_.ms.log_var npereno = length(options_.ms.percent_var); % number of endogenous variables in options_.ms.percent_var if (nvar~=(nlogeno+npereno)) - skipline() - warning('Check xlab, nlogeno or npereno to make sure of endogenous variables in options_.ms.vlist') - disp('Press ctrl-c to abort') - return + skipline() + warning('Check xlab, nlogeno or npereno to make sure of endogenous variables in options_.ms.vlist') + disp('Press ctrl-c to abort') + return elseif (nvar==length(options_.ms.vlist)) - nexo=1; % only constants as an exogenous variable. The default setting. + nexo=1; % only constants as an exogenous variable. The default setting. elseif (nvar<length(options_.ms.vlist)) - nexo=length(options_.ms.vlist)-nvar+1; + nexo=length(options_.ms.vlist)-nvar+1; else - skipline() - warning('Make sure there are only nvar endogenous variables in options_.ms.vlist') - disp('Press ctrl-c to abort') - return + skipline() + warning('Make sure there are only nvar endogenous variables in options_.ms.vlist') + disp('Press ctrl-c to abort') + return end @@ -84,24 +84,24 @@ yrEnd=options_.ms.final_year; qmEnd=options_.ms.final_subperiod; %options_.forecast = 4; % number of years for forecasting if options_.forecast<1 - error('To be safe, the number of forecast years should be at least 1') + error('To be safe, the number of forecast years should be at least 1') end forelabel = [num2str(yrEnd) ':' num2str(qmEnd) ' Forecast']; nSample=(yrEnd-yrStart)*options_.ms.freq + (qmEnd-qmStart+1); if qmEnd==options_.ms.freq - E1yrqm = [yrEnd+1 1]; % first year and quarter (month) after the sample + E1yrqm = [yrEnd+1 1]; % first year and quarter (month) after the sample else - E1yrqm = [yrEnd qmEnd+1]; % first year and quarter (month) after the sample + E1yrqm = [yrEnd qmEnd+1]; % first year and quarter (month) after the sample end E2yrqm = [yrEnd+options_.forecast qmEnd]; % end at the last month (quarter) of a calendar year after the sample [fdates,nfqm]=fn_calyrqm(options_.ms.freq,E1yrqm,E2yrqm); % forecast dates and number of forecast dates [sdates,nsqm] = fn_calyrqm(options_.ms.freq,[yrStart qmStart],[yrEnd qmEnd]); - % sdates: dates for the whole sample (including options_.ms.nlags) +% sdates: dates for the whole sample (including options_.ms.nlags) if nSample~=nsqm - warning('Make sure that nSample is consistent with the size of sdates') - disp('Hit any key to continue, or ctrl-c to abort') - pause + warning('Make sure that nSample is consistent with the size of sdates') + disp('Hit any key to continue, or ctrl-c to abort') + pause end imstp = 4*options_.ms.freq; % <<>> impulse responses (4 years) nayr = 4; %options_.forecast; % number of years before forecasting for plotting. @@ -110,18 +110,18 @@ nayr = 4; %options_.forecast; % number of years before forecasting for plotting %------- Prior, etc. ------- %options_.ms.nlags = 4; % number of options_.ms.nlags %options_.ms.cross_restrictions = 0; % 1: cross-A0-and-A+ restrictions; 0: options_.ms.restriction_fname is all we have - % Example for indxOres==1: restrictions of the form P(t) = P(t-1). +% Example for indxOres==1: restrictions of the form P(t) = P(t-1). %options_.ms.contemp_reduced_form = 0; % 1: contemporaneous recursive reduced form; 0: restricted (non-recursive) form %options_.ms.real_pseudo_forecast = 0; % 1: options_.ms.real_pseudo_forecast forecasts; 0: real time forecasts %options_.ms.bayesian_prior = 1; % 1: Bayesian prior; 0: no prior indxDummy = options_.ms.bayesian_prior; % 1: add dummy observations to the data; 0: no dummy added. -%options_.ms.dummy_obs = 0; % No dummy observations for xtx, phi, fss, xdatae, etc. Dummy observations are used as an explicit prior in fn_rnrprior_covres_dobs.m. -%if indxDummy -% options_.ms.dummy_obs=nvar+1; % number of dummy observations -%else -% options_.ms.dummy_obs=0; % no dummy observations -%end -%=== The following mu is effective only if options_.ms.bayesian_prior==1. + %options_.ms.dummy_obs = 0; % No dummy observations for xtx, phi, fss, xdatae, etc. Dummy observations are used as an explicit prior in fn_rnrprior_covres_dobs.m. + %if indxDummy + % options_.ms.dummy_obs=nvar+1; % number of dummy observations + %else + % options_.ms.dummy_obs=0; % no dummy observations + %end + %=== The following mu is effective only if options_.ms.bayesian_prior==1. mu = options_.ms.coefficients_prior_hyperparameters; @@ -142,20 +142,15 @@ tdf = 3; % degrees of freedom for t-dist for initial draw of the MC loo nbuffer = 1000; % a block or buffer of draws (buffer) that is saved to the disk (not memory) ndraws1=1*nbuffer; % 1st part of Monte Carlo draws ndraws2=10*ndraws1; % 2nd part of Monte Carlo draws -% seednumber = options_.DynareRandomStreams.seed; %7910; %472534; % if 0, random state at each clock time -% % good one 420 for [29 45], [29 54] -% if seednumber -% randn('state',seednumber); -% rand('state',seednumber); -% else -% randn('state',fix(100*sum(clock))); -% rand('state',fix(100*sum(clock))); -% end -% nstarts=1 % number of starting points -% imndraws = nstarts*ndraws2; % total draws for impulse responses or forecasts -%<<<<<<<<<<<<<<<<<<< - - - - - + % seednumber = options_.DynareRandomStreams.seed; %7910; %472534; % if 0, random state at each clock time + % % good one 420 for [29 45], [29 54] + % if seednumber + % randn('state',seednumber); + % rand('state',seednumber); + % else + % randn('state',fix(100*sum(clock))); + % rand('state',fix(100*sum(clock))); + % end + % nstarts=1 % number of starting points + % imndraws = nstarts*ndraws2; % total draws for impulse responses or forecasts + %<<<<<<<<<<<<<<<<<<< diff --git a/matlab/ms-sbvar/plot_ms_forecast.m b/matlab/ms-sbvar/plot_ms_forecast.m index c6f0661f3c..c76f8af895 100644 --- a/matlab/ms-sbvar/plot_ms_forecast.m +++ b/matlab/ms-sbvar/plot_ms_forecast.m @@ -32,122 +32,122 @@ function plot_ms_forecast(M_, options_, forecast, figure_name) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - nc = 2; - nr = 2; - nvars = M_.endo_nbr; - endo_names = M_.endo_names; - var_list = endo_names(1:M_.orig_endo_nbr,:); - names = {}; - tex_names = {}; - m = 1; - 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 - tex_name = deblank(M_.endo_names_tex(i,:)); - if ~isempty(tex_name) - names{m} = deblank(var_list(i,:)); - tex_names{m} = tex_name; - m = m + 1; - end +nc = 2; +nr = 2; +nvars = M_.endo_nbr; +endo_names = M_.endo_names; +var_list = endo_names(1:M_.orig_endo_nbr,:); +names = {}; +tex_names = {}; +m = 1; +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 - - dims = size(forecast); - if (length(dims) == 2) - % Point Forecast (horizon x nvars ) - horizon = dims(1); - num_percentiles = 1; - elseif (length(dims) == 3) - % Banded Forecast - horizon = dims(2); - num_percentiles = dims(1); - else - error('The impulse response matrix passed to be plotted does not appear to be the correct size'); + tex_name = deblank(M_.endo_names_tex(i,:)); + if ~isempty(tex_name) + names{m} = deblank(var_list(i,:)); + tex_names{m} = tex_name; + m = m + 1; end +end - if num_percentiles == 1 - plot_point_forecast(forecast, nvars, nr, nc, var_list, figure_name, ... - options_.graph_save_formats, options_.TeX, names, tex_names, ... - [options_.ms.output_file_tag filesep 'Output' filesep 'Forecast']); - else - plot_banded_forecast(forecast, nvars, nr, nc, var_list, num_percentiles, ... - figure_name, options_.graph_save_formats, options_.TeX, names, tex_names, ... - [options_.ms.output_file_tag filesep 'Output' filesep 'Forecast']); - end +dims = size(forecast); +if (length(dims) == 2) + % Point Forecast (horizon x nvars ) + horizon = dims(1); + num_percentiles = 1; +elseif (length(dims) == 3) + % Banded Forecast + horizon = dims(2); + num_percentiles = dims(1); +else + error('The impulse response matrix passed to be plotted does not appear to be the correct size'); +end + +if num_percentiles == 1 + plot_point_forecast(forecast, nvars, nr, nc, var_list, figure_name, ... + options_.graph_save_formats, options_.TeX, names, tex_names, ... + [options_.ms.output_file_tag filesep 'Output' filesep 'Forecast']); +else + plot_banded_forecast(forecast, nvars, nr, nc, var_list, num_percentiles, ... + figure_name, options_.graph_save_formats, options_.TeX, names, tex_names, ... + [options_.ms.output_file_tag filesep 'Output' filesep 'Forecast']); +end end function plot_point_forecast(forecast,nvars,nr,nc,endo_names,figure_name,save_graph_formats,TeX,names,tex_names,dirname) - if nvars > nr*nc - graph_name = ['MS (1) ' figure_name]; - figure('Name', graph_name); - else - graph_name = figure_name; - figure('Name', graph_name); - end - m = 1; - n_fig = 1; - for j=1:nvars - if m > nr*nc - graph_name = ['MS (' int2str(n_fig) ') ' figure_name]; - dyn_save_graph(dirname,['MS-forecast-' int2str(n_fig)],... - save_graph_formats,TeX,names,tex_names,graph_name); - n_fig =n_fig+1; - figure('Name', graph_name); - m = 1; - end - subplot(nr,nc,m); - vn = deblank(endo_names(j,:)); - plot(forecast(:,j)) - title(vn,'Interpreter','none'); - grid on; - m = m+1; - end - if m > 1 +if nvars > nr*nc + graph_name = ['MS (1) ' figure_name]; + figure('Name', graph_name); +else + graph_name = figure_name; + figure('Name', graph_name); +end +m = 1; +n_fig = 1; +for j=1:nvars + if m > nr*nc + graph_name = ['MS (' int2str(n_fig) ') ' figure_name]; dyn_save_graph(dirname,['MS-forecast-' int2str(n_fig)],... save_graph_formats,TeX,names,tex_names,graph_name); + n_fig =n_fig+1; + figure('Name', graph_name); + m = 1; end + subplot(nr,nc,m); + vn = deblank(endo_names(j,:)); + plot(forecast(:,j)) + title(vn,'Interpreter','none'); + grid on; + m = m+1; +end +if m > 1 + dyn_save_graph(dirname,['MS-forecast-' int2str(n_fig)],... + save_graph_formats,TeX,names,tex_names,graph_name); +end end function plot_banded_forecast(forecast,nvars,nr,nc,endo_names,num_percentiles,figure_name,save_graph_formats,TeX,names,tex_names,dirname) - if nvars > nr*nc - graph_name = ['MS (1) ' figure_name]; - figure('Name', graph_name); - else - graph_name = figure_name; - figure('Name', graph_name); +if nvars > nr*nc + graph_name = ['MS (1) ' figure_name]; + figure('Name', graph_name); +else + graph_name = figure_name; + figure('Name', graph_name); +end +m = 1; +n_fig = 1; +for j=1:nvars + if m > nr*nc + graph_name = ['MS (' int2str(n_fig) ') ' figure_name]; + dyn_save_graph(dirname,['MS-forecast-' int2str(n_fig)],... + save_graph_formats,TeX,names,tex_names,graph_name); + n_fig =n_fig+1; + figure('Name',graph_name); + m = 1; end - m = 1; - n_fig = 1; - for j=1:nvars - if m > nr*nc - graph_name = ['MS (' int2str(n_fig) ') ' figure_name]; - dyn_save_graph(dirname,['MS-forecast-' int2str(n_fig)],... - save_graph_formats,TeX,names,tex_names,graph_name); - n_fig =n_fig+1; - figure('Name',graph_name); - m = 1; + subplot(nr,nc,m); + vn = deblank(endo_names(j,:)); + for k=1:num_percentiles + if ceil(num_percentiles/2) == k + plot(forecast(k,:,j),'LineWidth',1.5) + else + plot(forecast(k,:,j),'LineWidth',1.1) end - subplot(nr,nc,m); - vn = deblank(endo_names(j,:)); - for k=1:num_percentiles - if ceil(num_percentiles/2) == k - plot(forecast(k,:,j),'LineWidth',1.5) - else - plot(forecast(k,:,j),'LineWidth',1.1) - end - if k==1 - hold on; - end + if k==1 + hold on; end - title(vn,'Interpreter','none'); - hold off - grid on; - m = m+1; - end - if m > 1 - dyn_save_graph(dirname,['MS-forecast-' int2str(n_fig)],... - save_graph_formats,TeX,names,tex_names,graph_name); end + title(vn,'Interpreter','none'); + hold off + grid on; + m = m+1; +end +if m > 1 + dyn_save_graph(dirname,['MS-forecast-' int2str(n_fig)],... + save_graph_formats,TeX,names,tex_names,graph_name); +end end diff --git a/matlab/ms-sbvar/plot_ms_irf.m b/matlab/ms-sbvar/plot_ms_irf.m index 82c9727479..39ca642cff 100644 --- a/matlab/ms-sbvar/plot_ms_irf.m +++ b/matlab/ms-sbvar/plot_ms_irf.m @@ -32,108 +32,108 @@ function plot_ms_irf(M_, options_, irf, figure_name, varlist) % 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 - figure_name = ''; - end +if nargin < 4 + figure_name = ''; +end - nvars = M_.endo_nbr; - endo_names = M_.endo_names; +nvars = M_.endo_nbr; +endo_names = M_.endo_names; - if isempty(varlist) - var_list = endo_names(1:M_.orig_endo_nbr,:); - end +if isempty(varlist) + var_list = endo_names(1:M_.orig_endo_nbr,:); +end - names = {}; - tex_names = {}; - m = 1; - 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 - tex_name = deblank(M_.endo_names_tex(tmp,:)); - if ~isempty(tex_name) - names{m} = deblank(var_list(i,:)); - tex_names{m} = tex_name; - m = m + 1; - end +names = {}; +tex_names = {}; +m = 1; +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 - - for i=1:M_.exo_nbr - tex_name = deblank(M_.exo_names_tex(i,:)); - if ~isempty(tex_name) - names{m} = deblank(M_.exo_names(i,:)); - tex_names{m} = tex_name; - m = m + 1; - end + tex_name = deblank(M_.endo_names_tex(tmp,:)); + if ~isempty(tex_name) + names{m} = deblank(var_list(i,:)); + tex_names{m} = tex_name; + m = m + 1; end +end - dims = size(irf); - if (length(dims) == 2) - % Point IRF (horizon x (nvarsxnvars) ) - horizon = dims(1); - num_percentiles = 1; - elseif (length(dims) == 3) - % Banded IRF - horizon = dims(2); - num_percentiles = dims(1); - else - error('The impulse response matrix passed to be plotted does not appear to be the correct size'); +for i=1:M_.exo_nbr + tex_name = deblank(M_.exo_names_tex(i,:)); + if ~isempty(tex_name) + names{m} = deblank(M_.exo_names(i,:)); + tex_names{m} = tex_name; + m = m + 1; end +end - if size(endo_names,1) ~= nvars - error('The names passed are not the same length as the number of variables'); - end +dims = size(irf); +if (length(dims) == 2) + % Point IRF (horizon x (nvarsxnvars) ) + horizon = dims(1); + num_percentiles = 1; +elseif (length(dims) == 3) + % Banded IRF + horizon = dims(2); + num_percentiles = dims(1); +else + error('The impulse response matrix passed to be plotted does not appear to be the correct size'); +end - if num_percentiles == 1 - % loop through the shocks - for s=1:nvars - shock = zeros(horizon,nvars); - for i=1:nvars - shock(:,i) = irf(:,((i-1) + ((s-1)*nvars)+1)); - end - plot_point_irf_for_shock(shock, nvars,endo_names, deblank(endo_names(s,:)), ... - figure_name, [options_.ms.output_file_tag filesep 'Output' filesep 'IRF'], options_, names, tex_names); +if size(endo_names,1) ~= nvars + error('The names passed are not the same length as the number of variables'); +end + +if num_percentiles == 1 + % loop through the shocks + for s=1:nvars + shock = zeros(horizon,nvars); + for i=1:nvars + shock(:,i) = irf(:,((i-1) + ((s-1)*nvars)+1)); end - else - for s=1:nvars - shock = zeros(horizon,nvars,num_percentiles); - for n=1:num_percentiles - for i=1:nvars - shock(:,i,n) = irf(n,:,((i-1) + ((s-1)*nvars)+1)); - end + plot_point_irf_for_shock(shock, nvars,endo_names, deblank(endo_names(s,:)), ... + figure_name, [options_.ms.output_file_tag filesep 'Output' filesep 'IRF'], options_, names, tex_names); + end +else + for s=1:nvars + shock = zeros(horizon,nvars,num_percentiles); + for n=1:num_percentiles + for i=1:nvars + shock(:,i,n) = irf(n,:,((i-1) + ((s-1)*nvars)+1)); end - plot_banded_irf_for_shock(shock, nvars,endo_names, deblank(endo_names(s,:)), ... - figure_name, [options_.ms.output_file_tag filesep 'Output' filesep 'IRF'], options_, names, tex_names); end + plot_banded_irf_for_shock(shock, nvars,endo_names, deblank(endo_names(s,:)), ... + figure_name, [options_.ms.output_file_tag filesep 'Output' filesep 'IRF'], options_, names, tex_names); end end +end function [fig] = plot_point_irf_for_shock(irf,nvars,endo_names,shock_name,figure_name,dirname,options_,names,tex_names) - fig = figure('Name',figure_name); - for k=1:nvars - subplot(ceil(sqrt(nvars)), ceil(sqrt(nvars)),k); - plot(irf(:,k)) - disp([endo_names(k,:) ' shock from ' shock_name]); - title([endo_names(k,:) ' shock from ' shock_name]); - end - dyn_save_graph(dirname,[figure_name ' ' shock_name],options_.graph_save_formats, ... - options_.TeX,names,tex_names,[figure_name ' ' shock_name]); +fig = figure('Name',figure_name); +for k=1:nvars + subplot(ceil(sqrt(nvars)), ceil(sqrt(nvars)),k); + plot(irf(:,k)) + disp([endo_names(k,:) ' shock from ' shock_name]); + title([endo_names(k,:) ' shock from ' shock_name]); +end +dyn_save_graph(dirname,[figure_name ' ' shock_name],options_.graph_save_formats, ... + options_.TeX,names,tex_names,[figure_name ' ' shock_name]); end function [fig] = plot_banded_irf_for_shock(irf,nvars, endo_names, shock_name,figure_name,dirname,options_,names,tex_names) - fig = figure('Name',figure_name); - npercentiles = size(irf,3); - for k=1:nvars - subplot(ceil(sqrt(nvars)), ceil(sqrt(nvars)),k); - for nn=1:npercentiles - plot(irf(:,k,nn)) - hold on - end - hold off - disp([endo_names(k,:) ' shock from ' shock_name]); - title([endo_names(k,:) ' shock from ' shock_name]); +fig = figure('Name',figure_name); +npercentiles = size(irf,3); +for k=1:nvars + subplot(ceil(sqrt(nvars)), ceil(sqrt(nvars)),k); + for nn=1:npercentiles + plot(irf(:,k,nn)) + hold on end - dyn_save_graph(dirname,[figure_name ' ' shock_name],options_.graph_save_formats, ... - options_.TeX,names,tex_names,[figure_name ' ' shock_name]); + hold off + disp([endo_names(k,:) ' shock from ' shock_name]); + title([endo_names(k,:) ' shock from ' shock_name]); +end +dyn_save_graph(dirname,[figure_name ' ' shock_name],options_.graph_save_formats, ... + options_.TeX,names,tex_names,[figure_name ' ' shock_name]); end diff --git a/matlab/ms-sbvar/plot_ms_probabilities.m b/matlab/ms-sbvar/plot_ms_probabilities.m index 023ecfd449..0b1125de30 100644 --- a/matlab/ms-sbvar/plot_ms_probabilities.m +++ b/matlab/ms-sbvar/plot_ms_probabilities.m @@ -3,7 +3,7 @@ function plot_ms_probabilities(computed_probabilities, options_) % Plots the regime probablities for each graph % % INPUTS -% computed_probabilities: Txnstates +% computed_probabilities: Txnstates % % OUTPUTS % none @@ -27,41 +27,41 @@ function plot_ms_probabilities(computed_probabilities, options_) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - [T,num_grand_regimes] = size(computed_probabilities); - num_chains = length(options_.ms.ms_chain); - for i=1:num_chains + +[T,num_grand_regimes] = size(computed_probabilities); +num_chains = length(options_.ms.ms_chain); +for i=1:num_chains chains(i).num_regimes = length(options_.ms.ms_chain(i).regime); chains(i).probabilities = zeros([T,chains(i).num_regimes]); - end - - for t=1:T +end + +for t=1:T chains = iterate_chain(computed_probabilities(t,:), t, chains, 1, num_chains); - end - - for i=1:num_chains +end + +for i=1:num_chains graph_name = ['MS-Probabilities, Chain ' int2str(i)]; figure('Name',graph_name) plot(chains(i).probabilities,'LineWidth', 1.2); ltxt = {}; for j=1:chains(i).num_regimes - ltxt{j} = ['Regime ' int2str(j)]; + ltxt{j} = ['Regime ' int2str(j)]; end legend(ltxt{:}); title(['Chain ' int2str(i)]); ylim([0 1.0]); dyn_save_graph([options_.ms.output_file_tag filesep 'Output' filesep 'Probabilities'], ['MS-Probabilities-Chain-' int2str(i)], ... - options_.graph_save_formats,options_.TeX,[],[],graph_name); - end + options_.graph_save_formats,options_.TeX,[],[],graph_name); +end end function [chains] = iterate_chain(probs, t, chains, chain, num_chains) - offset_length = length(probs)/chains(chain).num_regimes; - for i=1:chains(chain).num_regimes +offset_length = length(probs)/chains(chain).num_regimes; +for i=1:chains(chain).num_regimes p = probs( (i-1)*offset_length+1 : i*offset_length ); chains(chain).probabilities(t, i) = chains(chain).probabilities(t, i) + sum( p ); if chain < num_chains - chains = iterate_chain(p, t, chains, chain+1, num_chains); + chains = iterate_chain(p, t, chains, chain+1, num_chains); end - end +end end diff --git a/matlab/ms-sbvar/plot_ms_variance_decomposition.m b/matlab/ms-sbvar/plot_ms_variance_decomposition.m index a1998b8e46..81aab9263f 100644 --- a/matlab/ms-sbvar/plot_ms_variance_decomposition.m +++ b/matlab/ms-sbvar/plot_ms_variance_decomposition.m @@ -9,12 +9,12 @@ function plot_ms_variance_decomposition(M_, options_, vd, figure_name, varargin) % figure_name: (string) graph name % % OPTIONAL INPUTS -% 'data': the actual data, TxK with K=number of data series -% 'steady': the steady state value, TxK -% 'shock_names': to specify the names of the shocks -% 'series_names': to specify the names of the different series -% 'dates': pass a date vector to use, otherwise will just index on 1:T -% 'colors': Jx3 list of the rgb colors to use for each shock +% 'data': the actual data, TxK with K=number of data series +% 'steady': the steady state value, TxK +% 'shock_names': to specify the names of the shocks +% 'series_names': to specify the names of the different series +% 'dates': pass a date vector to use, otherwise will just index on 1:T +% 'colors': Jx3 list of the rgb colors to use for each shock % % OUTPUTS % none @@ -44,130 +44,130 @@ if length(size(vd)) == 3 return; end - nvars = M_.endo_nbr; - endo_names = M_.endo_names; +nvars = M_.endo_nbr; +endo_names = M_.endo_names; - names = {}; - tex_names = {}; - m = 1; - for i=1:M_.orig_endo_nbr - tex_name = deblank(M_.endo_names_tex(i,:)); - if ~isempty(tex_name) - names{m} = deblank(endo_names(i,:)); - tex_names{m} = tex_name; - m = m + 1; - end +names = {}; +tex_names = {}; +m = 1; +for i=1:M_.orig_endo_nbr + tex_name = deblank(M_.endo_names_tex(i,:)); + if ~isempty(tex_name) + names{m} = deblank(endo_names(i,:)); + tex_names{m} = tex_name; + m = m + 1; end +end - dims = size(vd); - if length(dims) == 3 - T = dims(1); - K = dims(2); - J = dims(3); - shocks = vd; - else - T = dims(1); - K = nvars; - J = nvars; - temp_vd = zeros(T,K,J); - for i=1:nvars - for j=1:nvars - temp_vd(:,i,j) = vd(:,((j-1) + ((i-1)*nvars)+1)); - end +dims = size(vd); +if length(dims) == 3 + T = dims(1); + K = dims(2); + J = dims(3); + shocks = vd; +else + T = dims(1); + K = nvars; + J = nvars; + temp_vd = zeros(T,K,J); + for i=1:nvars + for j=1:nvars + temp_vd(:,i,j) = vd(:,((j-1) + ((i-1)*nvars)+1)); end - shocks = temp_vd; end + shocks = temp_vd; +end - for i=1:nvars - shock_names{i} = endo_names(i,:); - series_names{i} = endo_names(i,:); - end +for i=1:nvars + shock_names{i} = endo_names(i,:); + series_names{i} = endo_names(i,:); +end - x = [1:T]; - plot_dates = 0; - data = 0; - steady = 0; - colors = [ .1 .1 .75 - .8 0 0 - 1 .7 .25 - 1 1 0 - .5 1 .5 - .7 .7 .1 - .5 .6 .2 - .1 .5 .1]; +x = [1:T]; +plot_dates = 0; +data = 0; +steady = 0; +colors = [ .1 .1 .75 + .8 0 0 + 1 .7 .25 + 1 1 0 + .5 1 .5 + .7 .7 .1 + .5 .6 .2 + .1 .5 .1]; - % overide the defaults with optional inputs - for i=1:length(varargin) - if strcmpi(varargin{i},'data') - data = varargin{i+1}; - elseif strcmpi(varargin{i},'steady') - steady = varargin{i+1}; - elseif strcmpi(varargin{i},'shock_names') - shock_names = varargin{i+1}; - elseif strcmpi(varargin{i},'series_names') - series_names = varargin{i+1}; - elseif strcmpi(varargin{i}, 'dates') - x = varargin{i+1}; plot_dates = 1; - elseif strcmpi(varargin{i},'colors') - colors = varargin{i+1}; - end +% overide the defaults with optional inputs +for i=1:length(varargin) + if strcmpi(varargin{i},'data') + data = varargin{i+1}; + elseif strcmpi(varargin{i},'steady') + steady = varargin{i+1}; + elseif strcmpi(varargin{i},'shock_names') + shock_names = varargin{i+1}; + elseif strcmpi(varargin{i},'series_names') + series_names = varargin{i+1}; + elseif strcmpi(varargin{i}, 'dates') + x = varargin{i+1}; plot_dates = 1; + elseif strcmpi(varargin{i},'colors') + colors = varargin{i+1}; end +end - % add an extra period to the time series - x(T+1) = x(T) + (x(T) - x(T-1)); +% add an extra period to the time series +x(T+1) = x(T) + (x(T) - x(T-1)); - figure('Name',figure_name) - for k=1:K - % Go through each series - subplot(K,1,k); - sshocks = shocks(:,k,:); - hold on - % plot the stacked shocks - for t=1:T - % step through each time period - pos_position = 0; neg_position = 0; - xt = [x(t) x(t) x(t+1) x(t+1)]; - for j=1:J - % stack each shock - st = sshocks(t,1,j); - if st < 0 - yi = st+neg_position; - y = [neg_position yi yi neg_position]; - neg_position = yi; - else - yi = st+pos_position; - y = [pos_position yi yi pos_position]; - pos_position = yi; - end - fill(xt,y,colors(j,:)); - XY(t,j,:) = y; - end - end - if data - plot(x(2:end)',data(:,k),'k','LineWidth',2.5); - end - if steady - plot(x(2:end)',steady(:,k), '--k','LineWidth',2.25); - end - if k==K - if isoctave - legend(shock_names,'Location','SouthOutside'); +figure('Name',figure_name) +for k=1:K + % Go through each series + subplot(K,1,k); + sshocks = shocks(:,k,:); + hold on + % plot the stacked shocks + for t=1:T + % step through each time period + pos_position = 0; neg_position = 0; + xt = [x(t) x(t) x(t+1) x(t+1)]; + for j=1:J + % stack each shock + st = sshocks(t,1,j); + if st < 0 + yi = st+neg_position; + y = [neg_position yi yi neg_position]; + neg_position = yi; else - legend(shock_names,'Location','BestOutside','Orientation','horizontal'); + yi = st+pos_position; + y = [pos_position yi yi pos_position]; + pos_position = yi; end + fill(xt,y,colors(j,:)); + XY(t,j,:) = y; end - - hold off - if plot_dates - datetick 'x'; + end + if data + plot(x(2:end)',data(:,k),'k','LineWidth',2.5); + end + if steady + plot(x(2:end)',steady(:,k), '--k','LineWidth',2.25); + end + if k==K + if isoctave + legend(shock_names,'Location','SouthOutside'); + else + legend(shock_names,'Location','BestOutside','Orientation','horizontal'); end - xlim([min(x),max(x)]) - ylim([0 , 1]) - grid on - title(series_names{k}); end - dyn_save_graph([options_.ms.output_file_tag filesep 'Output' ... - filesep 'Variance_Decomposition'], 'MS-Variance-Decomposition', ... - options_.graph_save_formats, options_.TeX, names, tex_names, ... - 'Variance decomposition'); + + hold off + if plot_dates + datetick 'x'; + end + xlim([min(x),max(x)]) + ylim([0 , 1]) + grid on + title(series_names{k}); +end +dyn_save_graph([options_.ms.output_file_tag filesep 'Output' ... + filesep 'Variance_Decomposition'], 'MS-Variance-Decomposition', ... + options_.graph_save_formats, options_.TeX, names, tex_names, ... + 'Variance decomposition'); end diff --git a/matlab/ms-sbvar/plot_ms_variance_decomposition_error_bands.m b/matlab/ms-sbvar/plot_ms_variance_decomposition_error_bands.m index cc03e87c7f..193c9b59ff 100644 --- a/matlab/ms-sbvar/plot_ms_variance_decomposition_error_bands.m +++ b/matlab/ms-sbvar/plot_ms_variance_decomposition_error_bands.m @@ -79,14 +79,14 @@ for s=1:nvars end end plot_banded_vddata_for_shock(shock, nvars, endo_names, ... - deblank(endo_names(s,:)), figure_name, ... - [options_.ms.output_file_tag filesep 'Output' filesep 'Variance_Decomposition'], ... - options_, names, tex_names); + deblank(endo_names(s,:)), figure_name, ... + [options_.ms.output_file_tag filesep 'Output' filesep 'Variance_Decomposition'], ... + options_, names, tex_names); end end function [fig] = plot_banded_vddata_for_shock(vddata, nvars, endo_names, ... - shock_name, figure_name, dirname, options_, names, tex_names) + shock_name, figure_name, dirname, options_, names, tex_names) fig = figure('Name', figure_name); npercentiles = size(vddata,3); for k=1:nvars @@ -100,6 +100,6 @@ for k=1:nvars title([endo_names(k,:) ' contribution to ' shock_name]); end dyn_save_graph(dirname, [figure_name ' ' shock_name], ... - options_.graph_save_formats, options_.TeX, names, tex_names, ... - [figure_name ' ' shock_name]); + options_.graph_save_formats, options_.TeX, names, tex_names, ... + [figure_name ' ' shock_name]); end diff --git a/matlab/ms-sbvar/svar_global_identification_check.m b/matlab/ms-sbvar/svar_global_identification_check.m index 549d5c7fd4..b0884defe5 100644 --- a/matlab/ms-sbvar/svar_global_identification_check.m +++ b/matlab/ms-sbvar/svar_global_identification_check.m @@ -47,7 +47,7 @@ if isequal(options_.ms.restriction_fname, 'upper_cholesky') || ... end nvar = length(options_.varobs); % number of endogenous variables nexo = 1; - + [Uiconst,Viconst,n0,np,ixmC0Pres,Qi,Ri] = exclusions(nvar,nexo,options_.ms ); % order column constraints by rank diff --git a/matlab/mult_elimination.m b/matlab/mult_elimination.m index 17f0d18db5..347c702cb2 100644 --- a/matlab/mult_elimination.m +++ b/matlab/mult_elimination.m @@ -4,7 +4,7 @@ function dr=mult_elimination(varlist,M_, options_, oo_) % and shock variables % % INPUT -% none +% none % % OUTPUT % dr: a structure with the new decision rule @@ -107,13 +107,13 @@ if nvar > 0 && options_.noprint == 0 for i=1:length(varlist) k = strmatch(varlist{i},M_.endo_names(dr.order_var,:),'exact'); headers = char(headers,varlist{i}); - + res_table(1:nm_nbr,i) = M1(k,:)'; res_table(nm_nbr+(1:nm_nbr),i) = M2(k,:)'; res_table(2*nm_nbr+(1:M_.exo_nbr),i) = M3(k,:)'; res_table(2*nm_nbr+M_.exo_nbr+(1:M_.exo_nbr),i) = M4(k,:)'; end - + my_title='ELIMINATION OF THE MULTIPLIERS'; lab = nstates(nil,:); labels = strcat(deblank(lab(i,:)),'(-1)'); diff --git a/matlab/multivariate_sample_autocovariance.m b/matlab/multivariate_sample_autocovariance.m index 6bc0ea32ea..3b35db5f3b 100644 --- a/matlab/multivariate_sample_autocovariance.m +++ b/matlab/multivariate_sample_autocovariance.m @@ -1,12 +1,12 @@ function autocov = multivariate_sample_autocovariance(data,q) % Computes the autocovariance function of multivariate time series. -% % -% INPUTS +% +% INPUTS % data [double] T*m matrix of data. -% q [integer] Order of the autocovariance function. -% -% OUTPUTS +% q [integer] Order of the autocovariance function. +% +% OUTPUTS % autocov [double] m*m*(q+1) array, autocovariance function. % % SPECIAL REQUIREMENTS diff --git a/matlab/myboxplot.m b/matlab/myboxplot.m index 5d513c4cc9..b3490a4b39 100644 --- a/matlab/myboxplot.m +++ b/matlab/myboxplot.m @@ -33,7 +33,7 @@ if notched==1, notched=0.25; end a=1-notched; % ## figure out how many data sets we have -if iscell(data) +if iscell(data) nc = length(data); else % if isvector(data), data = data(:); end @@ -133,7 +133,7 @@ whisker_x(:,[chop,chop+nc]) = []; whisker_y(:,[chop,chop+nc]) = []; median_x(:,chop) = []; median_y(:,chop) = []; -% % % % +% % % % % ## Add caps to the remaining whiskers cap_x = whisker_x; cap_x(1,:) =cap_x(1,:)- 0.05; @@ -144,7 +144,7 @@ cap_y = whisker_y([1,1],:); % #whisker_x,whisker_y % #median_x,median_y % #cap_x,cap_y -% +% % ## Do the plot mm=min(min(data)); diff --git a/matlab/name2index.m b/matlab/name2index.m index b653e71c62..29723160b6 100644 --- a/matlab/name2index.m +++ b/matlab/name2index.m @@ -2,14 +2,14 @@ function i = name2index(options_, M_, estim_params_, type, name1, name2 ) % Returns the index associated to an estimated object (deep parameter, % variance of a structural shock or measurement error, covariance between % two structural shocks, covariance between two measurement errors). -% +% % INPUTS: % options_ [structure] Dynare structure. % M_ [structure] Dynare structure (related to model definition). % estim_params_ [structure] Dynare structure (related to estimation). % type [string] 'DeepParameter', 'MeasurementError' (for measurement equation error) or 'StructuralShock' (for structural shock). -% name1 [string] -% name2 [string] +% name1 [string] +% name2 [string] % OUTPUTS % i [integer] column index (in x2, an array of mh draws) associated to name1[,name2]. % @@ -63,7 +63,7 @@ if strcmpi(type,'StructuralShock') end else% Covariance matrix off-diagonal term offset = nvx+nvn; - try + 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'); diff --git a/matlab/non_linear_dsge_likelihood.m b/matlab/non_linear_dsge_likelihood.m index 57e02a0b7a..1f56c3be41 100644 --- a/matlab/non_linear_dsge_likelihood.m +++ b/matlab/non_linear_dsge_likelihood.m @@ -229,8 +229,8 @@ end if info(1) if info(1) == 3 || info(1) == 4 || info(1) == 5 || info(1)==6 ||info(1) == 19 || ... - info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ... - info(1) == 81 || info(1) == 84 || info(1) == 85 + info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ... + info(1) == 81 || info(1) == 84 || info(1) == 85 %meaningful second entry of output that can be used fval = Inf; info(4) = info(2); @@ -376,4 +376,3 @@ if isinf(LIK)~=0 exit_flag = 0; return end - diff --git a/matlab/occbin/call_solve_one_constraint.m b/matlab/occbin/call_solve_one_constraint.m index c613b50346..65b98c4319 100755 --- a/matlab/occbin/call_solve_one_constraint.m +++ b/matlab/occbin/call_solve_one_constraint.m @@ -1,21 +1,21 @@ -% Solve model, generate model IRFs -[zdatalinear, zdatapiecewise, zdatass, oobase_, Mbase_ ] = ... - solve_one_constraint(modnam,modnamstar,... - constraint, constraint_relax,... - shockssequence,irfshock,nperiods,maxiter); - - - -% unpack the IRFs -for i=1:Mbase_.endo_nbr - eval([deblank(Mbase_.endo_names(i,:)),'_uncdifference=zdatalinear(:,i);']); - eval([deblank(Mbase_.endo_names(i,:)),'_difference=zdatapiecewise(:,i);']); - eval([deblank(Mbase_.endo_names(i,:)),'_ss=zdatass(i);']); -end - - -nparams = size(Mbase_.param_names,1); - -for i = 1:nparams - eval([Mbase_.param_names(i,:),'= Mbase_.params(i);']); -end +% Solve model, generate model IRFs +[zdatalinear, zdatapiecewise, zdatass, oobase_, Mbase_ ] = ... + solve_one_constraint(modnam,modnamstar,... + constraint, constraint_relax,... + shockssequence,irfshock,nperiods,maxiter); + + + +% unpack the IRFs +for i=1:Mbase_.endo_nbr + eval([deblank(Mbase_.endo_names(i,:)),'_uncdifference=zdatalinear(:,i);']); + eval([deblank(Mbase_.endo_names(i,:)),'_difference=zdatapiecewise(:,i);']); + eval([deblank(Mbase_.endo_names(i,:)),'_ss=zdatass(i);']); +end + + +nparams = size(Mbase_.param_names,1); + +for i = 1:nparams + eval([Mbase_.param_names(i,:),'= Mbase_.params(i);']); +end diff --git a/matlab/occbin/call_solve_two_constraints.m b/matlab/occbin/call_solve_two_constraints.m index 3adda90d73..5bbc1beb86 100755 --- a/matlab/occbin/call_solve_two_constraints.m +++ b/matlab/occbin/call_solve_two_constraints.m @@ -1,21 +1,21 @@ -[zdatalinear, zdatapiecewise, zdatass, oobase_, Mbase_] = solve_two_constraints(... - modnam_00,modnam_10,modnam_01,modnam_11,... - constraint1, constraint2,... - constraint_relax1, constraint_relax2,... - scalefactormod,irfshock,nperiods,curb_retrench,maxiter); - - -for i=1:Mbase_.endo_nbr - eval([deblank(Mbase_.endo_names(i,:)),'_uncdifference=zdatalinear(:,i);']); - eval([deblank(Mbase_.endo_names(i,:)),'_difference=zdatapiecewise(:,i);']); - eval([deblank(Mbase_.endo_names(i,:)),'_ss=zdatass(i);']); -end - -constraint1_difference = process_constraint(constraint1,'_difference',Mbase_.endo_names,0); -constraint2_difference = process_constraint(constraint2,'_difference',Mbase_.endo_names,0); - -nparams = size(Mbase_.param_names,1); - -for i = 1:nparams - eval([Mbase_.param_names(i,:),'= Mbase_.params(i);']); -end +[zdatalinear, zdatapiecewise, zdatass, oobase_, Mbase_] = solve_two_constraints(... + modnam_00,modnam_10,modnam_01,modnam_11,... + constraint1, constraint2,... + constraint_relax1, constraint_relax2,... + scalefactormod,irfshock,nperiods,curb_retrench,maxiter); + + +for i=1:Mbase_.endo_nbr + eval([deblank(Mbase_.endo_names(i,:)),'_uncdifference=zdatalinear(:,i);']); + eval([deblank(Mbase_.endo_names(i,:)),'_difference=zdatapiecewise(:,i);']); + eval([deblank(Mbase_.endo_names(i,:)),'_ss=zdatass(i);']); +end + +constraint1_difference = process_constraint(constraint1,'_difference',Mbase_.endo_names,0); +constraint2_difference = process_constraint(constraint2,'_difference',Mbase_.endo_names,0); + +nparams = size(Mbase_.param_names,1); + +for i = 1:nparams + eval([Mbase_.param_names(i,:),'= Mbase_.params(i);']); +end diff --git a/matlab/occbin/get_deriv.m b/matlab/occbin/get_deriv.m index d1fe780328..214b1cf425 100755 --- a/matlab/occbin/get_deriv.m +++ b/matlab/occbin/get_deriv.m @@ -1,83 +1,82 @@ -function [hm1,h,hl1,j,resid] = get_deriv(M_,ys_) - -iy_ = M_.lead_lag_incidence; -it_ = 1; - -x = zeros(1,M_.exo_nbr); - -% For most models, there are leads, lags and current values of variables -if size(iy_,1)==3 - % find non-zero columns of hm1 - lag_cols = find(iy_(1,:)~=0); - % find non-zero columns of h - con_cols = find(iy_(2,:)); - % find non-zero columns of hl1 - lea_cols = find(iy_(3,:)); - -% If models either lacks leads or lags, iy_ will have two rows -% In this case, we guess that the row with more nonzeros is the row with current variables -elseif size(iy_,1)==2 - % if first row has more nonzero entries than the second, assume model lacks lagged variables - if length(find(iy_(1,:)))>length(find(iy_(2,:))) - warning('Model does not have lagged endogenous variables') - con_cols = find(iy_(1,:)); - lea_cols = find(iy_(2,:)); - lag_cols = []; - else - warning('Model does not have expected future endogenous variables') - lag_cols = find(iy_(1,:)); - con_cols = find(iy_(2,:)); - lea_cols = []; - end - -end - - - -% find number of entries for y vector -ny = length(find(iy_~=0)); - -% build steady state y -y = ys_(lag_cols); -y = [y;ys_(con_cols)]; -y = [y;ys_(lea_cols)]; - - -if ismac -eval(['[resid,g1]=',M_.fname,'_dynamic(y,x, M_.params, ys_, it_);']); -% Older versions of DYNARE for Mac did not include ys_ in the call structure -%eval(['[resid,g1]=',M_.fname,'_dynamic(y,x, M_.params, it_);']); -else -eval(['[resid,g1]=',M_.fname,'_dynamic(y,x, M_.params, ys_, it_);']); -end - - -hm1=zeros(M_.endo_nbr); -h = hm1; -hl1 = hm1; -j = zeros(M_.endo_nbr,M_.exo_nbr); - - -% build hm1 -nlag_cols = length(lag_cols); -for i=1:nlag_cols - hm1(:,lag_cols(i)) = g1(:,i); -end - -% build h -ncon_cols = length(con_cols); -for i=1:ncon_cols - h(:,con_cols(i)) = g1(:,i+nlag_cols); -end - -% build hl1 -nlea_cols = length(lea_cols); -for i=1:nlea_cols - hl1(:,lea_cols(i)) = g1(:,i+nlag_cols+ncon_cols); -end - - -for i = 1:M_.exo_nbr - j(:,i) =g1(:,i+ny); -end - +function [hm1,h,hl1,j,resid] = get_deriv(M_,ys_) + +iy_ = M_.lead_lag_incidence; +it_ = 1; + +x = zeros(1,M_.exo_nbr); + +% For most models, there are leads, lags and current values of variables +if size(iy_,1)==3 + % find non-zero columns of hm1 + lag_cols = find(iy_(1,:)~=0); + % find non-zero columns of h + con_cols = find(iy_(2,:)); + % find non-zero columns of hl1 + lea_cols = find(iy_(3,:)); + + % If models either lacks leads or lags, iy_ will have two rows + % In this case, we guess that the row with more nonzeros is the row with current variables +elseif size(iy_,1)==2 + % if first row has more nonzero entries than the second, assume model lacks lagged variables + if length(find(iy_(1,:)))>length(find(iy_(2,:))) + warning('Model does not have lagged endogenous variables') + con_cols = find(iy_(1,:)); + lea_cols = find(iy_(2,:)); + lag_cols = []; + else + warning('Model does not have expected future endogenous variables') + lag_cols = find(iy_(1,:)); + con_cols = find(iy_(2,:)); + lea_cols = []; + end + +end + + + +% find number of entries for y vector +ny = length(find(iy_~=0)); + +% build steady state y +y = ys_(lag_cols); +y = [y;ys_(con_cols)]; +y = [y;ys_(lea_cols)]; + + +if ismac + eval(['[resid,g1]=',M_.fname,'_dynamic(y,x, M_.params, ys_, it_);']); + % Older versions of DYNARE for Mac did not include ys_ in the call structure + %eval(['[resid,g1]=',M_.fname,'_dynamic(y,x, M_.params, it_);']); +else + eval(['[resid,g1]=',M_.fname,'_dynamic(y,x, M_.params, ys_, it_);']); +end + + +hm1=zeros(M_.endo_nbr); +h = hm1; +hl1 = hm1; +j = zeros(M_.endo_nbr,M_.exo_nbr); + + +% build hm1 +nlag_cols = length(lag_cols); +for i=1:nlag_cols + hm1(:,lag_cols(i)) = g1(:,i); +end + +% build h +ncon_cols = length(con_cols); +for i=1:ncon_cols + h(:,con_cols(i)) = g1(:,i+nlag_cols); +end + +% build hl1 +nlea_cols = length(lea_cols); +for i=1:nlea_cols + hl1(:,lea_cols(i)) = g1(:,i+nlag_cols+ncon_cols); +end + + +for i = 1:M_.exo_nbr + j(:,i) =g1(:,i+ny); +end diff --git a/matlab/occbin/get_pq.m b/matlab/occbin/get_pq.m index 2924eacf5e..99888b8068 100755 --- a/matlab/occbin/get_pq.m +++ b/matlab/occbin/get_pq.m @@ -1,28 +1,28 @@ -function [p,q]=get_pq(dr_,nstatic,nfwrd) - -nvars = size(dr_.ghx,1); -nshocks = size(dr_.ghu,2); -statevar_pos = (nstatic +1):(nvars-nfwrd); - -p = zeros(nvars); -% interlace matrix -nnotzero = length(statevar_pos); -for i=1:nnotzero - p(:,statevar_pos(i)) = dr_.ghx(:,i); -end - -% reorder p matrix according to order in lgy_ -inverse_order = zeros(nvars,1); -for i=1:nvars - inverse_order(i) = find(i==dr_.order_var); -end - -p_reordered = zeros(nvars); -q = zeros(nvars,nshocks); -for i=1:nvars - for j=1:nvars - p_reordered(i,j)=p(inverse_order(i),inverse_order(j)); - end - q(i,:)=dr_.ghu(inverse_order(i),:); -end +function [p,q]=get_pq(dr_,nstatic,nfwrd) + +nvars = size(dr_.ghx,1); +nshocks = size(dr_.ghu,2); +statevar_pos = (nstatic +1):(nvars-nfwrd); + +p = zeros(nvars); +% interlace matrix +nnotzero = length(statevar_pos); +for i=1:nnotzero + p(:,statevar_pos(i)) = dr_.ghx(:,i); +end + +% reorder p matrix according to order in lgy_ +inverse_order = zeros(nvars,1); +for i=1:nvars + inverse_order(i) = find(i==dr_.order_var); +end + +p_reordered = zeros(nvars); +q = zeros(nvars,nshocks); +for i=1:nvars + for j=1:nvars + p_reordered(i,j)=p(inverse_order(i),inverse_order(j)); + end + q(i,:)=dr_.ghu(inverse_order(i),:); +end p=p_reordered; \ No newline at end of file diff --git a/matlab/occbin/makechart.m b/matlab/occbin/makechart.m index c3ea7719ee..934e8463bf 100755 --- a/matlab/occbin/makechart.m +++ b/matlab/occbin/makechart.m @@ -1,81 +1,81 @@ -function makechart(titlelist,legendlist,figlabel,ylabels,zdata1,zdata2,zdata3) - - - -figure - -titlelist = char(strrep(cellstr(titlelist),'_','.')); - -ndsets=3; % default, changed below as applicable -if nargin==5 - zdata2=nan*zdata1; - zdata3=nan*zdata1; - ndsets =1; -elseif nargin == 6 - zdata3 =nan*zdata1; - ndsets=2; -elseif ((nargin>8) | (nargin <=4)) - error ('makechart takes 5 to 6 arguments') -end - -nobs = size(zdata1,1); -xvalues = (1:nobs)'; - -nvars = size(titlelist,1); -if nvars==1 - nrows=1; - ncols = 1; -elseif nvars==2 - nrows =2; - ncols = 1; -elseif (nvars == 3 | nvars ==4) - nrows = 2; - ncols =2; -elseif (nvars==5 |nvars ==6) - nrows = 3; - ncols = 2; -elseif (nvars==7 | nvars==8) - nrows = 4; - ncols = 2; -elseif (nvars==9 | nvars==10) - nrows = 5; - ncols = 2; -else - error('too many variables (makechart)') -end - -for i = 1:nvars - subplot(nrows,ncols,i) - h1=plot(xvalues,zdata1(:,i),'b-','linewidth',2); hold on - h1=plot(xvalues,zdata2(:,i),'r--','linewidth',2); hold on - h2=plot(xvalues,zdata3(:,i),'b-','LineWidth',3); - [x0, x1, y10, y11] = pickaxes(xvalues,zdata1(:,i)); - [x0, x1, y20, y21] = pickaxes(xvalues,zdata2(:,i)); - [x0, x1, y30, y31] = pickaxes(xvalues,zdata3(:,i)); - y0 = min([y10,y20,y30]); - y1 = max([y11,y21,y31]); - if y0==y1 - y1=y0+1; - end - - axis([x0 x1 y0 y1]) - set(h1); - - if i==1 && isempty(legendlist)==0 - legend(legendlist) - text('String',figlabel,'Units','normalized','Position',[1.2 1.24],... - 'FontSize',14,'FontWeight','bold','HorizontalAlignment','center'); - end - - if i==nvars | i==nvars-1 - xlabel('Time'); - end -% set(gca,'XTick',xtick) -% set(gca,'XTickLabel',xticklabel) - - title([num2str(i),'. ',titlelist(i,:)]); - ylabel(ylabels(i,:)) -end - -% sets printing preferences -%printpref +function makechart(titlelist,legendlist,figlabel,ylabels,zdata1,zdata2,zdata3) + + + +figure + +titlelist = char(strrep(cellstr(titlelist),'_','.')); + +ndsets=3; % default, changed below as applicable +if nargin==5 + zdata2=nan*zdata1; + zdata3=nan*zdata1; + ndsets =1; +elseif nargin == 6 + zdata3 =nan*zdata1; + ndsets=2; +elseif ((nargin>8) | (nargin <=4)) + error ('makechart takes 5 to 6 arguments') +end + +nobs = size(zdata1,1); +xvalues = (1:nobs)'; + +nvars = size(titlelist,1); +if nvars==1 + nrows=1; + ncols = 1; +elseif nvars==2 + nrows =2; + ncols = 1; +elseif (nvars == 3 | nvars ==4) + nrows = 2; + ncols =2; +elseif (nvars==5 |nvars ==6) + nrows = 3; + ncols = 2; +elseif (nvars==7 | nvars==8) + nrows = 4; + ncols = 2; +elseif (nvars==9 | nvars==10) + nrows = 5; + ncols = 2; +else + error('too many variables (makechart)') +end + +for i = 1:nvars + subplot(nrows,ncols,i) + h1=plot(xvalues,zdata1(:,i),'b-','linewidth',2); hold on + h1=plot(xvalues,zdata2(:,i),'r--','linewidth',2); hold on + h2=plot(xvalues,zdata3(:,i),'b-','LineWidth',3); + [x0, x1, y10, y11] = pickaxes(xvalues,zdata1(:,i)); + [x0, x1, y20, y21] = pickaxes(xvalues,zdata2(:,i)); + [x0, x1, y30, y31] = pickaxes(xvalues,zdata3(:,i)); + y0 = min([y10,y20,y30]); + y1 = max([y11,y21,y31]); + if y0==y1 + y1=y0+1; + end + + axis([x0 x1 y0 y1]) + set(h1); + + if i==1 && isempty(legendlist)==0 + legend(legendlist) + text('String',figlabel,'Units','normalized','Position',[1.2 1.24],... + 'FontSize',14,'FontWeight','bold','HorizontalAlignment','center'); + end + + if i==nvars | i==nvars-1 + xlabel('Time'); + end + % set(gca,'XTick',xtick) + % set(gca,'XTickLabel',xticklabel) + + title([num2str(i),'. ',titlelist(i,:)]); + ylabel(ylabels(i,:)) +end + +% sets printing preferences +%printpref diff --git a/matlab/occbin/makechart9.m b/matlab/occbin/makechart9.m index 8f9ae54793..264f9f58f7 100755 --- a/matlab/occbin/makechart9.m +++ b/matlab/occbin/makechart9.m @@ -1,136 +1,136 @@ -function makechart9(titlelist,legendlist,figlabel,yearshock,ylabels,... - zdata1,zdata2,zdata3,zdata4,zdata5,zdata6,zdata7) - - - -figure - -titlelist = char(strrep(cellstr(titlelist),'_','.')); - -ndsets=7; % default, changed below as applicable -if nargin==6 - zdata2=nan*zdata1; - zdata3=nan*zdata1; - zdata4=nan*zdata1; - zdata5=nan*zdata1; - zdata6=nan*zdata1; - zdata7=nan*zdata1; - ndsets =1; -elseif nargin==7 - zdata3=nan*zdata1; - zdata4=nan*zdata1; - zdata5=nan*zdata1; - zdata6=nan*zdata1; - zdata7=nan*zdata1; - ndsets =2; -elseif nargin == 8 - zdata4 =nan*zdata1; - zdata5 =nan*zdata1; - zdata6=nan*zdata1; - zdata7=nan*zdata1; - ndsets=3; -elseif nargin == 9 - zdata5 =nan*zdata1; - zdata6=nan*zdata1; - zdata7=nan*zdata1; - ndsets=4; -elseif nargin == 10 - zdata6 =nan*zdata1; - zdata7=nan*zdata1; - ndsets=5; -elseif nargin == 11 - zdata7=nan*zdata1; - ndsets=6; -elseif ((nargin>=13) | (nargin <=3)) - error ('makechart takes 4 to 10 arguments') -end - -nobs = size(zdata1,1); - -if yearshock>-100 -xvalues = yearshock+(0:nobs-1)'/4; % Matteo plot year on x axis -else -xvalues = (1:nobs)'; % Matteo plot year on x axis -end - -nvars = size(titlelist,1); -if nvars==1 - nrows=1; - ncols = 1; -elseif nvars==2 - nrows =2; - ncols = 1; -elseif nvars == 3 - nrows = 3; - ncols = 1; -elseif nvars==4 - nrows = 2; - ncols = 2; -elseif (nvars==5 | nvars ==6) - nrows = 3; - ncols = 2; -elseif (nvars==7 | nvars==8) - nrows = 4; - ncols = 2; -elseif nvars>8 & nvars<=12 - nrows = 3; - ncols = 4; -elseif nvars>12 & nvars<=15 - nrows = 5; - ncols = 3; -else - error('too many variables (makechart)') -end - - -for i = 1:nvars - subplot(nrows,ncols,i) - h1=plot(xvalues,zdata1(:,i),'k',... - xvalues,zdata2(:,i),'r',... - xvalues,zdata3(:,i),'b',... - xvalues,zdata4(:,i),'g',... - xvalues,zdata5(:,i),'g',... - xvalues,zdata6(:,i),'c',... - xvalues,zdata7(:,i),'y'); - [x0, x1, y10, y11] = pickaxes(xvalues,zdata1(:,i)); - [x0, x1, y20, y21] = pickaxes(xvalues,zdata2(:,i)); - [x0, x1, y30, y31] = pickaxes(xvalues,zdata3(:,i)); - [x0, x1, y40, y41] = pickaxes(xvalues,zdata4(:,i)); - [x0, x1, y50, y51] = pickaxes(xvalues,zdata5(:,i)); - [x0, x1, y60, y61] = pickaxes(xvalues,zdata6(:,i)); - [x0, x1, y70, y71] = pickaxes(xvalues,zdata7(:,i)); - grid on - y0 = min([y10,y20,y30,y40,y50,y60,y70]); - y1 = max([y11,y21,y31,y41,y51,y61,y71]); - if y0==y1 - y1=y0+1; - end - - axis([x0 x1 y0 y1]) - set(h1,'linewidth',2); - if i==1 - if numel(strvcat(legendlist(1,:))) - h=legend(legendlist,'Location','Northwest'); - set(h,'Fontsize',8) - end - end - if i==1 - if nvars>3 - text('String',figlabel,'Units','normalized','Position',[1.2 1.21],... - 'FontSize',13,'FontWeight','bold','HorizontalAlignment','center'); - else - text('String',figlabel,'Units','normalized','Position',[0.4 1.24],... - 'FontSize',13,'FontWeight','bold','HorizontalAlignment','center'); - end - end - - %set(gca,'XTick',xtick) - %set(gca,'XTickLabel',xticklabel) - - title(titlelist(i,:),'Fontsize',11); - ylabel(ylabels(i,:)) - -end - -% sets printing preferences -%printpref +function makechart9(titlelist,legendlist,figlabel,yearshock,ylabels,... + zdata1,zdata2,zdata3,zdata4,zdata5,zdata6,zdata7) + + + +figure + +titlelist = char(strrep(cellstr(titlelist),'_','.')); + +ndsets=7; % default, changed below as applicable +if nargin==6 + zdata2=nan*zdata1; + zdata3=nan*zdata1; + zdata4=nan*zdata1; + zdata5=nan*zdata1; + zdata6=nan*zdata1; + zdata7=nan*zdata1; + ndsets =1; +elseif nargin==7 + zdata3=nan*zdata1; + zdata4=nan*zdata1; + zdata5=nan*zdata1; + zdata6=nan*zdata1; + zdata7=nan*zdata1; + ndsets =2; +elseif nargin == 8 + zdata4 =nan*zdata1; + zdata5 =nan*zdata1; + zdata6=nan*zdata1; + zdata7=nan*zdata1; + ndsets=3; +elseif nargin == 9 + zdata5 =nan*zdata1; + zdata6=nan*zdata1; + zdata7=nan*zdata1; + ndsets=4; +elseif nargin == 10 + zdata6 =nan*zdata1; + zdata7=nan*zdata1; + ndsets=5; +elseif nargin == 11 + zdata7=nan*zdata1; + ndsets=6; +elseif ((nargin>=13) | (nargin <=3)) + error ('makechart takes 4 to 10 arguments') +end + +nobs = size(zdata1,1); + +if yearshock>-100 + xvalues = yearshock+(0:nobs-1)'/4; % Matteo plot year on x axis +else + xvalues = (1:nobs)'; % Matteo plot year on x axis +end + +nvars = size(titlelist,1); +if nvars==1 + nrows=1; + ncols = 1; +elseif nvars==2 + nrows =2; + ncols = 1; +elseif nvars == 3 + nrows = 3; + ncols = 1; +elseif nvars==4 + nrows = 2; + ncols = 2; +elseif (nvars==5 | nvars ==6) + nrows = 3; + ncols = 2; +elseif (nvars==7 | nvars==8) + nrows = 4; + ncols = 2; +elseif nvars>8 & nvars<=12 + nrows = 3; + ncols = 4; +elseif nvars>12 & nvars<=15 + nrows = 5; + ncols = 3; +else + error('too many variables (makechart)') +end + + +for i = 1:nvars + subplot(nrows,ncols,i) + h1=plot(xvalues,zdata1(:,i),'k',... + xvalues,zdata2(:,i),'r',... + xvalues,zdata3(:,i),'b',... + xvalues,zdata4(:,i),'g',... + xvalues,zdata5(:,i),'g',... + xvalues,zdata6(:,i),'c',... + xvalues,zdata7(:,i),'y'); + [x0, x1, y10, y11] = pickaxes(xvalues,zdata1(:,i)); + [x0, x1, y20, y21] = pickaxes(xvalues,zdata2(:,i)); + [x0, x1, y30, y31] = pickaxes(xvalues,zdata3(:,i)); + [x0, x1, y40, y41] = pickaxes(xvalues,zdata4(:,i)); + [x0, x1, y50, y51] = pickaxes(xvalues,zdata5(:,i)); + [x0, x1, y60, y61] = pickaxes(xvalues,zdata6(:,i)); + [x0, x1, y70, y71] = pickaxes(xvalues,zdata7(:,i)); + grid on + y0 = min([y10,y20,y30,y40,y50,y60,y70]); + y1 = max([y11,y21,y31,y41,y51,y61,y71]); + if y0==y1 + y1=y0+1; + end + + axis([x0 x1 y0 y1]) + set(h1,'linewidth',2); + if i==1 + if numel(strvcat(legendlist(1,:))) + h=legend(legendlist,'Location','Northwest'); + set(h,'Fontsize',8) + end + end + if i==1 + if nvars>3 + text('String',figlabel,'Units','normalized','Position',[1.2 1.21],... + 'FontSize',13,'FontWeight','bold','HorizontalAlignment','center'); + else + text('String',figlabel,'Units','normalized','Position',[0.4 1.24],... + 'FontSize',13,'FontWeight','bold','HorizontalAlignment','center'); + end + end + + %set(gca,'XTick',xtick) + %set(gca,'XTickLabel',xticklabel) + + title(titlelist(i,:),'Fontsize',11); + ylabel(ylabels(i,:)) + +end + +% sets printing preferences +%printpref diff --git a/matlab/occbin/map_regime.m b/matlab/occbin/map_regime.m index 1c84871bd0..702b011f9f 100755 --- a/matlab/occbin/map_regime.m +++ b/matlab/occbin/map_regime.m @@ -1,25 +1,24 @@ -function [regime, regimestart]=map_regimes(violvecbool) - -nperiods = length(violvecbool)-1; - -% analyse violvec and isolate contiguous periods in the other regime. - regime(1) = violvecbool(1); - regimeindx = 1; - regimestart(1) = 1; - for i=2:nperiods - if violvecbool(i)~=regime(regimeindx) - regimeindx=regimeindx+1; - regime(regimeindx) = violvecbool(i); - regimestart(regimeindx)=i; - end - end - - - if (regime(1) == 1 & length(regimestart)==1) - warning('Increase nperiods'); - end - - if (regime(end)==1) - warning('Increase nperiods'); - end - +function [regime, regimestart]=map_regime(violvecbool) + +nperiods = length(violvecbool)-1; + +% analyse violvec and isolate contiguous periods in the other regime. +regime(1) = violvecbool(1); +regimeindx = 1; +regimestart(1) = 1; +for i=2:nperiods + if violvecbool(i)~=regime(regimeindx) + regimeindx=regimeindx+1; + regime(regimeindx) = violvecbool(i); + regimestart(regimeindx)=i; + end +end + + +if (regime(1) == 1 & length(regimestart)==1) + warning('Increase nperiods'); +end + +if (regime(end)==1) + warning('Increase nperiods'); +end diff --git a/matlab/occbin/mkdata.m b/matlab/occbin/mkdata.m index a7f855743d..f22fb45f65 100755 --- a/matlab/occbin/mkdata.m +++ b/matlab/occbin/mkdata.m @@ -1,63 +1,63 @@ -function [zdata]=mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,scalefactormod,init) - -%[nsim, ksim, ysim, isim, csim] = mkdata(nperiods,cofb,endog_) - -% given decision rule -neqs = size(endog_,1); - -if nargin<9 - init = zeros(neqs,1); -end - -if nargin<8 - scalefactormod=1; -end - -if nargin<7 - error('Not enough inputs') -end - -history = zeros(neqs,nperiods+1); - - nshocks = size(irfshock,1); - for i = 1:nshocks - shockpos = strmatch(irfshock(i,:),exog_,'exact'); - if ~isempty(shockpos) - irfshockpos(i) = shockpos; - else - error(['Shock ',irfshock(i,:),' is not in the model']); - end - end - - -% generate data -% history will contain data, the state vector at each period in time will -% be stored columnwise. -history = zeros(neqs,nperiods); -history(:,1)= init; - -lengthshock = size(scalefactormod,1); - -errvec = zeros(size(exog_,1),1); - -for i = 2:nperiods+1 - if i<=(lengthshock+1) - for j = 1:nshocks - errvec(irfshockpos(j)) = scalefactormod(i-1,j); - end - history(:,i) = decrulea * history(:,i-1)+decruleb*errvec; - else - % update endogenous variables - history(:,i) = decrulea * history(:,i-1); - end -end - -% extract desired variables -nwish=size(wishlist,1); -wishpos = zeros(nwish,1); - -history=history'; -for i=1:nwish - wishpos(i) = strmatch(wishlist(i,:),endog_,'exact'); -end +function [zdata]=mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,scalefactormod,init) + +%[nsim, ksim, ysim, isim, csim] = mkdata(nperiods,cofb,endog_) + +% given decision rule +neqs = size(endog_,1); + +if nargin<9 + init = zeros(neqs,1); +end + +if nargin<8 + scalefactormod=1; +end + +if nargin<7 + error('Not enough inputs') +end + +history = zeros(neqs,nperiods+1); + +nshocks = size(irfshock,1); +for i = 1:nshocks + shockpos = strmatch(irfshock(i,:),exog_,'exact'); + if ~isempty(shockpos) + irfshockpos(i) = shockpos; + else + error(['Shock ',irfshock(i,:),' is not in the model']); + end +end + + +% generate data +% history will contain data, the state vector at each period in time will +% be stored columnwise. +history = zeros(neqs,nperiods); +history(:,1)= init; + +lengthshock = size(scalefactormod,1); + +errvec = zeros(size(exog_,1),1); + +for i = 2:nperiods+1 + if i<=(lengthshock+1) + for j = 1:nshocks + errvec(irfshockpos(j)) = scalefactormod(i-1,j); + end + history(:,i) = decrulea * history(:,i-1)+decruleb*errvec; + else + % update endogenous variables + history(:,i) = decrulea * history(:,i-1); + end +end + +% extract desired variables +nwish=size(wishlist,1); +wishpos = zeros(nwish,1); + +history=history'; +for i=1:nwish + wishpos(i) = strmatch(wishlist(i,:),endog_,'exact'); +end zdata = history(2:end,wishpos); \ No newline at end of file diff --git a/matlab/occbin/mkdatap_anticipated.m b/matlab/occbin/mkdatap_anticipated.m index 6fef8c7f2d..a9c9249663 100755 --- a/matlab/occbin/mkdatap_anticipated.m +++ b/matlab/occbin/mkdatap_anticipated.m @@ -1,125 +1,125 @@ -function [zdata]=mkdatap_anticipated(nperiods,decrulea,decruleb,... - cof,Jbarmat,cofstar,Jstarbarmat,Dstarbarmat,... - regime,regimestart,violvecbool,... - endog_,exog_,irfshock,scalefactormod,init) - - - -nvars = size(endog_,1); - - -if nargin<16 - init=zeros(nvars,1); -end - -if nargin<15 - scalefactormod=1; -end - - -nshocks = size(irfshock,1); -for i = 1:nshocks - shockpos = strmatch(irfshock(i,:),exog_,'exact'); - if ~isempty(shockpos) - irfshockpos(i) = shockpos; - else - error(['Shock ',irfshock(i,:),' is not in the model']); - end -end - - -nregimes = length(regime); - -Cbarmat = cof(:,1:nvars); -Bbarmat = cof(:,nvars+1:2*nvars); -Abarmat = cof(:,2*nvars+1:3*nvars); - - -% cofstar contains the system for the model when the constraint binds -Cstarbarmat = cofstar(:,1:nvars); -Bstarbarmat = cofstar(:,nvars+1:2*nvars); -Astarbarmat = cofstar(:,2*nvars+1:3*nvars); - -% get the time-dependent decision rules - -Tmax = regimestart(nregimes)-1; % Tmax is the position of the last period -% when the constraint binds - -if Tmax > 0 - P = zeros(nvars,nvars,Tmax); - D = zeros(nvars,Tmax); - - - invmat = inv((Astarbarmat*decrulea+Bstarbarmat)); - P(:,:,Tmax) = -invmat*Cstarbarmat; - D(:,Tmax) = -invmat*Dstarbarmat; - - - % equivalent to pre-multiplying by the inverse above if the target - % matrix is invertible. Otherwise it yields the minimum state solution - %P(:,:,Tmax) = -(Astarbarmat*decrulea+Bstarbarmat)\Cstarbarmat; - %D(:,Tmax) = -(Astarbarmat*decrulea+Bstarbarmat)\Dstarbarmat; - - - for i = Tmax-1:-1:1 - - if violvecbool(i) - invmat = inv(Bstarbarmat+Astarbarmat*P(:,:,i+1)); - P(:,:,i)=-invmat*Cstarbarmat; - D(:,i) = -invmat*(Astarbarmat*D(:,i+1)+Dstarbarmat); - else - invmat = inv(Bbarmat+Abarmat*P(:,:,i+1)); - P(:,:,i)=-invmat*Cbarmat; - D(:,i) = -invmat*(Abarmat*D(:,i+1)); - end - end - -if Tmax > 1 -if violvecbool(1) - E = -invmat*Jstarbarmat; -else - E = -invmat*Jbarmat; -end -else - invmat = inv(Astarbarmat*decrulea+Bstarbarmat); - E = -invmat*Jstarbarmat; - -end - - -end - -% generate data -% history will contain data, the state vector at each period in time will -% be stored columnwise. -history = zeros(nvars,nperiods+1); -history(:,1) = init; -errvec = zeros(size(exog_,1),1); - -% deal with predetermined conditions -for i = 1:nshocks - errvec(irfshockpos(i)) = scalefactormod(i); -end - -% deal with shocks -irfpos =1; -if irfpos <=Tmax - history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+... - D(:,irfpos) + E*errvec; -else - history(:,irfpos+1) = decrulea*history(:,irfpos)+decruleb*errvec; -end - -% all other periods -for irfpos=2:nperiods+1 - if irfpos <=Tmax - history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+... - D(:,irfpos); - else - history(:,irfpos+1) = decrulea*history(:,irfpos); - end -end - - -history=history'; +function [zdata]=mkdatap_anticipated(nperiods,decrulea,decruleb,... + cof,Jbarmat,cofstar,Jstarbarmat,Dstarbarmat,... + regime,regimestart,violvecbool,... + endog_,exog_,irfshock,scalefactormod,init) + + + +nvars = size(endog_,1); + + +if nargin<16 + init=zeros(nvars,1); +end + +if nargin<15 + scalefactormod=1; +end + + +nshocks = size(irfshock,1); +for i = 1:nshocks + shockpos = strmatch(irfshock(i,:),exog_,'exact'); + if ~isempty(shockpos) + irfshockpos(i) = shockpos; + else + error(['Shock ',irfshock(i,:),' is not in the model']); + end +end + + +nregimes = length(regime); + +Cbarmat = cof(:,1:nvars); +Bbarmat = cof(:,nvars+1:2*nvars); +Abarmat = cof(:,2*nvars+1:3*nvars); + + +% cofstar contains the system for the model when the constraint binds +Cstarbarmat = cofstar(:,1:nvars); +Bstarbarmat = cofstar(:,nvars+1:2*nvars); +Astarbarmat = cofstar(:,2*nvars+1:3*nvars); + +% get the time-dependent decision rules + +Tmax = regimestart(nregimes)-1; % Tmax is the position of the last period + % when the constraint binds + +if Tmax > 0 + P = zeros(nvars,nvars,Tmax); + D = zeros(nvars,Tmax); + + + invmat = inv((Astarbarmat*decrulea+Bstarbarmat)); + P(:,:,Tmax) = -invmat*Cstarbarmat; + D(:,Tmax) = -invmat*Dstarbarmat; + + + % equivalent to pre-multiplying by the inverse above if the target + % matrix is invertible. Otherwise it yields the minimum state solution + %P(:,:,Tmax) = -(Astarbarmat*decrulea+Bstarbarmat)\Cstarbarmat; + %D(:,Tmax) = -(Astarbarmat*decrulea+Bstarbarmat)\Dstarbarmat; + + + for i = Tmax-1:-1:1 + + if violvecbool(i) + invmat = inv(Bstarbarmat+Astarbarmat*P(:,:,i+1)); + P(:,:,i)=-invmat*Cstarbarmat; + D(:,i) = -invmat*(Astarbarmat*D(:,i+1)+Dstarbarmat); + else + invmat = inv(Bbarmat+Abarmat*P(:,:,i+1)); + P(:,:,i)=-invmat*Cbarmat; + D(:,i) = -invmat*(Abarmat*D(:,i+1)); + end + end + + if Tmax > 1 + if violvecbool(1) + E = -invmat*Jstarbarmat; + else + E = -invmat*Jbarmat; + end + else + invmat = inv(Astarbarmat*decrulea+Bstarbarmat); + E = -invmat*Jstarbarmat; + + end + + +end + +% generate data +% history will contain data, the state vector at each period in time will +% be stored columnwise. +history = zeros(nvars,nperiods+1); +history(:,1) = init; +errvec = zeros(size(exog_,1),1); + +% deal with predetermined conditions +for i = 1:nshocks + errvec(irfshockpos(i)) = scalefactormod(i); +end + +% deal with shocks +irfpos =1; +if irfpos <=Tmax + history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+... + D(:,irfpos) + E*errvec; +else + history(:,irfpos+1) = decrulea*history(:,irfpos)+decruleb*errvec; +end + +% all other periods +for irfpos=2:nperiods+1 + if irfpos <=Tmax + history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+... + D(:,irfpos); + else + history(:,irfpos+1) = decrulea*history(:,irfpos); + end +end + + +history=history'; zdata = history(2:end,:); \ No newline at end of file diff --git a/matlab/occbin/mkdatap_anticipated_2constraints.m b/matlab/occbin/mkdatap_anticipated_2constraints.m index 85da740e55..496f5a931c 100755 --- a/matlab/occbin/mkdatap_anticipated_2constraints.m +++ b/matlab/occbin/mkdatap_anticipated_2constraints.m @@ -1,180 +1,180 @@ -function [zdata]=mkdatap_anticipated_2constraints_alt(nperiods,decrulea,decruleb,... - cof,Jbarmat,... - cof10,Jbarmat10,Dbarmat10,... - cof01,Jbarmat01,Dbarmat01,... - cof11,Jbarmat11,Dbarmat11,... - regime1,regimestart1,... - regime2,regimestart2,... - violvecbool,endog_,exog_,... - irfshock,scalefactormod,init) - - -nvars = size(endog_,1); - - -if nargin<16 - init=zeros(nvars,1); -end - -if nargin<15 - scalefactormod=1; -end - - -nshocks = size(irfshock,1); -for i = 1:nshocks - shockpos = strmatch(irfshock(i,:),exog_,'exact'); - if ~isempty(shockpos) - irfshockpos(i) = shockpos; - else - error(['Shock ',irfshock(i,:),' is not in the model']); - end -end - - - -Cbarmat = cof(:,1:nvars); -Bbarmat = cof(:,nvars+1:2*nvars); -Abarmat = cof(:,2*nvars+1:3*nvars); - - -% cofstar contains the system for the model when the constraint binds - - -Cbarmat10 = cof10(:,1:nvars); -Bbarmat10 = cof10(:,nvars+1:2*nvars); -Abarmat10 = cof10(:,2*nvars+1:3*nvars); - -Cbarmat01 = cof01(:,1:nvars); -Bbarmat01 = cof01(:,nvars+1:2*nvars); -Abarmat01 = cof01(:,2*nvars+1:3*nvars); - -Cbarmat11 = cof11(:,1:nvars); -Bbarmat11 = cof11(:,nvars+1:2*nvars); -Abarmat11 = cof11(:,2*nvars+1:3*nvars); - -% get the time-dependent decision rules -nregimes1 = length(regime1); -nregimes2 = length(regime2); - -Tmax = max([regimestart1(nregimes1) regimestart2(nregimes2)])-1; % Tmax is the position of the last period -% when the constraint binds - -if Tmax > 0 - P = zeros(nvars,nvars,Tmax); - D = zeros(nvars,Tmax); - -% invmat = inv((Astarbarmat*decrulea+Bstarbarmat)); -% P(:,:,Tmax) = -invmat*Cstarbarmat; -% D(:,Tmax) = -invmat*Dstarbarmat; - - - if (violvecbool(Tmax,1) & ~violvecbool(Tmax,2)) - %XXX fix next three lines - invmat = inv((Abarmat10*decrulea+Bbarmat10)); - P(:,:,Tmax) = -invmat*Cbarmat10; - D(:,Tmax) = -invmat*Dbarmat10; - elseif (violvecbool(Tmax,1) & violvecbool(Tmax,2)) - invmat = inv((Abarmat11*decrulea+Bbarmat11)); - P(:,:,Tmax) = -invmat*Cbarmat11; - D(:,Tmax) = -invmat*Dbarmat11; - else - invmat = inv((Abarmat01*decrulea+Bbarmat01)); - P(:,:,Tmax) = -invmat*Cbarmat01; - D(:,Tmax) = -invmat*Dbarmat01; - end - - - - - for i = Tmax-1:-1:1 - - if (violvecbool(i,1) & ~violvecbool(i,2)) - invmat = inv(Bbarmat10+Abarmat10*P(:,:,i+1)); - P(:,:,i)=-invmat*Cbarmat10; - D(:,i) = -invmat*(Abarmat10*D(:,i+1)+Dbarmat10); - elseif (~violvecbool(i,1) & violvecbool(i,2)) - invmat = inv(Bbarmat01+Abarmat01*P(:,:,i+1)); - P(:,:,i)=-invmat*Cbarmat01; - D(:,i) = -invmat*(Abarmat01*D(:,i+1)+Dbarmat01); - elseif (violvecbool(i,1) & violvecbool(i,2)) - invmat = inv(Bbarmat11+Abarmat11*P(:,:,i+1)); - P(:,:,i)=-invmat*Cbarmat11; - D(:,i) = -invmat*(Abarmat11*D(:,i+1)+Dbarmat11); - else - invmat = inv(Bbarmat+Abarmat*P(:,:,i+1)); - P(:,:,i)=-invmat*Cbarmat; - D(:,i) = -invmat*(Abarmat*D(:,i+1)); - end - - end - - -% Double check the appropriate invmat in each case -% right now -- inherited from previous loop -if Tmax > 1 - - if ( ~violvecbool(1,1) & violvecbool(1,2) ) - E = -invmat*Jbarmat01; - elseif ( violvecbool(1,1) & ~violvecbool(1,2) ) - E = -invmat*Jbarmat10; - elseif ( violvecbool(1,1) & violvecbool(1,2) ) - E = -invmat*Jbarmat11; - else - E = -invmat*Jbarmat; - end - -else % Tmax is equal to 1 -% invmat = inv((Astarbarmat*decrulea+Bstarbarmat)); -% E = -invmat*Jstarbarmat; - - if ( ~violvecbool(1,1) & violvecbool(1,2) ) - invmat = inv((Abarmat01*decrulea+Bbarmat01)); - E = -invmat*Jbarmat01; - elseif ( violvecbool(1,1) & violvecbool(1,2) ) - invmat = inv((Abarmat11*decrulea+Bbarmat11)); - E = -invmat*Jbarmat11; - else - invmat = inv((Abarmat10*decrulea+Bbarmat10)); - E = -invmat*Jbarmat10; - - end - -end - - -end - -% generate data -% history will contain data, the state vector at each period in time will -% be stored columnwise. -history = zeros(nvars,nperiods+1); -history(:,1) = init; -errvec = zeros(size(exog_,1),1); - -for i = 1:nshocks - errvec(irfshockpos(i)) = scalefactormod(i); -end - -% deal with shocks -irfpos =1; -if irfpos <=Tmax - history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+... - D(:,irfpos) + E*errvec; -else - history(:,irfpos+1) = decrulea*history(:,irfpos)+decruleb*errvec; -end - -% all other periods -for irfpos=2:nperiods+1 - if irfpos <=Tmax - history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+... - D(:,irfpos); - else - history(:,irfpos+1) = decrulea*history(:,irfpos); - end -end - - -history=history'; +function [zdata]=mkdatap_anticipated_2constraints(nperiods,decrulea,decruleb,... + cof,Jbarmat,... + cof10,Jbarmat10,Dbarmat10,... + cof01,Jbarmat01,Dbarmat01,... + cof11,Jbarmat11,Dbarmat11,... + regime1,regimestart1,... + regime2,regimestart2,... + violvecbool,endog_,exog_,... + irfshock,scalefactormod,init) + + +nvars = size(endog_,1); + + +if nargin<16 + init=zeros(nvars,1); +end + +if nargin<15 + scalefactormod=1; +end + + +nshocks = size(irfshock,1); +for i = 1:nshocks + shockpos = strmatch(irfshock(i,:),exog_,'exact'); + if ~isempty(shockpos) + irfshockpos(i) = shockpos; + else + error(['Shock ',irfshock(i,:),' is not in the model']); + end +end + + + +Cbarmat = cof(:,1:nvars); +Bbarmat = cof(:,nvars+1:2*nvars); +Abarmat = cof(:,2*nvars+1:3*nvars); + + +% cofstar contains the system for the model when the constraint binds + + +Cbarmat10 = cof10(:,1:nvars); +Bbarmat10 = cof10(:,nvars+1:2*nvars); +Abarmat10 = cof10(:,2*nvars+1:3*nvars); + +Cbarmat01 = cof01(:,1:nvars); +Bbarmat01 = cof01(:,nvars+1:2*nvars); +Abarmat01 = cof01(:,2*nvars+1:3*nvars); + +Cbarmat11 = cof11(:,1:nvars); +Bbarmat11 = cof11(:,nvars+1:2*nvars); +Abarmat11 = cof11(:,2*nvars+1:3*nvars); + +% get the time-dependent decision rules +nregimes1 = length(regime1); +nregimes2 = length(regime2); + +Tmax = max([regimestart1(nregimes1) regimestart2(nregimes2)])-1; % Tmax is the position of the last period + % when the constraint binds + +if Tmax > 0 + P = zeros(nvars,nvars,Tmax); + D = zeros(nvars,Tmax); + + % invmat = inv((Astarbarmat*decrulea+Bstarbarmat)); + % P(:,:,Tmax) = -invmat*Cstarbarmat; + % D(:,Tmax) = -invmat*Dstarbarmat; + + + if (violvecbool(Tmax,1) & ~violvecbool(Tmax,2)) + %XXX fix next three lines + invmat = inv((Abarmat10*decrulea+Bbarmat10)); + P(:,:,Tmax) = -invmat*Cbarmat10; + D(:,Tmax) = -invmat*Dbarmat10; + elseif (violvecbool(Tmax,1) & violvecbool(Tmax,2)) + invmat = inv((Abarmat11*decrulea+Bbarmat11)); + P(:,:,Tmax) = -invmat*Cbarmat11; + D(:,Tmax) = -invmat*Dbarmat11; + else + invmat = inv((Abarmat01*decrulea+Bbarmat01)); + P(:,:,Tmax) = -invmat*Cbarmat01; + D(:,Tmax) = -invmat*Dbarmat01; + end + + + + + for i = Tmax-1:-1:1 + + if (violvecbool(i,1) & ~violvecbool(i,2)) + invmat = inv(Bbarmat10+Abarmat10*P(:,:,i+1)); + P(:,:,i)=-invmat*Cbarmat10; + D(:,i) = -invmat*(Abarmat10*D(:,i+1)+Dbarmat10); + elseif (~violvecbool(i,1) & violvecbool(i,2)) + invmat = inv(Bbarmat01+Abarmat01*P(:,:,i+1)); + P(:,:,i)=-invmat*Cbarmat01; + D(:,i) = -invmat*(Abarmat01*D(:,i+1)+Dbarmat01); + elseif (violvecbool(i,1) & violvecbool(i,2)) + invmat = inv(Bbarmat11+Abarmat11*P(:,:,i+1)); + P(:,:,i)=-invmat*Cbarmat11; + D(:,i) = -invmat*(Abarmat11*D(:,i+1)+Dbarmat11); + else + invmat = inv(Bbarmat+Abarmat*P(:,:,i+1)); + P(:,:,i)=-invmat*Cbarmat; + D(:,i) = -invmat*(Abarmat*D(:,i+1)); + end + + end + + + % Double check the appropriate invmat in each case + % right now -- inherited from previous loop + if Tmax > 1 + + if ( ~violvecbool(1,1) & violvecbool(1,2) ) + E = -invmat*Jbarmat01; + elseif ( violvecbool(1,1) & ~violvecbool(1,2) ) + E = -invmat*Jbarmat10; + elseif ( violvecbool(1,1) & violvecbool(1,2) ) + E = -invmat*Jbarmat11; + else + E = -invmat*Jbarmat; + end + + else % Tmax is equal to 1 + % invmat = inv((Astarbarmat*decrulea+Bstarbarmat)); + % E = -invmat*Jstarbarmat; + + if ( ~violvecbool(1,1) & violvecbool(1,2) ) + invmat = inv((Abarmat01*decrulea+Bbarmat01)); + E = -invmat*Jbarmat01; + elseif ( violvecbool(1,1) & violvecbool(1,2) ) + invmat = inv((Abarmat11*decrulea+Bbarmat11)); + E = -invmat*Jbarmat11; + else + invmat = inv((Abarmat10*decrulea+Bbarmat10)); + E = -invmat*Jbarmat10; + + end + + end + + +end + +% generate data +% history will contain data, the state vector at each period in time will +% be stored columnwise. +history = zeros(nvars,nperiods+1); +history(:,1) = init; +errvec = zeros(size(exog_,1),1); + +for i = 1:nshocks + errvec(irfshockpos(i)) = scalefactormod(i); +end + +% deal with shocks +irfpos =1; +if irfpos <=Tmax + history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+... + D(:,irfpos) + E*errvec; +else + history(:,irfpos+1) = decrulea*history(:,irfpos)+decruleb*errvec; +end + +% all other periods +for irfpos=2:nperiods+1 + if irfpos <=Tmax + history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+... + D(:,irfpos); + else + history(:,irfpos+1) = decrulea*history(:,irfpos); + end +end + + +history=history'; zdata = history(2:end,:); \ No newline at end of file diff --git a/matlab/occbin/pickaxes.m b/matlab/occbin/pickaxes.m index 46c4b79c6d..26c9b6b1a3 100755 --- a/matlab/occbin/pickaxes.m +++ b/matlab/occbin/pickaxes.m @@ -1,16 +1,16 @@ -function [x0,x1,y0,y1] = pickaxes(xvalues,yvalues) - -x0=xvalues(1); -nobs = length(xvalues); -x1=xvalues(nobs); - -maxy = max(yvalues); -miny = min(yvalues); - - -y0 = miny - .05*abs(miny); -if (miny>0 & y0<0) - y0 = 0; -end - -y1 = maxy + .05*abs(maxy); +function [x0,x1,y0,y1] = pickaxes(xvalues,yvalues) + +x0=xvalues(1); +nobs = length(xvalues); +x1=xvalues(nobs); + +maxy = max(yvalues); +miny = min(yvalues); + + +y0 = miny - .05*abs(miny); +if (miny>0 & y0<0) + y0 = 0; +end + +y1 = maxy + .05*abs(maxy); diff --git a/matlab/occbin/process_constraint.m b/matlab/occbin/process_constraint.m index d209111755..2d2b35f364 100755 --- a/matlab/occbin/process_constraint.m +++ b/matlab/occbin/process_constraint.m @@ -1,38 +1,38 @@ -% this function looks for occurrences of the endogenous variables in -% endo_names in the input string constraint -% all occurrences of the endogenous variables are appended a suffix -% if the invert_switch is true, the direction of the inequality in the -% constraint is inverted - -function constraint1 = process_constraint(constraint,suffix,endo_names,invert_switch) - -% create a list of delimiters that can separate parameters and endogenoous -% variables in the string that expresses the constraint -delimiters = char(',',';','(',')','+','-','^','*','/',' ','>','<','='); - -% split the string that holds the constraint into tokens -tokens = tokenize(constraint,delimiters); - -ntokens = length(tokens); - -% search for tokens that match the list of endogenous variables -for i=1:ntokens - if ~isempty(find(strcmp(tokens(i),endo_names))) - % when there is a match with an endogenous variable append the - % suffix - tokens(i) = cellstr([char(tokens(i)),suffix]); - end - - % if the invert_switch is true - % reverse the direction of the inequality - if invert_switch - if strcmp(tokens(i),cellstr('>')) - tokens(i) = cellstr('<'); - elseif strcmp(tokens(i),cellstr('<')) - tokens(i) = cellstr('>'); - end - end -end - -% reassemble the tokens to create a string that expresses the constraint +% this function looks for occurrences of the endogenous variables in +% endo_names in the input string constraint +% all occurrences of the endogenous variables are appended a suffix +% if the invert_switch is true, the direction of the inequality in the +% constraint is inverted + +function constraint1 = process_constraint(constraint,suffix,endo_names,invert_switch) + +% create a list of delimiters that can separate parameters and endogenoous +% variables in the string that expresses the constraint +delimiters = char(',',';','(',')','+','-','^','*','/',' ','>','<','='); + +% split the string that holds the constraint into tokens +tokens = tokenize(constraint,delimiters); + +ntokens = length(tokens); + +% search for tokens that match the list of endogenous variables +for i=1:ntokens + if ~isempty(find(strcmp(tokens(i),endo_names))) + % when there is a match with an endogenous variable append the + % suffix + tokens(i) = cellstr([char(tokens(i)),suffix]); + end + + % if the invert_switch is true + % reverse the direction of the inequality + if invert_switch + if strcmp(tokens(i),cellstr('>')) + tokens(i) = cellstr('<'); + elseif strcmp(tokens(i),cellstr('<')) + tokens(i) = cellstr('>'); + end + end +end + +% reassemble the tokens to create a string that expresses the constraint constraint1 = strmerge(tokens); \ No newline at end of file diff --git a/matlab/occbin/setss.m b/matlab/occbin/setss.m index d1c0e440ac..7fc52f6c0e 100755 --- a/matlab/occbin/setss.m +++ b/matlab/occbin/setss.m @@ -1,14 +1,13 @@ -% Script that retrieves parameter values once model is solved - -nendog = size(Mbase_.endo_names,1); - -for i=1:nendog - eval([deblank(Mbase_.endo_names(i,:)) '_ss = oo_.dr.ys(i); ']); -end - -nparams = size(Mbase_.param_names); - -for i = 1:nparams - eval([Mbase_.param_names(i,:),'= M_.params(i);']); -end - +% Script that retrieves parameter values once model is solved + +nendog = size(Mbase_.endo_names,1); + +for i=1:nendog + eval([deblank(Mbase_.endo_names(i,:)) '_ss = oo_.dr.ys(i); ']); +end + +nparams = size(Mbase_.param_names); + +for i = 1:nparams + eval([Mbase_.param_names(i,:),'= M_.params(i);']); +end diff --git a/matlab/occbin/solve_no_constraint.m b/matlab/occbin/solve_no_constraint.m index d9671409d2..27af64f1ce 100755 --- a/matlab/occbin/solve_no_constraint.m +++ b/matlab/occbin/solve_no_constraint.m @@ -1,50 +1,49 @@ -function [zdata_, zdatass_, oobase_, Mbase_ ] = ... - solve_no_constraint(modnam,... - shockssequence,irfshock,nperiods) - -global M_ oo_ - -errlist = []; - -% solve model -eval(['dynare ',modnam,' noclearall']) -oobase_ = oo_; -Mbase_ = M_; - -ys_ = oobase_.dr.ys; -nvars = numel(ys_); -zdatass_ = ys_ ; - -for i=1:Mbase_.endo_nbr - eval([deblank(Mbase_.endo_names(i,:)) '_ss = oo_.dr.ys(i); ']); -end - -for i = 1:size(Mbase_.param_names) - eval([Mbase_.param_names(i,:),'= M_.params(i);']); -end - - - - - - - -[hm1,h,hl1,Jbarmat] = get_deriv(Mbase_,ys_); -cof = [hm1,h,hl1]; - -[decrulea,decruleb]=get_pq(oobase_.dr); -endog_ = M_.endo_names; -exog_ = M_.exo_names; - -nvars = numel(Mbase_.endo_nbr); - - -nshocks = size(shockssequence,1); -init = zeros(nvars,1); - -wishlist = endog_; -nwishes = size(wishlist,1); - - -zdata_ = mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,shockssequence); - +function [zdata_, zdatass_, oobase_, Mbase_ ] = ... + solve_no_constraint(modnam,... + shockssequence,irfshock,nperiods) + +global M_ oo_ + +errlist = []; + +% solve model +eval(['dynare ',modnam,' noclearall']) +oobase_ = oo_; +Mbase_ = M_; + +ys_ = oobase_.dr.ys; +nvars = numel(ys_); +zdatass_ = ys_ ; + +for i=1:Mbase_.endo_nbr + eval([deblank(Mbase_.endo_names(i,:)) '_ss = oo_.dr.ys(i); ']); +end + +for i = 1:size(Mbase_.param_names) + eval([Mbase_.param_names(i,:),'= M_.params(i);']); +end + + + + + + + +[hm1,h,hl1,Jbarmat] = get_deriv(Mbase_,ys_); +cof = [hm1,h,hl1]; + +[decrulea,decruleb]=get_pq(oobase_.dr); +endog_ = M_.endo_names; +exog_ = M_.exo_names; + +nvars = numel(Mbase_.endo_nbr); + + +nshocks = size(shockssequence,1); +init = zeros(nvars,1); + +wishlist = endog_; +nwishes = size(wishlist,1); + + +zdata_ = mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,shockssequence); diff --git a/matlab/occbin/solve_no_constraint_noclear.m b/matlab/occbin/solve_no_constraint_noclear.m index 0dab8c8165..8012f9126c 100755 --- a/matlab/occbin/solve_no_constraint_noclear.m +++ b/matlab/occbin/solve_no_constraint_noclear.m @@ -1,48 +1,47 @@ -function [zdata, oobase_, Mbase_ ] = ... - solve_no_constraint_noclear(modnam,... - shockssequence,irfshock,nperiods) - -global M_ oo_ - -errlist = []; - -% solve model -eval(['dynare ',modnam,' nolog']); -oobase_ = oo_; -Mbase_ = M_; - -ys_ = oobase_.dr.ys; - -for i=1:Mbase_.endo_nbr - eval([deblank(Mbase_.endo_names(i,:)) '_ss = oo_.dr.ys(i); ']); -end - -for i = 1:size(Mbase_.param_names) - eval([Mbase_.param_names(i,:),'= M_.params(i);']); -end - -setss - - - - - -[hm1,h,hl1,Jbarmat] = get_deriv(Mbase_,ys_); -cof = [hm1,h,hl1]; - -[decrulea,decruleb]=get_pq(oobase_.dr); -endog_ = M_.endo_names; -exog_ = M_.exo_names; - - -nvars = numel(Mbase_.endo_nbr); - -nshocks = size(shockssequence,1); -init = zeros(nvars,1); - -wishlist = endog_; -nwishes = size(wishlist,1); - - -zdata = mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,shockssequence); - +function [zdata, oobase_, Mbase_ ] = ... + solve_no_constraint_noclear(modnam,... + shockssequence,irfshock,nperiods) + +global M_ oo_ + +errlist = []; + +% solve model +eval(['dynare ',modnam,' nolog']); +oobase_ = oo_; +Mbase_ = M_; + +ys_ = oobase_.dr.ys; + +for i=1:Mbase_.endo_nbr + eval([deblank(Mbase_.endo_names(i,:)) '_ss = oo_.dr.ys(i); ']); +end + +for i = 1:size(Mbase_.param_names) + eval([Mbase_.param_names(i,:),'= M_.params(i);']); +end + +setss + + + + + +[hm1,h,hl1,Jbarmat] = get_deriv(Mbase_,ys_); +cof = [hm1,h,hl1]; + +[decrulea,decruleb]=get_pq(oobase_.dr); +endog_ = M_.endo_names; +exog_ = M_.exo_names; + + +nvars = numel(Mbase_.endo_nbr); + +nshocks = size(shockssequence,1); +init = zeros(nvars,1); + +wishlist = endog_; +nwishes = size(wishlist,1); + + +zdata = mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,shockssequence); diff --git a/matlab/occbin/solve_one_constraint.1.m b/matlab/occbin/solve_one_constraint.1.m index 34e296496b..aa155c234f 100755 --- a/matlab/occbin/solve_one_constraint.1.m +++ b/matlab/occbin/solve_one_constraint.1.m @@ -1,192 +1,192 @@ -% solve_one_constraint [zdatalinear zdatapiecewise zdatass oo base M base] = solve one constraint(modnam, modnamstar, constraint, constraint relax, shockssequence, irfshock, nperiods, maxiter, init); -% -% Inputs: -% modnam: name of .mod file for the reference regime (excludes the .mod extension). -% modnamstar: name of .mod file for the alternative regime (excludes the .mod exten- sion). -% constraint: the constraint (see notes 1 and 2 below). When the condition in constraint evaluates to true, the solution switches from the reference to the alternative regime. -% constraint relax: when the condition in constraint relax evaluates to true, the solution returns to the reference regime. -% shockssequence: a sequence of unforeseen shocks under which one wants to solve the model (size T�nshocks). -% irfshock: label for innovation for IRFs, from Dynare .mod file (one or more of the ?varexo?). -% nperiods: simulation horizon (can be longer than the sequence of shocks defined in shockssequence; must be long enough to ensure convergence back to the reference model at the end of the simulation horizon and may need to be varied depending on the sequence of shocks). -% maxiter: maximum number of iterations allowed for the solution algorithm (20 if not specified). -% init: the initial position for the vector of state variables, in deviation from steady state (if not specified, the default is steady state). The ordering follows the definition order in the .mod files. -% -% Outputs: -% zdatalinear: an array containing paths for all endogenous variables ignoring the occasionally binding constraint (the linear solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files. -% zdatapiecewise: an array containing paths for all endogenous variables satisfying the occasionally binding constraint (the occbin/piecewise solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files. -% zdatass: theinitialpositionforthevectorofstatevariables,indeviationfromsteady state (if not specified, the default is a vectors of zero implying that the initial conditions coincide with the steady state). The ordering follows the definition order in the .mod files. -% oobase,Mbase: structures produced by Dynare for the reference model ? see Dynare User Guide. - -% Log of changes: -% 6/17/2013 -- Luca added a trailing underscore to local variables in an -% attempt to avoid conflicts with parameter names defined in the .mod files -% to be processed. -% 6/17/2013 -- Luca replaced external .m file setss.m - - -function [zdatalinear_ zdatapiecewise_ zdatass_ oobase_ Mbase_ ] = ... - solve_one_constraint(modnam_,modnamstar_,... - constraint_, constraint_relax_,... - shockssequence_,irfshock_,nperiods_,maxiter_,init_) - -global M_ oo_ - -errlist_ = []; - -% solve the reference model linearly -eval(['dynare ',modnam_,' noclearall nolog ']) -oobase_ = oo_; -Mbase_ = M_; - -% import locally the values of parameters assigned in the reference .mod -% file -for i_indx_ = 1:Mbase_.param_nbr - eval([Mbase_.param_names(i_indx_,:),'= M_.params(i_indx_);']); -end - -% Create steady state values of the variables if needed for processing the constraint -for i=1:Mbase_.endo_nbr - eval([deblank(Mbase_.endo_names(i,:)) '_ss = oobase_.dr.ys(i); ']); -end - - -% parse the .mod file for the alternative regime -eval(['dynare ',modnamstar_,' noclearall nolog ']) -oostar_ = oo_; -Mstar_ = M_; - - -% check inputs -if ~strcmp(Mbase_.endo_names,Mstar_.endo_names) - error('The two .mod files need to have exactly the same endogenous variables declared in the same order') -end - -if ~strcmp(Mbase_.exo_names,Mstar_.exo_names) - error('The two .mod files need to have exactly the same exogenous variables declared in the same order') -end - -if ~strcmp(Mbase_.param_names,Mstar_.param_names) - warning('The parameter list does not match across .mod files') -end - -% ensure that the two models have the same parameters -% use the parameters for the base model. -Mstar_.params = Mbase_.params; - -nvars_ = Mbase_.endo_nbr; -zdatass_ = oobase_.dr.ys; - - -% get the matrices holding the first derivatives for the model -% each regime is treated separately -[hm1_,h_,hl1_,Jbarmat_] = get_deriv(Mbase_,zdatass_); -cof_ = [hm1_,h_,hl1_]; - -[hm1_,h_,hl1_,Jstarbarmat_,resid_] = get_deriv(Mstar_,zdatass_); -cofstar_ = [hm1_,h_,hl1_]; -Dstartbarmat_ = resid_; - -[decrulea_,decruleb_]=get_pq(oobase_.dr); -endog_ = M_.endo_names; -exog_ = M_.exo_names; - - -% processes the constraints specified in the call to this function -% uppend a suffix to each endogenous variable -constraint_difference_ = process_constraint(constraint_,'_difference',Mbase_.endo_names,0); - -constraint_relax_difference_ = process_constraint(constraint_relax_,'_difference',Mbase_.endo_names,0); - - - -nshocks_ = size(shockssequence_,1); - -% if necessary, set default values for optional arguments -if ~exist('init_') - init_ = zeros(nvars_,1); -end - -if ~exist('maxiter_') - maxiter_ = 20; -end - -if ~exist('nperiods_') - nperiods_ = 100; -end - - -% set some initial conditions and loop through the shocks -% period by period -init_orig_ = init_; -zdatapiecewise_ = zeros(nperiods_,nvars_); -wishlist_ = endog_; -nwishes_ = size(wishlist_,1); -violvecbool_ = zeros(nperiods_+1,1); - - -for ishock_ = 1:nshocks_ - - changes_=1; - iter_ = 0; - - - while (changes_ & iter_<maxiter_) - iter_ = iter_ +1; - - % analyze when each regime starts based on current guess - [regime regimestart]=map_regime(violvecbool_); - - - % get the hypothesized piece wise linear solution - [zdatalinear_]=mkdatap_anticipated(nperiods_,decrulea_,decruleb_,... - cof_,Jbarmat_,cofstar_,Jstarbarmat_,Dstartbarmat_,... - regime,regimestart,violvecbool_,... - endog_,exog_,irfshock_,shockssequence_(ishock_,:),init_); - - for i_indx_=1:nwishes_ - eval([deblank(wishlist_(i_indx_,:)),'_difference=zdatalinear_(:,i_indx_);']); - end - - - - newviolvecbool_ = eval(constraint_difference_); - relaxconstraint_ = eval(constraint_relax_difference_); - - - - % check if changes to the hypothesis of the duration for each - % regime - if (max(newviolvecbool_-violvecbool_>0)) | sum(relaxconstraint_(find(violvecbool_==1))>0) - changes_ = 1; - else - changes_ = 0; - end - - - violvecbool_ = (violvecbool_|newviolvecbool_)-(relaxconstraint_ & violvecbool_); - - - end - - init_ = zdatalinear_(1,:); - zdatapiecewise_(ishock_,:)=init_; - init_= init_'; - - % reset violvecbool_ for next period's shock -- this resetting is - % consistent with expecting no additional shocks - violvecbool_=[violvecbool_(2:end);0]; - -end - -% if necessary, fill in the rest of the path with the remainder of the -% last IRF computed. -zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:); - -% get the linear responses -zdatalinear_ = mkdata(max(nperiods_,size(shockssequence_,1)),... - decrulea_,decruleb_,endog_,exog_,... - wishlist_,irfshock_,shockssequence_,init_orig_); - -if changes_ ==1 - display('Did not converge -- increase maxiter_') -end +% solve_one_constraint [zdatalinear zdatapiecewise zdatass oo base M base] = solve one constraint(modnam, modnamstar, constraint, constraint relax, shockssequence, irfshock, nperiods, maxiter, init); +% +% Inputs: +% modnam: name of .mod file for the reference regime (excludes the .mod extension). +% modnamstar: name of .mod file for the alternative regime (excludes the .mod exten- sion). +% constraint: the constraint (see notes 1 and 2 below). When the condition in constraint evaluates to true, the solution switches from the reference to the alternative regime. +% constraint relax: when the condition in constraint relax evaluates to true, the solution returns to the reference regime. +% shockssequence: a sequence of unforeseen shocks under which one wants to solve the model (size T×nshocks). +% irfshock: label for innovation for IRFs, from Dynare .mod file (one or more of the ?varexo?). +% nperiods: simulation horizon (can be longer than the sequence of shocks defined in shockssequence; must be long enough to ensure convergence back to the reference model at the end of the simulation horizon and may need to be varied depending on the sequence of shocks). +% maxiter: maximum number of iterations allowed for the solution algorithm (20 if not specified). +% init: the initial position for the vector of state variables, in deviation from steady state (if not specified, the default is steady state). The ordering follows the definition order in the .mod files. +% +% Outputs: +% zdatalinear: an array containing paths for all endogenous variables ignoring the occasionally binding constraint (the linear solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files. +% zdatapiecewise: an array containing paths for all endogenous variables satisfying the occasionally binding constraint (the occbin/piecewise solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files. +% zdatass: theinitialpositionforthevectorofstatevariables,indeviationfromsteady state (if not specified, the default is a vectors of zero implying that the initial conditions coincide with the steady state). The ordering follows the definition order in the .mod files. +% oobase,Mbase: structures produced by Dynare for the reference model ? see Dynare User Guide. + +% Log of changes: +% 6/17/2013 -- Luca added a trailing underscore to local variables in an +% attempt to avoid conflicts with parameter names defined in the .mod files +% to be processed. +% 6/17/2013 -- Luca replaced external .m file setss.m + + +function [zdatalinear_ zdatapiecewise_ zdatass_ oobase_ Mbase_ ] = ... + solve_one_constraint.1(modnam_,modnamstar_,... + constraint_, constraint_relax_,... + shockssequence_,irfshock_,nperiods_,maxiter_,init_) + +global M_ oo_ + +errlist_ = []; + +% solve the reference model linearly +eval(['dynare ',modnam_,' noclearall nolog ']) +oobase_ = oo_; +Mbase_ = M_; + +% import locally the values of parameters assigned in the reference .mod +% file +for i_indx_ = 1:Mbase_.param_nbr + eval([Mbase_.param_names(i_indx_,:),'= M_.params(i_indx_);']); +end + +% Create steady state values of the variables if needed for processing the constraint +for i=1:Mbase_.endo_nbr + eval([deblank(Mbase_.endo_names(i,:)) '_ss = oobase_.dr.ys(i); ']); +end + + +% parse the .mod file for the alternative regime +eval(['dynare ',modnamstar_,' noclearall nolog ']) +oostar_ = oo_; +Mstar_ = M_; + + +% check inputs +if ~strcmp(Mbase_.endo_names,Mstar_.endo_names) + error('The two .mod files need to have exactly the same endogenous variables declared in the same order') +end + +if ~strcmp(Mbase_.exo_names,Mstar_.exo_names) + error('The two .mod files need to have exactly the same exogenous variables declared in the same order') +end + +if ~strcmp(Mbase_.param_names,Mstar_.param_names) + warning('The parameter list does not match across .mod files') +end + +% ensure that the two models have the same parameters +% use the parameters for the base model. +Mstar_.params = Mbase_.params; + +nvars_ = Mbase_.endo_nbr; +zdatass_ = oobase_.dr.ys; + + +% get the matrices holding the first derivatives for the model +% each regime is treated separately +[hm1_,h_,hl1_,Jbarmat_] = get_deriv(Mbase_,zdatass_); +cof_ = [hm1_,h_,hl1_]; + +[hm1_,h_,hl1_,Jstarbarmat_,resid_] = get_deriv(Mstar_,zdatass_); +cofstar_ = [hm1_,h_,hl1_]; +Dstartbarmat_ = resid_; + +[decrulea_,decruleb_]=get_pq(oobase_.dr); +endog_ = M_.endo_names; +exog_ = M_.exo_names; + + +% processes the constraints specified in the call to this function +% uppend a suffix to each endogenous variable +constraint_difference_ = process_constraint(constraint_,'_difference',Mbase_.endo_names,0); + +constraint_relax_difference_ = process_constraint(constraint_relax_,'_difference',Mbase_.endo_names,0); + + + +nshocks_ = size(shockssequence_,1); + +% if necessary, set default values for optional arguments +if ~exist('init_') + init_ = zeros(nvars_,1); +end + +if ~exist('maxiter_') + maxiter_ = 20; +end + +if ~exist('nperiods_') + nperiods_ = 100; +end + + +% set some initial conditions and loop through the shocks +% period by period +init_orig_ = init_; +zdatapiecewise_ = zeros(nperiods_,nvars_); +wishlist_ = endog_; +nwishes_ = size(wishlist_,1); +violvecbool_ = zeros(nperiods_+1,1); + + +for ishock_ = 1:nshocks_ + + changes_=1; + iter_ = 0; + + + while (changes_ & iter_<maxiter_) + iter_ = iter_ +1; + + % analyze when each regime starts based on current guess + [regime regimestart]=map_regime(violvecbool_); + + + % get the hypothesized piece wise linear solution + [zdatalinear_]=mkdatap_anticipated(nperiods_,decrulea_,decruleb_,... + cof_,Jbarmat_,cofstar_,Jstarbarmat_,Dstartbarmat_,... + regime,regimestart,violvecbool_,... + endog_,exog_,irfshock_,shockssequence_(ishock_,:),init_); + + for i_indx_=1:nwishes_ + eval([deblank(wishlist_(i_indx_,:)),'_difference=zdatalinear_(:,i_indx_);']); + end + + + + newviolvecbool_ = eval(constraint_difference_); + relaxconstraint_ = eval(constraint_relax_difference_); + + + + % check if changes to the hypothesis of the duration for each + % regime + if (max(newviolvecbool_-violvecbool_>0)) | sum(relaxconstraint_(find(violvecbool_==1))>0) + changes_ = 1; + else + changes_ = 0; + end + + + violvecbool_ = (violvecbool_|newviolvecbool_)-(relaxconstraint_ & violvecbool_); + + + end + + init_ = zdatalinear_(1,:); + zdatapiecewise_(ishock_,:)=init_; + init_= init_'; + + % reset violvecbool_ for next period's shock -- this resetting is + % consistent with expecting no additional shocks + violvecbool_=[violvecbool_(2:end);0]; + +end + +% if necessary, fill in the rest of the path with the remainder of the +% last IRF computed. +zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:); + +% get the linear responses +zdatalinear_ = mkdata(max(nperiods_,size(shockssequence_,1)),... + decrulea_,decruleb_,endog_,exog_,... + wishlist_,irfshock_,shockssequence_,init_orig_); + +if changes_ ==1 + display('Did not converge -- increase maxiter_') +end diff --git a/matlab/occbin/solve_one_constraint.m b/matlab/occbin/solve_one_constraint.m index c8a7c2494d..5959636bf7 100755 --- a/matlab/occbin/solve_one_constraint.m +++ b/matlab/occbin/solve_one_constraint.m @@ -1,200 +1,200 @@ -% solve_one_constraint [zdatalinear zdatapiecewise zdatass oo base M base] = solve one constraint(modnam, modnamstar, constraint, constraint relax, shockssequence, irfshock, nperiods, maxiter, init); -% -% Inputs: -% modnam: name of .mod file for the reference regime (excludes the .mod extension). -% modnamstar: name of .mod file for the alternative regime (excludes the .mod exten- sion). -% constraint: the constraint (see notes 1 and 2 below). When the condition in constraint evaluates to true, the solution switches from the reference to the alternative regime. -% constraint relax: when the condition in constraint relax evaluates to true, the solution returns to the reference regime. -% shockssequence: a sequence of unforeseen shocks under which one wants to solve the model (size T�nshocks). -% irfshock: label for innovation for IRFs, from Dynare .mod file (one or more of the ?varexo?). -% nperiods: simulation horizon (can be longer than the sequence of shocks defined in shockssequence; must be long enough to ensure convergence back to the reference model at the end of the simulation horizon and may need to be varied depending on the sequence of shocks). -% maxiter: maximum number of iterations allowed for the solution algorithm (20 if not specified). -% init: the initial position for the vector of state variables, in deviation from steady state (if not specified, the default is steady state). The ordering follows the definition order in the .mod files. -% -% Outputs: -% zdatalinear: an array containing paths for all endogenous variables ignoring the occasionally binding constraint (the linear solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files. -% zdatapiecewise: an array containing paths for all endogenous variables satisfying the occasionally binding constraint (the occbin/piecewise solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files. -% zdatass: theinitialpositionforthevectorofstatevariables,indeviationfromsteady state (if not specified, the default is a vectors of zero implying that the initial conditions coincide with the steady state). The ordering follows the definition order in the .mod files. -% oobase,Mbase: structures produced by Dynare for the reference model ? see Dynare User Guide. - -% Log of changes: -% 6/17/2013 -- Luca added a trailing underscore to local variables in an -% attempt to avoid conflicts with parameter names defined in the .mod files -% to be processed. -% 6/17/2013 -- Luca replaced external .m file setss.m - - -function [zdatalinear_, zdatapiecewise_, zdatass_, oobase_, Mbase_ ] = ... - solve_one_constraint(modnam_,modnamstar_,... - constraint_, constraint_relax_,... - shockssequence_,irfshock_,nperiods_,maxiter_,init_) - -global M_ oo_ - -errlist_ = []; - -% solve the reference model linearly -eval(['dynare ',modnam_,' noclearall nolog ']) -oobase_ = oo_; -Mbase_ = M_; - -% import locally the values of parameters assigned in the reference .mod -% file -for i_indx_ = 1:Mbase_.param_nbr - eval([Mbase_.param_names(i_indx_,:),'= M_.params(i_indx_);']); -end - -% Create steady state values of the variables if needed for processing the constraint -for i=1:Mbase_.endo_nbr - eval([deblank(Mbase_.endo_names(i,:)) '_ss = oobase_.dr.ys(i); ']); -end - - -% parse the .mod file for the alternative regime -eval(['dynare ',modnamstar_,' noclearall nolog ']) -oostar_ = oo_; -Mstar_ = M_; - - -% check inputs -if ~strcmp(Mbase_.endo_names,Mstar_.endo_names) - error('The two .mod files need to have exactly the same endogenous variables declared in the same order') -end - -if ~strcmp(Mbase_.exo_names,Mstar_.exo_names) - error('The two .mod files need to have exactly the same exogenous variables declared in the same order') -end - -if ~strcmp(Mbase_.param_names,Mstar_.param_names) - warning('The parameter list does not match across .mod files') -end - -% ensure that the two models have the same parameters -% use the parameters for the base model. -Mstar_.params = Mbase_.params; - -nvars_ = Mbase_.endo_nbr; -zdatass_ = oobase_.dr.ys; - - -% get the matrices holding the first derivatives for the model -% each regime is treated separately -[hm1_,h_,hl1_,Jbarmat_] = get_deriv(Mbase_,zdatass_); -cof_ = [hm1_,h_,hl1_]; - -[hm1_,h_,hl1_,Jstarbarmat_,resid_] = get_deriv(Mstar_,zdatass_); -cofstar_ = [hm1_,h_,hl1_]; -Dstartbarmat_ = resid_; - -if isfield(Mbase_,'nfwrd') - % the latest Dynare distributions have moved nstatic and nfwrd - [decrulea_,decruleb_]=get_pq(oobase_.dr,Mbase_.nstatic,Mbase_.nfwrd); -else - [decrulea_,decruleb_]=get_pq(oobase_.dr,oobase_.dr.nstatic,oobase_.dr.nfwrd); -end - -endog_ = M_.endo_names; -exog_ = M_.exo_names; - - -% processes the constraints specified in the call to this function -% uppend a suffix to each endogenous variable -constraint_difference_ = process_constraint(constraint_,'_difference',Mbase_.endo_names,0); - -constraint_relax_difference_ = process_constraint(constraint_relax_,'_difference',Mbase_.endo_names,0); - - - -nshocks_ = size(shockssequence_,1); - -% if necessary, set default values for optional arguments -if ~exist('init_') - init_ = zeros(nvars_,1); -end - -if ~exist('maxiter_') - maxiter_ = 20; -end - -if ~exist('nperiods_') - nperiods_ = 100; -end - - -% set some initial conditions and loop through the shocks -% period by period -init_orig_ = init_; -zdatapiecewise_ = zeros(nperiods_,nvars_); -wishlist_ = endog_; -nwishes_ = size(wishlist_,1); -violvecbool_ = zeros(nperiods_+1,1); - - -for ishock_ = 1:nshocks_ - - changes_=1; - iter_ = 0; - - - while (changes_ & iter_<maxiter_) - iter_ = iter_ +1; - - % analyze when each regime starts based on current guess - [regime, regimestart]=map_regime(violvecbool_); - - - - % get the hypothesized piece wise linear solution - [zdatalinear_]=mkdatap_anticipated(nperiods_,decrulea_,decruleb_,... - cof_,Jbarmat_,cofstar_,Jstarbarmat_,Dstartbarmat_,... - regime,regimestart,violvecbool_,... - endog_,exog_,irfshock_,shockssequence_(ishock_,:),init_); - - for i_indx_=1:nwishes_ - eval([deblank(wishlist_(i_indx_,:)),'_difference=zdatalinear_(:,i_indx_);']); - end - - - - newviolvecbool_ = eval(constraint_difference_); - relaxconstraint_ = eval(constraint_relax_difference_); - - - - % check if changes to the hypothesis of the duration for each - % regime - if (max(newviolvecbool_-violvecbool_>0)) | sum(relaxconstraint_(find(violvecbool_==1))>0) - changes_ = 1; - else - changes_ = 0; - end - - - - violvecbool_ = (violvecbool_|newviolvecbool_)-(relaxconstraint_ & violvecbool_); - - - end - - init_ = zdatalinear_(1,:); - zdatapiecewise_(ishock_,:)=init_; - init_= init_'; - - % reset violvecbool_ for next period's shock -- this resetting is - % consistent with expecting no additional shocks - violvecbool_=[violvecbool_(2:end);0]; - -end - -% if necessary, fill in the rest of the path with the remainder of the -% last IRF computed. -zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:); - -% get the linear responses -zdatalinear_ = mkdata(max(nperiods_,size(shockssequence_,1)),... - decrulea_,decruleb_,endog_,exog_,... - wishlist_,irfshock_,shockssequence_,init_orig_); - -if changes_ ==1 - display('Did not converge -- increase maxiter_') -end +% solve_one_constraint [zdatalinear zdatapiecewise zdatass oo base M base] = solve one constraint(modnam, modnamstar, constraint, constraint relax, shockssequence, irfshock, nperiods, maxiter, init); +% +% Inputs: +% modnam: name of .mod file for the reference regime (excludes the .mod extension). +% modnamstar: name of .mod file for the alternative regime (excludes the .mod exten- sion). +% constraint: the constraint (see notes 1 and 2 below). When the condition in constraint evaluates to true, the solution switches from the reference to the alternative regime. +% constraint relax: when the condition in constraint relax evaluates to true, the solution returns to the reference regime. +% shockssequence: a sequence of unforeseen shocks under which one wants to solve the model (size T×nshocks). +% irfshock: label for innovation for IRFs, from Dynare .mod file (one or more of the ?varexo?). +% nperiods: simulation horizon (can be longer than the sequence of shocks defined in shockssequence; must be long enough to ensure convergence back to the reference model at the end of the simulation horizon and may need to be varied depending on the sequence of shocks). +% maxiter: maximum number of iterations allowed for the solution algorithm (20 if not specified). +% init: the initial position for the vector of state variables, in deviation from steady state (if not specified, the default is steady state). The ordering follows the definition order in the .mod files. +% +% Outputs: +% zdatalinear: an array containing paths for all endogenous variables ignoring the occasionally binding constraint (the linear solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files. +% zdatapiecewise: an array containing paths for all endogenous variables satisfying the occasionally binding constraint (the occbin/piecewise solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files. +% zdatass: theinitialpositionforthevectorofstatevariables,indeviationfromsteady state (if not specified, the default is a vectors of zero implying that the initial conditions coincide with the steady state). The ordering follows the definition order in the .mod files. +% oobase,Mbase: structures produced by Dynare for the reference model ? see Dynare User Guide. + +% Log of changes: +% 6/17/2013 -- Luca added a trailing underscore to local variables in an +% attempt to avoid conflicts with parameter names defined in the .mod files +% to be processed. +% 6/17/2013 -- Luca replaced external .m file setss.m + + +function [zdatalinear_, zdatapiecewise_, zdatass_, oobase_, Mbase_ ] = ... + solve_one_constraint(modnam_,modnamstar_,... + constraint_, constraint_relax_,... + shockssequence_,irfshock_,nperiods_,maxiter_,init_) + +global M_ oo_ + +errlist_ = []; + +% solve the reference model linearly +eval(['dynare ',modnam_,' noclearall nolog ']) +oobase_ = oo_; +Mbase_ = M_; + +% import locally the values of parameters assigned in the reference .mod +% file +for i_indx_ = 1:Mbase_.param_nbr + eval([Mbase_.param_names(i_indx_,:),'= M_.params(i_indx_);']); +end + +% Create steady state values of the variables if needed for processing the constraint +for i=1:Mbase_.endo_nbr + eval([deblank(Mbase_.endo_names(i,:)) '_ss = oobase_.dr.ys(i); ']); +end + + +% parse the .mod file for the alternative regime +eval(['dynare ',modnamstar_,' noclearall nolog ']) +oostar_ = oo_; +Mstar_ = M_; + + +% check inputs +if ~strcmp(Mbase_.endo_names,Mstar_.endo_names) + error('The two .mod files need to have exactly the same endogenous variables declared in the same order') +end + +if ~strcmp(Mbase_.exo_names,Mstar_.exo_names) + error('The two .mod files need to have exactly the same exogenous variables declared in the same order') +end + +if ~strcmp(Mbase_.param_names,Mstar_.param_names) + warning('The parameter list does not match across .mod files') +end + +% ensure that the two models have the same parameters +% use the parameters for the base model. +Mstar_.params = Mbase_.params; + +nvars_ = Mbase_.endo_nbr; +zdatass_ = oobase_.dr.ys; + + +% get the matrices holding the first derivatives for the model +% each regime is treated separately +[hm1_,h_,hl1_,Jbarmat_] = get_deriv(Mbase_,zdatass_); +cof_ = [hm1_,h_,hl1_]; + +[hm1_,h_,hl1_,Jstarbarmat_,resid_] = get_deriv(Mstar_,zdatass_); +cofstar_ = [hm1_,h_,hl1_]; +Dstartbarmat_ = resid_; + +if isfield(Mbase_,'nfwrd') + % the latest Dynare distributions have moved nstatic and nfwrd + [decrulea_,decruleb_]=get_pq(oobase_.dr,Mbase_.nstatic,Mbase_.nfwrd); +else + [decrulea_,decruleb_]=get_pq(oobase_.dr,oobase_.dr.nstatic,oobase_.dr.nfwrd); +end + +endog_ = M_.endo_names; +exog_ = M_.exo_names; + + +% processes the constraints specified in the call to this function +% uppend a suffix to each endogenous variable +constraint_difference_ = process_constraint(constraint_,'_difference',Mbase_.endo_names,0); + +constraint_relax_difference_ = process_constraint(constraint_relax_,'_difference',Mbase_.endo_names,0); + + + +nshocks_ = size(shockssequence_,1); + +% if necessary, set default values for optional arguments +if ~exist('init_') + init_ = zeros(nvars_,1); +end + +if ~exist('maxiter_') + maxiter_ = 20; +end + +if ~exist('nperiods_') + nperiods_ = 100; +end + + +% set some initial conditions and loop through the shocks +% period by period +init_orig_ = init_; +zdatapiecewise_ = zeros(nperiods_,nvars_); +wishlist_ = endog_; +nwishes_ = size(wishlist_,1); +violvecbool_ = zeros(nperiods_+1,1); + + +for ishock_ = 1:nshocks_ + + changes_=1; + iter_ = 0; + + + while (changes_ & iter_<maxiter_) + iter_ = iter_ +1; + + % analyze when each regime starts based on current guess + [regime, regimestart]=map_regime(violvecbool_); + + + + % get the hypothesized piece wise linear solution + [zdatalinear_]=mkdatap_anticipated(nperiods_,decrulea_,decruleb_,... + cof_,Jbarmat_,cofstar_,Jstarbarmat_,Dstartbarmat_,... + regime,regimestart,violvecbool_,... + endog_,exog_,irfshock_,shockssequence_(ishock_,:),init_); + + for i_indx_=1:nwishes_ + eval([deblank(wishlist_(i_indx_,:)),'_difference=zdatalinear_(:,i_indx_);']); + end + + + + newviolvecbool_ = eval(constraint_difference_); + relaxconstraint_ = eval(constraint_relax_difference_); + + + + % check if changes to the hypothesis of the duration for each + % regime + if (max(newviolvecbool_-violvecbool_>0)) | sum(relaxconstraint_(find(violvecbool_==1))>0) + changes_ = 1; + else + changes_ = 0; + end + + + + violvecbool_ = (violvecbool_|newviolvecbool_)-(relaxconstraint_ & violvecbool_); + + + end + + init_ = zdatalinear_(1,:); + zdatapiecewise_(ishock_,:)=init_; + init_= init_'; + + % reset violvecbool_ for next period's shock -- this resetting is + % consistent with expecting no additional shocks + violvecbool_=[violvecbool_(2:end);0]; + +end + +% if necessary, fill in the rest of the path with the remainder of the +% last IRF computed. +zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:); + +% get the linear responses +zdatalinear_ = mkdata(max(nperiods_,size(shockssequence_,1)),... + decrulea_,decruleb_,endog_,exog_,... + wishlist_,irfshock_,shockssequence_,init_orig_); + +if changes_ ==1 + display('Did not converge -- increase maxiter_') +end diff --git a/matlab/occbin/solve_two_constraints.m b/matlab/occbin/solve_two_constraints.m index ff5f734edd..1b436ad00f 100755 --- a/matlab/occbin/solve_two_constraints.m +++ b/matlab/occbin/solve_two_constraints.m @@ -1,305 +1,304 @@ -% [zdatalinear zdatapiecewise zdatass oo 00 M 00] = solve two constraints(modnam 00,modnam 10,modnam 01,modnam 11,... constraint1, constraint2,... constraint relax1, constraint relax2,... shockssequence,irfshock,nperiods,curb retrench,maxiter,init); -% -% Inputs: -% modnam 00: name of the .mod file for reference regime (excludes the .mod extension). modnam10: name of the .mod file for the alternative regime governed by the first -% constraint. -% modnam01: name of the .mod file for the alternative regime governed by the second constraint. -% modnam 11: name of the .mod file for the case in which both constraints force a switch to their alternative regimes. -% constraint1: the first constraint (see notes 1 and 2 below). If constraint1 evaluates to true, then the solution switches to the alternative regime for condition 1. In thatcase, if constraint2 (described below) evaluates to false, then the model solution switches to enforcing the conditions for an equilibrium in modnam 10. Otherwise, if constraint2 also evaluates to true, then the model solution switches to enforcing the conditions for an equilibrium in modnam 11. -% constraint relax1: when the condition in constraint relax1 evaluates to true, the solution returns to the reference regime for constraint1. -% constraint2: the second constraint (see notes 1 and 2 below). constraint relax2: when the condition in constraint relax2 evaluates to true, the -% solution returns to the reference regime for constraint2. shockssequence: a sequence of unforeseen shocks under which one wants to solve the -% model -% irfshock: label for innovation for IRFs, from Dynare .mod file (one or more of the ?varexo?) -% nperiods: simulation horizon (can be longer than the sequence of shocks defined in shockssequence; must be long enough to ensure convergence back to the reference model at the end of the simulation horizon and may need to be varied depending on the sequence of shocks). -% curb retrench: a scalar equal to 0 or 1. Default is 0. When set to 0, it updates the guess based of regimes based on the previous iteration. When set to 1, it updates in a manner similar to a Gauss-Jacobi scheme, slowing the iterations down by updating the guess of regimes only one period at a time. -% maxiter: maximum number of iterations allowed for the solution algorithm (20 if not specified). -% init: the initial position for the vector of state variables, in deviation from steady state (if not specified, the default is a vector of zero implying that the initial conditions coincide with the steady state). The ordering follows the definition order in the .mod files. -% -% Outputs: -% zdatalinear: an array containing paths for all endogenous variables ignoring the occasionally binding constraint (the linear solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files. -% zdatapiecewise: an array containing paths for all endogenous variables satisfying the occasionally binding constraint (the occbin/piecewise solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files. -% zdatass: a vector that holds the steady state values of the endogenous variables ( following the definition order in the .mod file). -% oo00 , M00 : structures produced by Dynare for the reference model ? see Dynare User Guide. - - -% Log of changes -% 6/17/2013 -- Luca added a trailing underscore to local variables in an -% attempt to avoid conflicts with parameter names defined in the .mod files -% to be processed. -% 6/17/2013 -- Luca replaced external .m file setss.m - -function [ zdatalinear_, zdatapiecewise_, zdatass_, oo00_ , M00_ ] = ... - solve_two_constraints(modnam_00_,modnam_10_,modnam_01_,modnam_11_,... - constrain1_, constrain2_,... - constraint_relax1_, constraint_relax2_,... - shockssequence_,irfshock_,nperiods_,curb_retrench_,maxiter_,init_) - -global M_ oo_ - - - -% solve model -eval(['dynare ',modnam_00_,' noclearall nolog']) -oo00_ = oo_; -M00_ = M_; - - -for i=1:M00_.endo_nbr - eval([deblank(M00_.endo_names(i,:)) '_ss = oo00_.dr.ys(i); ']); -end - -for i_indx_ = 1:M00_.param_nbr - eval([M00_.param_names(i_indx_,:),'= M00_.params(i_indx_);']); -end - - - -eval(['dynare ',modnam_10_,' noclearall']) -oo10_ = oo_; -M10_ = M_; - -eval(['dynare ',modnam_01_,' noclearall']) -oo01_ = oo_; -M01_ = M_; - -eval(['dynare ',modnam_11_,' noclearall']) -oo11_ = oo_; -M11_ = M_; - - -% do some error checking - -% check inputs -if ~strcmp(M00_.endo_names,M10_.endo_names) - error([modnam_00_,' and ',modnam_10_,' need to have exactly the same endogenous variables and they need to be declared in the same order']) -end - -if ~strcmp(M00_.exo_names,M10_.exo_names) - error([modnam_00_,' and ',modnam_10_,' need to have exactly the same exogenous variables and they need to be declared in the same order']) -end - -if ~strcmp(M00_.param_names,M10_.param_names) - warning(['The parameter list does not match across the files ',modnam_00_,' and ',modnam_10_]) -end - - -if ~strcmp(M00_.endo_names,M01_.endo_names) - error([modnam_00,' and ',modnam_01_,' need to have exactly the same endogenous variables and they need to be declared in the same order']) -end - -if ~strcmp(M00_.exo_names,M01_.exo_names) - error([modnam_00_,' and ',modnam_01_,' need to have exactly the same exogenous variables and they need to be declared in the same order']) -end - -if ~strcmp(M00_.param_names,M01_.param_names) - warning(['The parameter list does not match across the files ',modnam_00_,' and ',modnam_01_]) -end - - -if ~strcmp(M00_.endo_names,M11_.endo_names) - error([modnam_00_,' and ',modnam_11_,' need to have exactly the same endogenous variables and they need to be declared in the same order']) -end - -if ~strcmp(M00_.exo_names,M11_.exo_names) - error([modnam_00_,' and ',modnam_11_,' need to have exactly the same exogenous variables and they need to be declared in the same order']) -end - -if ~strcmp(M00_.param_names,M11_.param_names) - warning(['The parameter list does not match across the files ',modnam_00_,' and ',modnam_11_]) -end - - - - - -nvars_ = M00_.endo_nbr; -zdatass_ = oo00_.dr.ys; - - -[hm1_,h_,hl1_,Jbarmat_] = get_deriv(M00_,zdatass_); -cof_ = [hm1_,h_,hl1_]; - - -M10_.params = M00_.params; -[hm1_,h_,hl1_,Jbarmat10_,resid_] = get_deriv(M10_,zdatass_); -cof10_ = [hm1_,h_,hl1_]; -Dbarmat10_ = resid_; - -M01_.params = M00_.params; -[hm1_,h_,hl1_,Jbarmat01_,resid_] = get_deriv(M01_,zdatass_); -cof01_ = [hm1_,h_,hl1_]; -Dbarmat01_ = resid_; - -M11_.params = M00_.params; -[hm1_,h_,hl1_,Jbarmat11_,resid_] = get_deriv(M11_,zdatass_); -cof11_ = [hm1_,h_,hl1_]; -Dbarmat11_ = resid_; - - -if isfield(M00_,'nfwrd') % needed for bakward compatibility with older Dynare releases -[decrulea,decruleb]=get_pq(oo00_.dr,M00_.nstatic,M00_.nfwrd); -else -[decrulea,decruleb]=get_pq(oo00_.dr,oo00_.dr.nstatic,oo00_.dr.nfwrd); -end -endog_ = M00_.endo_names; -exog_ = M00_.exo_names; - - -% processes the constrain so as to uppend a suffix to each -% endogenous variables -constraint1_difference_ = process_constraint(constrain1_,'_difference',M00_.endo_names,0); - -% when the last argument in process_constraint is set to 1, the -% direction of the inequality in the constraint is inverted -constraint_relax1_difference_ = process_constraint(constraint_relax1_,'_difference',M00_.endo_names,0); - - -% processes the constrain so as to uppend a suffix to each -% endogenous variables -constraint2_difference_ = process_constraint(constrain2_,'_difference',M00_.endo_names,0); - -% when the last argument in process_constraint is set to 1, the -% direction of the inequality in the constraint is inverted -constraint_relax2_difference_ = process_constraint(constraint_relax2_,'_difference',M00_.endo_names,0); - - - -nshocks = size(shockssequence_,1); - - - - -if ~exist('init_') - init_ = zeros(nvars_,1); -end - -if ~exist('maxiter_') - maxiter_ = 20; -end - -if ~exist('curb_retrench_') - curb_retrench_ = 0; -end - -init_orig_ = init_; - - - - - - -zdatapiecewise_ = zeros(nperiods_,nvars_); - - -violvecbool_ = zeros(nperiods_+1,2); % This sets the first guess for when -% the constraints are going to hold. -% The variable is a boolean with two -% columns. The first column refers to -% constrain1_; the second to -% constrain2_. -% Each row is a period in time. -% If the boolean is true it indicates -% the relevant constraint is expected -% to evaluate to true. -% The default initial guess is -% consistent with the base model always -% holding -- equivalent to the linear -% solution. - -wishlist_ = endog_; -nwishes_ = size(wishlist_,1); -for ishock_ = 1:nshocks - - - changes_=1; - iter_ = 0; - - while (changes_ & iter_<maxiter_) - iter_ = iter_ +1; - - % analyse violvec and isolate contiguous periods in the other - % regime. - [regime1, regimestart1]=map_regime(violvecbool_(:,1)); - [regime2, regimestart2]=map_regime(violvecbool_(:,2)); - - - [zdatalinear_]=mkdatap_anticipated_2constraints(nperiods_,decrulea,decruleb,... - cof_,Jbarmat_,... - cof10_,Jbarmat10_,Dbarmat10_,... - cof01_,Jbarmat01_,Dbarmat01_,... - cof11_,Jbarmat11_,Dbarmat11_,... - regime1,regimestart1,... - regime2,regimestart2,... - violvecbool_,endog_,exog_,... - irfshock_,shockssequence_(ishock_,:),init_); - - for i_indx_=1:nwishes_ - eval([deblank(wishlist_(i_indx_,:)),'_difference=zdatalinear_(:,i_indx_);']); - end - - - - - newviolvecbool1_ = eval(constraint1_difference_); - relaxconstraint1_ = eval(constraint_relax1_difference_); - - newviolvecbool2_ = eval(constraint2_difference_); - relaxconstraint2_ = eval(constraint_relax2_difference_); - - - - newviolvecbool_ = [newviolvecbool1_;newviolvecbool2_]; - relaxconstraint_ = [relaxconstraint1_;relaxconstraint2_]; - - - - % check if changes_ - if (max(newviolvecbool_(:)-violvecbool_(:)>0)) | sum(relaxconstraint_(find(violvecbool_==1))>0) - changes_ = 1; - else - changes_ = 0; - end - - if curb_retrench_ % apply Gauss-Sidel idea of slowing down the change in the guess - % for the constraint -- only relax one - % period at a time starting from the last - % one when each of the constraints is true. - retrench = 0*violvecbool_(:); - if ~isempty(find(relaxconstraint1_ & violvecbool_(:,1))) - retrenchpos = max(find(relaxconstraint1_ & violvecbool_(:,1))); - retrench(retrenchpos) = 1; - end - if ~isempty(find(relaxconstraint2_ & violvecbool_(:,2))) - retrenchpos = max(find(relaxconstraint2_ & violvecbool_(:,2))); - retrench(retrenchpos+nperiods_+1) = 1; - end - violvecbool_ = (violvecbool_(:) | newviolvecbool_(:))-retrench(:); - else - violvecbool_ = (violvecbool_(:) | newviolvecbool_(:))-(relaxconstraint_(:) & violvecbool_(:)); - end - - violvecbool_ = reshape(violvecbool_,nperiods_+1,2); - - - - end - if changes_ ==1 - display('Did not converge -- increase maxiter') - end - - init_ = zdatalinear_(1,:); - zdatapiecewise_(ishock_,:)=init_; - init_= init_'; - - % update the guess for constraint violations for next period - % update is consistent with expecting no additional shocks next period - violvecbool_=[violvecbool_(2:end,:);zeros(1,2)]; - -end - - -zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:); - -zdatalinear_ = mkdata(nperiods_,decrulea,decruleb,endog_,exog_,wishlist_,irfshock_,shockssequence_,init_orig_); - +% [zdatalinear zdatapiecewise zdatass oo 00 M 00] = solve two constraints(modnam 00,modnam 10,modnam 01,modnam 11,... constraint1, constraint2,... constraint relax1, constraint relax2,... shockssequence,irfshock,nperiods,curb retrench,maxiter,init); +% +% Inputs: +% modnam 00: name of the .mod file for reference regime (excludes the .mod extension). modnam10: name of the .mod file for the alternative regime governed by the first +% constraint. +% modnam01: name of the .mod file for the alternative regime governed by the second constraint. +% modnam 11: name of the .mod file for the case in which both constraints force a switch to their alternative regimes. +% constraint1: the first constraint (see notes 1 and 2 below). If constraint1 evaluates to true, then the solution switches to the alternative regime for condition 1. In thatcase, if constraint2 (described below) evaluates to false, then the model solution switches to enforcing the conditions for an equilibrium in modnam 10. Otherwise, if constraint2 also evaluates to true, then the model solution switches to enforcing the conditions for an equilibrium in modnam 11. +% constraint relax1: when the condition in constraint relax1 evaluates to true, the solution returns to the reference regime for constraint1. +% constraint2: the second constraint (see notes 1 and 2 below). constraint relax2: when the condition in constraint relax2 evaluates to true, the +% solution returns to the reference regime for constraint2. shockssequence: a sequence of unforeseen shocks under which one wants to solve the +% model +% irfshock: label for innovation for IRFs, from Dynare .mod file (one or more of the ?varexo?) +% nperiods: simulation horizon (can be longer than the sequence of shocks defined in shockssequence; must be long enough to ensure convergence back to the reference model at the end of the simulation horizon and may need to be varied depending on the sequence of shocks). +% curb retrench: a scalar equal to 0 or 1. Default is 0. When set to 0, it updates the guess based of regimes based on the previous iteration. When set to 1, it updates in a manner similar to a Gauss-Jacobi scheme, slowing the iterations down by updating the guess of regimes only one period at a time. +% maxiter: maximum number of iterations allowed for the solution algorithm (20 if not specified). +% init: the initial position for the vector of state variables, in deviation from steady state (if not specified, the default is a vector of zero implying that the initial conditions coincide with the steady state). The ordering follows the definition order in the .mod files. +% +% Outputs: +% zdatalinear: an array containing paths for all endogenous variables ignoring the occasionally binding constraint (the linear solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files. +% zdatapiecewise: an array containing paths for all endogenous variables satisfying the occasionally binding constraint (the occbin/piecewise solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files. +% zdatass: a vector that holds the steady state values of the endogenous variables ( following the definition order in the .mod file). +% oo00 , M00 : structures produced by Dynare for the reference model ? see Dynare User Guide. + + +% Log of changes +% 6/17/2013 -- Luca added a trailing underscore to local variables in an +% attempt to avoid conflicts with parameter names defined in the .mod files +% to be processed. +% 6/17/2013 -- Luca replaced external .m file setss.m + +function [ zdatalinear_, zdatapiecewise_, zdatass_, oo00_ , M00_ ] = ... + solve_two_constraints(modnam_00_,modnam_10_,modnam_01_,modnam_11_,... + constrain1_, constrain2_,... + constraint_relax1_, constraint_relax2_,... + shockssequence_,irfshock_,nperiods_,curb_retrench_,maxiter_,init_) + +global M_ oo_ + + + +% solve model +eval(['dynare ',modnam_00_,' noclearall nolog']) +oo00_ = oo_; +M00_ = M_; + + +for i=1:M00_.endo_nbr + eval([deblank(M00_.endo_names(i,:)) '_ss = oo00_.dr.ys(i); ']); +end + +for i_indx_ = 1:M00_.param_nbr + eval([M00_.param_names(i_indx_,:),'= M00_.params(i_indx_);']); +end + + + +eval(['dynare ',modnam_10_,' noclearall']) +oo10_ = oo_; +M10_ = M_; + +eval(['dynare ',modnam_01_,' noclearall']) +oo01_ = oo_; +M01_ = M_; + +eval(['dynare ',modnam_11_,' noclearall']) +oo11_ = oo_; +M11_ = M_; + + +% do some error checking + +% check inputs +if ~strcmp(M00_.endo_names,M10_.endo_names) + error([modnam_00_,' and ',modnam_10_,' need to have exactly the same endogenous variables and they need to be declared in the same order']) +end + +if ~strcmp(M00_.exo_names,M10_.exo_names) + error([modnam_00_,' and ',modnam_10_,' need to have exactly the same exogenous variables and they need to be declared in the same order']) +end + +if ~strcmp(M00_.param_names,M10_.param_names) + warning(['The parameter list does not match across the files ',modnam_00_,' and ',modnam_10_]) +end + + +if ~strcmp(M00_.endo_names,M01_.endo_names) + error([modnam_00,' and ',modnam_01_,' need to have exactly the same endogenous variables and they need to be declared in the same order']) +end + +if ~strcmp(M00_.exo_names,M01_.exo_names) + error([modnam_00_,' and ',modnam_01_,' need to have exactly the same exogenous variables and they need to be declared in the same order']) +end + +if ~strcmp(M00_.param_names,M01_.param_names) + warning(['The parameter list does not match across the files ',modnam_00_,' and ',modnam_01_]) +end + + +if ~strcmp(M00_.endo_names,M11_.endo_names) + error([modnam_00_,' and ',modnam_11_,' need to have exactly the same endogenous variables and they need to be declared in the same order']) +end + +if ~strcmp(M00_.exo_names,M11_.exo_names) + error([modnam_00_,' and ',modnam_11_,' need to have exactly the same exogenous variables and they need to be declared in the same order']) +end + +if ~strcmp(M00_.param_names,M11_.param_names) + warning(['The parameter list does not match across the files ',modnam_00_,' and ',modnam_11_]) +end + + + + + +nvars_ = M00_.endo_nbr; +zdatass_ = oo00_.dr.ys; + + +[hm1_,h_,hl1_,Jbarmat_] = get_deriv(M00_,zdatass_); +cof_ = [hm1_,h_,hl1_]; + + +M10_.params = M00_.params; +[hm1_,h_,hl1_,Jbarmat10_,resid_] = get_deriv(M10_,zdatass_); +cof10_ = [hm1_,h_,hl1_]; +Dbarmat10_ = resid_; + +M01_.params = M00_.params; +[hm1_,h_,hl1_,Jbarmat01_,resid_] = get_deriv(M01_,zdatass_); +cof01_ = [hm1_,h_,hl1_]; +Dbarmat01_ = resid_; + +M11_.params = M00_.params; +[hm1_,h_,hl1_,Jbarmat11_,resid_] = get_deriv(M11_,zdatass_); +cof11_ = [hm1_,h_,hl1_]; +Dbarmat11_ = resid_; + + +if isfield(M00_,'nfwrd') % needed for bakward compatibility with older Dynare releases + [decrulea,decruleb]=get_pq(oo00_.dr,M00_.nstatic,M00_.nfwrd); +else + [decrulea,decruleb]=get_pq(oo00_.dr,oo00_.dr.nstatic,oo00_.dr.nfwrd); +end +endog_ = M00_.endo_names; +exog_ = M00_.exo_names; + + +% processes the constrain so as to uppend a suffix to each +% endogenous variables +constraint1_difference_ = process_constraint(constrain1_,'_difference',M00_.endo_names,0); + +% when the last argument in process_constraint is set to 1, the +% direction of the inequality in the constraint is inverted +constraint_relax1_difference_ = process_constraint(constraint_relax1_,'_difference',M00_.endo_names,0); + + +% processes the constrain so as to uppend a suffix to each +% endogenous variables +constraint2_difference_ = process_constraint(constrain2_,'_difference',M00_.endo_names,0); + +% when the last argument in process_constraint is set to 1, the +% direction of the inequality in the constraint is inverted +constraint_relax2_difference_ = process_constraint(constraint_relax2_,'_difference',M00_.endo_names,0); + + + +nshocks = size(shockssequence_,1); + + + + +if ~exist('init_') + init_ = zeros(nvars_,1); +end + +if ~exist('maxiter_') + maxiter_ = 20; +end + +if ~exist('curb_retrench_') + curb_retrench_ = 0; +end + +init_orig_ = init_; + + + + + + +zdatapiecewise_ = zeros(nperiods_,nvars_); + + +violvecbool_ = zeros(nperiods_+1,2); % This sets the first guess for when + % the constraints are going to hold. + % The variable is a boolean with two + % columns. The first column refers to + % constrain1_; the second to + % constrain2_. + % Each row is a period in time. + % If the boolean is true it indicates + % the relevant constraint is expected + % to evaluate to true. + % The default initial guess is + % consistent with the base model always + % holding -- equivalent to the linear + % solution. + +wishlist_ = endog_; +nwishes_ = size(wishlist_,1); +for ishock_ = 1:nshocks + + + changes_=1; + iter_ = 0; + + while (changes_ & iter_<maxiter_) + iter_ = iter_ +1; + + % analyse violvec and isolate contiguous periods in the other + % regime. + [regime1, regimestart1]=map_regime(violvecbool_(:,1)); + [regime2, regimestart2]=map_regime(violvecbool_(:,2)); + + + [zdatalinear_]=mkdatap_anticipated_2constraints(nperiods_,decrulea,decruleb,... + cof_,Jbarmat_,... + cof10_,Jbarmat10_,Dbarmat10_,... + cof01_,Jbarmat01_,Dbarmat01_,... + cof11_,Jbarmat11_,Dbarmat11_,... + regime1,regimestart1,... + regime2,regimestart2,... + violvecbool_,endog_,exog_,... + irfshock_,shockssequence_(ishock_,:),init_); + + for i_indx_=1:nwishes_ + eval([deblank(wishlist_(i_indx_,:)),'_difference=zdatalinear_(:,i_indx_);']); + end + + + + + newviolvecbool1_ = eval(constraint1_difference_); + relaxconstraint1_ = eval(constraint_relax1_difference_); + + newviolvecbool2_ = eval(constraint2_difference_); + relaxconstraint2_ = eval(constraint_relax2_difference_); + + + + newviolvecbool_ = [newviolvecbool1_;newviolvecbool2_]; + relaxconstraint_ = [relaxconstraint1_;relaxconstraint2_]; + + + + % check if changes_ + if (max(newviolvecbool_(:)-violvecbool_(:)>0)) | sum(relaxconstraint_(find(violvecbool_==1))>0) + changes_ = 1; + else + changes_ = 0; + end + + if curb_retrench_ % apply Gauss-Sidel idea of slowing down the change in the guess + % for the constraint -- only relax one + % period at a time starting from the last + % one when each of the constraints is true. + retrench = 0*violvecbool_(:); + if ~isempty(find(relaxconstraint1_ & violvecbool_(:,1))) + retrenchpos = max(find(relaxconstraint1_ & violvecbool_(:,1))); + retrench(retrenchpos) = 1; + end + if ~isempty(find(relaxconstraint2_ & violvecbool_(:,2))) + retrenchpos = max(find(relaxconstraint2_ & violvecbool_(:,2))); + retrench(retrenchpos+nperiods_+1) = 1; + end + violvecbool_ = (violvecbool_(:) | newviolvecbool_(:))-retrench(:); + else + violvecbool_ = (violvecbool_(:) | newviolvecbool_(:))-(relaxconstraint_(:) & violvecbool_(:)); + end + + violvecbool_ = reshape(violvecbool_,nperiods_+1,2); + + + + end + if changes_ ==1 + display('Did not converge -- increase maxiter') + end + + init_ = zdatalinear_(1,:); + zdatapiecewise_(ishock_,:)=init_; + init_= init_'; + + % update the guess for constraint violations for next period + % update is consistent with expecting no additional shocks next period + violvecbool_=[violvecbool_(2:end,:);zeros(1,2)]; + +end + + +zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:); + +zdatalinear_ = mkdata(nperiods_,decrulea,decruleb,endog_,exog_,wishlist_,irfshock_,shockssequence_,init_orig_); diff --git a/matlab/occbin/strmerge.m b/matlab/occbin/strmerge.m index b8585df04d..8aebb00995 100755 --- a/matlab/occbin/strmerge.m +++ b/matlab/occbin/strmerge.m @@ -1,9 +1,9 @@ -function string = strmerge(tokens) - -ntokens = length(tokens); - -string = char(tokens(1)); - -for i=2:ntokens - string = [string,char(tokens(i))]; +function string = strmerge(tokens) + +ntokens = length(tokens); + +string = char(tokens(1)); + +for i=2:ntokens + string = [string,char(tokens(i))]; end \ No newline at end of file diff --git a/matlab/occbin/tokenize.m b/matlab/occbin/tokenize.m index b711ca0820..2cd8fb4103 100755 --- a/matlab/occbin/tokenize.m +++ b/matlab/occbin/tokenize.m @@ -1,55 +1,54 @@ -function tokens = tokenize(source,delimiter) -% syntax -% tokens = tokenize(source,delimiters) -% -% source is a string to be broken into tokens -% delimiters is a character array of single character delimiters -% tokens is a cell string array containing the tokens - - -posdelims = []; - -% assumes that delimiter cannot be in the first position or the last -% position -ndelimiters = size(delimiter,1); -for i=1:ndelimiters - newpositions = strfind(source,delimiter(i,:)); - if ~isempty(newpositions) - posdelims =[posdelims, newpositions]; - end -end - -% reorder posdelims in ascending order -posdelims = sort(posdelims); - -if isempty(posdelims) - tokens = cellstr(source); -else - ndelims = length(posdelims); - % build positions for substrings - delims = zeros(ndelims+1,2); - for i=1:ndelims+1 - if i==1 - if posdelims(1) == 1 - tokens = cellstr(source(1)); - else - delims(i,:) = [1,posdelims(i)-1]; - tokens = cellstr(source([delims(i,1):delims(i,2)])); - tokens = [tokens, source(posdelims(i))]; - end - elseif i==ndelims+1 - if (posdelims(i-1) < length(source)) - delims(i,:) = [posdelims(i-1)+1,length(source)]; - tokens = [tokens, cellstr(source([delims(i,1):delims(i,2)]))]; - end - else - if posdelims(i)>posdelims(i-1)+1 - delims(i,:) = [posdelims(i-1)+1,posdelims(i)-1]; - tokens = [tokens, cellstr(source([delims(i,1):delims(i,2)]))]; - end - tokens = [tokens, source(posdelims(i))]; - end - end - -end - +function tokens = tokenize(source,delimiter) +% syntax +% tokens = tokenize(source,delimiters) +% +% source is a string to be broken into tokens +% delimiters is a character array of single character delimiters +% tokens is a cell string array containing the tokens + + +posdelims = []; + +% assumes that delimiter cannot be in the first position or the last +% position +ndelimiters = size(delimiter,1); +for i=1:ndelimiters + newpositions = strfind(source,delimiter(i,:)); + if ~isempty(newpositions) + posdelims =[posdelims, newpositions]; + end +end + +% reorder posdelims in ascending order +posdelims = sort(posdelims); + +if isempty(posdelims) + tokens = cellstr(source); +else + ndelims = length(posdelims); + % build positions for substrings + delims = zeros(ndelims+1,2); + for i=1:ndelims+1 + if i==1 + if posdelims(1) == 1 + tokens = cellstr(source(1)); + else + delims(i,:) = [1,posdelims(i)-1]; + tokens = cellstr(source([delims(i,1):delims(i,2)])); + tokens = [tokens, source(posdelims(i))]; + end + elseif i==ndelims+1 + if (posdelims(i-1) < length(source)) + delims(i,:) = [posdelims(i-1)+1,length(source)]; + tokens = [tokens, cellstr(source([delims(i,1):delims(i,2)]))]; + end + else + if posdelims(i)>posdelims(i-1)+1 + delims(i,:) = [posdelims(i-1)+1,posdelims(i)-1]; + tokens = [tokens, cellstr(source([delims(i,1):delims(i,2)]))]; + end + tokens = [tokens, source(posdelims(i))]; + end + end + +end diff --git a/matlab/octave_ver_less_than.m b/matlab/octave_ver_less_than.m index 9d702d5972..d60bea88da 100644 --- a/matlab/octave_ver_less_than.m +++ b/matlab/octave_ver_less_than.m @@ -8,7 +8,7 @@ function r = octave_ver_less_than(verstr) % % INPUTS % verstr: a string of the format 'x.y' or 'x.y.z' -% +% % OUTPUTS % r: 0 or 1 % diff --git a/matlab/one_sided_hp_filter.m b/matlab/one_sided_hp_filter.m index 38af32ea28..53e494a9ad 100644 --- a/matlab/one_sided_hp_filter.m +++ b/matlab/one_sided_hp_filter.m @@ -32,8 +32,8 @@ function [ytrend,ycycle]=one_sided_hp_filter(y,lambda,x_user,P_user,discard) % % y_t=tau_t+epsilon_t % (1-L)^2 tau_t=eta_t" -% -% The Kalman filter notation follows Chapter 13 of Hamilton, J.D. (1994). +% +% The Kalman filter notation follows Chapter 13 of Hamilton, J.D. (1994). % Time Series Analysis, with the exception of H, which is equivalent to his H'. @@ -63,26 +63,26 @@ end %Set up state space q=1/lambda; % the signal-to-noise ration: i.e. var eta_t / var epsilon_t F=[2,-1; - 1,0]; % state transition matrix + 1,0]; % state transition matrix H=[1,0]; % observation matrix Q=[q,0; - 0,0]; % covariance matrix state equation errors + 0,0]; % covariance matrix state equation errors R=1; % variance observation equation error for k=1:n %Run the Kalman filter for each variable if nargin < 4 || isempty(x_user) %no intial value for state, extrapolate back two periods from the observations - x=[2*y(1,k)-y(2,k); - 3*y(1,k)-2*y(2,k)]; + x=[2*y(1,k)-y(2,k); + 3*y(1,k)-2*y(2,k)]; else x=x_user(:,k); - end + end if nargin < 4 || isempty(P_user) %no initial value for the MSE, set a rather high one P= [1e5 0; - 0 1e5]; + 0 1e5]; else P=P_user{k}; - end - + end + for j=1:T %Get the estimates for each period [x,P]=kalman_update(F,H,Q,R,y(j,k),x,P); %get new state estimate and update recursion ytrend(j,k)=x(2);%second state is trend estimate @@ -103,9 +103,9 @@ end function [x,P]=kalman_update(F,H,Q,R,obs,x,P) % Updates the Kalman filter estimation of the state and MSE -S=H*P*H'+R; -K=F*P*H'; -K=K/S; +S=H*P*H'+R; +K=F*P*H'; +K=K/S; x=F*x+K*(obs -H*x); %State estimate Temp=F-K*H; P=Temp*P*Temp'; diff --git a/matlab/optimization/apprgrdn.m b/matlab/optimization/apprgrdn.m index 633cfbf9c7..a195690868 100644 --- a/matlab/optimization/apprgrdn.m +++ b/matlab/optimization/apprgrdn.m @@ -2,7 +2,7 @@ function g = apprgrdn(x,f,fun,deltax,obj,varargin) % g = apprgrdn(x,f,fun,deltax,obj,varargin) % Performs the finite difference approximation of the gradient <g> at a % point <x> used in solveopt -% +% % Inputs: % x: point at which to evaluate gradient % f: calculated function value at a point x; @@ -14,8 +14,8 @@ function g = apprgrdn(x,f,fun,deltax,obj,varargin) % Modified by Giovanni Lombardo and Johannes Pfeifer to accomodate Dynare % structure % -% -% Copyright (C) 1997-2008, Alexei Kuntsevich and Franz Kappel +% +% Copyright (C) 1997-2008, Alexei Kuntsevich and Franz Kappel % Copyright (C) 2008-2015 Giovanni Lombardo % Copyright (C) 2015 Dynare Team % @@ -38,10 +38,10 @@ n=max(size(x)); ee=ones(size(x)); di=abs(x); idx=find(di<5e-15); di(idx)=5e-15*ee(idx); di=deltax.*di; if obj - idx=find(abs(di)<2e-10); + idx=find(abs(di)<2e-10); di(idx)=2e-10*sign(di(idx)); else - idx=find(abs(di)<5e-15); + idx=find(abs(di)<5e-15); di(idx)=5e-15*sign(di(idx)); end y=x; diff --git a/matlab/optimization/bfgsi1.m b/matlab/optimization/bfgsi1.m index 696ee410b1..7ed5b0db08 100644 --- a/matlab/optimization/bfgsi1.m +++ b/matlab/optimization/bfgsi1.m @@ -1,20 +1,20 @@ function H = bfgsi1(H0,dg,dx,Verbose,Save_files) % H = bfgsi1(H0,dg,dx,Verbose,Save_files) % Update Inverse Hessian matrix -% +% % Inputs: % H0 [npar by npar] initial inverse Hessian matrix % dg [npar by 1] previous change in gradient % dx [npar by 1] previous change in x; % Verbose [scalar] Indicator for silent mode -% Save_files [scalar] Indicator whether to save files -% +% Save_files [scalar] Indicator whether to save files +% % 6/8/93 version that updates inverse Hessian instead of Hessian % itself. -% +% % Original file downloaded from: % http://sims.princeton.edu/yftp/optimize/mfiles/bfgsi.m -% +% % Copyright (C) 1993-2009 Christopher Sims % Copyright (C) 2009-2015 Dynare Team % diff --git a/matlab/optimization/cmaes.m b/matlab/optimization/cmaes.m index 8ec94e5ea6..db68693062 100644 --- a/matlab/optimization/cmaes.m +++ b/matlab/optimization/cmaes.m @@ -1,163 +1,163 @@ function [xmin, ... % minimum search point of last iteration - fmin, ... % function value of xmin - counteval, ... % number of function evaluations done - stopflag, ... % stop criterion reached - out, ... % struct with various histories and solutions - bestever ... % struct containing overall best solution (for convenience) - ] = cmaes( ... - fitfun, ... % name of objective/fitness function - xstart, ... % objective variables initial point, determines N - insigma, ... % initial coordinate wise standard deviation(s) - inopts, ... % options struct, see defopts below - varargin ) % arguments passed to objective function -% cmaes.m, Version 3.56.beta, last change: February, 2012 -% CMAES implements an Evolution Strategy with Covariance Matrix -% Adaptation (CMA-ES) for nonlinear function minimization. For -% introductory comments and copyright (GPL) see end of file (type -% 'type cmaes'). cmaes.m runs with MATLAB (Windows, Linux) and, -% without data logging and plotting, it should run under Octave -% (Linux, package octave-forge is needed). -% -% OPTS = CMAES returns default options. -% OPTS = CMAES('defaults') returns default options quietly. -% OPTS = CMAES('displayoptions') displays options. -% OPTS = CMAES('defaults', OPTS) supplements options OPTS with default -% options. -% -% XMIN = CMAES(FUN, X0, SIGMA[, OPTS]) locates the minimum XMIN of -% function FUN starting from column vector X0 with the initial -% coordinate wise search standard deviation SIGMA. -% -% Input arguments: -% -% FUN is a string function name like 'myfun'. FUN takes as argument a -% column vector of size of X0 and returns a scalar. An easy way to -% implement a hard non-linear constraint is to return NaN. Then, -% this function evaluation is not counted and a newly sampled -% point is tried immediately. -% -% X0 is a column vector, or a matrix, or a string. If X0 is a matrix, -% mean(X0, 2) is taken as initial point. If X0 is a string like -% '2*rand(10,1)-1', the string is evaluated first. -% -% SIGMA is a scalar, or a column vector of size(X0,1), or a string -% that can be evaluated into one of these. SIGMA determines the -% initial coordinate wise standard deviations for the search. -% Setting SIGMA one third of the initial search region is -% appropriate, e.g., the initial point in [0, 6]^10 and SIGMA=2 -% means cmaes('myfun', 3*rand(10,1), 2). If SIGMA is missing and -% size(X0,2) > 1, SIGMA is set to sqrt(var(X0')'). That is, X0 is -% used as a sample for estimating initial mean and variance of the -% search distribution. -% -% OPTS (an optional argument) is a struct holding additional input -% options. Valid field names and a short documentation can be -% discovered by looking at the default options (type 'cmaes' -% without arguments, see above). Empty or missing fields in OPTS -% invoke the default value, i.e. OPTS needs not to have all valid -% field names. Capitalization does not matter and unambiguous -% abbreviations can be used for the field names. If a string is -% given where a numerical value is needed, the string is evaluated -% by eval, where 'N' expands to the problem dimension -% (==size(X0,1)) and 'popsize' to the population size. -% -% [XMIN, FMIN, COUNTEVAL, STOPFLAG, OUT, BESTEVER] = ... -% CMAES(FITFUN, X0, SIGMA) -% returns the best (minimal) point XMIN (found in the last -% generation); function value FMIN of XMIN; the number of needed -% function evaluations COUNTEVAL; a STOPFLAG value as cell array, -% where possible entries are 'fitness', 'tolx', 'tolupx', 'tolfun', -% 'maxfunevals', 'maxiter', 'stoptoresume', 'manual', -% 'warnconditioncov', 'warnnoeffectcoord', 'warnnoeffectaxis', -% 'warnequalfunvals', 'warnequalfunvalhist', 'bug' (use -% e.g. any(strcmp(STOPFLAG, 'tolx')) or findstr(strcat(STOPFLAG, -% 'tolx')) for further processing); a record struct OUT with some -% more output, where the struct SOLUTIONS.BESTEVER contains the overall -% best evaluated point X with function value F evaluated at evaluation -% count EVALS. The last output argument BESTEVER equals -% OUT.SOLUTIONS.BESTEVER. Moreover a history of solutions and -% parameters is written to files according to the Log-options. -% -% A regular manual stop can be achieved via the file signals.par. The -% program is terminated if the first two non-white sequences in any -% line of this file are 'stop' and the value of the LogFilenamePrefix -% option (by default 'outcmaes'). Also a run can be skipped. -% Given, for example, 'skip outcmaes run 2', skips the second run -% if option Restarts is at least 2, and another run will be started. -% -% To run the code completely silently set Disp, Save, and Log options -% to 0. With OPTS.LogModulo > 0 (1 by default) the most important -% data are written to ASCII files permitting to investigate the -% results (e.g. plot with function plotcmaesdat) even while CMAES is -% still running (which can be quite useful on expensive objective -% functions). When OPTS.SaveVariables==1 (default) everything is saved -% in file OPTS.SaveFilename (default 'variablescmaes.mat') allowing to -% resume the search afterwards by using the resume option. -% -% To find the best ever evaluated point load the variables typing -% "es=load('variablescmaes')" and investigate the variable -% es.out.solutions.bestever. -% -% In case of a noisy objective function (uncertainties) set -% OPTS.Noise.on = 1. This option interferes presumably with some -% termination criteria, because the step-size sigma will presumably -% not converge to zero anymore. If CMAES was provided with a -% fifth argument (P1 in the below example, which is passed to the -% objective function FUN), this argument is multiplied with the -% factor given in option Noise.alphaevals, each time the detected -% noise exceeds a threshold. This argument can be used within -% FUN, for example, as averaging number to reduce the noise level. -% -% OPTS.DiagonalOnly > 1 defines the number of initial iterations, -% where the covariance matrix remains diagonal and the algorithm has -% internally linear time complexity. OPTS.DiagonalOnly = 1 means -% keeping the covariance matrix always diagonal and this setting -% also exhibits linear space complexity. This can be particularly -% useful for dimension > 100. The default is OPTS.DiagonalOnly = 0. -% -% OPTS.CMA.active = 1 turns on "active CMA" with a negative update -% of the covariance matrix and checks for positive definiteness. -% OPTS.CMA.active = 2 does not check for pos. def. and is numerically -% faster. Active CMA usually speeds up the adaptation and might -% become a default in near future. -% -% The primary strategy parameter to play with is OPTS.PopSize, which -% can be increased from its default value. Increasing the population -% size (by default linked to increasing parent number OPTS.ParentNumber) -% improves global search properties in exchange to speed. Speed -% decreases, as a rule, at most linearely with increasing population -% size. It is advisable to begin with the default small population -% size. The options Restarts and IncPopSize can be used for an -% automated multistart where the population size is increased by the -% factor IncPopSize (two by default) before each restart. X0 (given as -% string) is reevaluated for each restart. Stopping options -% StopFunEvals, StopIter, MaxFunEvals, and Fitness terminate the -% program, all others including MaxIter invoke another restart, where -% the iteration counter is reset to zero. -% -% Examples: -% -% XMIN = cmaes('myfun', 5*ones(10,1), 1.5); starts the search at -% 10D-point 5 and initially searches mainly between 5-3 and 5+3 -% (+- two standard deviations), but this is not a strict bound. -% 'myfun' is a name of a function that returns a scalar from a 10D -% column vector. -% -% opts.LBounds = 0; opts.UBounds = 10; -% X=cmaes('myfun', 10*rand(10,1), 5, opts); -% search within lower bound of 0 and upper bound of 10. Bounds can -% also be given as column vectors. If the optimum is not located -% on the boundary, use rather a penalty approach to handle bounds. -% -% opts=cmaes; opts.StopFitness=1e-10; -% X=cmaes('myfun', rand(5,1), 0.5, opts); stops the search, if -% the function value is smaller than 1e-10. -% -% [X, F, E, STOP, OUT] = cmaes('myfun2', 'rand(5,1)', 1, [], P1, P2); -% passes two additional parameters to the function MYFUN2. -% - -% Copyright (C) 2001-2012 Nikolaus Hansen, + fmin, ... % function value of xmin + counteval, ... % number of function evaluations done + stopflag, ... % stop criterion reached + out, ... % struct with various histories and solutions + bestever ... % struct containing overall best solution (for convenience) + ] = cmaes( ... + fitfun, ... % name of objective/fitness function + xstart, ... % objective variables initial point, determines N + insigma, ... % initial coordinate wise standard deviation(s) + inopts, ... % options struct, see defopts below + varargin ) % arguments passed to objective function + % cmaes.m, Version 3.56.beta, last change: February, 2012 + % CMAES implements an Evolution Strategy with Covariance Matrix + % Adaptation (CMA-ES) for nonlinear function minimization. For + % introductory comments and copyright (GPL) see end of file (type + % 'type cmaes'). cmaes.m runs with MATLAB (Windows, Linux) and, + % without data logging and plotting, it should run under Octave + % (Linux, package octave-forge is needed). + % + % OPTS = CMAES returns default options. + % OPTS = CMAES('defaults') returns default options quietly. + % OPTS = CMAES('displayoptions') displays options. + % OPTS = CMAES('defaults', OPTS) supplements options OPTS with default + % options. + % + % XMIN = CMAES(FUN, X0, SIGMA[, OPTS]) locates the minimum XMIN of + % function FUN starting from column vector X0 with the initial + % coordinate wise search standard deviation SIGMA. + % + % Input arguments: + % + % FUN is a string function name like 'myfun'. FUN takes as argument a + % column vector of size of X0 and returns a scalar. An easy way to + % implement a hard non-linear constraint is to return NaN. Then, + % this function evaluation is not counted and a newly sampled + % point is tried immediately. + % + % X0 is a column vector, or a matrix, or a string. If X0 is a matrix, + % mean(X0, 2) is taken as initial point. If X0 is a string like + % '2*rand(10,1)-1', the string is evaluated first. + % + % SIGMA is a scalar, or a column vector of size(X0,1), or a string + % that can be evaluated into one of these. SIGMA determines the + % initial coordinate wise standard deviations for the search. + % Setting SIGMA one third of the initial search region is + % appropriate, e.g., the initial point in [0, 6]^10 and SIGMA=2 + % means cmaes('myfun', 3*rand(10,1), 2). If SIGMA is missing and + % size(X0,2) > 1, SIGMA is set to sqrt(var(X0')'). That is, X0 is + % used as a sample for estimating initial mean and variance of the + % search distribution. + % + % OPTS (an optional argument) is a struct holding additional input + % options. Valid field names and a short documentation can be + % discovered by looking at the default options (type 'cmaes' + % without arguments, see above). Empty or missing fields in OPTS + % invoke the default value, i.e. OPTS needs not to have all valid + % field names. Capitalization does not matter and unambiguous + % abbreviations can be used for the field names. If a string is + % given where a numerical value is needed, the string is evaluated + % by eval, where 'N' expands to the problem dimension + % (==size(X0,1)) and 'popsize' to the population size. + % + % [XMIN, FMIN, COUNTEVAL, STOPFLAG, OUT, BESTEVER] = ... + % CMAES(FITFUN, X0, SIGMA) + % returns the best (minimal) point XMIN (found in the last + % generation); function value FMIN of XMIN; the number of needed + % function evaluations COUNTEVAL; a STOPFLAG value as cell array, + % where possible entries are 'fitness', 'tolx', 'tolupx', 'tolfun', + % 'maxfunevals', 'maxiter', 'stoptoresume', 'manual', + % 'warnconditioncov', 'warnnoeffectcoord', 'warnnoeffectaxis', + % 'warnequalfunvals', 'warnequalfunvalhist', 'bug' (use + % e.g. any(strcmp(STOPFLAG, 'tolx')) or findstr(strcat(STOPFLAG, + % 'tolx')) for further processing); a record struct OUT with some + % more output, where the struct SOLUTIONS.BESTEVER contains the overall + % best evaluated point X with function value F evaluated at evaluation + % count EVALS. The last output argument BESTEVER equals + % OUT.SOLUTIONS.BESTEVER. Moreover a history of solutions and + % parameters is written to files according to the Log-options. + % + % A regular manual stop can be achieved via the file signals.par. The + % program is terminated if the first two non-white sequences in any + % line of this file are 'stop' and the value of the LogFilenamePrefix + % option (by default 'outcmaes'). Also a run can be skipped. + % Given, for example, 'skip outcmaes run 2', skips the second run + % if option Restarts is at least 2, and another run will be started. + % + % To run the code completely silently set Disp, Save, and Log options + % to 0. With OPTS.LogModulo > 0 (1 by default) the most important + % data are written to ASCII files permitting to investigate the + % results (e.g. plot with function plotcmaesdat) even while CMAES is + % still running (which can be quite useful on expensive objective + % functions). When OPTS.SaveVariables==1 (default) everything is saved + % in file OPTS.SaveFilename (default 'variablescmaes.mat') allowing to + % resume the search afterwards by using the resume option. + % + % To find the best ever evaluated point load the variables typing + % "es=load('variablescmaes')" and investigate the variable + % es.out.solutions.bestever. + % + % In case of a noisy objective function (uncertainties) set + % OPTS.Noise.on = 1. This option interferes presumably with some + % termination criteria, because the step-size sigma will presumably + % not converge to zero anymore. If CMAES was provided with a + % fifth argument (P1 in the below example, which is passed to the + % objective function FUN), this argument is multiplied with the + % factor given in option Noise.alphaevals, each time the detected + % noise exceeds a threshold. This argument can be used within + % FUN, for example, as averaging number to reduce the noise level. + % + % OPTS.DiagonalOnly > 1 defines the number of initial iterations, + % where the covariance matrix remains diagonal and the algorithm has + % internally linear time complexity. OPTS.DiagonalOnly = 1 means + % keeping the covariance matrix always diagonal and this setting + % also exhibits linear space complexity. This can be particularly + % useful for dimension > 100. The default is OPTS.DiagonalOnly = 0. + % + % OPTS.CMA.active = 1 turns on "active CMA" with a negative update + % of the covariance matrix and checks for positive definiteness. + % OPTS.CMA.active = 2 does not check for pos. def. and is numerically + % faster. Active CMA usually speeds up the adaptation and might + % become a default in near future. + % + % The primary strategy parameter to play with is OPTS.PopSize, which + % can be increased from its default value. Increasing the population + % size (by default linked to increasing parent number OPTS.ParentNumber) + % improves global search properties in exchange to speed. Speed + % decreases, as a rule, at most linearely with increasing population + % size. It is advisable to begin with the default small population + % size. The options Restarts and IncPopSize can be used for an + % automated multistart where the population size is increased by the + % factor IncPopSize (two by default) before each restart. X0 (given as + % string) is reevaluated for each restart. Stopping options + % StopFunEvals, StopIter, MaxFunEvals, and Fitness terminate the + % program, all others including MaxIter invoke another restart, where + % the iteration counter is reset to zero. + % + % Examples: + % + % XMIN = cmaes('myfun', 5*ones(10,1), 1.5); starts the search at + % 10D-point 5 and initially searches mainly between 5-3 and 5+3 + % (+- two standard deviations), but this is not a strict bound. + % 'myfun' is a name of a function that returns a scalar from a 10D + % column vector. + % + % opts.LBounds = 0; opts.UBounds = 10; + % X=cmaes('myfun', 10*rand(10,1), 5, opts); + % search within lower bound of 0 and upper bound of 10. Bounds can + % also be given as column vectors. If the optimum is not located + % on the boundary, use rather a penalty approach to handle bounds. + % + % opts=cmaes; opts.StopFitness=1e-10; + % X=cmaes('myfun', rand(5,1), 0.5, opts); stops the search, if + % the function value is smaller than 1e-10. + % + % [X, F, E, STOP, OUT] = cmaes('myfun2', 'rand(5,1)', 1, [], P1, P2); + % passes two additional parameters to the function MYFUN2. + % + +% Copyright (C) 2001-2012 Nikolaus Hansen, % Copyright (C) 2012 Dynare Team % % This file is part of Dynare. @@ -176,7 +176,7 @@ function [xmin, ... % minimum search point of last iteration % along with Dynare. If not, see <http://www.gnu.org/licenses/>. -cmaVersion = '3.60.beta'; +cmaVersion = '3.60.beta'; % ----------- Set Defaults for Input Parameters and Options ------------- % These defaults may be edited for convenience @@ -197,1596 +197,1596 @@ defopts.TolFun = '1e-10 % stop if fun-changes smaller TolFun'; defopts.TolHistFun = '1e-11 % stop if back fun-changes smaller TolHistFun'; defopts.StopOnStagnation = 'on % stop when fitness stagnates for a long time'; defopts.StopOnWarnings = 'yes % ''no''==''off''==0, ''on''==''yes''==1 '; -defopts.StopOnEqualFunctionValues = '2 + N/3 % number of iterations'; +defopts.StopOnEqualFunctionValues = '2 + N/3 % number of iterations'; % Options defaults: Other defopts.DiffMaxChange = 'Inf % maximal variable change(s), can be Nx1-vector'; defopts.DiffMinChange = '0 % minimal variable change(s), can be Nx1-vector'; defopts.WarnOnEqualFunctionValues = ... 'yes % ''no''==''off''==0, ''on''==''yes''==1 '; -defopts.LBounds = '-Inf % lower bounds, scalar or Nx1-vector'; -defopts.UBounds = 'Inf % upper bounds, scalar or Nx1-vector'; +defopts.LBounds = '-Inf % lower bounds, scalar or Nx1-vector'; +defopts.UBounds = 'Inf % upper bounds, scalar or Nx1-vector'; defopts.EvalParallel = 'no % objective function FUN accepts NxM matrix, with M>1?'; defopts.EvalInitialX = 'yes % evaluation of initial solution'; defopts.Restarts = '0 % number of restarts '; defopts.IncPopSize = '2 % multiplier for population size before each restart'; -defopts.PopSize = '(4 + floor(3*log(N))) % population size, lambda'; +defopts.PopSize = '(4 + floor(3*log(N))) % population size, lambda'; defopts.ParentNumber = 'floor(popsize/2) % AKA mu, popsize equals lambda'; defopts.RecombinationWeights = 'superlinear decrease % or linear, or equal'; -defopts.DiagonalOnly = '0*(1+100*N/sqrt(popsize))+(N>=1000) % C is diagonal for given iterations, 1==always'; -defopts.Noise.on = '0 % uncertainty handling is off by default'; +defopts.DiagonalOnly = '0*(1+100*N/sqrt(popsize))+(N>=1000) % C is diagonal for given iterations, 1==always'; +defopts.Noise.on = '0 % uncertainty handling is off by default'; defopts.Noise.reevals = '1*ceil(0.05*lambda) % nb. of re-evaluated for uncertainty measurement'; defopts.Noise.theta = '0.5 % threshold to invoke uncertainty treatment'; % smaller: more likely to diverge -defopts.Noise.cum = '0.3 % cumulation constant for uncertainty'; +defopts.Noise.cum = '0.3 % cumulation constant for uncertainty'; defopts.Noise.cutoff = '2*lambda/3 % rank change cutoff for summation'; defopts.Noise.alphasigma = '1+2/(N+10) % factor for increasing sigma'; % smaller: slower adaptation defopts.Noise.epsilon = '1e-7 % additional relative perturbation before reevaluation'; -defopts.Noise.minmaxevals = '[1 inf] % min and max value of 2nd arg to fitfun, start value is 5th arg to cmaes'; -defopts.Noise.alphaevals = '1+2/(N+10) % factor for increasing 2nd arg to fitfun'; +defopts.Noise.minmaxevals = '[1 inf] % min and max value of 2nd arg to fitfun, start value is 5th arg to cmaes'; +defopts.Noise.alphaevals = '1+2/(N+10) % factor for increasing 2nd arg to fitfun'; defopts.Noise.callback = '[] % callback function when uncertainty threshold is exceeded'; -% defopts.TPA = 0; -defopts.CMA.cs = '(mueff+2)/(N+mueff+3) % cumulation constant for step-size'; - %qqq cs = (mueff^0.5)/(N^0.5+mueff^0.5) % the short time horizon version +% defopts.TPA = 0; +defopts.CMA.cs = '(mueff+2)/(N+mueff+3) % cumulation constant for step-size'; +%qqq cs = (mueff^0.5)/(N^0.5+mueff^0.5) % the short time horizon version defopts.CMA.damps = '1 + 2*max(0,sqrt((mueff-1)/(N+1))-1) + cs % damping for step-size'; -% defopts.CMA.ccum = '4/(N+4) % cumulation constant for covariance matrix'; +% defopts.CMA.ccum = '4/(N+4) % cumulation constant for covariance matrix'; defopts.CMA.ccum = '(4 + mueff/N) / (N+4 + 2*mueff/N) % cumulation constant for pc'; -defopts.CMA.ccov1 = '2 / ((N+1.3)^2+mueff) % learning rate for rank-one update'; -defopts.CMA.ccovmu = '2 * (mueff-2+1/mueff) / ((N+2)^2+mueff) % learning rate for rank-mu update'; -defopts.CMA.on = 'yes'; -defopts.CMA.active = '0 % active CMA 1: neg. updates with pos. def. check, 2: neg. updates'; +defopts.CMA.ccov1 = '2 / ((N+1.3)^2+mueff) % learning rate for rank-one update'; +defopts.CMA.ccovmu = '2 * (mueff-2+1/mueff) / ((N+2)^2+mueff) % learning rate for rank-mu update'; +defopts.CMA.on = 'yes'; +defopts.CMA.active = '0 % active CMA 1: neg. updates with pos. def. check, 2: neg. updates'; flg_future_setting = 0; % testing for possible future variant(s) -if flg_future_setting - disp('in the future') +if flg_future_setting + disp('in the future') - % damps setting from Brockhoff et al 2010 - % this damps diverges with popsize 400: - % cmaeshtml('benchmarkszero', ones(20,1)*2, 5, o, 15); - defopts.CMA.damps = '2*mueff/lambda + 0.3 + cs % damping for step-size'; % cs: for large mueff - % how about: - % defopts.CMA.damps = '2*mueff/lambda + 0.3 + 2*max(0,sqrt((mueff-1)/(N+1))-1) + cs % damping for step-size'; + % damps setting from Brockhoff et al 2010 + % this damps diverges with popsize 400: + % cmaeshtml('benchmarkszero', ones(20,1)*2, 5, o, 15); + defopts.CMA.damps = '2*mueff/lambda + 0.3 + cs % damping for step-size'; % cs: for large mueff + % how about: + % defopts.CMA.damps = '2*mueff/lambda + 0.3 + 2*max(0,sqrt((mueff-1)/(N+1))-1) + cs % damping for step-size'; - % ccum adjusted for large mueff, better on schefelmult? - % TODO: this should also depend on diagonal option!? - defopts.CMA.ccum = '(4 + mueff/N) / (N+4 + 2*mueff/N) % cumulation constant for pc'; + % ccum adjusted for large mueff, better on schefelmult? + % TODO: this should also depend on diagonal option!? + defopts.CMA.ccum = '(4 + mueff/N) / (N+4 + 2*mueff/N) % cumulation constant for pc'; - defopts.CMA.active = '1 % active CMA 1: neg. updates with pos. def. check, 2: neg. updates'; + defopts.CMA.active = '1 % active CMA 1: neg. updates with pos. def. check, 2: neg. updates'; end - -defopts.Resume = 'no % resume former run from SaveFile'; -defopts.Science = 'on % off==do some additional (minor) problem capturing, NOT IN USE'; + +defopts.Resume = 'no % resume former run from SaveFile'; +defopts.Science = 'on % off==do some additional (minor) problem capturing, NOT IN USE'; defopts.ReadSignals = 'on % from file signals.par for termination, yet a stumb'; defopts.Seed = 'sum(100*clock) % evaluated if it is a string'; defopts.DispFinal = 'on % display messages like initial and final message'; defopts.DispModulo = '100 % [0:Inf], disp messages after every i-th iteration'; defopts.SaveVariables = 'on % [on|final|off][-v6] save variables to .mat file'; -defopts.SaveFilename = 'variablescmaes.mat % save all variables, see SaveVariables'; +defopts.SaveFilename = 'variablescmaes.mat % save all variables, see SaveVariables'; defopts.LogModulo = '1 % [0:Inf] if >1 record data less frequently after gen=100'; defopts.LogTime = '25 % [0:100] max. percentage of time for recording data'; -defopts.LogFilenamePrefix = 'outcmaes % files for output data'; +defopts.LogFilenamePrefix = 'outcmaes % files for output data'; defopts.LogPlot = 'off % plot while running using output data files'; -%qqqkkk -%defopts.varopt1 = ''; % 'for temporary and hacking purposes'; -%defopts.varopt2 = ''; % 'for temporary and hacking purposes'; +%qqqkkk +%defopts.varopt1 = ''; % 'for temporary and hacking purposes'; +%defopts.varopt2 = ''; % 'for temporary and hacking purposes'; defopts.UserData = 'for saving data/comments associated with the run'; defopts.UserDat2 = ''; 'for saving data/comments associated with the run'; % ---------------------- Handling Input Parameters ---------------------- if nargin < 1 || isequal(fitfun, 'defaults') % pass default options - if nargin < 1 - disp('Default options returned (type "help cmaes" for help).'); - end - xmin = defopts; - if nargin > 1 % supplement second argument with default options - xmin = getoptions(xstart, defopts); - end - return + if nargin < 1 + disp('Default options returned (type "help cmaes" for help).'); + end + xmin = defopts; + if nargin > 1 % supplement second argument with default options + xmin = getoptions(xstart, defopts); + end + return end if isequal(fitfun, 'displayoptions') - names = fieldnames(defopts); - for name = names' - disp([name{:} repmat(' ', 1, 20-length(name{:})) ': ''' defopts.(name{:}) '''']); - end - return + names = fieldnames(defopts); + for name = names' + disp([name{:} repmat(' ', 1, 20-length(name{:})) ': ''' defopts.(name{:}) '''']); + end + return end input.fitfun = fitfun; % record used input if isempty(fitfun) - % fitfun = definput.fitfun; - % warning(['Objective function not determined, ''' fitfun ''' used']); - error(['Objective function not determined']); + % fitfun = definput.fitfun; + % warning(['Objective function not determined, ''' fitfun ''' used']); + error(['Objective function not determined']); end if ~ischar(fitfun) - error('first argument FUN must be a string'); + error('first argument FUN must be a string'); end -if nargin < 2 - xstart = []; +if nargin < 2 + xstart = []; end input.xstart = xstart; if isempty(xstart) - % xstart = definput.xstart; % objective variables initial point - % warning('Initial search point, and problem dimension, not determined'); - error('Initial search point, and problem dimension, not determined'); + % xstart = definput.xstart; % objective variables initial point + % warning('Initial search point, and problem dimension, not determined'); + error('Initial search point, and problem dimension, not determined'); end -if nargin < 3 - insigma = []; +if nargin < 3 + insigma = []; end if isa(insigma, 'struct') - error(['Third argument SIGMA must be (or eval to) a scalar '... - 'or a column vector of size(X0,1)']); + error(['Third argument SIGMA must be (or eval to) a scalar '... + 'or a column vector of size(X0,1)']); end input.sigma = insigma; if isempty(insigma) - if all(size(myeval(xstart)) > 1) - insigma = std(xstart, 0, 2); - if any(insigma == 0) - error(['Initial search volume is zero, choose SIGMA or X0 appropriate']); + if all(size(myeval(xstart)) > 1) + insigma = std(xstart, 0, 2); + if any(insigma == 0) + error(['Initial search volume is zero, choose SIGMA or X0 appropriate']); + end + else + % will be captured later + % error(['Initial step sizes (SIGMA) not determined']); end - else - % will be captured later - % error(['Initial step sizes (SIGMA) not determined']); - end end % Compose options opts if nargin < 4 || isempty(inopts) % no input options available - inopts = []; - opts = defopts; + inopts = []; + opts = defopts; else - opts = getoptions(inopts, defopts); + opts = getoptions(inopts, defopts); end i = strfind(opts.SaveFilename, ' '); % remove everything after white space if ~isempty(i) - opts.SaveFilename = opts.SaveFilename(1:i(1)-1); + opts.SaveFilename = opts.SaveFilename(1:i(1)-1); end -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -counteval = 0; countevalNaN = 0; +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +counteval = 0; countevalNaN = 0; irun = 0; while irun <= myeval(opts.Restarts) % for-loop does not work with resume - irun = irun + 1; - -% ------------------------ Initialization ------------------------------- - -% Handle resuming of old run -flgresume = myevalbool(opts.Resume); -xmean = myeval(xstart); -if all(size(xmean) > 1) - xmean = mean(xmean, 2); % in case if xstart is a population -elseif size(xmean, 2) > 1 - xmean = xmean'; -end -if ~flgresume % not resuming a former run - % Assign settings from input parameters and options for myeval... - N = size(xmean, 1); numberofvariables = N; - lambda0 = floor(myeval(opts.PopSize) * myeval(opts.IncPopSize)^(irun-1)); - % lambda0 = floor(myeval(opts.PopSize) * 3^floor((irun-1)/2)); - popsize = lambda0; - lambda = lambda0; - insigma = myeval(insigma); - if all(size(insigma) == [N 2]) - insigma = 0.5 * (insigma(:,2) - insigma(:,1)); - end -else % flgresume is true, do resume former run - tmp = whos('-file', opts.SaveFilename); - for i = 1:length(tmp) - if strcmp(tmp(i).name, 'localopts') - error('Saved variables include variable "localopts", please remove'); - end - end - local.opts = opts; % keep stopping and display options - local.varargin = varargin; - load(opts.SaveFilename); - varargin = local.varargin; - flgresume = 1; - - % Overwrite old stopping and display options - opts.StopFitness = local.opts.StopFitness; - %%opts.MaxFunEvals = local.opts.MaxFunEvals; - %%opts.MaxIter = local.opts.MaxIter; - opts.StopFunEvals = local.opts.StopFunEvals; - opts.StopIter = local.opts.StopIter; - opts.TolX = local.opts.TolX; - opts.TolUpX = local.opts.TolUpX; - opts.TolFun = local.opts.TolFun; - opts.TolHistFun = local.opts.TolHistFun; - opts.StopOnStagnation = local.opts.StopOnStagnation; - opts.StopOnWarnings = local.opts.StopOnWarnings; - opts.ReadSignals = local.opts.ReadSignals; - opts.DispFinal = local.opts.DispFinal; - opts.LogPlot = local.opts.LogPlot; - opts.DispModulo = local.opts.DispModulo; - opts.SaveVariables = local.opts.SaveVariables; - opts.LogModulo = local.opts.LogModulo; - opts.LogTime = local.opts.LogTime; - clear local; % otherwise local would be overwritten during load -end - -%-------------------------------------------------------------- -% Evaluate options -stopFitness = myeval(opts.StopFitness); -stopMaxFunEvals = myeval(opts.MaxFunEvals); -stopMaxIter = myeval(opts.MaxIter); -stopFunEvals = myeval(opts.StopFunEvals); -stopIter = myeval(opts.StopIter); -stopTolX = myeval(opts.TolX); -stopTolUpX = myeval(opts.TolUpX); -stopTolFun = myeval(opts.TolFun); -stopTolHistFun = myeval(opts.TolHistFun); -stopOnStagnation = myevalbool(opts.StopOnStagnation); -stopOnWarnings = myevalbool(opts.StopOnWarnings); -flgreadsignals = myevalbool(opts.ReadSignals); -flgWarnOnEqualFunctionValues = myevalbool(opts.WarnOnEqualFunctionValues); -flgEvalParallel = myevalbool(opts.EvalParallel); -stopOnEqualFunctionValues = myeval(opts.StopOnEqualFunctionValues); -arrEqualFunvals = zeros(1,10+N); -flgDiagonalOnly = myeval(opts.DiagonalOnly); -flgActiveCMA = myeval(opts.CMA.active); -noiseHandling = myevalbool(opts.Noise.on); -noiseMinMaxEvals = myeval(opts.Noise.minmaxevals); -noiseAlphaEvals = myeval(opts.Noise.alphaevals); -noiseCallback = myeval(opts.Noise.callback); -flgdisplay = myevalbool(opts.DispFinal); -flgplotting = myevalbool(opts.LogPlot); -verbosemodulo = myeval(opts.DispModulo); -flgscience = myevalbool(opts.Science); -flgsaving = []; -strsaving = []; -if strfind(opts.SaveVariables, '-v6') - i = strfind(opts.SaveVariables, '%'); - if isempty(i) || i == 0 || strfind(opts.SaveVariables, '-v6') < i - strsaving = '-v6'; - flgsaving = 1; - flgsavingfinal = 1; - end -end -if strncmp('final', opts.SaveVariables, 5) - flgsaving = 0; - flgsavingfinal = 1; -end -if isempty(flgsaving) - flgsaving = myevalbool(opts.SaveVariables); - flgsavingfinal = flgsaving; -end -savemodulo = myeval(opts.LogModulo); -savetime = myeval(opts.LogTime); - -i = strfind(opts.LogFilenamePrefix, ' '); % remove everything after white space -if ~isempty(i) - opts.LogFilenamePrefix = opts.LogFilenamePrefix(1:i(1)-1); -end - -% TODO here silent option? set disp, save and log options to 0 - -%-------------------------------------------------------------- - -if (isfinite(stopFunEvals) || isfinite(stopIter)) && ~flgsaving - warning('To resume later the saving option needs to be set'); -end - - -% Do more checking and initialization -if flgresume % resume is on - time.t0 = clock; - if flgdisplay - disp([' resumed from ' opts.SaveFilename ]); - end - if counteval >= stopMaxFunEvals - error(['MaxFunEvals exceeded, use StopFunEvals as stopping ' ... - 'criterion before resume']); - end - if countiter >= stopMaxIter - error(['MaxIter exceeded, use StopIter as stopping criterion ' ... - 'before resume']); - end - -else % flgresume - % xmean = mean(myeval(xstart), 2); % evaluate xstart again, because of irun - maxdx = myeval(opts.DiffMaxChange); % maximal sensible variable change - mindx = myeval(opts.DiffMinChange); % minimal sensible variable change - % can both also be defined as Nx1 vectors - lbounds = myeval(opts.LBounds); - ubounds = myeval(opts.UBounds); - if length(lbounds) == 1 - lbounds = repmat(lbounds, N, 1); - end - if length(ubounds) == 1 - ubounds = repmat(ubounds, N, 1); - end - if isempty(insigma) % last chance to set insigma - if all(lbounds > -Inf) && all(ubounds < Inf) - if any(lbounds>=ubounds) - error('upper bound must be greater than lower bound'); - end - insigma = 0.3*(ubounds-lbounds); - stopTolX = myeval(opts.TolX); % reevaluate these - stopTolUpX = myeval(opts.TolUpX); - else - error(['Initial step sizes (SIGMA) not determined']); - end - end - - % Check all vector sizes - if size(xmean, 2) > 1 || size(xmean,1) ~= N - error(['intial search point should be a column vector of size ' ... - num2str(N)]); - elseif ~(all(size(insigma) == [1 1]) || all(size(insigma) == [N 1])) - error(['input parameter SIGMA should be (or eval to) a scalar '... - 'or a column vector of size ' num2str(N)] ); - elseif size(stopTolX, 2) > 1 || ~ismember(size(stopTolX, 1), [1 N]) - error(['option TolX should be (or eval to) a scalar '... - 'or a column vector of size ' num2str(N)] ); - elseif size(stopTolUpX, 2) > 1 || ~ismember(size(stopTolUpX, 1), [1 N]) - error(['option TolUpX should be (or eval to) a scalar '... - 'or a column vector of size ' num2str(N)] ); - elseif size(maxdx, 2) > 1 || ~ismember(size(maxdx, 1), [1 N]) - error(['option DiffMaxChange should be (or eval to) a scalar '... - 'or a column vector of size ' num2str(N)] ); - elseif size(mindx, 2) > 1 || ~ismember(size(mindx, 1), [1 N]) - error(['option DiffMinChange should be (or eval to) a scalar '... - 'or a column vector of size ' num2str(N)] ); - elseif size(lbounds, 2) > 1 || ~ismember(size(lbounds, 1), [1 N]) - error(['option lbounds should be (or eval to) a scalar '... - 'or a column vector of size ' num2str(N)] ); - elseif size(ubounds, 2) > 1 || ~ismember(size(ubounds, 1), [1 N]) - error(['option ubounds should be (or eval to) a scalar '... - 'or a column vector of size ' num2str(N)] ); - end - - % Initialize dynamic internal state parameters - if any(insigma <= 0) - error(['Initial search volume (SIGMA) must be greater than zero']); - end - if max(insigma)/min(insigma) > 1e6 - error(['Initial search volume (SIGMA) badly conditioned']); - end - sigma = max(insigma); % overall standard deviation - pc = zeros(N,1); ps = zeros(N,1); % evolution paths for C and sigma - - if length(insigma) == 1 - insigma = insigma * ones(N,1) ; - end - diagD = insigma/max(insigma); % diagonal matrix D defines the scaling - diagC = diagD.^2; - if flgDiagonalOnly ~= 1 % use at some point full covariance matrix - B = eye(N,N); % B defines the coordinate system - BD = B.*repmat(diagD',N,1); % B*D for speed up only - C = diag(diagC); % covariance matrix == BD*(BD)' - end - if flgDiagonalOnly - B = 1; - end - - fitness.hist=NaN*ones(1,10+ceil(3*10*N/lambda)); % history of fitness values - fitness.histsel=NaN*ones(1,10+ceil(3*10*N/lambda)); % history of fitness values - fitness.histbest=[]; % history of fitness values - fitness.histmedian=[]; % history of fitness values - - % Initialize boundary handling - bnd.isactive = any(lbounds > -Inf) || any(ubounds < Inf); - if bnd.isactive - if any(lbounds>ubounds) - error('lower bound found to be greater than upper bound'); + irun = irun + 1; + + % ------------------------ Initialization ------------------------------- + + % Handle resuming of old run + flgresume = myevalbool(opts.Resume); + xmean = myeval(xstart); + if all(size(xmean) > 1) + xmean = mean(xmean, 2); % in case if xstart is a population + elseif size(xmean, 2) > 1 + xmean = xmean'; end - [xmean, ti] = xintobounds(xmean, lbounds, ubounds); % just in case - if any(ti) - warning('Initial point was out of bounds, corrected'); + if ~flgresume % not resuming a former run + % Assign settings from input parameters and options for myeval... + N = size(xmean, 1); numberofvariables = N; + lambda0 = floor(myeval(opts.PopSize) * myeval(opts.IncPopSize)^(irun-1)); + % lambda0 = floor(myeval(opts.PopSize) * 3^floor((irun-1)/2)); + popsize = lambda0; + lambda = lambda0; + insigma = myeval(insigma); + if all(size(insigma) == [N 2]) + insigma = 0.5 * (insigma(:,2) - insigma(:,1)); + end + else % flgresume is true, do resume former run + tmp = whos('-file', opts.SaveFilename); + for i = 1:length(tmp) + if strcmp(tmp(i).name, 'localopts') + error('Saved variables include variable "localopts", please remove'); + end + end + local.opts = opts; % keep stopping and display options + local.varargin = varargin; + load(opts.SaveFilename); + varargin = local.varargin; + flgresume = 1; + + % Overwrite old stopping and display options + opts.StopFitness = local.opts.StopFitness; + %%opts.MaxFunEvals = local.opts.MaxFunEvals; + %%opts.MaxIter = local.opts.MaxIter; + opts.StopFunEvals = local.opts.StopFunEvals; + opts.StopIter = local.opts.StopIter; + opts.TolX = local.opts.TolX; + opts.TolUpX = local.opts.TolUpX; + opts.TolFun = local.opts.TolFun; + opts.TolHistFun = local.opts.TolHistFun; + opts.StopOnStagnation = local.opts.StopOnStagnation; + opts.StopOnWarnings = local.opts.StopOnWarnings; + opts.ReadSignals = local.opts.ReadSignals; + opts.DispFinal = local.opts.DispFinal; + opts.LogPlot = local.opts.LogPlot; + opts.DispModulo = local.opts.DispModulo; + opts.SaveVariables = local.opts.SaveVariables; + opts.LogModulo = local.opts.LogModulo; + opts.LogTime = local.opts.LogTime; + clear local; % otherwise local would be overwritten during load end - bnd.weights = zeros(N,1); % weights for bound penalty - % scaling is better in axis-parallel case, worse in rotated - bnd.flgscale = 0; % scaling will be omitted if zero - if bnd.flgscale ~= 0 - bnd.scale = diagC/mean(diagC); - else - bnd.scale = ones(N,1); + + %-------------------------------------------------------------- + % Evaluate options + stopFitness = myeval(opts.StopFitness); + stopMaxFunEvals = myeval(opts.MaxFunEvals); + stopMaxIter = myeval(opts.MaxIter); + stopFunEvals = myeval(opts.StopFunEvals); + stopIter = myeval(opts.StopIter); + stopTolX = myeval(opts.TolX); + stopTolUpX = myeval(opts.TolUpX); + stopTolFun = myeval(opts.TolFun); + stopTolHistFun = myeval(opts.TolHistFun); + stopOnStagnation = myevalbool(opts.StopOnStagnation); + stopOnWarnings = myevalbool(opts.StopOnWarnings); + flgreadsignals = myevalbool(opts.ReadSignals); + flgWarnOnEqualFunctionValues = myevalbool(opts.WarnOnEqualFunctionValues); + flgEvalParallel = myevalbool(opts.EvalParallel); + stopOnEqualFunctionValues = myeval(opts.StopOnEqualFunctionValues); + arrEqualFunvals = zeros(1,10+N); + flgDiagonalOnly = myeval(opts.DiagonalOnly); + flgActiveCMA = myeval(opts.CMA.active); + noiseHandling = myevalbool(opts.Noise.on); + noiseMinMaxEvals = myeval(opts.Noise.minmaxevals); + noiseAlphaEvals = myeval(opts.Noise.alphaevals); + noiseCallback = myeval(opts.Noise.callback); + flgdisplay = myevalbool(opts.DispFinal); + flgplotting = myevalbool(opts.LogPlot); + verbosemodulo = myeval(opts.DispModulo); + flgscience = myevalbool(opts.Science); + flgsaving = []; + strsaving = []; + if strfind(opts.SaveVariables, '-v6') + i = strfind(opts.SaveVariables, '%'); + if isempty(i) || i == 0 || strfind(opts.SaveVariables, '-v6') < i + strsaving = '-v6'; + flgsaving = 1; + flgsavingfinal = 1; + end end - - idx = (lbounds > -Inf) | (ubounds < Inf); - if length(idx) == 1 - idx = idx * ones(N,1); + if strncmp('final', opts.SaveVariables, 5) + flgsaving = 0; + flgsavingfinal = 1; end - bnd.isbounded = zeros(N,1); - bnd.isbounded(find(idx)) = 1; - maxdx = min(maxdx, (ubounds - lbounds)/2); - if any(sigma*sqrt(diagC) > maxdx) - fac = min(maxdx ./ sqrt(diagC))/sigma; - sigma = min(maxdx ./ sqrt(diagC)); - warning(['Initial SIGMA multiplied by the factor ' num2str(fac) ... - ', because it was larger than half' ... - ' of one of the boundary intervals']); + if isempty(flgsaving) + flgsaving = myevalbool(opts.SaveVariables); + flgsavingfinal = flgsaving; end - idx = (lbounds > -Inf) & (ubounds < Inf); - dd = diagC; - if any(5*sigma*sqrt(dd(idx)) < ubounds(idx) - lbounds(idx)) - warning(['Initial SIGMA is, in at least one coordinate, ' ... - 'much smaller than the '... - 'given boundary intervals. For reasonable ' ... - 'global search performance SIGMA should be ' ... - 'between 0.2 and 0.5 of the bounded interval in ' ... - 'each coordinate. If all coordinates have ' ... - 'lower and upper bounds SIGMA can be empty']); + savemodulo = myeval(opts.LogModulo); + savetime = myeval(opts.LogTime); + + i = strfind(opts.LogFilenamePrefix, ' '); % remove everything after white space + if ~isempty(i) + opts.LogFilenamePrefix = opts.LogFilenamePrefix(1:i(1)-1); end - bnd.dfithist = 1; % delta fit for setting weights - bnd.aridxpoints = []; % remember complete outside points - bnd.arfitness = []; % and their fitness - bnd.validfitval = 0; - bnd.iniphase = 1; - end - - % ooo initial feval, for output only - if irun == 1 - out.solutions.bestever.x = xmean; - out.solutions.bestever.f = Inf; % for simpler comparison below - out.solutions.bestever.evals = counteval; - bestever = out.solutions.bestever; - end - if myevalbool(opts.EvalInitialX) - fitness.hist(1)=feval(fitfun, xmean, varargin{:}); - fitness.histsel(1)=fitness.hist(1); - counteval = counteval + 1; - if fitness.hist(1) < out.solutions.bestever.f - out.solutions.bestever.x = xmean; - out.solutions.bestever.f = fitness.hist(1); - out.solutions.bestever.evals = counteval; - bestever = out.solutions.bestever; + + % TODO here silent option? set disp, save and log options to 0 + + %-------------------------------------------------------------- + + if (isfinite(stopFunEvals) || isfinite(stopIter)) && ~flgsaving + warning('To resume later the saving option needs to be set'); end - else - fitness.hist(1)=NaN; - fitness.histsel(1)=NaN; - end - - % initialize random number generator + + + % Do more checking and initialization + if flgresume % resume is on + time.t0 = clock; + if flgdisplay + disp([' resumed from ' opts.SaveFilename ]); + end + if counteval >= stopMaxFunEvals + error(['MaxFunEvals exceeded, use StopFunEvals as stopping ' ... + 'criterion before resume']); + end + if countiter >= stopMaxIter + error(['MaxIter exceeded, use StopIter as stopping criterion ' ... + 'before resume']); + end + + else % flgresume + % xmean = mean(myeval(xstart), 2); % evaluate xstart again, because of irun + maxdx = myeval(opts.DiffMaxChange); % maximal sensible variable change + mindx = myeval(opts.DiffMinChange); % minimal sensible variable change + % can both also be defined as Nx1 vectors + lbounds = myeval(opts.LBounds); + ubounds = myeval(opts.UBounds); + if length(lbounds) == 1 + lbounds = repmat(lbounds, N, 1); + end + if length(ubounds) == 1 + ubounds = repmat(ubounds, N, 1); + end + if isempty(insigma) % last chance to set insigma + if all(lbounds > -Inf) && all(ubounds < Inf) + if any(lbounds>=ubounds) + error('upper bound must be greater than lower bound'); + end + insigma = 0.3*(ubounds-lbounds); + stopTolX = myeval(opts.TolX); % reevaluate these + stopTolUpX = myeval(opts.TolUpX); + else + error(['Initial step sizes (SIGMA) not determined']); + end + end + + % Check all vector sizes + if size(xmean, 2) > 1 || size(xmean,1) ~= N + error(['intial search point should be a column vector of size ' ... + num2str(N)]); + elseif ~(all(size(insigma) == [1 1]) || all(size(insigma) == [N 1])) + error(['input parameter SIGMA should be (or eval to) a scalar '... + 'or a column vector of size ' num2str(N)] ); + elseif size(stopTolX, 2) > 1 || ~ismember(size(stopTolX, 1), [1 N]) + error(['option TolX should be (or eval to) a scalar '... + 'or a column vector of size ' num2str(N)] ); + elseif size(stopTolUpX, 2) > 1 || ~ismember(size(stopTolUpX, 1), [1 N]) + error(['option TolUpX should be (or eval to) a scalar '... + 'or a column vector of size ' num2str(N)] ); + elseif size(maxdx, 2) > 1 || ~ismember(size(maxdx, 1), [1 N]) + error(['option DiffMaxChange should be (or eval to) a scalar '... + 'or a column vector of size ' num2str(N)] ); + elseif size(mindx, 2) > 1 || ~ismember(size(mindx, 1), [1 N]) + error(['option DiffMinChange should be (or eval to) a scalar '... + 'or a column vector of size ' num2str(N)] ); + elseif size(lbounds, 2) > 1 || ~ismember(size(lbounds, 1), [1 N]) + error(['option lbounds should be (or eval to) a scalar '... + 'or a column vector of size ' num2str(N)] ); + elseif size(ubounds, 2) > 1 || ~ismember(size(ubounds, 1), [1 N]) + error(['option ubounds should be (or eval to) a scalar '... + 'or a column vector of size ' num2str(N)] ); + end + + % Initialize dynamic internal state parameters + if any(insigma <= 0) + error(['Initial search volume (SIGMA) must be greater than zero']); + end + if max(insigma)/min(insigma) > 1e6 + error(['Initial search volume (SIGMA) badly conditioned']); + end + sigma = max(insigma); % overall standard deviation + pc = zeros(N,1); ps = zeros(N,1); % evolution paths for C and sigma + + if length(insigma) == 1 + insigma = insigma * ones(N,1) ; + end + diagD = insigma/max(insigma); % diagonal matrix D defines the scaling + diagC = diagD.^2; + if flgDiagonalOnly ~= 1 % use at some point full covariance matrix + B = eye(N,N); % B defines the coordinate system + BD = B.*repmat(diagD',N,1); % B*D for speed up only + C = diag(diagC); % covariance matrix == BD*(BD)' + end + if flgDiagonalOnly + B = 1; + end + + fitness.hist=NaN*ones(1,10+ceil(3*10*N/lambda)); % history of fitness values + fitness.histsel=NaN*ones(1,10+ceil(3*10*N/lambda)); % history of fitness values + fitness.histbest=[]; % history of fitness values + fitness.histmedian=[]; % history of fitness values + + % Initialize boundary handling + bnd.isactive = any(lbounds > -Inf) || any(ubounds < Inf); + if bnd.isactive + if any(lbounds>ubounds) + error('lower bound found to be greater than upper bound'); + end + [xmean, ti] = xintobounds(xmean, lbounds, ubounds); % just in case + if any(ti) + warning('Initial point was out of bounds, corrected'); + end + bnd.weights = zeros(N,1); % weights for bound penalty + % scaling is better in axis-parallel case, worse in rotated + bnd.flgscale = 0; % scaling will be omitted if zero + if bnd.flgscale ~= 0 + bnd.scale = diagC/mean(diagC); + else + bnd.scale = ones(N,1); + end + + idx = (lbounds > -Inf) | (ubounds < Inf); + if length(idx) == 1 + idx = idx * ones(N,1); + end + bnd.isbounded = zeros(N,1); + bnd.isbounded(find(idx)) = 1; + maxdx = min(maxdx, (ubounds - lbounds)/2); + if any(sigma*sqrt(diagC) > maxdx) + fac = min(maxdx ./ sqrt(diagC))/sigma; + sigma = min(maxdx ./ sqrt(diagC)); + warning(['Initial SIGMA multiplied by the factor ' num2str(fac) ... + ', because it was larger than half' ... + ' of one of the boundary intervals']); + end + idx = (lbounds > -Inf) & (ubounds < Inf); + dd = diagC; + if any(5*sigma*sqrt(dd(idx)) < ubounds(idx) - lbounds(idx)) + warning(['Initial SIGMA is, in at least one coordinate, ' ... + 'much smaller than the '... + 'given boundary intervals. For reasonable ' ... + 'global search performance SIGMA should be ' ... + 'between 0.2 and 0.5 of the bounded interval in ' ... + 'each coordinate. If all coordinates have ' ... + 'lower and upper bounds SIGMA can be empty']); + end + bnd.dfithist = 1; % delta fit for setting weights + bnd.aridxpoints = []; % remember complete outside points + bnd.arfitness = []; % and their fitness + bnd.validfitval = 0; + bnd.iniphase = 1; + end + + % ooo initial feval, for output only + if irun == 1 + out.solutions.bestever.x = xmean; + out.solutions.bestever.f = Inf; % for simpler comparison below + out.solutions.bestever.evals = counteval; + bestever = out.solutions.bestever; + end + if myevalbool(opts.EvalInitialX) + fitness.hist(1)=feval(fitfun, xmean, varargin{:}); + fitness.histsel(1)=fitness.hist(1); + counteval = counteval + 1; + if fitness.hist(1) < out.solutions.bestever.f + out.solutions.bestever.x = xmean; + out.solutions.bestever.f = fitness.hist(1); + out.solutions.bestever.evals = counteval; + bestever = out.solutions.bestever; + end + else + fitness.hist(1)=NaN; + fitness.histsel(1)=NaN; + end + + % initialize random number generator % $$$ if ischar(opts.Seed) % $$$ randn('state', eval(opts.Seed)); % random number generator state % $$$ else % $$$ randn('state', opts.Seed); % $$$ end - %qqq +%qqq % load(opts.SaveFilename, 'startseed'); % randn('state', startseed); % disp(['SEED RELOADED FROM ' opts.SaveFilename]); % startseed = randn('state'); % for retrieving in saved variables - % Initialize further constants - chiN=N^0.5*(1-1/(4*N)+1/(21*N^2)); % expectation of - % ||N(0,I)|| == norm(randn(N,1)) - - countiter = 0; - % Initialize records and output - if irun == 1 - time.t0 = clock; - - % TODO: keep also median solution? - out.evals = counteval; % should be first entry - out.stopflag = {}; - - outiter = 0; - - % Write headers to output data files - filenameprefix = opts.LogFilenamePrefix; - if savemodulo && savetime - filenames = {}; - filenames(end+1) = {'axlen'}; - filenames(end+1) = {'fit'}; - filenames(end+1) = {'stddev'}; - filenames(end+1) = {'xmean'}; - filenames(end+1) = {'xrecentbest'}; - str = [' (startseed=' num2str(startseed(2)) ... - ', ' num2str(clock, '%d/%02d/%d %d:%d:%2.2f') ')']; - for namecell = filenames(:)' - name = namecell{:}; - - [fid, err] = fopen(['./' filenameprefix name '.dat'], 'w'); - if fid < 1 % err ~= 0 - warning(['could not open ' filenameprefix name '.dat']); - filenames(find(strcmp(filenames,name))) = []; - else -% fprintf(fid, '%s\n', ... -% ['<CMAES-OUTPUT version="' cmaVersion '">']); -% fprintf(fid, [' <NAME>' name '</NAME>\n']); -% fprintf(fid, [' <DATE>' date() '</DATE>\n']); -% fprintf(fid, ' <PARAMETERS>\n'); -% fprintf(fid, [' dimension=' num2str(N) '\n']); -% fprintf(fid, ' </PARAMETERS>\n'); - % different cases for DATA columns annotations here -% fprintf(fid, ' <DATA'); - if strcmp(name, 'axlen') - fprintf(fid, ['%% columns="iteration, evaluation, sigma, ' ... - 'max axis length, min axis length, ' ... - 'all principal axes lengths (sorted square roots ' ... - 'of eigenvalues of C)"' str]); - elseif strcmp(name, 'fit') - fprintf(fid, ['%% columns="iteration, evaluation, sigma, axis ratio, bestever,' ... - ' best, median, worst fitness function value,' ... - ' further objective values of best"' str]); - elseif strcmp(name, 'stddev') - fprintf(fid, ['%% columns=["iteration, evaluation, sigma, void, void, ' ... - 'stds==sigma*sqrt(diag(C))"' str]); - elseif strcmp(name, 'xmean') - fprintf(fid, ['%% columns="iteration, evaluation, void, ' ... - 'void, void, xmean"' str]); - elseif strcmp(name, 'xrecentbest') - fprintf(fid, ['%% columns="iteration, evaluation, fitness, ' ... - 'void, void, xrecentbest"' str]); - end - fprintf(fid, '\n'); % DATA - if strcmp(name, 'xmean') - fprintf(fid, '%ld %ld 0 0 0 ', 0, counteval); - % fprintf(fid, '%ld %ld 0 0 %e ', countiter, counteval, fmean); -%qqq fprintf(fid, msprintf('%e ', genophenotransform(out.genopheno, xmean)) + '\n'); - fprintf(fid, '%e ', xmean); - fprintf(fid, '\n'); - end - fclose(fid); - clear fid; % preventing - end - end % for files - end % savemodulo - end % irun == 1 - -end % else flgresume - -% -------------------- Generation Loop -------------------------------- -stopflag = {}; -while isempty(stopflag) - % set internal parameters - if countiter == 0 || lambda ~= lambda_last - if countiter > 0 && floor(log10(lambda)) ~= floor(log10(lambda_last)) ... - && flgdisplay - disp([' lambda = ' num2str(lambda)]); - lambda_hist(:,end+1) = [countiter+1; lambda]; - else - lambda_hist = [countiter+1; lambda]; - end - lambda_last = lambda; - % Strategy internal parameter setting: Selection - mu = myeval(opts.ParentNumber); % number of parents/points for recombination - if strncmp(lower(opts.RecombinationWeights), 'equal', 3) - weights = ones(mu,1); % (mu_I,lambda)-CMA-ES - elseif strncmp(lower(opts.RecombinationWeights), 'linear', 3) - weights = mu+0.5-(1:mu)'; - elseif strncmp(lower(opts.RecombinationWeights), 'superlinear', 3) - weights = log(mu+0.5)-log(1:mu)'; % muXone array for weighted recombination - % qqq mu can be non-integer and - % should become ceil(mu-0.5) (minor correction) - else - error(['Recombination weights to be "' opts.RecombinationWeights ... - '" is not implemented']); - end - mueff=sum(weights)^2/sum(weights.^2); % variance-effective size of mu - weights = weights/sum(weights); % normalize recombination weights array - if mueff == lambda - error(['Combination of values for PopSize, ParentNumber and ' ... - ' and RecombinationWeights is not reasonable']); - end - - % Strategy internal parameter setting: Adaptation - cc = myeval(opts.CMA.ccum); % time constant for cumulation for covariance matrix - cs = myeval(opts.CMA.cs); - - % old way TODO: remove this at some point - % mucov = mueff; % size of mu used for calculating learning rate ccov - % ccov = (1/mucov) * 2/(N+1.41)^2 ... % learning rate for covariance matrix - % + (1-1/mucov) * min(1,(2*mucov-1)/((N+2)^2+mucov)); - - % new way - if myevalbool(opts.CMA.on) - ccov1 = myeval(opts.CMA.ccov1); - ccovmu = min(1-ccov1, myeval(opts.CMA.ccovmu)); - else - ccov1 = 0; - ccovmu = 0; - end - - % flgDiagonalOnly = -lambda*4*1/ccov; % for ccov==1 it is not needed - % 0 : C will never be diagonal anymore - % 1 : C will always be diagonal - % >1: C is diagonal for first iterations, set to 0 afterwards - if flgDiagonalOnly < 1 - flgDiagonalOnly = 0; - end - if flgDiagonalOnly - ccov1_sep = min(1, ccov1 * (N+1.5) / 3); - ccovmu_sep = min(1-ccov1_sep, ccovmu * (N+1.5) / 3); - elseif N > 98 && flgdisplay && countiter == 0 - disp('consider option DiagonalOnly for high-dimensional problems'); - end - - % ||ps|| is close to sqrt(mueff/N) for mueff large on linear fitness - %damps = ... % damping for step size control, usually close to one - % (1 + 2*max(0,sqrt((mueff-1)/(N+1))-1)) ... % limit sigma increase - % * max(0.3, ... % reduce damps, if max. iteration number is small - % 1 - N/min(stopMaxIter,stopMaxFunEvals/lambda)) + cs; - damps = myeval(opts.CMA.damps); - if noiseHandling - noiseReevals = min(myeval(opts.Noise.reevals), lambda); - noiseAlpha = myeval(opts.Noise.alphasigma); - noiseEpsilon = myeval(opts.Noise.epsilon); - noiseTheta = myeval(opts.Noise.theta); - noisecum = myeval(opts.Noise.cum); - noiseCutOff = myeval(opts.Noise.cutoff); % arguably of minor relevance - else - noiseReevals = 0; % more convenient in later coding - end + % Initialize further constants + chiN=N^0.5*(1-1/(4*N)+1/(21*N^2)); % expectation of + % ||N(0,I)|| == norm(randn(N,1)) + + countiter = 0; + % Initialize records and output + if irun == 1 + time.t0 = clock; + + % TODO: keep also median solution? + out.evals = counteval; % should be first entry + out.stopflag = {}; + + outiter = 0; + + % Write headers to output data files + filenameprefix = opts.LogFilenamePrefix; + if savemodulo && savetime + filenames = {}; + filenames(end+1) = {'axlen'}; + filenames(end+1) = {'fit'}; + filenames(end+1) = {'stddev'}; + filenames(end+1) = {'xmean'}; + filenames(end+1) = {'xrecentbest'}; + str = [' (startseed=' num2str(startseed(2)) ... + ', ' num2str(clock, '%d/%02d/%d %d:%d:%2.2f') ')']; + for namecell = filenames(:)' + name = namecell{:}; + + [fid, err] = fopen(['./' filenameprefix name '.dat'], 'w'); + if fid < 1 % err ~= 0 + warning(['could not open ' filenameprefix name '.dat']); + filenames(find(strcmp(filenames,name))) = []; + else + % fprintf(fid, '%s\n', ... + % ['<CMAES-OUTPUT version="' cmaVersion '">']); + % fprintf(fid, [' <NAME>' name '</NAME>\n']); + % fprintf(fid, [' <DATE>' date() '</DATE>\n']); + % fprintf(fid, ' <PARAMETERS>\n'); + % fprintf(fid, [' dimension=' num2str(N) '\n']); + % fprintf(fid, ' </PARAMETERS>\n'); + % different cases for DATA columns annotations here + % fprintf(fid, ' <DATA'); + if strcmp(name, 'axlen') + fprintf(fid, ['%% columns="iteration, evaluation, sigma, ' ... + 'max axis length, min axis length, ' ... + 'all principal axes lengths (sorted square roots ' ... + 'of eigenvalues of C)"' str]); + elseif strcmp(name, 'fit') + fprintf(fid, ['%% columns="iteration, evaluation, sigma, axis ratio, bestever,' ... + ' best, median, worst fitness function value,' ... + ' further objective values of best"' str]); + elseif strcmp(name, 'stddev') + fprintf(fid, ['%% columns=["iteration, evaluation, sigma, void, void, ' ... + 'stds==sigma*sqrt(diag(C))"' str]); + elseif strcmp(name, 'xmean') + fprintf(fid, ['%% columns="iteration, evaluation, void, ' ... + 'void, void, xmean"' str]); + elseif strcmp(name, 'xrecentbest') + fprintf(fid, ['%% columns="iteration, evaluation, fitness, ' ... + 'void, void, xrecentbest"' str]); + end + fprintf(fid, '\n'); % DATA + if strcmp(name, 'xmean') + fprintf(fid, '%ld %ld 0 0 0 ', 0, counteval); + % fprintf(fid, '%ld %ld 0 0 %e ', countiter, counteval, fmean); + %qqq fprintf(fid, msprintf('%e ', genophenotransform(out.genopheno, xmean)) + '\n'); + fprintf(fid, '%e ', xmean); + fprintf(fid, '\n'); + end + fclose(fid); + clear fid; % preventing + end + end % for files + end % savemodulo + end % irun == 1 + + end % else flgresume + + % -------------------- Generation Loop -------------------------------- + stopflag = {}; + while isempty(stopflag) + % set internal parameters + if countiter == 0 || lambda ~= lambda_last + if countiter > 0 && floor(log10(lambda)) ~= floor(log10(lambda_last)) ... + && flgdisplay + disp([' lambda = ' num2str(lambda)]); + lambda_hist(:,end+1) = [countiter+1; lambda]; + else + lambda_hist = [countiter+1; lambda]; + end + lambda_last = lambda; + % Strategy internal parameter setting: Selection + mu = myeval(opts.ParentNumber); % number of parents/points for recombination + if strncmp(lower(opts.RecombinationWeights), 'equal', 3) + weights = ones(mu,1); % (mu_I,lambda)-CMA-ES + elseif strncmp(lower(opts.RecombinationWeights), 'linear', 3) + weights = mu+0.5-(1:mu)'; + elseif strncmp(lower(opts.RecombinationWeights), 'superlinear', 3) + weights = log(mu+0.5)-log(1:mu)'; % muXone array for weighted recombination + % qqq mu can be non-integer and + % should become ceil(mu-0.5) (minor correction) + else + error(['Recombination weights to be "' opts.RecombinationWeights ... + '" is not implemented']); + end + mueff=sum(weights)^2/sum(weights.^2); % variance-effective size of mu + weights = weights/sum(weights); % normalize recombination weights array + if mueff == lambda + error(['Combination of values for PopSize, ParentNumber and ' ... + ' and RecombinationWeights is not reasonable']); + end + + % Strategy internal parameter setting: Adaptation + cc = myeval(opts.CMA.ccum); % time constant for cumulation for covariance matrix + cs = myeval(opts.CMA.cs); + + % old way TODO: remove this at some point + % mucov = mueff; % size of mu used for calculating learning rate ccov + % ccov = (1/mucov) * 2/(N+1.41)^2 ... % learning rate for covariance matrix + % + (1-1/mucov) * min(1,(2*mucov-1)/((N+2)^2+mucov)); + + % new way + if myevalbool(opts.CMA.on) + ccov1 = myeval(opts.CMA.ccov1); + ccovmu = min(1-ccov1, myeval(opts.CMA.ccovmu)); + else + ccov1 = 0; + ccovmu = 0; + end + + % flgDiagonalOnly = -lambda*4*1/ccov; % for ccov==1 it is not needed + % 0 : C will never be diagonal anymore + % 1 : C will always be diagonal + % >1: C is diagonal for first iterations, set to 0 afterwards + if flgDiagonalOnly < 1 + flgDiagonalOnly = 0; + end + if flgDiagonalOnly + ccov1_sep = min(1, ccov1 * (N+1.5) / 3); + ccovmu_sep = min(1-ccov1_sep, ccovmu * (N+1.5) / 3); + elseif N > 98 && flgdisplay && countiter == 0 + disp('consider option DiagonalOnly for high-dimensional problems'); + end + + % ||ps|| is close to sqrt(mueff/N) for mueff large on linear fitness + %damps = ... % damping for step size control, usually close to one + % (1 + 2*max(0,sqrt((mueff-1)/(N+1))-1)) ... % limit sigma increase + % * max(0.3, ... % reduce damps, if max. iteration number is small + % 1 - N/min(stopMaxIter,stopMaxFunEvals/lambda)) + cs; + damps = myeval(opts.CMA.damps); + if noiseHandling + noiseReevals = min(myeval(opts.Noise.reevals), lambda); + noiseAlpha = myeval(opts.Noise.alphasigma); + noiseEpsilon = myeval(opts.Noise.epsilon); + noiseTheta = myeval(opts.Noise.theta); + noisecum = myeval(opts.Noise.cum); + noiseCutOff = myeval(opts.Noise.cutoff); % arguably of minor relevance + else + noiseReevals = 0; % more convenient in later coding + end + + %qqq hacking of a different parameter setting, e.g. for ccov or damps, + % can be done here, but is not necessary anymore, see opts.CMA. + % ccov1 = 0.0*ccov1; disp(['CAVE: ccov1=' num2str(ccov1)]); + % ccovmu = 0.0*ccovmu; disp(['CAVE: ccovmu=' num2str(ccovmu)]); + % damps = inf*damps; disp(['CAVE: damps=' num2str(damps)]); + % cc = 1; disp(['CAVE: cc=' num2str(cc)]); - %qqq hacking of a different parameter setting, e.g. for ccov or damps, - % can be done here, but is not necessary anymore, see opts.CMA. - % ccov1 = 0.0*ccov1; disp(['CAVE: ccov1=' num2str(ccov1)]); - % ccovmu = 0.0*ccovmu; disp(['CAVE: ccovmu=' num2str(ccovmu)]); - % damps = inf*damps; disp(['CAVE: damps=' num2str(damps)]); - % cc = 1; disp(['CAVE: cc=' num2str(cc)]); - - end - - % Display initial message - if countiter == 0 && flgdisplay - if mu == 1 - strw = '100'; - elseif mu < 8 - strw = [sprintf('%.0f', 100*weights(1)) ... - sprintf(' %.0f', 100*weights(2:end)')]; - else - strw = [sprintf('%.2g ', 100*weights(1:2)') ... - sprintf('%.2g', 100*weights(3)') '...' ... - sprintf(' %.2g', 100*weights(end-1:end)') ']%, ']; - end - if irun > 1 - strrun = [', run ' num2str(irun)]; - else - strrun = ''; - end - disp([' n=' num2str(N) ': (' num2str(mu) ',' ... - num2str(lambda) ')-CMA-ES(w=[' ... - strw ']%, ' ... - 'mu_eff=' num2str(mueff,'%.1f') ... - ') on function ' ... - (fitfun) strrun]); - if flgDiagonalOnly == 1 - disp(' C is diagonal'); - elseif flgDiagonalOnly - disp([' C is diagonal for ' num2str(floor(flgDiagonalOnly)) ' iterations']); - end - end - - flush; - - countiter = countiter + 1; - - % Generate and evaluate lambda offspring - - fitness.raw = repmat(NaN, 1, lambda + noiseReevals); - - % parallel evaluation - if flgEvalParallel - arz = randn(N,lambda); - - if ~flgDiagonalOnly - arx = repmat(xmean, 1, lambda) + sigma * (BD * arz); % Eq. (1) - else - arx = repmat(xmean, 1, lambda) + repmat(sigma * diagD, 1, lambda) .* arz; - end - - if noiseHandling - if noiseEpsilon == 0 - arx = [arx arx(:,1:noiseReevals)]; - elseif flgDiagonalOnly - arx = [arx arx(:,1:noiseReevals) + ... - repmat(noiseEpsilon * sigma * diagD, 1, noiseReevals) ... - .* randn(N,noiseReevals)]; - else - arx = [arx arx(:,1:noiseReevals) + ... - noiseEpsilon * sigma * ... - (BD * randn(N,noiseReevals))]; - end - end - - % You may handle constraints here. You may either resample - % arz(:,k) and/or multiply it with a factor between -1 and 1 - % (the latter will decrease the overall step size) and - % recalculate arx accordingly. Do not change arx or arz in any - % other way. - - if ~bnd.isactive - arxvalid = arx; - else - arxvalid = xintobounds(arx, lbounds, ubounds); - end - % You may handle constraints here. You may copy and alter - % (columns of) arxvalid(:,k) only for the evaluation of the - % fitness function. arx and arxvalid should not be changed. - fitness.raw = feval(fitfun, arxvalid, varargin{:}); - countevalNaN = countevalNaN + sum(isnan(fitness.raw)); - counteval = counteval + sum(~isnan(fitness.raw)); - end - - % non-parallel evaluation and remaining NaN-values - % set also the reevaluated solution to NaN - fitness.raw(lambda + find(isnan(fitness.raw(1:noiseReevals)))) = NaN; - for k=find(isnan(fitness.raw)) - % fitness.raw(k) = NaN; - tries = 0; - % Resample, until fitness is not NaN - while isnan(fitness.raw(k)) - if k <= lambda % regular samples (not the re-evaluation-samples) - arz(:,k) = randn(N,1); % (re)sample - - if flgDiagonalOnly - arx(:,k) = xmean + sigma * diagD .* arz(:,k); % Eq. (1) - else - arx(:,k) = xmean + sigma * (BD * arz(:,k)); % Eq. (1) end - else % re-evaluation solution with index > lambda - if flgDiagonalOnly - arx(:,k) = arx(:,k-lambda) + (noiseEpsilon * sigma) * diagD .* randn(N,1); - else - arx(:,k) = arx(:,k-lambda) + (noiseEpsilon * sigma) * (BD * randn(N,1)); - end - end - - % You may handle constraints here. You may either resample - % arz(:,k) and/or multiply it with a factor between -1 and 1 - % (the latter will decrease the overall step size) and - % recalculate arx accordingly. Do not change arx or arz in any - % other way. - - if ~bnd.isactive - arxvalid(:,k) = arx(:,k); - else - arxvalid(:,k) = xintobounds(arx(:,k), lbounds, ubounds); - end - % You may handle constraints here. You may copy and alter - % (columns of) arxvalid(:,k) only for the evaluation of the - % fitness function. arx should not be changed. - fitness.raw(k) = feval(fitfun, arxvalid(:,k), varargin{:}); - tries = tries + 1; - if isnan(fitness.raw(k)) - countevalNaN = countevalNaN + 1; - end - if mod(tries, 100) == 0 - warning([num2str(tries) ... - ' NaN objective function values at evaluation ' ... - num2str(counteval)]); - end - end - counteval = counteval + 1; % retries due to NaN are not counted - end - - fitness.sel = fitness.raw; - - % ----- handle boundaries ----- - if 1 < 3 && bnd.isactive - % Get delta fitness values - val = myprctile(fitness.raw, [25 75]); - % more precise would be exp(mean(log(diagC))) - val = (val(2) - val(1)) / N / mean(diagC) / sigma^2; - %val = (myprctile(fitness.raw, 75) - myprctile(fitness.raw, 25)) ... - % / N / mean(diagC) / sigma^2; - % Catch non-sensible values - if ~isfinite(val) - warning('Non-finite fitness range'); - val = max(bnd.dfithist); - elseif val == 0 % happens if all points are out of bounds - val = min(bnd.dfithist(bnd.dfithist>0)); % seems not to make sense, given all solutions are out of bounds - elseif bnd.validfitval == 0 % flag that first sensible val was found - bnd.dfithist = []; - bnd.validfitval = 1; - end - % Store delta fitness values - if length(bnd.dfithist) < 20+(3*N)/lambda - bnd.dfithist = [bnd.dfithist val]; - else - bnd.dfithist = [bnd.dfithist(2:end) val]; - end - - [tx, ti] = xintobounds(xmean, lbounds, ubounds); - - % Set initial weights - if bnd.iniphase - if any(ti) - bnd.weights(find(bnd.isbounded)) = 2.0002 * median(bnd.dfithist); - if bnd.flgscale == 0 % scale only initial weights then - dd = diagC; - idx = find(bnd.isbounded); - dd = dd(idx) / mean(dd); % remove mean scaling - bnd.weights(idx) = bnd.weights(idx) ./ dd; - end - if bnd.validfitval && countiter > 2 - bnd.iniphase = 0; - end - end - end - - % Increase weights - if 1 < 3 && any(ti) % any coordinate of xmean out of bounds - % judge distance of xmean to boundary - tx = xmean - tx; - idx = (ti ~= 0 & abs(tx) > 3*max(1,sqrt(N)/mueff) ... - * sigma*sqrt(diagC)) ; - % only increase if xmean is moving away - idx = idx & (sign(tx) == sign(xmean - xold)); - if ~isempty(idx) % increase - % the factor became 1.2 instead of 1.1, because - % changed from max to min in version 3.52 - bnd.weights(idx) = 1.2^(min(1, mueff/10/N)) * bnd.weights(idx); - end - end - - % Calculate scaling biased to unity, product is one - if bnd.flgscale ~= 0 - bnd.scale = exp(0.9*(log(diagC)-mean(log(diagC)))); - end + % Display initial message + if countiter == 0 && flgdisplay + if mu == 1 + strw = '100'; + elseif mu < 8 + strw = [sprintf('%.0f', 100*weights(1)) ... + sprintf(' %.0f', 100*weights(2:end)')]; + else + strw = [sprintf('%.2g ', 100*weights(1:2)') ... + sprintf('%.2g', 100*weights(3)') '...' ... + sprintf(' %.2g', 100*weights(end-1:end)') ']%, ']; + end + if irun > 1 + strrun = [', run ' num2str(irun)]; + else + strrun = ''; + end + disp([' n=' num2str(N) ': (' num2str(mu) ',' ... + num2str(lambda) ')-CMA-ES(w=[' ... + strw ']%, ' ... + 'mu_eff=' num2str(mueff,'%.1f') ... + ') on function ' ... + (fitfun) strrun]); + if flgDiagonalOnly == 1 + disp(' C is diagonal'); + elseif flgDiagonalOnly + disp([' C is diagonal for ' num2str(floor(flgDiagonalOnly)) ' iterations']); + end + end - % Assigned penalized fitness - bnd.arpenalty = (bnd.weights ./ bnd.scale)' * (arxvalid - arx).^2; - - fitness.sel = fitness.raw + bnd.arpenalty; - - end % handle boundaries - % ----- end handle boundaries ----- - - % compute noise measurement and reduce fitness arrays to size lambda - if noiseHandling - [noiseS] = local_noisemeasurement(fitness.sel(1:lambda), ... - fitness.sel(lambda+(1:noiseReevals)), ... - noiseReevals, noiseTheta, noiseCutOff); - if countiter == 1 % TODO: improve this very rude way of initialization - noiseSS = 0; - noiseN = 0; % counter for mean - end - noiseSS = noiseSS + noisecum * (noiseS - noiseSS); - - % noise-handling could be done here, but the original sigma is still needed - % disp([noiseS noiseSS noisecum]) - - fitness.rawar12 = fitness.raw; % just documentary - fitness.selar12 = fitness.sel; % just documentary - % qqq refine fitness based on both values - if 11 < 3 % TODO: in case of outliers this mean is counterproductive - % median out of three would be ok - fitness.raw(1:noiseReevals) = ... % not so raw anymore - (fitness.raw(1:noiseReevals) + fitness.raw(lambda+(1:noiseReevals))) / 2; - fitness.sel(1:noiseReevals) = ... - (fitness.sel(1:noiseReevals) + fitness.sel(lambda+(1:noiseReevals))) / 2; - end - fitness.raw = fitness.raw(1:lambda); - fitness.sel = fitness.sel(1:lambda); - end - - % Sort by fitness - [fitness.raw, fitness.idx] = sort(fitness.raw); - [fitness.sel, fitness.idxsel] = sort(fitness.sel); % minimization - fitness.hist(2:end) = fitness.hist(1:end-1); % record short history of - fitness.hist(1) = fitness.raw(1); % best fitness values - if length(fitness.histbest) < 120+ceil(30*N/lambda) || ... - (mod(countiter, 5) == 0 && length(fitness.histbest) < 2e4) % 20 percent of 1e5 gen. - fitness.histbest = [fitness.raw(1) fitness.histbest]; % best fitness values - fitness.histmedian = [median(fitness.raw) fitness.histmedian]; % median fitness values - else - fitness.histbest(2:end) = fitness.histbest(1:end-1); - fitness.histmedian(2:end) = fitness.histmedian(1:end-1); - fitness.histbest(1) = fitness.raw(1); % best fitness values - fitness.histmedian(1) = median(fitness.raw); % median fitness values - end - fitness.histsel(2:end) = fitness.histsel(1:end-1); % record short history of - fitness.histsel(1) = fitness.sel(1); % best sel fitness values - - % Calculate new xmean, this is selection and recombination - xold = xmean; % for speed up of Eq. (2) and (3) - xmean = arx(:,fitness.idxsel(1:mu))*weights; - zmean = arz(:,fitness.idxsel(1:mu))*weights;%==D^-1*B'*(xmean-xold)/sigma - if mu == 1 - fmean = fitness.sel(1); - else - fmean = NaN; % [] does not work in the latter assignment - % fmean = feval(fitfun, xintobounds(xmean, lbounds, ubounds), varargin{:}); - % counteval = counteval + 1; - end - - % Cumulation: update evolution paths - ps = (1-cs)*ps + sqrt(cs*(2-cs)*mueff) * (B*zmean); % Eq. (4) - hsig = norm(ps)/sqrt(1-(1-cs)^(2*countiter))/chiN < 1.4 + 2/(N+1); - if flg_future_setting - hsig = sum(ps.^2) / (1-(1-cs)^(2*countiter)) / N < 2 + 4/(N+1); % just simplified - end -% hsig = norm(ps)/sqrt(1-(1-cs)^(2*countiter))/chiN < 1.4 + 2/(N+1); -% hsig = norm(ps)/sqrt(1-(1-cs)^(2*countiter))/chiN < 1.5 + 1/(N-0.5); -% hsig = norm(ps) < 1.5 * sqrt(N); -% hsig = 1; - - pc = (1-cc)*pc ... - + hsig*(sqrt(cc*(2-cc)*mueff)/sigma) * (xmean-xold); % Eq. (2) - if hsig == 0 - % disp([num2str(countiter) ' ' num2str(counteval) ' pc update stalled']); - end - - % Adapt covariance matrix - neg.ccov = 0; % TODO: move parameter setting upwards at some point - if ccov1 + ccovmu > 0 % Eq. (3) - if flgDiagonalOnly % internal linear(?) complexity - diagC = (1-ccov1_sep-ccovmu_sep+(1-hsig)*ccov1_sep*cc*(2-cc)) * diagC ... % regard old matrix - + ccov1_sep * pc.^2 ... % plus rank one update - + ccovmu_sep ... % plus rank mu update - * (diagC .* (arz(:,fitness.idxsel(1:mu)).^2 * weights)); -% * (repmat(diagC,1,mu) .* arz(:,fitness.idxsel(1:mu)).^2 * weights); - diagD = sqrt(diagC); % replaces eig(C) - else - arpos = (arx(:,fitness.idxsel(1:mu))-repmat(xold,1,mu)) / sigma; - % "active" CMA update: negative update, in case controlling pos. definiteness - if flgActiveCMA > 0 - % set parameters - neg.mu = mu; - neg.mueff = mueff; - if flgActiveCMA > 10 % flat weights with mu=lambda/2 - neg.mu = floor(lambda/2); - neg.mueff = neg.mu; + flush; + + countiter = countiter + 1; + + % Generate and evaluate lambda offspring + + fitness.raw = repmat(NaN, 1, lambda + noiseReevals); + + % parallel evaluation + if flgEvalParallel + arz = randn(N,lambda); + + if ~flgDiagonalOnly + arx = repmat(xmean, 1, lambda) + sigma * (BD * arz); % Eq. (1) + else + arx = repmat(xmean, 1, lambda) + repmat(sigma * diagD, 1, lambda) .* arz; + end + + if noiseHandling + if noiseEpsilon == 0 + arx = [arx arx(:,1:noiseReevals)]; + elseif flgDiagonalOnly + arx = [arx arx(:,1:noiseReevals) + ... + repmat(noiseEpsilon * sigma * diagD, 1, noiseReevals) ... + .* randn(N,noiseReevals)]; + else + arx = [arx arx(:,1:noiseReevals) + ... + noiseEpsilon * sigma * ... + (BD * randn(N,noiseReevals))]; + end + end + + % You may handle constraints here. You may either resample + % arz(:,k) and/or multiply it with a factor between -1 and 1 + % (the latter will decrease the overall step size) and + % recalculate arx accordingly. Do not change arx or arz in any + % other way. + + if ~bnd.isactive + arxvalid = arx; + else + arxvalid = xintobounds(arx, lbounds, ubounds); + end + % You may handle constraints here. You may copy and alter + % (columns of) arxvalid(:,k) only for the evaluation of the + % fitness function. arx and arxvalid should not be changed. + fitness.raw = feval(fitfun, arxvalid, varargin{:}); + countevalNaN = countevalNaN + sum(isnan(fitness.raw)); + counteval = counteval + sum(~isnan(fitness.raw)); end - % neg.mu = ceil(min([N, lambda/4, mueff])); neg.mueff = mu; % i.e. neg.mu <= N - % Parameter study: in 3-D lambda=50,100, 10-D lambda=200,400, 30-D lambda=1000,2000 a - % three times larger neg.ccov does not work. - % increasing all ccov rates three times does work (probably because of the factor (1-ccovmu)) - % in 30-D to looks fine - - neg.ccov = (1 - ccovmu) * 0.25 * neg.mueff / ((N+2)^1.5 + 2*neg.mueff); - neg.minresidualvariance = 0.66; % keep at least 0.66 in all directions, small popsize are most critical - neg.alphaold = 0.5; % where to make up for the variance loss, 0.5 means no idea what to do - % 1 is slightly more robust and gives a better "guaranty" for pos. def., - % but does it make sense from the learning perspective for large ccovmu? - - neg.ccovfinal = neg.ccov; - - % prepare vectors, compute negative updating matrix Cneg and checking matrix Ccheck - arzneg = arz(:,fitness.idxsel(lambda:-1:lambda - neg.mu + 1)); - % i-th longest becomes i-th shortest - % TODO: this is not in compliance with the paper Hansen&Ros2010, - % where simply arnorms = arnorms(end:-1:1) ? - [arnorms, idxnorms] = sort(sqrt(sum(arzneg.^2, 1))); - [ignore, idxnorms] = sort(idxnorms); % inverse index - arnormfacs = arnorms(end:-1:1) ./ arnorms; - % arnormfacs = arnorms(randperm(neg.mu)) ./ arnorms; - arnorms = arnorms(end:-1:1); % for the record - if flgActiveCMA < 20 - arzneg = arzneg .* repmat(arnormfacs(idxnorms), N, 1); % E x*x' is N - % arzneg = sqrt(N) * arzneg ./ repmat(sqrt(sum(arzneg.^2, 1)), N, 1); % E x*x' is N + + % non-parallel evaluation and remaining NaN-values + % set also the reevaluated solution to NaN + fitness.raw(lambda + find(isnan(fitness.raw(1:noiseReevals)))) = NaN; + for k=find(isnan(fitness.raw)) + % fitness.raw(k) = NaN; + tries = 0; + % Resample, until fitness is not NaN + while isnan(fitness.raw(k)) + if k <= lambda % regular samples (not the re-evaluation-samples) + arz(:,k) = randn(N,1); % (re)sample + + if flgDiagonalOnly + arx(:,k) = xmean + sigma * diagD .* arz(:,k); % Eq. (1) + else + arx(:,k) = xmean + sigma * (BD * arz(:,k)); % Eq. (1) + end + else % re-evaluation solution with index > lambda + if flgDiagonalOnly + arx(:,k) = arx(:,k-lambda) + (noiseEpsilon * sigma) * diagD .* randn(N,1); + else + arx(:,k) = arx(:,k-lambda) + (noiseEpsilon * sigma) * (BD * randn(N,1)); + end + end + + % You may handle constraints here. You may either resample + % arz(:,k) and/or multiply it with a factor between -1 and 1 + % (the latter will decrease the overall step size) and + % recalculate arx accordingly. Do not change arx or arz in any + % other way. + + if ~bnd.isactive + arxvalid(:,k) = arx(:,k); + else + arxvalid(:,k) = xintobounds(arx(:,k), lbounds, ubounds); + end + % You may handle constraints here. You may copy and alter + % (columns of) arxvalid(:,k) only for the evaluation of the + % fitness function. arx should not be changed. + fitness.raw(k) = feval(fitfun, arxvalid(:,k), varargin{:}); + tries = tries + 1; + if isnan(fitness.raw(k)) + countevalNaN = countevalNaN + 1; + end + if mod(tries, 100) == 0 + warning([num2str(tries) ... + ' NaN objective function values at evaluation ' ... + num2str(counteval)]); + end + end + counteval = counteval + 1; % retries due to NaN are not counted end - if flgActiveCMA < 10 && neg.mu == mu % weighted sum - if mod(flgActiveCMA, 10) == 1 % TODO: prevent this with a less tight but more efficient check (see below) - Ccheck = arzneg * diag(weights) * arzneg'; % in order to check the largest EV - end - artmp = BD * arzneg; - Cneg = artmp * diag(weights) * artmp'; - else % simple sum - if mod(flgActiveCMA, 10) == 1 - Ccheck = (1/neg.mu) * arzneg*arzneg'; % in order to check largest EV - end - artmp = BD * arzneg; - Cneg = (1/neg.mu) * artmp*artmp'; + fitness.sel = fitness.raw; + + % ----- handle boundaries ----- + if 1 < 3 && bnd.isactive + % Get delta fitness values + val = myprctile(fitness.raw, [25 75]); + % more precise would be exp(mean(log(diagC))) + val = (val(2) - val(1)) / N / mean(diagC) / sigma^2; + %val = (myprctile(fitness.raw, 75) - myprctile(fitness.raw, 25)) ... + % / N / mean(diagC) / sigma^2; + % Catch non-sensible values + if ~isfinite(val) + warning('Non-finite fitness range'); + val = max(bnd.dfithist); + elseif val == 0 % happens if all points are out of bounds + val = min(bnd.dfithist(bnd.dfithist>0)); % seems not to make sense, given all solutions are out of bounds + elseif bnd.validfitval == 0 % flag that first sensible val was found + bnd.dfithist = []; + bnd.validfitval = 1; + end + + % Store delta fitness values + if length(bnd.dfithist) < 20+(3*N)/lambda + bnd.dfithist = [bnd.dfithist val]; + else + bnd.dfithist = [bnd.dfithist(2:end) val]; + end + + [tx, ti] = xintobounds(xmean, lbounds, ubounds); + + % Set initial weights + if bnd.iniphase + if any(ti) + bnd.weights(find(bnd.isbounded)) = 2.0002 * median(bnd.dfithist); + if bnd.flgscale == 0 % scale only initial weights then + dd = diagC; + idx = find(bnd.isbounded); + dd = dd(idx) / mean(dd); % remove mean scaling + bnd.weights(idx) = bnd.weights(idx) ./ dd; + end + if bnd.validfitval && countiter > 2 + bnd.iniphase = 0; + end + end + end + + % Increase weights + if 1 < 3 && any(ti) % any coordinate of xmean out of bounds + % judge distance of xmean to boundary + tx = xmean - tx; + idx = (ti ~= 0 & abs(tx) > 3*max(1,sqrt(N)/mueff) ... + * sigma*sqrt(diagC)) ; + % only increase if xmean is moving away + idx = idx & (sign(tx) == sign(xmean - xold)); + if ~isempty(idx) % increase + % the factor became 1.2 instead of 1.1, because + % changed from max to min in version 3.52 + bnd.weights(idx) = 1.2^(min(1, mueff/10/N)) * bnd.weights(idx); + end + end + + % Calculate scaling biased to unity, product is one + if bnd.flgscale ~= 0 + bnd.scale = exp(0.9*(log(diagC)-mean(log(diagC)))); + end + + % Assigned penalized fitness + bnd.arpenalty = (bnd.weights ./ bnd.scale)' * (arxvalid - arx).^2; + + fitness.sel = fitness.raw + bnd.arpenalty; + + end % handle boundaries + % ----- end handle boundaries ----- + + % compute noise measurement and reduce fitness arrays to size lambda + if noiseHandling + [noiseS] = local_noisemeasurement(fitness.sel(1:lambda), ... + fitness.sel(lambda+(1:noiseReevals)), ... + noiseReevals, noiseTheta, noiseCutOff); + if countiter == 1 % TODO: improve this very rude way of initialization + noiseSS = 0; + noiseN = 0; % counter for mean + end + noiseSS = noiseSS + noisecum * (noiseS - noiseSS); + + % noise-handling could be done here, but the original sigma is still needed + % disp([noiseS noiseSS noisecum]) + + fitness.rawar12 = fitness.raw; % just documentary + fitness.selar12 = fitness.sel; % just documentary + % qqq refine fitness based on both values + if 11 < 3 % TODO: in case of outliers this mean is counterproductive + % median out of three would be ok + fitness.raw(1:noiseReevals) = ... % not so raw anymore + (fitness.raw(1:noiseReevals) + fitness.raw(lambda+(1:noiseReevals))) / 2; + fitness.sel(1:noiseReevals) = ... + (fitness.sel(1:noiseReevals) + fitness.sel(lambda+(1:noiseReevals))) / 2; + end + fitness.raw = fitness.raw(1:lambda); + fitness.sel = fitness.sel(1:lambda); + end + + % Sort by fitness + [fitness.raw, fitness.idx] = sort(fitness.raw); + [fitness.sel, fitness.idxsel] = sort(fitness.sel); % minimization + fitness.hist(2:end) = fitness.hist(1:end-1); % record short history of + fitness.hist(1) = fitness.raw(1); % best fitness values + if length(fitness.histbest) < 120+ceil(30*N/lambda) || ... + (mod(countiter, 5) == 0 && length(fitness.histbest) < 2e4) % 20 percent of 1e5 gen. + fitness.histbest = [fitness.raw(1) fitness.histbest]; % best fitness values + fitness.histmedian = [median(fitness.raw) fitness.histmedian]; % median fitness values + else + fitness.histbest(2:end) = fitness.histbest(1:end-1); + fitness.histmedian(2:end) = fitness.histmedian(1:end-1); + fitness.histbest(1) = fitness.raw(1); % best fitness values + fitness.histmedian(1) = median(fitness.raw); % median fitness values + end + fitness.histsel(2:end) = fitness.histsel(1:end-1); % record short history of + fitness.histsel(1) = fitness.sel(1); % best sel fitness values + + % Calculate new xmean, this is selection and recombination + xold = xmean; % for speed up of Eq. (2) and (3) + xmean = arx(:,fitness.idxsel(1:mu))*weights; + zmean = arz(:,fitness.idxsel(1:mu))*weights;%==D^-1*B'*(xmean-xold)/sigma + if mu == 1 + fmean = fitness.sel(1); + else + fmean = NaN; % [] does not work in the latter assignment + % fmean = feval(fitfun, xintobounds(xmean, lbounds, ubounds), varargin{:}); + % counteval = counteval + 1; + end + + % Cumulation: update evolution paths + ps = (1-cs)*ps + sqrt(cs*(2-cs)*mueff) * (B*zmean); % Eq. (4) + hsig = norm(ps)/sqrt(1-(1-cs)^(2*countiter))/chiN < 1.4 + 2/(N+1); + if flg_future_setting + hsig = sum(ps.^2) / (1-(1-cs)^(2*countiter)) / N < 2 + 4/(N+1); % just simplified + end + % hsig = norm(ps)/sqrt(1-(1-cs)^(2*countiter))/chiN < 1.4 + 2/(N+1); + % hsig = norm(ps)/sqrt(1-(1-cs)^(2*countiter))/chiN < 1.5 + 1/(N-0.5); + % hsig = norm(ps) < 1.5 * sqrt(N); + % hsig = 1; + + pc = (1-cc)*pc ... + + hsig*(sqrt(cc*(2-cc)*mueff)/sigma) * (xmean-xold); % Eq. (2) + if hsig == 0 + % disp([num2str(countiter) ' ' num2str(counteval) ' pc update stalled']); + end + + % Adapt covariance matrix + neg.ccov = 0; % TODO: move parameter setting upwards at some point + if ccov1 + ccovmu > 0 % Eq. (3) + if flgDiagonalOnly % internal linear(?) complexity + diagC = (1-ccov1_sep-ccovmu_sep+(1-hsig)*ccov1_sep*cc*(2-cc)) * diagC ... % regard old matrix + + ccov1_sep * pc.^2 ... % plus rank one update + + ccovmu_sep ... % plus rank mu update + * (diagC .* (arz(:,fitness.idxsel(1:mu)).^2 * weights)); + % * (repmat(diagC,1,mu) .* arz(:,fitness.idxsel(1:mu)).^2 * weights); + diagD = sqrt(diagC); % replaces eig(C) + else + arpos = (arx(:,fitness.idxsel(1:mu))-repmat(xold,1,mu)) / sigma; + % "active" CMA update: negative update, in case controlling pos. definiteness + if flgActiveCMA > 0 + % set parameters + neg.mu = mu; + neg.mueff = mueff; + if flgActiveCMA > 10 % flat weights with mu=lambda/2 + neg.mu = floor(lambda/2); + neg.mueff = neg.mu; + end + % neg.mu = ceil(min([N, lambda/4, mueff])); neg.mueff = mu; % i.e. neg.mu <= N + % Parameter study: in 3-D lambda=50,100, 10-D lambda=200,400, 30-D lambda=1000,2000 a + % three times larger neg.ccov does not work. + % increasing all ccov rates three times does work (probably because of the factor (1-ccovmu)) + % in 30-D to looks fine + + neg.ccov = (1 - ccovmu) * 0.25 * neg.mueff / ((N+2)^1.5 + 2*neg.mueff); + neg.minresidualvariance = 0.66; % keep at least 0.66 in all directions, small popsize are most critical + neg.alphaold = 0.5; % where to make up for the variance loss, 0.5 means no idea what to do + % 1 is slightly more robust and gives a better "guaranty" for pos. def., + % but does it make sense from the learning perspective for large ccovmu? + + neg.ccovfinal = neg.ccov; + + % prepare vectors, compute negative updating matrix Cneg and checking matrix Ccheck + arzneg = arz(:,fitness.idxsel(lambda:-1:lambda - neg.mu + 1)); + % i-th longest becomes i-th shortest + % TODO: this is not in compliance with the paper Hansen&Ros2010, + % where simply arnorms = arnorms(end:-1:1) ? + [arnorms, idxnorms] = sort(sqrt(sum(arzneg.^2, 1))); + [ignore, idxnorms] = sort(idxnorms); % inverse index + arnormfacs = arnorms(end:-1:1) ./ arnorms; + % arnormfacs = arnorms(randperm(neg.mu)) ./ arnorms; + arnorms = arnorms(end:-1:1); % for the record + if flgActiveCMA < 20 + arzneg = arzneg .* repmat(arnormfacs(idxnorms), N, 1); % E x*x' is N + % arzneg = sqrt(N) * arzneg ./ repmat(sqrt(sum(arzneg.^2, 1)), N, 1); % E x*x' is N + end + if flgActiveCMA < 10 && neg.mu == mu % weighted sum + if mod(flgActiveCMA, 10) == 1 % TODO: prevent this with a less tight but more efficient check (see below) + Ccheck = arzneg * diag(weights) * arzneg'; % in order to check the largest EV + end + artmp = BD * arzneg; + Cneg = artmp * diag(weights) * artmp'; + else % simple sum + if mod(flgActiveCMA, 10) == 1 + Ccheck = (1/neg.mu) * arzneg*arzneg'; % in order to check largest EV + end + artmp = BD * arzneg; + Cneg = (1/neg.mu) * artmp*artmp'; + + end + + % check pos.def. and set learning rate neg.ccov accordingly, + % this check makes the original choice of neg.ccov extremly failsafe + % still assuming C == BD*BD', which is only approxim. correct + if mod(flgActiveCMA, 10) == 1 && 1 - neg.ccov * arnorms(idxnorms).^2 * weights < neg.minresidualvariance + % TODO: the simple and cheap way would be to set + % fac = 1 - ccovmu - ccov1 OR 1 - mueff/lambda and + % neg.ccov = fac*(1 - neg.minresidualvariance) / (arnorms(idxnorms).^2 * weights) + % this is the more sophisticated way: + % maxeigenval = eigs(arzneg * arzneg', 1, 'lm', eigsopts); % not faster + maxeigenval = max(eig(Ccheck)); % norm is much slower, because (norm()==max(svd()) + %disp([countiter log10([neg.ccov, maxeigenval, arnorms(idxnorms).^2 * weights, max(arnorms)^2]), ... + % neg.ccov * arnorms(idxnorms).^2 * weights]) + % pause + % remove less than ??34*(1-cmu)%?? of variance in any direction + % 1-ccovmu is the variance left from the old C + neg.ccovfinal = min(neg.ccov, (1-ccovmu)*(1-neg.minresidualvariance)/maxeigenval); + % -ccov1 removed to avoid error message?? + if neg.ccovfinal < neg.ccov + disp(['active CMA at iteration ' num2str(countiter) ... + ': max EV ==', num2str([maxeigenval, neg.ccov, neg.ccovfinal])]); + end + end + % xmean = xold; % the distribution does not degenerate!? + % update C + C = (1-ccov1-ccovmu+neg.alphaold*neg.ccovfinal+(1-hsig)*ccov1*cc*(2-cc)) * C ... % regard old matrix + + ccov1 * pc*pc' ... % plus rank one update + + (ccovmu + (1-neg.alphaold)*neg.ccovfinal) ... % plus rank mu update + * arpos * (repmat(weights,1,N) .* arpos') ... + - neg.ccovfinal * Cneg; % minus rank mu update + else % no active (negative) update + C = (1-ccov1-ccovmu+(1-hsig)*ccov1*cc*(2-cc)) * C ... % regard old matrix + + ccov1 * pc*pc' ... % plus rank one update + + ccovmu ... % plus rank mu update + * arpos * (repmat(weights,1,N) .* arpos'); + % is now O(mu*N^2 + mu*N), was O(mu*N^2 + mu^2*N) when using diag(weights) + % for mu=30*N it is now 10 times faster, overall 3 times faster + end + diagC = diag(C); + end + end + + % the following is de-preciated and will be removed in future + % better setting for cc makes this hack obsolete + if 11 < 2 && ~flgscience + % remove momentum in ps, if ps is large and fitness is getting worse. + % this should rarely happen. + % this might very well be counterproductive in dynamic environments + if sum(ps.^2)/N > 1.5 + 10*(2/N)^.5 && ... + fitness.histsel(1) > max(fitness.histsel(2:3)) + ps = ps * sqrt(N*(1+max(0,log(sum(ps.^2)/N))) / sum(ps.^2)); + if flgdisplay + disp(['Momentum in ps removed at [niter neval]=' ... + num2str([countiter counteval]) ']']); + end + end + end + + % Adapt sigma + if flg_future_setting % according to a suggestion from Dirk Arnold (2000) + % exp(1) is still not reasonably small enough + sigma = sigma * exp(min(1, (sum(ps.^2)/N - 1)/2 * cs/damps)); % Eq. (5) + else + % exp(1) is still not reasonably small enough + sigma = sigma * exp(min(1, (sqrt(sum(ps.^2))/chiN - 1) * cs/damps)); % Eq. (5) + end + % disp([countiter norm(ps)/chiN]); + + if 11 < 3 % testing with optimal step-size + if countiter == 1 + disp('*********** sigma set to const * ||x|| ******************'); + end + sigma = 0.04 * mueff * sqrt(sum(xmean.^2)) / N; % 20D,lam=1000:25e3 + sigma = 0.3 * mueff * sqrt(sum(xmean.^2)) / N; % 20D,lam=(40,1000):17e3 + % 75e3 with def (1.5) + % 35e3 with damps=0.25 + end + if 11 < 3 + if countiter == 1 + disp('*********** xmean set to const ******************'); + end + xmean = ones(N,1); + end + + % Update B and D from C + + if ~flgDiagonalOnly && (ccov1+ccovmu+neg.ccov) > 0 && mod(countiter, 1/(ccov1+ccovmu+neg.ccov)/N/10) < 1 + C=triu(C)+triu(C,1)'; % enforce symmetry to prevent complex numbers + [B,tmp] = eig(C); % eigen decomposition, B==normalized eigenvectors + % effort: approx. 15*N matrix-vector multiplications + diagD = diag(tmp); + + if any(~isfinite(diagD)) + clear idx; % prevents error under octave + save(['tmp' opts.SaveFilename]); + error(['function eig returned non-finited eigenvalues, cond(C)=' ... + num2str(cond(C)) ]); + end + if any(any(~isfinite(B))) + clear idx; % prevents error under octave + save(['tmp' opts.SaveFilename]); + error(['function eig returned non-finited eigenvectors, cond(C)=' ... + num2str(cond(C)) ]); + end + + % limit condition of C to 1e14 + 1 + if min(diagD) <= 0 + if stopOnWarnings + stopflag(end+1) = {'warnconditioncov'}; + else + warning(['Iteration ' num2str(countiter) ... + ': Eigenvalue (smaller) zero']); + diagD(diagD<0) = 0; + tmp = max(diagD)/1e14; + C = C + tmp*eye(N,N); diagD = diagD + tmp*ones(N,1); + end + end + if max(diagD) > 1e14*min(diagD) + if stopOnWarnings + stopflag(end+1) = {'warnconditioncov'}; + else + warning(['Iteration ' num2str(countiter) ': condition of C ' ... + 'at upper limit' ]); + tmp = max(diagD)/1e14 - min(diagD); + C = C + tmp*eye(N,N); diagD = diagD + tmp*ones(N,1); + end + end + + diagC = diag(C); + diagD = sqrt(diagD); % D contains standard deviations now + % diagD = diagD / prod(diagD)^(1/N); C = C / prod(diagD)^(2/N); + BD = B.*repmat(diagD',N,1); % O(n^2) + end % if mod + + % Align/rescale order of magnitude of scales of sigma and C for nicer output + % not a very usual case + if 1 < 2 && sigma > 1e10*max(diagD) + fac = sigma / max(diagD); + sigma = sigma/fac; + pc = fac * pc; + diagD = fac * diagD; + if ~flgDiagonalOnly + C = fac^2 * C; % disp(fac); + BD = B.*repmat(diagD',N,1); % O(n^2), but repmat might be inefficient todo? + end + diagC = fac^2 * diagC; + end + + if flgDiagonalOnly > 1 && countiter > flgDiagonalOnly + % full covariance matrix from now on + flgDiagonalOnly = 0; + B = eye(N,N); + BD = diag(diagD); + C = diag(diagC); % is better, because correlations are spurious anyway + end + + if noiseHandling + if countiter == 1 % assign firstvarargin for noise treatment e.g. as #reevaluations + if ~isempty(varargin) && length(varargin{1}) == 1 && isnumeric(varargin{1}) + if irun == 1 + firstvarargin = varargin{1}; + else + varargin{1} = firstvarargin; % reset varargin{1} + end + else + firstvarargin = 0; + end + end + if noiseSS < 0 && noiseMinMaxEvals(2) > noiseMinMaxEvals(1) && firstvarargin + varargin{1} = max(noiseMinMaxEvals(1), varargin{1} / noiseAlphaEvals^(1/4)); % still experimental + elseif noiseSS > 0 + if ~isempty(noiseCallback) % to be removed? + res = feval(noiseCallback); % should also work without output argument!? + if ~isempty(res) && res > 1 % TODO: decide for interface of callback + % also a dynamic popsize could be done here + sigma = sigma * noiseAlpha; + end + else + if noiseMinMaxEvals(2) > noiseMinMaxEvals(1) && firstvarargin + varargin{1} = min(noiseMinMaxEvals(2), varargin{1} * noiseAlphaEvals); + end + + sigma = sigma * noiseAlpha; + % lambda = ceil(0.1 * sqrt(lambda) + lambda); + % TODO: find smallest increase of lambda with log-linear + % convergence in iterations + end + % qqq experimental: take a mean to estimate the true optimum + noiseN = noiseN + 1; + if noiseN == 1 + noiseX = xmean; + else + noiseX = noiseX + (3/noiseN) * (xmean - noiseX); + end + end + end + + % ----- numerical error management ----- + % Adjust maximal coordinate axis deviations + if any(sigma*sqrt(diagC) > maxdx) + sigma = min(maxdx ./ sqrt(diagC)); + %warning(['Iteration ' num2str(countiter) ': coordinate axis std ' ... + % 'deviation at upper limit of ' num2str(maxdx)]); + % stopflag(end+1) = {'maxcoorddev'}; + end + % Adjust minimal coordinate axis deviations + if any(sigma*sqrt(diagC) < mindx) + sigma = max(mindx ./ sqrt(diagC)) * exp(0.05+cs/damps); + %warning(['Iteration ' num2str(countiter) ': coordinate axis std ' ... + % 'deviation at lower limit of ' num2str(mindx)]); + % stopflag(end+1) = {'mincoorddev'};; + end + % Adjust too low coordinate axis deviations + if any(xmean == xmean + 0.2*sigma*sqrt(diagC)) + if stopOnWarnings + stopflag(end+1) = {'warnnoeffectcoord'}; + else + warning(['Iteration ' num2str(countiter) ': coordinate axis std ' ... + 'deviation too low' ]); + if flgDiagonalOnly + diagC = diagC + (ccov1_sep+ccovmu_sep) * (diagC .* ... + (xmean == xmean + 0.2*sigma*sqrt(diagC))); + else + C = C + (ccov1+ccovmu) * diag(diagC .* ... + (xmean == xmean + 0.2*sigma*sqrt(diagC))); + end + sigma = sigma * exp(0.05+cs/damps); + end + end + % Adjust step size in case of (numerical) precision problem + if flgDiagonalOnly + tmp = 0.1*sigma*diagD; + else + tmp = 0.1*sigma*BD(:,1+floor(mod(countiter,N))); + end + if all(xmean == xmean + tmp) + i = 1+floor(mod(countiter,N)); + if stopOnWarnings + stopflag(end+1) = {'warnnoeffectaxis'}; + else + warning(['Iteration ' num2str(countiter) ... + ': main axis standard deviation ' ... + num2str(sigma*diagD(i)) ' has no effect' ]); + sigma = sigma * exp(0.2+cs/damps); + end + end + % Adjust step size in case of equal function values (flat fitness) + % isequalfuncvalues = 0; + if fitness.sel(1) == fitness.sel(1+ceil(0.1+lambda/4)) + % isequalfuncvalues = 1; + if stopOnEqualFunctionValues + arrEqualFunvals = [countiter arrEqualFunvals(1:end-1)]; + % stop if this happens in more than 33% + if arrEqualFunvals(end) > countiter - 3 * length(arrEqualFunvals) + stopflag(end+1) = {'equalfunvals'}; + end + else + if flgWarnOnEqualFunctionValues + warning(['Iteration ' num2str(countiter) ... + ': equal function values f=' num2str(fitness.sel(1)) ... + ' at maximal main axis sigma ' ... + num2str(sigma*max(diagD))]); + end + sigma = sigma * exp(0.2+cs/damps); + end + end + % Adjust step size in case of equal function values + if countiter > 2 && myrange([fitness.hist fitness.sel(1)]) == 0 + if stopOnWarnings + stopflag(end+1) = {'warnequalfunvalhist'}; + else + warning(['Iteration ' num2str(countiter) ... + ': equal function values in history at maximal main ' ... + 'axis sigma ' num2str(sigma*max(diagD))]); + sigma = sigma * exp(0.2+cs/damps); + end + end + + % ----- end numerical error management ----- + + % Keep overall best solution + out.evals = counteval; + out.solutions.evals = counteval; + out.solutions.mean.x = xmean; + out.solutions.mean.f = fmean; + out.solutions.mean.evals = counteval; + out.solutions.recentbest.x = arxvalid(:, fitness.idx(1)); + out.solutions.recentbest.f = fitness.raw(1); + out.solutions.recentbest.evals = counteval + fitness.idx(1) - lambda; + out.solutions.recentworst.x = arxvalid(:, fitness.idx(end)); + out.solutions.recentworst.f = fitness.raw(end); + out.solutions.recentworst.evals = counteval + fitness.idx(end) - lambda; + if fitness.hist(1) < out.solutions.bestever.f + out.solutions.bestever.x = arxvalid(:, fitness.idx(1)); + out.solutions.bestever.f = fitness.hist(1); + out.solutions.bestever.evals = counteval + fitness.idx(1) - lambda; + bestever = out.solutions.bestever; + end + + % Set stop flag + if fitness.raw(1) <= stopFitness, stopflag(end+1) = {'fitness'}; end + if counteval >= stopMaxFunEvals, stopflag(end+1) = {'maxfunevals'}; end + if countiter >= stopMaxIter, stopflag(end+1) = {'maxiter'}; end + if all(sigma*(max(abs(pc), sqrt(diagC))) < stopTolX) + stopflag(end+1) = {'tolx'}; + end + if any(sigma*sqrt(diagC) > stopTolUpX) + stopflag(end+1) = {'tolupx'}; + end + if sigma*max(diagD) == 0 % should never happen + stopflag(end+1) = {'bug'}; + end + if countiter > 2 && myrange([fitness.sel fitness.hist]) <= stopTolFun + stopflag(end+1) = {'tolfun'}; + end + if countiter >= length(fitness.hist) && myrange(fitness.hist) <= stopTolHistFun + stopflag(end+1) = {'tolhistfun'}; + end + l = floor(length(fitness.histbest)/3); + if 1 < 2 && stopOnStagnation && ... % leads sometimes early stop on ftablet, fcigtab + countiter > N * (5+100/lambda) && ... + length(fitness.histbest) > 100 && ... + median(fitness.histmedian(1:l)) >= median(fitness.histmedian(end-l:end)) && ... + median(fitness.histbest(1:l)) >= median(fitness.histbest(end-l:end)) + stopflag(end+1) = {'stagnation'}; + end + + if counteval >= stopFunEvals || countiter >= stopIter + stopflag(end+1) = {'stoptoresume'}; + if length(stopflag) == 1 && flgsaving == 0 + error('To resume later the saving option needs to be set'); + end + end + % read stopping message from file signals.par + if flgreadsignals + fid = fopen('./signals.par', 'rt'); % can be performance critical + while fid > 0 + strline = fgetl(fid); %fgets(fid, 300); + if strline < 0 % fgets and fgetl returns -1 at end of file + break + end + % 'stop filename' sets stopflag to manual + str = sscanf(strline, ' %s %s', 2); + if strcmp(str, ['stop' opts.LogFilenamePrefix]) + stopflag(end+1) = {'manual'}; + break + end + % 'skip filename run 3' skips a run, but not the last + str = sscanf(strline, ' %s %s %s', 3); + if strcmp(str, ['skip' opts.LogFilenamePrefix 'run']) + i = strfind(strline, 'run'); + if irun == sscanf(strline(i+3:end), ' %d ', 1) && irun <= myeval(opts.Restarts) + stopflag(end+1) = {'skipped'}; + end + end + end % while, break + if fid > 0 + fclose(fid); + clear fid; % prevents strange error under octave + end + end + + out.stopflag = stopflag; + + % ----- output generation ----- + if verbosemodulo > 0 && isfinite(verbosemodulo) + if countiter == 1 || mod(countiter, 10*verbosemodulo) < 1 + disp(['Iterat, #Fevals: Function Value (median,worst) ' ... + '|Axis Ratio|' ... + 'idx:Min SD idx:Max SD']); + end + if mod(countiter, verbosemodulo) < 1 ... + || (verbosemodulo > 0 && isfinite(verbosemodulo) && ... + (countiter < 3 || ~isempty(stopflag))) + [minstd, minstdidx] = min(sigma*sqrt(diagC)); + [maxstd, maxstdidx] = max(sigma*sqrt(diagC)); + % format display nicely + disp([repmat(' ',1,4-floor(log10(countiter))) ... + num2str(countiter) ' , ' ... + repmat(' ',1,5-floor(log10(counteval))) ... + num2str(counteval) ' : ' ... + num2str(fitness.hist(1), '%.13e') ... + ' +(' num2str(median(fitness.raw)-fitness.hist(1), '%.0e ') ... + ',' num2str(max(fitness.raw)-fitness.hist(1), '%.0e ') ... + ') | ' ... + num2str(max(diagD)/min(diagD), '%4.2e') ' | ' ... + repmat(' ',1,1-floor(log10(minstdidx))) num2str(minstdidx) ':' ... + num2str(minstd, ' %.1e') ' ' ... + repmat(' ',1,1-floor(log10(maxstdidx))) num2str(maxstdidx) ':' ... + num2str(maxstd, ' %.1e')]); + end + end + + % measure time for recording data + if countiter < 3 + time.c = 0.05; + time.nonoutput = 0; + time.recording = 0; + time.saving = 0.15; % first saving after 3 seconds of 100 iterations + time.plotting = 0; + elseif countiter > 300 + % set backward horizon, must be long enough to cover infrequent plotting etc + % time.c = min(1, time.nonoutput/3 + 1e-9); + time.c = max(1e-5, 0.1/sqrt(countiter)); % mean over all or 1e-5 + end + % get average time per iteration + time.t1 = clock; + time.act = max(0,etime(time.t1, time.t0)); + time.nonoutput = (1-time.c) * time.nonoutput ... + + time.c * time.act; + + time.recording = (1-time.c) * time.recording; % per iteration + time.saving = (1-time.c) * time.saving; + time.plotting = (1-time.c) * time.plotting; + + % record output data, concerning time issues + if savemodulo && savetime && (countiter < 1e2 || ~isempty(stopflag) || ... + countiter >= outiter + savemodulo) + outiter = countiter; + % Save output data to files + for namecell = filenames(:)' + name = namecell{:}; + + [fid, err] = fopen(['./' filenameprefix name '.dat'], 'a'); + if fid < 1 % err ~= 0 + warning(['could not open ' filenameprefix name '.dat']); + else + if strcmp(name, 'axlen') + fprintf(fid, '%d %d %e %e %e ', countiter, counteval, sigma, ... + max(diagD), min(diagD)); + fprintf(fid, '%e ', sort(diagD)); + fprintf(fid, '\n'); + elseif strcmp(name, 'disp') % TODO + elseif strcmp(name, 'fit') + fprintf(fid, '%ld %ld %e %e %25.18e %25.18e %25.18e %25.18e', ... + countiter, counteval, sigma, max(diagD)/min(diagD), ... + out.solutions.bestever.f, ... + fitness.raw(1), median(fitness.raw), fitness.raw(end)); + if ~isempty(varargin) && length(varargin{1}) == 1 && isnumeric(varargin{1}) && varargin{1} ~= 0 + fprintf(fid, ' %f', varargin{1}); + end + fprintf(fid, '\n'); + elseif strcmp(name, 'stddev') + fprintf(fid, '%ld %ld %e 0 0 ', countiter, counteval, sigma); + fprintf(fid, '%e ', sigma*sqrt(diagC)); + fprintf(fid, '\n'); + elseif strcmp(name, 'xmean') + if isnan(fmean) + fprintf(fid, '%ld %ld 0 0 0 ', countiter, counteval); + else + fprintf(fid, '%ld %ld 0 0 %e ', countiter, counteval, fmean); + end + fprintf(fid, '%e ', xmean); + fprintf(fid, '\n'); + elseif strcmp(name, 'xrecentbest') + % TODO: fitness is inconsistent with x-value + fprintf(fid, '%ld %ld %25.18e 0 0 ', countiter, counteval, fitness.raw(1)); + fprintf(fid, '%e ', arx(:,fitness.idx(1))); + fprintf(fid, '\n'); + end + fclose(fid); + end + end + + % get average time for recording data + time.t2 = clock; + time.recording = time.recording + time.c * max(0,etime(time.t2, time.t1)); + + % plot + if flgplotting && countiter > 1 + if countiter == 2 + iterplotted = 0; + end + if ~isempty(stopflag) || ... + ((time.nonoutput+time.recording) * (countiter - iterplotted) > 1 && ... + time.plotting < 0.05 * (time.nonoutput+time.recording)) + local_plotcmaesdat(324, filenameprefix); + iterplotted = countiter; + % outplot(out); % outplot defined below + if time.plotting == 0 % disregard opening of the window + time.plotting = time.nonoutput+time.recording; + else + time.plotting = time.plotting + time.c * max(0,etime(clock, time.t2)); + end + end + end + if countiter > 100 + 20 && savemodulo && ... + time.recording * countiter > 0.1 && ... % absolute time larger 0.1 second + time.recording > savetime * (time.nonoutput+time.recording) / 100 + savemodulo = floor(1.1 * savemodulo) + 1; + % disp('++savemodulo'); %qqq + end + end % if output + + % save everything + time.t3 = clock; + if ~isempty(stopflag) || time.saving < 0.05 * time.nonoutput || countiter == 100 + xmin = arxvalid(:, fitness.idx(1)); + fmin = fitness.raw(1); + if flgsaving && countiter > 2 + clear idx; % prevents error under octave + % -v6 : non-compressed non-unicode for version 6 and earlier + if ~isempty(strsaving) && ~isoctave + save('-mat', strsaving, opts.SaveFilename); % for inspection and possible restart + else + save('-mat', opts.SaveFilename); % for inspection and possible restart + end + time.saving = time.saving + time.c * max(0,etime(clock, time.t3)); + end + end + time.t0 = clock; + + % ----- end output generation ----- + + end % while, end generation loop + + % -------------------- Final Procedures ------------------------------- + + % Evaluate xmean and return best recent point in xmin + fmin = fitness.raw(1); + xmin = arxvalid(:, fitness.idx(1)); % Return best point of last generation. + if length(stopflag) > sum(strcmp(stopflag, 'stoptoresume')) % final stopping + out.solutions.mean.f = ... + feval(fitfun, xintobounds(xmean, lbounds, ubounds), varargin{:}); + counteval = counteval + 1; + out.solutions.mean.evals = counteval; + if out.solutions.mean.f < fitness.raw(1) + fmin = out.solutions.mean.f; + xmin = xintobounds(xmean, lbounds, ubounds); % Return xmean as best point + end + if out.solutions.mean.f < out.solutions.bestever.f + out.solutions.bestever = out.solutions.mean; % Return xmean as bestever point + out.solutions.bestever.x = xintobounds(xmean, lbounds, ubounds); + bestever = out.solutions.bestever; + end end - % check pos.def. and set learning rate neg.ccov accordingly, - % this check makes the original choice of neg.ccov extremly failsafe - % still assuming C == BD*BD', which is only approxim. correct - if mod(flgActiveCMA, 10) == 1 && 1 - neg.ccov * arnorms(idxnorms).^2 * weights < neg.minresidualvariance - % TODO: the simple and cheap way would be to set - % fac = 1 - ccovmu - ccov1 OR 1 - mueff/lambda and - % neg.ccov = fac*(1 - neg.minresidualvariance) / (arnorms(idxnorms).^2 * weights) - % this is the more sophisticated way: - % maxeigenval = eigs(arzneg * arzneg', 1, 'lm', eigsopts); % not faster - maxeigenval = max(eig(Ccheck)); % norm is much slower, because (norm()==max(svd()) - %disp([countiter log10([neg.ccov, maxeigenval, arnorms(idxnorms).^2 * weights, max(arnorms)^2]), ... - % neg.ccov * arnorms(idxnorms).^2 * weights]) - % pause - % remove less than ??34*(1-cmu)%?? of variance in any direction - % 1-ccovmu is the variance left from the old C - neg.ccovfinal = min(neg.ccov, (1-ccovmu)*(1-neg.minresidualvariance)/maxeigenval); - % -ccov1 removed to avoid error message?? - if neg.ccovfinal < neg.ccov - disp(['active CMA at iteration ' num2str(countiter) ... - ': max EV ==', num2str([maxeigenval, neg.ccov, neg.ccovfinal])]); - end + % Save everything and display final message + if flgsavingfinal + clear idx; % prevents error under octave + if ~isempty(strsaving) && ~isoctave + save('-mat', strsaving, opts.SaveFilename); % for inspection and possible restart + else + save('-mat', opts.SaveFilename); % for inspection and possible restart + end + message = [' (saved to ' opts.SaveFilename ')']; + else + message = []; end - % xmean = xold; % the distribution does not degenerate!? - % update C - C = (1-ccov1-ccovmu+neg.alphaold*neg.ccovfinal+(1-hsig)*ccov1*cc*(2-cc)) * C ... % regard old matrix - + ccov1 * pc*pc' ... % plus rank one update - + (ccovmu + (1-neg.alphaold)*neg.ccovfinal) ... % plus rank mu update - * arpos * (repmat(weights,1,N) .* arpos') ... - - neg.ccovfinal * Cneg; % minus rank mu update - else % no active (negative) update - C = (1-ccov1-ccovmu+(1-hsig)*ccov1*cc*(2-cc)) * C ... % regard old matrix - + ccov1 * pc*pc' ... % plus rank one update - + ccovmu ... % plus rank mu update - * arpos * (repmat(weights,1,N) .* arpos'); - % is now O(mu*N^2 + mu*N), was O(mu*N^2 + mu^2*N) when using diag(weights) - % for mu=30*N it is now 10 times faster, overall 3 times faster - end - diagC = diag(C); - end - end - - % the following is de-preciated and will be removed in future - % better setting for cc makes this hack obsolete - if 11 < 2 && ~flgscience - % remove momentum in ps, if ps is large and fitness is getting worse. - % this should rarely happen. - % this might very well be counterproductive in dynamic environments - if sum(ps.^2)/N > 1.5 + 10*(2/N)^.5 && ... - fitness.histsel(1) > max(fitness.histsel(2:3)) - ps = ps * sqrt(N*(1+max(0,log(sum(ps.^2)/N))) / sum(ps.^2)); - if flgdisplay - disp(['Momentum in ps removed at [niter neval]=' ... - num2str([countiter counteval]) ']']); - end - end - end - - % Adapt sigma - if flg_future_setting % according to a suggestion from Dirk Arnold (2000) - % exp(1) is still not reasonably small enough - sigma = sigma * exp(min(1, (sum(ps.^2)/N - 1)/2 * cs/damps)); % Eq. (5) - else - % exp(1) is still not reasonably small enough - sigma = sigma * exp(min(1, (sqrt(sum(ps.^2))/chiN - 1) * cs/damps)); % Eq. (5) - end - % disp([countiter norm(ps)/chiN]); - - if 11 < 3 % testing with optimal step-size - if countiter == 1 - disp('*********** sigma set to const * ||x|| ******************'); - end - sigma = 0.04 * mueff * sqrt(sum(xmean.^2)) / N; % 20D,lam=1000:25e3 - sigma = 0.3 * mueff * sqrt(sum(xmean.^2)) / N; % 20D,lam=(40,1000):17e3 - % 75e3 with def (1.5) - % 35e3 with damps=0.25 - end - if 11 < 3 - if countiter == 1 - disp('*********** xmean set to const ******************'); - end - xmean = ones(N,1); - end - - % Update B and D from C - - if ~flgDiagonalOnly && (ccov1+ccovmu+neg.ccov) > 0 && mod(countiter, 1/(ccov1+ccovmu+neg.ccov)/N/10) < 1 - C=triu(C)+triu(C,1)'; % enforce symmetry to prevent complex numbers - [B,tmp] = eig(C); % eigen decomposition, B==normalized eigenvectors - % effort: approx. 15*N matrix-vector multiplications - diagD = diag(tmp); - - if any(~isfinite(diagD)) - clear idx; % prevents error under octave - save(['tmp' opts.SaveFilename]); - error(['function eig returned non-finited eigenvalues, cond(C)=' ... - num2str(cond(C)) ]); - end - if any(any(~isfinite(B))) - clear idx; % prevents error under octave - save(['tmp' opts.SaveFilename]); - error(['function eig returned non-finited eigenvectors, cond(C)=' ... - num2str(cond(C)) ]); - end - % limit condition of C to 1e14 + 1 - if min(diagD) <= 0 - if stopOnWarnings - stopflag(end+1) = {'warnconditioncov'}; - else - warning(['Iteration ' num2str(countiter) ... - ': Eigenvalue (smaller) zero']); - diagD(diagD<0) = 0; - tmp = max(diagD)/1e14; - C = C + tmp*eye(N,N); diagD = diagD + tmp*ones(N,1); - end - end - if max(diagD) > 1e14*min(diagD) - if stopOnWarnings - stopflag(end+1) = {'warnconditioncov'}; - else - warning(['Iteration ' num2str(countiter) ': condition of C ' ... - 'at upper limit' ]); - tmp = max(diagD)/1e14 - min(diagD); - C = C + tmp*eye(N,N); diagD = diagD + tmp*ones(N,1); - end - end + if flgdisplay + disp(['#Fevals: f(returned x) | bestever.f | stopflag' ... + message]); + if isoctave + strstop = stopflag(:); + else + strcat(stopflag(:), '.'); + end + strstop = stopflag(:); %strcat(stopflag(:), '.'); + disp([repmat(' ',1,6-floor(log10(counteval))) ... + num2str(counteval, '%6.0f') ': ' num2str(fmin, '%.11e') ' | ' ... + num2str(out.solutions.bestever.f, '%.11e') ' | ' ... + strstop{1:end}]); + if N < 102 + disp(['mean solution:' sprintf(' %+.1e', xmean)]); + disp(['std deviation:' sprintf(' %.1e', sigma*sqrt(diagC))]); + disp(sprintf('use plotcmaesdat.m for plotting the output at any time (option LogModulo must not be zero)')); + end + if exist('sfile', 'var') + disp(['Results saved in ' sfile]); + end + end - diagC = diag(C); - diagD = sqrt(diagD); % D contains standard deviations now - % diagD = diagD / prod(diagD)^(1/N); C = C / prod(diagD)^(2/N); - BD = B.*repmat(diagD',N,1); % O(n^2) - end % if mod - - % Align/rescale order of magnitude of scales of sigma and C for nicer output - % not a very usual case - if 1 < 2 && sigma > 1e10*max(diagD) - fac = sigma / max(diagD); - sigma = sigma/fac; - pc = fac * pc; - diagD = fac * diagD; - if ~flgDiagonalOnly - C = fac^2 * C; % disp(fac); - BD = B.*repmat(diagD',N,1); % O(n^2), but repmat might be inefficient todo? - end - diagC = fac^2 * diagC; - end - - if flgDiagonalOnly > 1 && countiter > flgDiagonalOnly - % full covariance matrix from now on - flgDiagonalOnly = 0; - B = eye(N,N); - BD = diag(diagD); - C = diag(diagC); % is better, because correlations are spurious anyway - end - - if noiseHandling - if countiter == 1 % assign firstvarargin for noise treatment e.g. as #reevaluations - if ~isempty(varargin) && length(varargin{1}) == 1 && isnumeric(varargin{1}) - if irun == 1 - firstvarargin = varargin{1}; - else - varargin{1} = firstvarargin; % reset varargin{1} - end - else - firstvarargin = 0; - end - end - if noiseSS < 0 && noiseMinMaxEvals(2) > noiseMinMaxEvals(1) && firstvarargin - varargin{1} = max(noiseMinMaxEvals(1), varargin{1} / noiseAlphaEvals^(1/4)); % still experimental - elseif noiseSS > 0 - if ~isempty(noiseCallback) % to be removed? - res = feval(noiseCallback); % should also work without output argument!? - if ~isempty(res) && res > 1 % TODO: decide for interface of callback - % also a dynamic popsize could be done here - sigma = sigma * noiseAlpha; - end - else - if noiseMinMaxEvals(2) > noiseMinMaxEvals(1) && firstvarargin - varargin{1} = min(noiseMinMaxEvals(2), varargin{1} * noiseAlphaEvals); - end - - sigma = sigma * noiseAlpha; - % lambda = ceil(0.1 * sqrt(lambda) + lambda); - % TODO: find smallest increase of lambda with log-linear - % convergence in iterations - end - % qqq experimental: take a mean to estimate the true optimum - noiseN = noiseN + 1; - if noiseN == 1 - noiseX = xmean; - else - noiseX = noiseX + (3/noiseN) * (xmean - noiseX); - end - end - end - - % ----- numerical error management ----- - % Adjust maximal coordinate axis deviations - if any(sigma*sqrt(diagC) > maxdx) - sigma = min(maxdx ./ sqrt(diagC)); - %warning(['Iteration ' num2str(countiter) ': coordinate axis std ' ... - % 'deviation at upper limit of ' num2str(maxdx)]); - % stopflag(end+1) = {'maxcoorddev'}; - end - % Adjust minimal coordinate axis deviations - if any(sigma*sqrt(diagC) < mindx) - sigma = max(mindx ./ sqrt(diagC)) * exp(0.05+cs/damps); - %warning(['Iteration ' num2str(countiter) ': coordinate axis std ' ... - % 'deviation at lower limit of ' num2str(mindx)]); - % stopflag(end+1) = {'mincoorddev'};; - end - % Adjust too low coordinate axis deviations - if any(xmean == xmean + 0.2*sigma*sqrt(diagC)) - if stopOnWarnings - stopflag(end+1) = {'warnnoeffectcoord'}; - else - warning(['Iteration ' num2str(countiter) ': coordinate axis std ' ... - 'deviation too low' ]); - if flgDiagonalOnly - diagC = diagC + (ccov1_sep+ccovmu_sep) * (diagC .* ... - (xmean == xmean + 0.2*sigma*sqrt(diagC))); - else - C = C + (ccov1+ccovmu) * diag(diagC .* ... - (xmean == xmean + 0.2*sigma*sqrt(diagC))); - end - sigma = sigma * exp(0.05+cs/damps); - end - end - % Adjust step size in case of (numerical) precision problem - if flgDiagonalOnly - tmp = 0.1*sigma*diagD; - else - tmp = 0.1*sigma*BD(:,1+floor(mod(countiter,N))); - end - if all(xmean == xmean + tmp) - i = 1+floor(mod(countiter,N)); - if stopOnWarnings - stopflag(end+1) = {'warnnoeffectaxis'}; - else - warning(['Iteration ' num2str(countiter) ... - ': main axis standard deviation ' ... - num2str(sigma*diagD(i)) ' has no effect' ]); - sigma = sigma * exp(0.2+cs/damps); - end - end - % Adjust step size in case of equal function values (flat fitness) - % isequalfuncvalues = 0; - if fitness.sel(1) == fitness.sel(1+ceil(0.1+lambda/4)) - % isequalfuncvalues = 1; - if stopOnEqualFunctionValues - arrEqualFunvals = [countiter arrEqualFunvals(1:end-1)]; - % stop if this happens in more than 33% - if arrEqualFunvals(end) > countiter - 3 * length(arrEqualFunvals) - stopflag(end+1) = {'equalfunvals'}; - end - else - if flgWarnOnEqualFunctionValues - warning(['Iteration ' num2str(countiter) ... - ': equal function values f=' num2str(fitness.sel(1)) ... - ' at maximal main axis sigma ' ... - num2str(sigma*max(diagD))]); - end - sigma = sigma * exp(0.2+cs/damps); - end - end - % Adjust step size in case of equal function values - if countiter > 2 && myrange([fitness.hist fitness.sel(1)]) == 0 - if stopOnWarnings - stopflag(end+1) = {'warnequalfunvalhist'}; - else - warning(['Iteration ' num2str(countiter) ... - ': equal function values in history at maximal main ' ... - 'axis sigma ' num2str(sigma*max(diagD))]); - sigma = sigma * exp(0.2+cs/damps); - end - end - - % ----- end numerical error management ----- - - % Keep overall best solution - out.evals = counteval; - out.solutions.evals = counteval; - out.solutions.mean.x = xmean; - out.solutions.mean.f = fmean; - out.solutions.mean.evals = counteval; - out.solutions.recentbest.x = arxvalid(:, fitness.idx(1)); - out.solutions.recentbest.f = fitness.raw(1); - out.solutions.recentbest.evals = counteval + fitness.idx(1) - lambda; - out.solutions.recentworst.x = arxvalid(:, fitness.idx(end)); - out.solutions.recentworst.f = fitness.raw(end); - out.solutions.recentworst.evals = counteval + fitness.idx(end) - lambda; - if fitness.hist(1) < out.solutions.bestever.f - out.solutions.bestever.x = arxvalid(:, fitness.idx(1)); - out.solutions.bestever.f = fitness.hist(1); - out.solutions.bestever.evals = counteval + fitness.idx(1) - lambda; - bestever = out.solutions.bestever; - end - - % Set stop flag - if fitness.raw(1) <= stopFitness, stopflag(end+1) = {'fitness'}; end - if counteval >= stopMaxFunEvals, stopflag(end+1) = {'maxfunevals'}; end - if countiter >= stopMaxIter, stopflag(end+1) = {'maxiter'}; end - if all(sigma*(max(abs(pc), sqrt(diagC))) < stopTolX) - stopflag(end+1) = {'tolx'}; - end - if any(sigma*sqrt(diagC) > stopTolUpX) - stopflag(end+1) = {'tolupx'}; - end - if sigma*max(diagD) == 0 % should never happen - stopflag(end+1) = {'bug'}; - end - if countiter > 2 && myrange([fitness.sel fitness.hist]) <= stopTolFun - stopflag(end+1) = {'tolfun'}; - end - if countiter >= length(fitness.hist) && myrange(fitness.hist) <= stopTolHistFun - stopflag(end+1) = {'tolhistfun'}; - end - l = floor(length(fitness.histbest)/3); - if 1 < 2 && stopOnStagnation && ... % leads sometimes early stop on ftablet, fcigtab - countiter > N * (5+100/lambda) && ... - length(fitness.histbest) > 100 && ... - median(fitness.histmedian(1:l)) >= median(fitness.histmedian(end-l:end)) && ... - median(fitness.histbest(1:l)) >= median(fitness.histbest(end-l:end)) - stopflag(end+1) = {'stagnation'}; - end - - if counteval >= stopFunEvals || countiter >= stopIter - stopflag(end+1) = {'stoptoresume'}; - if length(stopflag) == 1 && flgsaving == 0 - error('To resume later the saving option needs to be set'); - end - end - % read stopping message from file signals.par - if flgreadsignals - fid = fopen('./signals.par', 'rt'); % can be performance critical - while fid > 0 - strline = fgetl(fid); %fgets(fid, 300); - if strline < 0 % fgets and fgetl returns -1 at end of file - break - end - % 'stop filename' sets stopflag to manual - str = sscanf(strline, ' %s %s', 2); - if strcmp(str, ['stop' opts.LogFilenamePrefix]) - stopflag(end+1) = {'manual'}; - break - end - % 'skip filename run 3' skips a run, but not the last - str = sscanf(strline, ' %s %s %s', 3); - if strcmp(str, ['skip' opts.LogFilenamePrefix 'run']) - i = strfind(strline, 'run'); - if irun == sscanf(strline(i+3:end), ' %d ', 1) && irun <= myeval(opts.Restarts) - stopflag(end+1) = {'skipped'}; - end - end - end % while, break - if fid > 0 - fclose(fid); - clear fid; % prevents strange error under octave - end - end - - out.stopflag = stopflag; - - % ----- output generation ----- - if verbosemodulo > 0 && isfinite(verbosemodulo) - if countiter == 1 || mod(countiter, 10*verbosemodulo) < 1 - disp(['Iterat, #Fevals: Function Value (median,worst) ' ... - '|Axis Ratio|' ... - 'idx:Min SD idx:Max SD']); - end - if mod(countiter, verbosemodulo) < 1 ... - || (verbosemodulo > 0 && isfinite(verbosemodulo) && ... - (countiter < 3 || ~isempty(stopflag))) - [minstd, minstdidx] = min(sigma*sqrt(diagC)); - [maxstd, maxstdidx] = max(sigma*sqrt(diagC)); - % format display nicely - disp([repmat(' ',1,4-floor(log10(countiter))) ... - num2str(countiter) ' , ' ... - repmat(' ',1,5-floor(log10(counteval))) ... - num2str(counteval) ' : ' ... - num2str(fitness.hist(1), '%.13e') ... - ' +(' num2str(median(fitness.raw)-fitness.hist(1), '%.0e ') ... - ',' num2str(max(fitness.raw)-fitness.hist(1), '%.0e ') ... - ') | ' ... - num2str(max(diagD)/min(diagD), '%4.2e') ' | ' ... - repmat(' ',1,1-floor(log10(minstdidx))) num2str(minstdidx) ':' ... - num2str(minstd, ' %.1e') ' ' ... - repmat(' ',1,1-floor(log10(maxstdidx))) num2str(maxstdidx) ':' ... - num2str(maxstd, ' %.1e')]); - end - end - - % measure time for recording data - if countiter < 3 - time.c = 0.05; - time.nonoutput = 0; - time.recording = 0; - time.saving = 0.15; % first saving after 3 seconds of 100 iterations - time.plotting = 0; - elseif countiter > 300 - % set backward horizon, must be long enough to cover infrequent plotting etc - % time.c = min(1, time.nonoutput/3 + 1e-9); - time.c = max(1e-5, 0.1/sqrt(countiter)); % mean over all or 1e-5 - end - % get average time per iteration - time.t1 = clock; - time.act = max(0,etime(time.t1, time.t0)); - time.nonoutput = (1-time.c) * time.nonoutput ... - + time.c * time.act; - - time.recording = (1-time.c) * time.recording; % per iteration - time.saving = (1-time.c) * time.saving; - time.plotting = (1-time.c) * time.plotting; - - % record output data, concerning time issues - if savemodulo && savetime && (countiter < 1e2 || ~isempty(stopflag) || ... - countiter >= outiter + savemodulo) - outiter = countiter; - % Save output data to files - for namecell = filenames(:)' - name = namecell{:}; - - [fid, err] = fopen(['./' filenameprefix name '.dat'], 'a'); - if fid < 1 % err ~= 0 - warning(['could not open ' filenameprefix name '.dat']); - else - if strcmp(name, 'axlen') - fprintf(fid, '%d %d %e %e %e ', countiter, counteval, sigma, ... - max(diagD), min(diagD)); - fprintf(fid, '%e ', sort(diagD)); - fprintf(fid, '\n'); - elseif strcmp(name, 'disp') % TODO - elseif strcmp(name, 'fit') - fprintf(fid, '%ld %ld %e %e %25.18e %25.18e %25.18e %25.18e', ... - countiter, counteval, sigma, max(diagD)/min(diagD), ... - out.solutions.bestever.f, ... - fitness.raw(1), median(fitness.raw), fitness.raw(end)); - if ~isempty(varargin) && length(varargin{1}) == 1 && isnumeric(varargin{1}) && varargin{1} ~= 0 - fprintf(fid, ' %f', varargin{1}); - end - fprintf(fid, '\n'); - elseif strcmp(name, 'stddev') - fprintf(fid, '%ld %ld %e 0 0 ', countiter, counteval, sigma); - fprintf(fid, '%e ', sigma*sqrt(diagC)); - fprintf(fid, '\n'); - elseif strcmp(name, 'xmean') - if isnan(fmean) - fprintf(fid, '%ld %ld 0 0 0 ', countiter, counteval); - else - fprintf(fid, '%ld %ld 0 0 %e ', countiter, counteval, fmean); - end - fprintf(fid, '%e ', xmean); - fprintf(fid, '\n'); - elseif strcmp(name, 'xrecentbest') - % TODO: fitness is inconsistent with x-value - fprintf(fid, '%ld %ld %25.18e 0 0 ', countiter, counteval, fitness.raw(1)); - fprintf(fid, '%e ', arx(:,fitness.idx(1))); - fprintf(fid, '\n'); - end - fclose(fid); - end - end - - % get average time for recording data - time.t2 = clock; - time.recording = time.recording + time.c * max(0,etime(time.t2, time.t1)); - - % plot - if flgplotting && countiter > 1 - if countiter == 2 - iterplotted = 0; - end - if ~isempty(stopflag) || ... - ((time.nonoutput+time.recording) * (countiter - iterplotted) > 1 && ... - time.plotting < 0.05 * (time.nonoutput+time.recording)) - local_plotcmaesdat(324, filenameprefix); - iterplotted = countiter; - % outplot(out); % outplot defined below - if time.plotting == 0 % disregard opening of the window - time.plotting = time.nonoutput+time.recording; - else - time.plotting = time.plotting + time.c * max(0,etime(clock, time.t2)); + out.arstopflags{irun} = stopflag; + if any(strcmp(stopflag, 'fitness')) ... + || any(strcmp(stopflag, 'maxfunevals')) ... + || any(strcmp(stopflag, 'stoptoresume')) ... + || any(strcmp(stopflag, 'manual')) + break end - end - end - if countiter > 100 + 20 && savemodulo && ... - time.recording * countiter > 0.1 && ... % absolute time larger 0.1 second - time.recording > savetime * (time.nonoutput+time.recording) / 100 - savemodulo = floor(1.1 * savemodulo) + 1; - % disp('++savemodulo'); %qqq - end - end % if output - - % save everything - time.t3 = clock; - if ~isempty(stopflag) || time.saving < 0.05 * time.nonoutput || countiter == 100 - xmin = arxvalid(:, fitness.idx(1)); - fmin = fitness.raw(1); - if flgsaving && countiter > 2 - clear idx; % prevents error under octave - % -v6 : non-compressed non-unicode for version 6 and earlier - if ~isempty(strsaving) && ~isoctave - save('-mat', strsaving, opts.SaveFilename); % for inspection and possible restart - else - save('-mat', opts.SaveFilename); % for inspection and possible restart - end - time.saving = time.saving + time.c * max(0,etime(clock, time.t3)); - end - end - time.t0 = clock; - - % ----- end output generation ----- - -end % while, end generation loop - -% -------------------- Final Procedures ------------------------------- - -% Evaluate xmean and return best recent point in xmin -fmin = fitness.raw(1); -xmin = arxvalid(:, fitness.idx(1)); % Return best point of last generation. -if length(stopflag) > sum(strcmp(stopflag, 'stoptoresume')) % final stopping - out.solutions.mean.f = ... - feval(fitfun, xintobounds(xmean, lbounds, ubounds), varargin{:}); - counteval = counteval + 1; - out.solutions.mean.evals = counteval; - if out.solutions.mean.f < fitness.raw(1) - fmin = out.solutions.mean.f; - xmin = xintobounds(xmean, lbounds, ubounds); % Return xmean as best point - end - if out.solutions.mean.f < out.solutions.bestever.f - out.solutions.bestever = out.solutions.mean; % Return xmean as bestever point - out.solutions.bestever.x = xintobounds(xmean, lbounds, ubounds); - bestever = out.solutions.bestever; - end -end - -% Save everything and display final message -if flgsavingfinal - clear idx; % prevents error under octave - if ~isempty(strsaving) && ~isoctave - save('-mat', strsaving, opts.SaveFilename); % for inspection and possible restart - else - save('-mat', opts.SaveFilename); % for inspection and possible restart - end - message = [' (saved to ' opts.SaveFilename ')']; -else - message = []; -end - -if flgdisplay - disp(['#Fevals: f(returned x) | bestever.f | stopflag' ... - message]); - if isoctave - strstop = stopflag(:); - else - strcat(stopflag(:), '.'); - end - strstop = stopflag(:); %strcat(stopflag(:), '.'); - disp([repmat(' ',1,6-floor(log10(counteval))) ... - num2str(counteval, '%6.0f') ': ' num2str(fmin, '%.11e') ' | ' ... - num2str(out.solutions.bestever.f, '%.11e') ' | ' ... - strstop{1:end}]); - if N < 102 - disp(['mean solution:' sprintf(' %+.1e', xmean)]); - disp(['std deviation:' sprintf(' %.1e', sigma*sqrt(diagC))]); - disp(sprintf('use plotcmaesdat.m for plotting the output at any time (option LogModulo must not be zero)')); - end - if exist('sfile', 'var') - disp(['Results saved in ' sfile]); - end -end - - out.arstopflags{irun} = stopflag; - if any(strcmp(stopflag, 'fitness')) ... - || any(strcmp(stopflag, 'maxfunevals')) ... - || any(strcmp(stopflag, 'stoptoresume')) ... - || any(strcmp(stopflag, 'manual')) - break - end end % while irun <= Restarts -% --------------------------------------------------------------- -% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- function [x, idx] = xintobounds(x, lbounds, ubounds) % % x can be a column vector or a matrix consisting of column vectors % - if ~isempty(lbounds) +if ~isempty(lbounds) if length(lbounds) == 1 - idx = x < lbounds; - x(idx) = lbounds; + idx = x < lbounds; + x(idx) = lbounds; else - arbounds = repmat(lbounds, 1, size(x,2)); - idx = x < arbounds; - x(idx) = arbounds(idx); + arbounds = repmat(lbounds, 1, size(x,2)); + idx = x < arbounds; + x(idx) = arbounds(idx); end - else +else idx = 0; - end - if ~isempty(ubounds) +end +if ~isempty(ubounds) if length(ubounds) == 1 - idx2 = x > ubounds; - x(idx2) = ubounds; + idx2 = x > ubounds; + x(idx2) = ubounds; else - arbounds = repmat(ubounds, 1, size(x,2)); - idx2 = x > arbounds; - x(idx2) = arbounds(idx2); + arbounds = repmat(ubounds, 1, size(x,2)); + idx2 = x > arbounds; + x(idx2) = arbounds(idx2); end - else +else idx2 = 0; - end - idx = idx2-idx; - -% --------------------------------------------------------------- -% --------------------------------------------------------------- +end +idx = idx2-idx; + +% --------------------------------------------------------------- +% --------------------------------------------------------------- function opts=getoptions(inopts, defopts) % OPTS = GETOPTIONS(INOPTS, DEFOPTS) handles an arbitrary number of % optional arguments to a function. The given arguments are collected @@ -1812,7 +1812,7 @@ function opts=getoptions(inopts, defopts) % defopts.ParentNumber = 50; % defopts.MaxIterations = 1e6; % defopts.MaxSigma = 1; -% +% % % merge default options with input options % opts = getoptions(inopts, defopts); % @@ -1823,148 +1823,148 @@ function opts=getoptions(inopts, defopts) % % do whatever % end % end -% +% % For calling the function myfunction with default options: % myfunction(argument1, []); % For calling the function myfunction with modified options: % opt.pop = 100; % redefine PopulationSize option % opt.PAR = 10; % redefine ParentNumber option -% opt.maxiter = 2; % opt.max=2 is ambiguous and would result in an error +% opt.maxiter = 2; % opt.max=2 is ambiguous and would result in an error % myfunction(argument1, opt); % % 04/07/19: Entries can be structs itself leading to a recursive -% call to getoptions. +% call to getoptions. % if nargin < 2 || isempty(defopts) % no default options available - opts=inopts; - return + opts=inopts; + return elseif isempty(inopts) % empty inopts invoke default options - opts = defopts; - return -elseif ~isstruct(defopts) % handle a single option value - if isempty(inopts) opts = defopts; - elseif ~isstruct(inopts) - opts = inopts; - else - error('Input options are a struct, while default options are not'); - end - return + return +elseif ~isstruct(defopts) % handle a single option value + if isempty(inopts) + opts = defopts; + elseif ~isstruct(inopts) + opts = inopts; + else + error('Input options are a struct, while default options are not'); + end + return elseif ~isstruct(inopts) % no valid input options - error('The options need to be a struct or empty'); + error('The options need to be a struct or empty'); end - opts = defopts; % start from defopts - % if necessary overwrite opts fields by inopts values - defnames = fieldnames(defopts); - idxmatched = []; % indices of defopts that already matched - for name = fieldnames(inopts)' +opts = defopts; % start from defopts + % if necessary overwrite opts fields by inopts values +defnames = fieldnames(defopts); +idxmatched = []; % indices of defopts that already matched +for name = fieldnames(inopts)' name = name{1}; % name of i-th inopts-field if isoctave - for i = 1:size(defnames, 1) - idx(i) = strncmp(lower(defnames(i)), lower(name), length(name)); - end + for i = 1:size(defnames, 1) + idx(i) = strncmp(lower(defnames(i)), lower(name), length(name)); + end else - idx = strncmpi(defnames, name, length(name)); + idx = strncmpi(defnames, name, length(name)); end if sum(idx) > 1 - error(['option "' name '" is not an unambigous abbreviation. ' ... - 'Use opts=RMFIELD(opts, ''' name, ... - ''') to remove the field from the struct.']); + error(['option "' name '" is not an unambigous abbreviation. ' ... + 'Use opts=RMFIELD(opts, ''' name, ... + ''') to remove the field from the struct.']); end if sum(idx) == 1 - defname = defnames{find(idx)}; - if ismember(find(idx), idxmatched) - error(['input options match more than ones with "' ... - defname '". ' ... - 'Use opts=RMFIELD(opts, ''' name, ... - ''') to remove the field from the struct.']); - end - idxmatched = [idxmatched find(idx)]; - val = getfield(inopts, name); - % next line can replace previous line from MATLAB version 6.5.0 on and in octave - % val = inopts.(name); - if isstruct(val) % valid syntax only from version 6.5.0 - opts = setfield(opts, defname, ... - getoptions(val, getfield(defopts, defname))); - elseif isstruct(getfield(defopts, defname)) - % next three lines can replace previous three lines from MATLAB - % version 6.5.0 on - % opts.(defname) = ... - % getoptions(val, defopts.(defname)); - % elseif isstruct(defopts.(defname)) - warning(['option "' name '" disregarded (must be struct)']); - elseif ~isempty(val) % empty value: do nothing, i.e. stick to default - opts = setfield(opts, defnames{find(idx)}, val); - % next line can replace previous line from MATLAB version 6.5.0 on - % opts.(defname) = inopts.(name); - end + defname = defnames{find(idx)}; + if ismember(find(idx), idxmatched) + error(['input options match more than ones with "' ... + defname '". ' ... + 'Use opts=RMFIELD(opts, ''' name, ... + ''') to remove the field from the struct.']); + end + idxmatched = [idxmatched find(idx)]; + val = getfield(inopts, name); + % next line can replace previous line from MATLAB version 6.5.0 on and in octave + % val = inopts.(name); + if isstruct(val) % valid syntax only from version 6.5.0 + opts = setfield(opts, defname, ... + getoptions(val, getfield(defopts, defname))); + elseif isstruct(getfield(defopts, defname)) + % next three lines can replace previous three lines from MATLAB + % version 6.5.0 on + % opts.(defname) = ... + % getoptions(val, defopts.(defname)); + % elseif isstruct(defopts.(defname)) + warning(['option "' name '" disregarded (must be struct)']); + elseif ~isempty(val) % empty value: do nothing, i.e. stick to default + opts = setfield(opts, defnames{find(idx)}, val); + % next line can replace previous line from MATLAB version 6.5.0 on + % opts.(defname) = inopts.(name); + end else - warning(['option "' name '" disregarded (unknown field name)']); + warning(['option "' name '" disregarded (unknown field name)']); end - end +end -% --------------------------------------------------------------- -% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- function res=myeval(s) - if ischar(s) +if ischar(s) res = evalin('caller', s); - else +else res = s; - end - -% --------------------------------------------------------------- -% --------------------------------------------------------------- +end + +% --------------------------------------------------------------- +% --------------------------------------------------------------- function res=myevalbool(s) - if ~ischar(s) % s may not and cannot be empty +if ~ischar(s) % s may not and cannot be empty res = s; - else % evaluation string s +else % evaluation string s if strncmpi(lower(s), 'yes', 3) || strncmpi(s, 'on', 2) ... - || strncmpi(s, 'true', 4) || strncmp(s, '1 ', 2) - res = 1; + || strncmpi(s, 'true', 4) || strncmp(s, '1 ', 2) + res = 1; elseif strncmpi(s, 'no', 2) || strncmpi(s, 'off', 3) ... - || strncmpi(s, 'false', 5) || strncmp(s, '0 ', 2) - res = 0; + || strncmpi(s, 'false', 5) || strncmp(s, '0 ', 2) + res = 0; else - try res = evalin('caller', s); catch - error(['String value "' s '" cannot be evaluated']); - end - try res ~= 0; catch - error(['String value "' s '" cannot be evaluated reasonably']); - end + try res = evalin('caller', s); catch + error(['String value "' s '" cannot be evaluated']); + end + try res ~= 0; catch + error(['String value "' s '" cannot be evaluated reasonably']); + end end - end - +end -% --------------------------------------------------------------- -% --------------------------------------------------------------- + +% --------------------------------------------------------------- +% --------------------------------------------------------------- function res = isoctave % any hack to find out whether we are running octave - s = version; - res = 0; - if exist('fflush', 'builtin') && eval(s(1)) < 7 +s = version; +res = 0; +if exist('fflush', 'builtin') && eval(s(1)) < 7 res = 1; - end +end -% --------------------------------------------------------------- -% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- function flush - if isoctave +if isoctave feval('fflush', stdout); - end +end -% --------------------------------------------------------------- -% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- % ----- replacements for statistic toolbox functions ------------ -% --------------------------------------------------------------- -% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- function res=myrange(x) - res = max(x) - min(x); - -% --------------------------------------------------------------- -% --------------------------------------------------------------- +res = max(x) - min(x); + +% --------------------------------------------------------------- +% --------------------------------------------------------------- function res = myprctile(inar, perc, idx) % % Computes the percentiles in vector perc from vector inar @@ -1975,105 +1975,105 @@ function res = myprctile(inar, perc, idx) N = length(inar); flgtranspose = 0; -% sizes +% sizes if size(perc,1) > 1 - perc = perc'; - flgtranspose = 1; - if size(perc,1) > 1 - error('perc must not be a matrix'); - end + perc = perc'; + flgtranspose = 1; + if size(perc,1) > 1 + error('perc must not be a matrix'); + end end if size(inar, 1) > 1 && size(inar,2) > 1 - error('data inar must not be a matrix'); + error('data inar must not be a matrix'); end - + % sort inar if nargin < 3 || isempty(idx) - [sar, idx] = sort(inar); + [sar, idx] = sort(inar); else - sar = inar(idx); + sar = inar(idx); end res = []; for p = perc - if p <= 100*(0.5/N) - res(end+1) = sar(1); - elseif p >= 100*((N-0.5)/N) - res(end+1) = sar(N); - else - % find largest index smaller than required percentile - availablepercentiles = 100*((1:N)-0.5)/N; - i = max(find(p > availablepercentiles)); - % interpolate linearly - res(end+1) = sar(i) ... - + (sar(i+1)-sar(i))*(p - availablepercentiles(i)) ... - / (availablepercentiles(i+1) - availablepercentiles(i)); - - end + if p <= 100*(0.5/N) + res(end+1) = sar(1); + elseif p >= 100*((N-0.5)/N) + res(end+1) = sar(N); + else + % find largest index smaller than required percentile + availablepercentiles = 100*((1:N)-0.5)/N; + i = max(find(p > availablepercentiles)); + % interpolate linearly + res(end+1) = sar(i) ... + + (sar(i+1)-sar(i))*(p - availablepercentiles(i)) ... + / (availablepercentiles(i+1) - availablepercentiles(i)); + + end end if flgtranspose - res = res'; + res = res'; end -% --------------------------------------------------------------- -% --------------------------------------------------------------- -% --------------------------------------------------------------- -% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- function [s, ranks, rankDelta] = local_noisemeasurement(arf1, arf2, lamreev, theta, cutlimit) % function [s ranks rankDelta] = noisemeasurement(arf1, arf2, lamreev, theta) % -% Input: -% arf1, arf2 : two arrays of function values. arf1 is of size 1xlambda, -% arf2 may be of size 1xlamreev or 1xlambda. The first lamreev values -% in arf2 are (re-)evaluations of the respective solutions, i.e. +% Input: +% arf1, arf2 : two arrays of function values. arf1 is of size 1xlambda, +% arf2 may be of size 1xlamreev or 1xlambda. The first lamreev values +% in arf2 are (re-)evaluations of the respective solutions, i.e. % arf1(1) and arf2(1) are two evaluations of "the first" solution. -% lamreev: number of reevaluated individuals in arf2 -% theta : parameter theta for the rank change limit, between 0 and 1, -% typically between 0.2 and 0.7. -% cutlimit (optional): output s is computed as a mean of rankchange minus -% threshold, where rankchange is <=2*(lambda-1). cutlimit limits -% abs(rankchange minus threshold) in this calculation to cutlimit. -% cutlimit=1 evaluates basically the sign only. cutlimit=2 could be -% the rank change with one solution (both evaluations of it). -% -% Output: +% lamreev: number of reevaluated individuals in arf2 +% theta : parameter theta for the rank change limit, between 0 and 1, +% typically between 0.2 and 0.7. +% cutlimit (optional): output s is computed as a mean of rankchange minus +% threshold, where rankchange is <=2*(lambda-1). cutlimit limits +% abs(rankchange minus threshold) in this calculation to cutlimit. +% cutlimit=1 evaluates basically the sign only. cutlimit=2 could be +% the rank change with one solution (both evaluations of it). +% +% Output: % s : noise measurement, s>0 means the noise measure is above the % acceptance threshold -% ranks : 2xlambda array, corresponding to [arf1; arf2], of ranks +% ranks : 2xlambda array, corresponding to [arf1; arf2], of ranks % of arf1 and arf2 in the set [arf1 arf2], values are in [1:2*lambda] % rankDelta: 1xlambda array of rank movements of arf2 compared to % arf1. rankDelta(i) agrees with the number of values from % the set [arf1 arf2] that lie between arf1(i) and arf2(i). % % Note: equal function values might lead to somewhat spurious results. -% For this case a revision is advisable. +% For this case a revision is advisable. %%% verify input argument sizes if size(arf1,1) ~= 1 - error('arf1 must be an 1xlambda array'); + error('arf1 must be an 1xlambda array'); elseif size(arf2,1) ~= 1 - error('arf2 must be an 1xsomething array'); + error('arf2 must be an 1xsomething array'); elseif size(arf1,2) < size(arf2,2) % not really necessary, but saver - error('arf2 must not be smaller than arf1 in length'); + error('arf2 must not be smaller than arf1 in length'); end lam = size(arf1, 2); if size(arf1,2) ~= size(arf2,2) - arf2(end+1:lam) = arf1((size(arf2,2)+1):lam); + arf2(end+1:lam) = arf1((size(arf2,2)+1):lam); end if nargin < 5 - cutlimit = inf; + cutlimit = inf; end %%% capture unusual values if any(diff(arf1) == 0) - % this will presumably interpreted as rank change, because - % sort(ones(...)) returns 1,2,3,... - warning([num2str(sum(diff(arf1)==0)) ' equal function values']); + % this will presumably interpreted as rank change, because + % sort(ones(...)) returns 1,2,3,... + warning([num2str(sum(diff(arf1)==0)) ' equal function values']); end %%% compute rank changes into rankDelta @@ -2086,12 +2086,12 @@ rankDelta = ranks(1,:) - ranks(2,:) - sign(ranks(1,:) - ranks(2,:)); %%% compute rank change limits using both ranks(1,...) and ranks(2,...) for i = 1:lamreev - sumlim(i) = ... - 0.5 * (... - myprctile(abs((1:2*lam-1) - (ranks(1,i) - (ranks(1,i)>ranks(2,i)))), ... - theta*50) ... - + myprctile(abs((1:2*lam-1) - (ranks(2,i) - (ranks(2,i)>ranks(1,i)))), ... - theta*50)); + sumlim(i) = ... + 0.5 * (... + myprctile(abs((1:2*lam-1) - (ranks(1,i) - (ranks(1,i)>ranks(2,i)))), ... + theta*50) ... + + myprctile(abs((1:2*lam-1) - (ranks(2,i) - (ranks(2,i)>ranks(1,i)))), ... + theta*50)); end %%% compute measurement @@ -2101,235 +2101,235 @@ end s = abs(rankDelta(1:lamreev)) - max(1, sumlim); % lives roughly in 0..2*lambda % cut-off limit -idx = abs(s) > cutlimit; +idx = abs(s) > cutlimit; s(idx) = sign(s(idx)) * cutlimit; s = mean(s); -% --------------------------------------------------------------- -% --------------------------------------------------------------- -% --------------------------------------------------------------- -% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- % just a "local" copy of plotcmaesdat.m, with manual_mode set to zero function local_plotcmaesdat(figNb, filenameprefix, filenameextension, objectvarname) % PLOTCMAESDAT; % PLOTCMAES(FIGURENUMBER_iBEGIN_iEND, FILENAMEPREFIX, FILENAMEEXTENSION, OBJECTVARNAME); -% plots output from CMA-ES, e.g. cmaes.m, Java class CMAEvolutionStrategy... -% mod(figNb,100)==1 plots versus iterations. +% plots output from CMA-ES, e.g. cmaes.m, Java class CMAEvolutionStrategy... +% mod(figNb,100)==1 plots versus iterations. % -% PLOTCMAES([101 300]) plots versus iteration, from iteration 300. -% PLOTCMAES([100 150 800]) plots versus function evaluations, between iteration 150 and 800. +% PLOTCMAES([101 300]) plots versus iteration, from iteration 300. +% PLOTCMAES([100 150 800]) plots versus function evaluations, between iteration 150 and 800. % -% Upper left subplot: blue/red: function value of the best solution in the +% Upper left subplot: blue/red: function value of the best solution in the % recent population, cyan: same function value minus best -% ever seen function value, green: sigma, red: ratio between +% ever seen function value, green: sigma, red: ratio between % longest and shortest principal axis length which is equivalent -% to sqrt(cond(C)). +% to sqrt(cond(C)). % Upper right plot: time evolution of the distribution mean (default) or -% the recent best solution vector. -% Lower left: principal axes lengths of the distribution ellipsoid, -% equivalent with the sqrt(eig(C)) square root eigenvalues of C. -% Lower right: magenta: minimal and maximal "true" standard deviation -% (with sigma included) in the coordinates, other colors: sqrt(diag(C)) +% the recent best solution vector. +% Lower left: principal axes lengths of the distribution ellipsoid, +% equivalent with the sqrt(eig(C)) square root eigenvalues of C. +% Lower right: magenta: minimal and maximal "true" standard deviation +% (with sigma included) in the coordinates, other colors: sqrt(diag(C)) % of all diagonal elements of C, if C is diagonal they equal to the -% lower left. +% lower left. % -% Files [FILENAMEPREFIX name FILENAMEEXTENSION] are used, where +% Files [FILENAMEPREFIX name FILENAMEEXTENSION] are used, where % name = axlen, OBJECTVARNAME (xmean|xrecentbest), fit, or stddev. % manual_mode = 0; - if nargin < 1 || isempty(figNb) +if nargin < 1 || isempty(figNb) figNb = 325; - end - if nargin < 2 || isempty(filenameprefix) +end +if nargin < 2 || isempty(filenameprefix) filenameprefix = 'outcmaes'; - end - if nargin < 3 || isempty(filenameextension) +end +if nargin < 3 || isempty(filenameextension) filenameextension = '.dat'; - end - if nargin < 4 || isempty(objectvarname) - objectvarname = 'xmean'; +end +if nargin < 4 || isempty(objectvarname) + objectvarname = 'xmean'; objectvarname = 'xrecentbest'; - end - % load data - d.x = load([filenameprefix objectvarname filenameextension]); - % d.x = load([filenameprefix 'xmean' filenameextension]); - % d.x = load([filenameprefix 'xrecentbest' filenameextension]); - d.f = load([filenameprefix 'fit' filenameextension]); - d.std = load([filenameprefix 'stddev' filenameextension]); - d.D = load([filenameprefix 'axlen' filenameextension]); - - % interpret entries in figNb for cutting out some data - if length(figNb) > 1 +end +% load data +d.x = load([filenameprefix objectvarname filenameextension]); +% d.x = load([filenameprefix 'xmean' filenameextension]); +% d.x = load([filenameprefix 'xrecentbest' filenameextension]); +d.f = load([filenameprefix 'fit' filenameextension]); +d.std = load([filenameprefix 'stddev' filenameextension]); +d.D = load([filenameprefix 'axlen' filenameextension]); + +% interpret entries in figNb for cutting out some data +if length(figNb) > 1 iend = inf; istart = figNb(2); if length(figNb) > 2 - iend = figNb(3); + iend = figNb(3); end figNb = figNb(1); d.x = d.x(d.x(:,1) >= istart & d.x(:,1) <= iend, :); d.f = d.f(d.f(:,1) >= istart & d.f(:,1) <= iend, :); d.std = d.std(d.std(:,1) >= istart & d.std(:,1) <= iend, :); d.D = d.D(d.D(:,1) >= istart & d.D(:,1) <= iend, :); - end +end - % decide for x-axis - iabscissa = 2; % 1== versus iterations, 2==versus fevals - if mod(figNb,100) == 1 +% decide for x-axis +iabscissa = 2; % 1== versus iterations, 2==versus fevals +if mod(figNb,100) == 1 iabscissa = 1; % a short hack - end - if iabscissa == 1 - xlab ='iterations'; - elseif iabscissa == 2 - xlab = 'function evaluations'; - end - - if size(d.x, 2) < 1000 +end +if iabscissa == 1 + xlab ='iterations'; +elseif iabscissa == 2 + xlab = 'function evaluations'; +end + +if size(d.x, 2) < 1000 minxend = 1.03*d.x(end, iabscissa); - else +else minxend = 0; - end +end - % set up figure window - if manual_mode +% set up figure window +if manual_mode figure(figNb); % just create and raise the figure window - else - if 1 < 3 && evalin('caller', 'iterplotted') == 0 && evalin('caller', 'irun') == 1 - figure(figNb); % incomment this, if figure raise in the beginning is not desired +else + if 1 < 3 && evalin('caller', 'iterplotted') == 0 && evalin('caller', 'irun') == 1 + figure(figNb); % incomment this, if figure raise in the beginning is not desired elseif ismember(figNb, findobj('Type', 'figure')) - set(0, 'CurrentFigure', figNb); % prevents raise of existing figure window + set(0, 'CurrentFigure', figNb); % prevents raise of existing figure window else - figure(figNb); + figure(figNb); end - end - - % plot fitness etc - foffset = 1e-99; - dfit = d.f(:,6)-min(d.f(:,6)); - [ignore, idxbest] = min(dfit); - dfit(dfit<1e-98) = NaN; - subplot(2,2,1); hold off; - dd = abs(d.f(:,7:8)) + foffset; - dd(d.f(:,7:8)==0) = NaN; - semilogy(d.f(:,iabscissa), dd, '-k'); hold on; - % additional fitness data, for example constraints values - if size(d.f,2) > 8 +end + +% plot fitness etc +foffset = 1e-99; +dfit = d.f(:,6)-min(d.f(:,6)); +[ignore, idxbest] = min(dfit); +dfit(dfit<1e-98) = NaN; +subplot(2,2,1); hold off; +dd = abs(d.f(:,7:8)) + foffset; +dd(d.f(:,7:8)==0) = NaN; +semilogy(d.f(:,iabscissa), dd, '-k'); hold on; +% additional fitness data, for example constraints values +if size(d.f,2) > 8 dd = abs(d.f(:,9:end)) + 10*foffset; % a hack - % dd(d.f(:,9:end)==0) = NaN; - semilogy(d.f(:,iabscissa), dd, '-m'); hold on; + % dd(d.f(:,9:end)==0) = NaN; + semilogy(d.f(:,iabscissa), dd, '-m'); hold on; if size(d.f,2) > 12 - semilogy(d.f(:,iabscissa),abs(d.f(:,[7 8 11 13]))+foffset,'-k'); hold on; + semilogy(d.f(:,iabscissa),abs(d.f(:,[7 8 11 13]))+foffset,'-k'); hold on; end - end - - idx = find(d.f(:,6)>1e-98); % positive values - if ~isempty(idx) % otherwise non-log plot gets hold - semilogy(d.f(idx,iabscissa), d.f(idx,6)+foffset, '.b'); hold on; - end - idx = find(d.f(:,6) < -1e-98); % negative values - if ~isempty(idx) - semilogy(d.f(idx, iabscissa), abs(d.f(idx,6))+foffset,'.r'); hold on; - end - semilogy(d.f(:,iabscissa),abs(d.f(:,6))+foffset,'-b'); hold on; - semilogy(d.f(:,iabscissa),dfit,'-c'); hold on; - semilogy(d.f(:,iabscissa),(d.f(:,4)),'-r'); hold on; % AR - semilogy(d.std(:,iabscissa), [max(d.std(:,6:end)')' ... - min(d.std(:,6:end)')'], '-m'); % max,min std - maxval = max(d.std(end,6:end)); - minval = min(d.std(end,6:end)); - text(d.std(end,iabscissa), maxval, sprintf('%.0e', maxval)); - text(d.std(end,iabscissa), minval, sprintf('%.0e', minval)); - - semilogy(d.std(:,iabscissa),(d.std(:,3)),'-g'); % sigma - % plot best f - semilogy(d.f(idxbest,iabscissa),min(dfit),'*c'); hold on; - semilogy(d.f(idxbest,iabscissa),abs(d.f(idxbest,6))+foffset,'*r'); hold on; - - ax = axis; - ax(2) = max(minxend, ax(2)); - axis(ax); - - yannote = 10^(log10(ax(3)) + 0.05*(log10(ax(4))-log10(ax(3)))); - text(ax(1), yannote, ... - [ 'f=' num2str(d.f(end,6), '%.15g') ]); - - title('blue:abs(f), cyan:f-min(f), green:sigma, red:axis ratio'); - grid on; - - subplot(2,2,2); hold off; - plot(d.x(:,iabscissa), d.x(:,6:end),'-'); hold on; - ax = axis; - ax(2) = max(minxend, ax(2)); - axis(ax); - - % add some annotation lines - [ignore idx] = sort(d.x(end,6:end)); - % choose no more than 25 indices - idxs = round(linspace(1, size(d.x,2)-5, min(size(d.x,2)-5, 25))); - yy = repmat(NaN, 2, size(d.x,2)-5); - yy(1,:) = d.x(end, 6:end); - yy(2,idx(idxs)) = linspace(ax(3), ax(4), length(idxs)); - plot([d.x(end,iabscissa) ax(2)], yy, '-'); - plot(repmat(d.x(end,iabscissa),2), [ax(3) ax(4)], 'k-'); - for i = idx(idxs) +end + +idx = find(d.f(:,6)>1e-98); % positive values +if ~isempty(idx) % otherwise non-log plot gets hold + semilogy(d.f(idx,iabscissa), d.f(idx,6)+foffset, '.b'); hold on; +end +idx = find(d.f(:,6) < -1e-98); % negative values +if ~isempty(idx) + semilogy(d.f(idx, iabscissa), abs(d.f(idx,6))+foffset,'.r'); hold on; +end +semilogy(d.f(:,iabscissa),abs(d.f(:,6))+foffset,'-b'); hold on; +semilogy(d.f(:,iabscissa),dfit,'-c'); hold on; +semilogy(d.f(:,iabscissa),(d.f(:,4)),'-r'); hold on; % AR +semilogy(d.std(:,iabscissa), [max(d.std(:,6:end)')' ... + min(d.std(:,6:end)')'], '-m'); % max,min std +maxval = max(d.std(end,6:end)); +minval = min(d.std(end,6:end)); +text(d.std(end,iabscissa), maxval, sprintf('%.0e', maxval)); +text(d.std(end,iabscissa), minval, sprintf('%.0e', minval)); + +semilogy(d.std(:,iabscissa),(d.std(:,3)),'-g'); % sigma + % plot best f +semilogy(d.f(idxbest,iabscissa),min(dfit),'*c'); hold on; +semilogy(d.f(idxbest,iabscissa),abs(d.f(idxbest,6))+foffset,'*r'); hold on; + +ax = axis; +ax(2) = max(minxend, ax(2)); +axis(ax); + +yannote = 10^(log10(ax(3)) + 0.05*(log10(ax(4))-log10(ax(3)))); +text(ax(1), yannote, ... + [ 'f=' num2str(d.f(end,6), '%.15g') ]); + +title('blue:abs(f), cyan:f-min(f), green:sigma, red:axis ratio'); +grid on; + +subplot(2,2,2); hold off; +plot(d.x(:,iabscissa), d.x(:,6:end),'-'); hold on; +ax = axis; +ax(2) = max(minxend, ax(2)); +axis(ax); + +% add some annotation lines +[ignore idx] = sort(d.x(end,6:end)); +% choose no more than 25 indices +idxs = round(linspace(1, size(d.x,2)-5, min(size(d.x,2)-5, 25))); +yy = repmat(NaN, 2, size(d.x,2)-5); +yy(1,:) = d.x(end, 6:end); +yy(2,idx(idxs)) = linspace(ax(3), ax(4), length(idxs)); +plot([d.x(end,iabscissa) ax(2)], yy, '-'); +plot(repmat(d.x(end,iabscissa),2), [ax(3) ax(4)], 'k-'); +for i = idx(idxs) text(ax(2), yy(2,i), ... ['x(' num2str(i) ')=' num2str(yy(1,i))]); - end - - lam = 'NA'; - if size(d.x, 1) > 1 && d.x(end, 1) > d.x(end-1, 1) +end + +lam = 'NA'; +if size(d.x, 1) > 1 && d.x(end, 1) > d.x(end-1, 1) lam = num2str((d.x(end, 2) - d.x(end-1, 2)) / (d.x(end, 1) - d.x(end-1, 1))); - end - title(['Object Variables (' num2str(size(d.x, 2)-5) ... - '-D, popsize~' lam ')']);grid on; - - subplot(2,2,3); hold off; semilogy(d.D(:,iabscissa), d.D(:,6:end), '-'); - ax = axis; - ax(2) = max(minxend, ax(2)); - axis(ax); - title('Principal Axes Lengths');grid on; - xlabel(xlab); - - subplot(2,2,4); hold off; - % semilogy(d.std(:,iabscissa), d.std(:,6:end), 'k-'); hold on; - % remove sigma from stds - d.std(:,6:end) = d.std(:,6:end) ./ (d.std(:,3) * ones(1,size(d.std,2)-5)); - semilogy(d.std(:,iabscissa), d.std(:,6:end), '-'); hold on; - if 11 < 3 % max and min std +end +title(['Object Variables (' num2str(size(d.x, 2)-5) ... + '-D, popsize~' lam ')']);grid on; + +subplot(2,2,3); hold off; semilogy(d.D(:,iabscissa), d.D(:,6:end), '-'); +ax = axis; +ax(2) = max(minxend, ax(2)); +axis(ax); +title('Principal Axes Lengths');grid on; +xlabel(xlab); + +subplot(2,2,4); hold off; +% semilogy(d.std(:,iabscissa), d.std(:,6:end), 'k-'); hold on; +% remove sigma from stds +d.std(:,6:end) = d.std(:,6:end) ./ (d.std(:,3) * ones(1,size(d.std,2)-5)); +semilogy(d.std(:,iabscissa), d.std(:,6:end), '-'); hold on; +if 11 < 3 % max and min std semilogy(d.std(:,iabscissa), [d.std(:,3).*max(d.std(:,6:end)')' ... d.std(:,3).*min(d.std(:,6:end)')'], '-m', 'linewidth', 2); maxval = max(d.std(end,6:end)); minval = min(d.std(end,6:end)); text(d.std(end,iabscissa), d.std(end,3)*maxval, sprintf('max=%.0e', maxval)); text(d.std(end,iabscissa), d.std(end,3)*minval, sprintf('min=%.0e', minval)); - end - ax = axis; - ax(2) = max(minxend, ax(2)); - axis(ax); - % add some annotation lines - [ignore, idx] = sort(d.std(end,6:end)); - % choose no more than 25 indices - idxs = round(linspace(1, size(d.x,2)-5, min(size(d.x,2)-5, 25))); - yy = repmat(NaN, 2, size(d.std,2)-5); - yy(1,:) = d.std(end, 6:end); - yy(2,idx(idxs)) = logspace(log10(ax(3)), log10(ax(4)), length(idxs)); - semilogy([d.std(end,iabscissa) ax(2)], yy, '-'); - semilogy(repmat(d.std(end,iabscissa),2), [ax(3) ax(4)], 'k-'); - for i = idx(idxs) +end +ax = axis; +ax(2) = max(minxend, ax(2)); +axis(ax); +% add some annotation lines +[ignore, idx] = sort(d.std(end,6:end)); +% choose no more than 25 indices +idxs = round(linspace(1, size(d.x,2)-5, min(size(d.x,2)-5, 25))); +yy = repmat(NaN, 2, size(d.std,2)-5); +yy(1,:) = d.std(end, 6:end); +yy(2,idx(idxs)) = logspace(log10(ax(3)), log10(ax(4)), length(idxs)); +semilogy([d.std(end,iabscissa) ax(2)], yy, '-'); +semilogy(repmat(d.std(end,iabscissa),2), [ax(3) ax(4)], 'k-'); +for i = idx(idxs) text(ax(2), yy(2,i), [' ' num2str(i)]); - end - title('Standard Deviations in Coordinates divided by sigma');grid on; - xlabel(xlab); +end +title('Standard Deviations in Coordinates divided by sigma');grid on; +xlabel(xlab); - if figNb ~= 324 +if figNb ~= 324 % zoom on; % does not work in Octave - end - drawnow; +end +drawnow; -% --------------------------------------------------------------- -% --------------- TEST OBJECTIVE FUNCTIONS ---------------------- -% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------- TEST OBJECTIVE FUNCTIONS ---------------------- +% --------------------------------------------------------------- %%% Unimodal functions @@ -2337,652 +2337,652 @@ function f=fjens1(x) % % use population size about 2*N % - f = sum((x>0) .* x.^1, 1); - if any(any(x<0)) +f = sum((x>0) .* x.^1, 1); +if any(any(x<0)) idx = sum(x < 0, 1) > 0; f(idx) = 1e3; -% f = f + 1e3 * sum(x<0, 1); -% f = f + 10 * sum((x<0) .* x.^2, 1); + % f = f + 1e3 * sum(x<0, 1); + % f = f + 10 * sum((x<0) .* x.^2, 1); f(idx) = f(idx) + 1e-3*abs(randn(1,sum(idx))); -% f(idx) = NaN; - end + % f(idx) = NaN; +end function f=fsphere(x) - f = sum(x.^2,1); +f = sum(x.^2,1); function f=fmax(x) - f = max(abs(x), [], 1); +f = max(abs(x), [], 1); function f=fssphere(x) - f=sqrt(sum(x.^2, 1)); +f=sqrt(sum(x.^2, 1)); -% lb = -0.512; ub = 512; -% xfeas = x; +% lb = -0.512; ub = 512; +% xfeas = x; % xfeas(x<lb) = lb; -% xfeas(x>ub) = ub; +% xfeas(x>ub) = ub; % f=sum(xfeas.^2, 1); -% f = f + 1e-9 * sum((xfeas-x).^2); - +% f = f + 1e-9 * sum((xfeas-x).^2); + function f=fspherenoise(x, Nevals) - if nargin < 2 || isempty(Nevals) +if nargin < 2 || isempty(Nevals) Nevals = 1; - end - [N,popsi] = size(x); +end +[N,popsi] = size(x); % x = x .* (1 + 0.3e-0 * randn(N, popsi)/(2*N)); % actuator noise - fsum = 10.^(0*(0:N-1)/(N-1)) * x.^2; +fsum = 10.^(0*(0:N-1)/(N-1)) * x.^2; % f = 0*rand(1,1) ... % + fsum ... % + fsum .* (2*randn(1,popsi) ./ randn(1,popsi).^0 / (2*N)) ... -% + 1*fsum.^0.9 .* 2*randn(1,popsi) / (2*N); % +% + 1*fsum.^0.9 .* 2*randn(1,popsi) / (2*N); % % f = fsum .* exp(0.1*randn(1,popsi)); - f = fsum .* (1 + (10/(N+10)/sqrt(Nevals))*randn(1,popsi)); +f = fsum .* (1 + (10/(N+10)/sqrt(Nevals))*randn(1,popsi)); % f = fsum .* (1 + (0.1/N)*randn(1,popsi)./randn(1,popsi).^1); - idx = rand(1,popsi) < 0.0; - if sum(idx) > 0 +idx = rand(1,popsi) < 0.0; +if sum(idx) > 0 f(idx) = f(idx) + 1e3*exp(randn(1,sum(idx))); - end - +end + function f=fmixranks(x) - N = size(x,1); - f=(10.^(0*(0:(N-1))/(N-1))*x.^2).^0.5; - if size(x, 2) > 1 % compute ranks, if it is a population +N = size(x,1); +f=(10.^(0*(0:(N-1))/(N-1))*x.^2).^0.5; +if size(x, 2) > 1 % compute ranks, if it is a population [ignore, idx] = sort(f); [ignore, ranks] = sort(idx); k = 9; % number of solutions randomly permuted, lambda/2-1 % works still quite well (two time slower) for i = k+1:k-0:size(x,2) - idx(i-k+(1:k)) = idx(i-k+randperm(k)); + idx(i-k+(1:k)) = idx(i-k+randperm(k)); end %disp([ranks' f']) [ignore, ranks] = sort(idx); %disp([ranks' f']) %pause f = ranks+1e-9*randn(1,1); - end - +end + function f = fsphereoneax(x) - f = x(1)^2; - f = mean(x)^2; - +f = x(1)^2; +f = mean(x)^2; + function f=frandsphere(x) - N = size(x,1); - idx = ceil(N*rand(7,1)); - f=sum(x(idx).^2); +N = size(x,1); +idx = ceil(N*rand(7,1)); +f=sum(x(idx).^2); function f=fspherelb0(x, M) % lbound at zero for 1:M needed - if nargin < 2 M = 0; end - N = size(x,1); - % M active bounds, f_i = 1 for x = 0 - f = -M + sum((x(1:M) + 1).^2); - f = f + sum(x(M+1:N).^2); - +if nargin < 2 M = 0; end +N = size(x,1); +% M active bounds, f_i = 1 for x = 0 +f = -M + sum((x(1:M) + 1).^2); +f = f + sum(x(M+1:N).^2); + function f=fspherehull(x) - % Patton, Dexter, Goodman, Punch - % in -500..500 - % spherical ridge through zeros(N,1) - % worst case start point seems x = 2*100*sqrt(N) - % and small step size - N = size(x,1); - f = norm(x) + (norm(x-100*sqrt(N)) - 100*N)^2; - +% Patton, Dexter, Goodman, Punch +% in -500..500 +% spherical ridge through zeros(N,1) +% worst case start point seems x = 2*100*sqrt(N) +% and small step size +N = size(x,1); +f = norm(x) + (norm(x-100*sqrt(N)) - 100*N)^2; + function f=fellilb0(x, idxM, scal) % lbound at zero for 1:M needed - N = size(x,1); - if nargin < 3 || isempty(scal) +N = size(x,1); +if nargin < 3 || isempty(scal) scal = 100; - end - scale=scal.^((0:N-1)/(N-1)); - if nargin < 2 || isempty(idxM) +end +scale=scal.^((0:N-1)/(N-1)); +if nargin < 2 || isempty(idxM) idxM = 1:N; - end - %scale(N) = 1e0; - % M active bounds - xopt = 0.1; - x(idxM) = x(idxM) + xopt; - f = scale.^2*x.^2; - f = f - sum((xopt*scale(idxM)).^2); +end +%scale(N) = 1e0; +% M active bounds +xopt = 0.1; +x(idxM) = x(idxM) + xopt; +f = scale.^2*x.^2; +f = f - sum((xopt*scale(idxM)).^2); % f = exp(f) - 1; % f = log10(f+1e-19) + 19; - f = f + 1e-19; - +f = f + 1e-19; + function f=fcornersphere(x) - w = ones(size(x,1)); - w(1) = 2.5; w(2)=2.5; - idx = x < 0; - f = sum(x(idx).^2); - idx = x > 0; - f = f + 2^2*sum(w(idx).*x(idx).^2); - +w = ones(size(x,1)); +w(1) = 2.5; w(2)=2.5; +idx = x < 0; +f = sum(x(idx).^2); +idx = x > 0; +f = f + 2^2*sum(w(idx).*x(idx).^2); + function f=fsectorsphere(x, scal) % % This is deceptive for cumulative sigma control CSA in large dimension: % The strategy (initially) diverges for N=50 and popsize = 150. (Even % for cs==1 this can be observed for larger settings of N and -% popsize.) The reason is obvious from the function topology. +% popsize.) The reason is obvious from the function topology. % Divergence can be avoided by setting boundaries or adding a -% penalty for large ||x||. Then, convergence can be observed again. +% penalty for large ||x||. Then, convergence can be observed again. % Conclusion: for popsize>N cumulative sigma control is not completely % reasonable, but I do not know better alternatives. In particular: -% TPA takes longer to converge than CSA when the latter still works. +% TPA takes longer to converge than CSA when the latter still works. % - if nargin < 2 || isempty (scal) +if nargin < 2 || isempty (scal) scal = 1e3; - end - f=sum(x.^2,1); - idx = x<0; - f = f + (scal^2 - 1) * sum((idx.*x).^2,1); - if 11 < 3 +end +f=sum(x.^2,1); +idx = x<0; +f = f + (scal^2 - 1) * sum((idx.*x).^2,1); +if 11 < 3 idxpen = find(f>1e9); if ~isempty(idxpen) - f(idxpen) = f(idxpen) + 1e8*sum(x(:,idxpen).^2,1); + f(idxpen) = f(idxpen) + 1e8*sum(x(:,idxpen).^2,1); end - end - +end + function f=fstepsphere(x, scal) - if nargin < 2 || isempty (scal) +if nargin < 2 || isempty (scal) scal = 1e0; - end - N = size(x,1); - f=1e-11+sum(scal.^((0:N-1)/(N-1))*floor(x+0.5).^2); - f=1e-11+sum(floor(scal.^((0:N-1)/(N-1))'.*x+0.5).^2); +end +N = size(x,1); +f=1e-11+sum(scal.^((0:N-1)/(N-1))*floor(x+0.5).^2); +f=1e-11+sum(floor(scal.^((0:N-1)/(N-1))'.*x+0.5).^2); % f=1e-11+sum(floor(x+0.5).^2); function f=fstep(x) - % in -5.12..5.12 (bounded) - N = size(x,1); - f=1e-11+6*N+sum(floor(x)); +% in -5.12..5.12 (bounded) +N = size(x,1); +f=1e-11+6*N+sum(floor(x)); function f=flnorm(x, scal, e) if nargin < 2 || isempty(scal) - scal = 1; + scal = 1; end if nargin < 3 || isempty(e) - e = 1; + e = 1; end if e==inf - f = max(abs(x)); + f = max(abs(x)); else - N = size(x,1); - scale = scal.^((0:N-1)/(N-1))'; - f=sum(abs(scale.*x).^e); + N = size(x,1); + scale = scal.^((0:N-1)/(N-1))'; + f=sum(abs(scale.*x).^e); end -function f=fneumaier3(x) - % in -n^2..n^2 - % x^*-i = i(n+1-i) - N = size(x,1); +function f=fneumaier3(x) +% in -n^2..n^2 +% x^*-i = i(n+1-i) +N = size(x,1); % f = N*(N+4)*(N-1)/6 + sum((x-1).^2) - sum(x(1:N-1).*x(2:N)); - f = sum((x-1).^2) - sum(x(1:N-1).*x(2:N)); +f = sum((x-1).^2) - sum(x(1:N-1).*x(2:N)); function f = fmaxmindist(y) - % y in [-1,1], y(1:2) is first point on a plane, y(3:4) second etc - % points best - % 5 1.4142 - % 8 1.03527618 - % 10 0.842535997 - % 20 0.5997 - pop = size(y,2); - N = size(y,1)/2; - f = []; - for ipop = 1:pop +% y in [-1,1], y(1:2) is first point on a plane, y(3:4) second etc +% points best +% 5 1.4142 +% 8 1.03527618 +% 10 0.842535997 +% 20 0.5997 +pop = size(y,2); +N = size(y,1)/2; +f = []; +for ipop = 1:pop if any(abs(y(:,ipop)) > 1) - f(ipop) = NaN; + f(ipop) = NaN; else - x = reshape(y(:,ipop), [2, N]); - f(ipop) = inf; - for i = 1:N - f(ipop) = min(f(ipop), min(sqrt(sum((x(:,[1:i-1 i+1:N]) - repmat(x(:,i), 1, N-1)).^2, 1)))); - end + x = reshape(y(:,ipop), [2, N]); + f(ipop) = inf; + for i = 1:N + f(ipop) = min(f(ipop), min(sqrt(sum((x(:,[1:i-1 i+1:N]) - repmat(x(:,i), 1, N-1)).^2, 1)))); + end end - end - f = -f; +end +f = -f; function f=fchangingsphere(x) - N = size(x,1); - global scale_G; global count_G; if isempty(count_G) count_G=-1; end - count_G = count_G+1; - if mod(count_G,10) == 0 +N = size(x,1); +global scale_G; global count_G; if isempty(count_G) count_G=-1; end +count_G = count_G+1; +if mod(count_G,10) == 0 scale_G = 10.^(2*rand(1,N)); - end - %disp(scale(1)); - f = scale_G*x.^2; - +end +%disp(scale(1)); +f = scale_G*x.^2; + function f= flogsphere(x) - f = 1-exp(-sum(x.^2)); - +f = 1-exp(-sum(x.^2)); + function f= fexpsphere(x) - f = exp(sum(x.^2)) - 1; - +f = exp(sum(x.^2)) - 1; + function f=fbaluja(x) - % in [-0.16 0.16] - y = x(1); - for i = 2:length(x) +% in [-0.16 0.16] +y = x(1); +for i = 2:length(x) y(i) = x(i) + y(i-1); - end - f = 1e5 - 1/(1e-5 + sum(abs(y))); +end +f = 1e5 - 1/(1e-5 + sum(abs(y))); function f=fschwefel(x) - f = 0; - for i = 1:size(x,1) +f = 0; +for i = 1:size(x,1) f = f+sum(x(1:i))^2; - end +end function f=fcigar(x, ar) - if nargin < 2 || isempty(ar) +if nargin < 2 || isempty(ar) ar = 1e3; - end - f = x(1,:).^2 + ar^2*sum(x(2:end,:).^2,1); - +end +f = x(1,:).^2 + ar^2*sum(x(2:end,:).^2,1); + function f=fcigtab(x) - f = x(1,:).^2 + 1e8*x(end,:).^2 + 1e4*sum(x(2:(end-1),:).^2, 1); - +f = x(1,:).^2 + 1e8*x(end,:).^2 + 1e4*sum(x(2:(end-1),:).^2, 1); + function f=ftablet(x) - f = 1e6*x(1,:).^2 + sum(x(2:end,:).^2, 1); +f = 1e6*x(1,:).^2 + sum(x(2:end,:).^2, 1); function f=felli(x, lgscal, expon, expon2) - % lgscal: log10(axis ratio) - % expon: x_i^expon, sphere==2 - N = size(x,1); if N < 2 error('dimension must be greater one'); end +% lgscal: log10(axis ratio) +% expon: x_i^expon, sphere==2 +N = size(x,1); if N < 2 error('dimension must be greater one'); end % x = x - repmat(-0.5+(1:N)',1,size(x,2)); % optimum in 1:N - if nargin < 2 || isempty(lgscal), lgscal = 3; end - if nargin < 3 || isempty(expon), expon = 2; end - if nargin < 4 || isempty(expon2), expon2 = 1; end +if nargin < 2 || isempty(lgscal), lgscal = 3; end +if nargin < 3 || isempty(expon), expon = 2; end +if nargin < 4 || isempty(expon2), expon2 = 1; end - f=((10^(lgscal*expon)).^((0:N-1)/(N-1)) * abs(x).^expon).^(1/expon2); +f=((10^(lgscal*expon)).^((0:N-1)/(N-1)) * abs(x).^expon).^(1/expon2); % if rand(1,1) > 0.015 % f = NaN; % end % f = f + randn(size(f)); function f=fellitest(x) - beta = 0.9; - N = size(x,1); - f = (1e6.^((0:(N-1))/(N-1))).^beta * (x.^2).^beta; +beta = 0.9; +N = size(x,1); +f = (1e6.^((0:(N-1))/(N-1))).^beta * (x.^2).^beta; + - function f=fellii(x, scal) - N = size(x,1); if N < 2 error('dimension must be greater one'); end - if nargin < 2 +N = size(x,1); if N < 2 error('dimension must be greater one'); end +if nargin < 2 scal = 1; - end - f= (scal*(1:N)).^2 * (x).^2; +end +f= (scal*(1:N)).^2 * (x).^2; function f=fellirot(x) - N = size(x,1); - global ORTHOGONALCOORSYSTEM_G - if isempty(ORTHOGONALCOORSYSTEM_G) ... - || length(ORTHOGONALCOORSYSTEM_G) < N ... - || isempty(ORTHOGONALCOORSYSTEM_G{N}) +N = size(x,1); +global ORTHOGONALCOORSYSTEM_G +if isempty(ORTHOGONALCOORSYSTEM_G) ... + || length(ORTHOGONALCOORSYSTEM_G) < N ... + || isempty(ORTHOGONALCOORSYSTEM_G{N}) coordinatesystem(N); - end - f = felli(ORTHOGONALCOORSYSTEM_G{N}*x); - +end +f = felli(ORTHOGONALCOORSYSTEM_G{N}*x); + function f=frot(x, fun, varargin) - N = size(x,1); - global ORTHOGONALCOORSYSTEM_G - if isempty(ORTHOGONALCOORSYSTEM_G) ... - || length(ORTHOGONALCOORSYSTEM_G) < N ... - || isempty(ORTHOGONALCOORSYSTEM_G{N}) +N = size(x,1); +global ORTHOGONALCOORSYSTEM_G +if isempty(ORTHOGONALCOORSYSTEM_G) ... + || length(ORTHOGONALCOORSYSTEM_G) < N ... + || isempty(ORTHOGONALCOORSYSTEM_G{N}) coordinatesystem(N); - end - f = feval(fun, ORTHOGONALCOORSYSTEM_G{N}*x, varargin{:}); - +end +f = feval(fun, ORTHOGONALCOORSYSTEM_G{N}*x, varargin{:}); + function coordinatesystem(N) - if nargin < 1 || isempty(N) +if nargin < 1 || isempty(N) arN = 2:30; - else +else arN = N; - end - global ORTHOGONALCOORSYSTEM_G - ORTHOGONALCOORSYSTEM_G{1} = 1; - for N = arN +end +global ORTHOGONALCOORSYSTEM_G +ORTHOGONALCOORSYSTEM_G{1} = 1; +for N = arN ar = randn(N,N); - for i = 1:N - for j = 1:i-1 - ar(:,i) = ar(:,i) - ar(:,i)'*ar(:,j) * ar(:,j); - end - ar(:,i) = ar(:,i) / norm(ar(:,i)); + for i = 1:N + for j = 1:i-1 + ar(:,i) = ar(:,i) - ar(:,i)'*ar(:,j) * ar(:,j); + end + ar(:,i) = ar(:,i) / norm(ar(:,i)); end - ORTHOGONALCOORSYSTEM_G{N} = ar; - end + ORTHOGONALCOORSYSTEM_G{N} = ar; +end function f=fplane(x) - f=x(1); +f=x(1); function f=ftwoaxes(x) - f = sum(x(1:floor(end/2),:).^2, 1) + 1e6*sum(x(floor(1+end/2):end,:).^2, 1); +f = sum(x(1:floor(end/2),:).^2, 1) + 1e6*sum(x(floor(1+end/2):end,:).^2, 1); function f=fparabR(x) - f = -x(1,:) + 100*sum(x(2:end,:).^2,1); +f = -x(1,:) + 100*sum(x(2:end,:).^2,1); function f=fsharpR(x) - f = abs(-x(1, :)).^2 + 100 * sqrt(sum(x(2:end,:).^2, 1)); - +f = abs(-x(1, :)).^2 + 100 * sqrt(sum(x(2:end,:).^2, 1)); + function f=frosen(x) - if size(x,1) < 2, error('dimension must be greater one'); end - N = size(x,1); - popsi = size(x,2); - f = 1e2*sum((x(1:end-1,:).^2 - x(2:end,:)).^2,1) + sum((x(1:end-1,:)-1).^2,1); - % f = f + f^0.9 .* (2*randn(1,popsi) ./ randn(1,popsi).^0 / (2*N)); +if size(x,1) < 2, error('dimension must be greater one'); end +N = size(x,1); +popsi = size(x,2); +f = 1e2*sum((x(1:end-1,:).^2 - x(2:end,:)).^2,1) + sum((x(1:end-1,:)-1).^2,1); +% f = f + f^0.9 .* (2*randn(1,popsi) ./ randn(1,popsi).^0 / (2*N)); function f=frosenlin(x) - if size(x,1) < 2 error('dimension must be greater one'); end +if size(x,1) < 2 error('dimension must be greater one'); end - x_org = x; - x(x>30) = 30; - x(x<-30) = -30; +x_org = x; +x(x>30) = 30; +x(x<-30) = -30; - f = 1e2*sum(-(x(1:end-1,:).^2 - x(2:end,:)),1) + ... - sum((x(1:end-1,:)-1).^2,1); +f = 1e2*sum(-(x(1:end-1,:).^2 - x(2:end,:)),1) + ... + sum((x(1:end-1,:)-1).^2,1); - f = f + sum((x-x_org).^2,1); -% f(any(abs(x)>30,1)) = NaN; +f = f + sum((x-x_org).^2,1); +% f(any(abs(x)>30,1)) = NaN; function f=frosenrot(x) - N = size(x,1); - global ORTHOGONALCOORSYSTEM_G - if isempty(ORTHOGONALCOORSYSTEM_G) ... - || length(ORTHOGONALCOORSYSTEM_G) < N ... - || isempty(ORTHOGONALCOORSYSTEM_G{N}) +N = size(x,1); +global ORTHOGONALCOORSYSTEM_G +if isempty(ORTHOGONALCOORSYSTEM_G) ... + || length(ORTHOGONALCOORSYSTEM_G) < N ... + || isempty(ORTHOGONALCOORSYSTEM_G{N}) coordinatesystem(N); - end - f = frosen(ORTHOGONALCOORSYSTEM_G{N}*x); +end +f = frosen(ORTHOGONALCOORSYSTEM_G{N}*x); function f=frosenmodif(x) - f = 74 + 100*(x(2)-x(1)^2)^2 + (1-x(1))^2 ... - - 400*exp(-sum((x+1).^2)/2/0.05); - +f = 74 + 100*(x(2)-x(1)^2)^2 + (1-x(1))^2 ... + - 400*exp(-sum((x+1).^2)/2/0.05); + function f=fschwefelrosen1(x) - % in [-10 10] - f=sum((x.^2-x(1)).^2 + (x-1).^2); - +% in [-10 10] +f=sum((x.^2-x(1)).^2 + (x-1).^2); + function f=fschwefelrosen2(x) - % in [-10 10] - f=sum((x(2:end).^2-x(1)).^2 + (x(2:end)-1).^2); +% in [-10 10] +f=sum((x(2:end).^2-x(1)).^2 + (x(2:end)-1).^2); function f=fdiffpow(x) - [N, popsi] = size(x); if N < 2 error('dimension must be greater one'); end +[N, popsi] = size(x); if N < 2 error('dimension must be greater one'); end - f = sum(abs(x).^repmat(2+10*(0:N-1)'/(N-1), 1, popsi), 1); - f = sqrt(f); +f = sum(abs(x).^repmat(2+10*(0:N-1)'/(N-1), 1, popsi), 1); +f = sqrt(f); function f=fabsprod(x) - f = sum(abs(x),1) + prod(abs(x),1); +f = sum(abs(x),1) + prod(abs(x),1); function f=ffloor(x) - f = sum(floor(x+0.5).^2,1); +f = sum(floor(x+0.5).^2,1); function f=fmaxx(x) - f = max(abs(x), [], 1); +f = max(abs(x), [], 1); -%%% Multimodal functions +%%% Multimodal functions function f=fbirastrigin(x) -% todo: the volume needs to be a constant - N = size(x,1); - idx = (sum(x, 1) < 0.5*N); % global optimum - f = zeros(1,size(x,2)); - f(idx) = 10*(N-sum(cos(2*pi*x(:,idx)),1)) + sum(x(:,idx).^2,1); - idx = ~idx; - f(idx) = 0.1 + 10*(N-sum(cos(2*pi*(x(:,idx)-2)),1)) + sum((x(:,idx)-2).^2,1); +% todo: the volume needs to be a constant +N = size(x,1); +idx = (sum(x, 1) < 0.5*N); % global optimum +f = zeros(1,size(x,2)); +f(idx) = 10*(N-sum(cos(2*pi*x(:,idx)),1)) + sum(x(:,idx).^2,1); +idx = ~idx; +f(idx) = 0.1 + 10*(N-sum(cos(2*pi*(x(:,idx)-2)),1)) + sum((x(:,idx)-2).^2,1); function f=fackley(x) - % -32.768..32.768 - % Adding a penalty outside the interval is recommended, - % because for large step sizes, fackley imposes like frand - % - N = size(x,1); - f = 20-20*exp(-0.2*sqrt(sum(x.^2)/N)); - f = f + (exp(1) - exp(sum(cos(2*pi*x))/N)); - % add penalty outside the search interval - f = f + sum((x(x>32.768)-32.768).^2) + sum((x(x<-32.768)+32.768).^2); - +% -32.768..32.768 +% Adding a penalty outside the interval is recommended, +% because for large step sizes, fackley imposes like frand +% +N = size(x,1); +f = 20-20*exp(-0.2*sqrt(sum(x.^2)/N)); +f = f + (exp(1) - exp(sum(cos(2*pi*x))/N)); +% add penalty outside the search interval +f = f + sum((x(x>32.768)-32.768).^2) + sum((x(x<-32.768)+32.768).^2); + function f = fbohachevsky(x) - % -15..15 - f = sum(x(1:end-1).^2 + 2 * x(2:end).^2 - 0.3 * cos(3*pi*x(1:end-1)) ... - - 0.4 * cos(4*pi*x(2:end)) + 0.7); - +% -15..15 +f = sum(x(1:end-1).^2 + 2 * x(2:end).^2 - 0.3 * cos(3*pi*x(1:end-1)) ... + - 0.4 * cos(4*pi*x(2:end)) + 0.7); + function f=fconcentric(x) - % in +-600 - s = sum(x.^2); - f = s^0.25 * (sin(50*s^0.1)^2 + 1); +% in +-600 +s = sum(x.^2); +f = s^0.25 * (sin(50*s^0.1)^2 + 1); function f=fgriewank(x) - % in [-600 600] - [N, P] = size(x); - f = 1 - prod(cos(x'./sqrt(1:N))) + sum(x.^2)/4e3; - scale = repmat(sqrt(1:N)', 1, P); - f = 1 - prod(cos(x./scale), 1) + sum(x.^2, 1)/4e3; - % f = f + 1e4*sum(x(abs(x)>5).^2); - % if sum(x(abs(x)>5).^2) > 0 - % f = 1e4 * sum(x(abs(x)>5).^2) + 1e8 * sum(x(x>5)).^2; - % end +% in [-600 600] +[N, P] = size(x); +f = 1 - prod(cos(x'./sqrt(1:N))) + sum(x.^2)/4e3; +scale = repmat(sqrt(1:N)', 1, P); +f = 1 - prod(cos(x./scale), 1) + sum(x.^2, 1)/4e3; +% f = f + 1e4*sum(x(abs(x)>5).^2); +% if sum(x(abs(x)>5).^2) > 0 +% f = 1e4 * sum(x(abs(x)>5).^2) + 1e8 * sum(x(x>5)).^2; +% end function f=fgriewrosen(x) % F13 or F8F2 - [N, P] = size(x); - scale = repmat(sqrt(1:N)', 1, P); - y = [x(2:end,:); x(1,:)]; - x = 100 * (x.^2 - y) + (x - 1).^2; % Rosenbrock part - f = 1 - prod(cos(x./scale), 1) + sum(x.^2, 1)/4e3; - f = sum(1 - cos(x) + x.^2/4e3, 1); +[N, P] = size(x); +scale = repmat(sqrt(1:N)', 1, P); +y = [x(2:end,:); x(1,:)]; +x = 100 * (x.^2 - y) + (x - 1).^2; % Rosenbrock part +f = 1 - prod(cos(x./scale), 1) + sum(x.^2, 1)/4e3; +f = sum(1 - cos(x) + x.^2/4e3, 1); function f=fspallpseudorastrigin(x, scal, skewfac, skewstart, amplitude) % by default multi-modal about between -30 and 30 - if nargin < 5 || isempty(amplitude) +if nargin < 5 || isempty(amplitude) amplitude = 40; - end - if nargin < 4 || isempty(skewstart) +end +if nargin < 4 || isempty(skewstart) skewstart = 0; - end - if nargin < 3 || isempty(skewfac) +end +if nargin < 3 || isempty(skewfac) skewfac = 1; - end - if nargin < 2 || isempty(scal) +end +if nargin < 2 || isempty(scal) scal = 1; - end - N = size(x,1); - scale = 1; - if N > 1 - scale=scal.^((0:N-1)'/(N-1)); - end - % simple version: - % f = amplitude*(N - sum(cos(2*pi*(scale.*x)))) + sum((scale.*x).^2); - - % skew version: - y = repmat(scale, 1, size(x,2)) .* x; - idx = find(x > skewstart); - if ~isempty(idx) +end +N = size(x,1); +scale = 1; +if N > 1 + scale=scal.^((0:N-1)'/(N-1)); +end +% simple version: +% f = amplitude*(N - sum(cos(2*pi*(scale.*x)))) + sum((scale.*x).^2); + +% skew version: +y = repmat(scale, 1, size(x,2)) .* x; +idx = find(x > skewstart); +if ~isempty(idx) y(idx) = skewfac*y(idx); - end - f = amplitude * (0*N-prod(cos((2*pi)^0*y),1)) + 0.05 * sum(y.^2,1) ... - + randn(1,1); +end +f = amplitude * (0*N-prod(cos((2*pi)^0*y),1)) + 0.05 * sum(y.^2,1) ... + + randn(1,1); function f=frastrigin(x, scal, skewfac, skewstart, amplitude) % by default multi-modal about between -30 and 30 - if nargin < 5 || isempty(amplitude) +if nargin < 5 || isempty(amplitude) amplitude = 10; - end - if nargin < 4 || isempty(skewstart) +end +if nargin < 4 || isempty(skewstart) skewstart = 0; - end - if nargin < 3 || isempty(skewfac) +end +if nargin < 3 || isempty(skewfac) skewfac = 1; - end - if nargin < 2 || isempty(scal) +end +if nargin < 2 || isempty(scal) scal = 1; - end - N = size(x,1); - scale = 1; - if N > 1 - scale=scal.^((0:N-1)'/(N-1)); - end - % simple version: - % f = amplitude*(N - sum(cos(2*pi*(scale.*x)))) + sum((scale.*x).^2); - - % skew version: - y = repmat(scale, 1, size(x,2)) .* x; - idx = find(x > skewstart); - % idx = intersect(idx, 2:2:10); - if ~isempty(idx) +end +N = size(x,1); +scale = 1; +if N > 1 + scale=scal.^((0:N-1)'/(N-1)); +end +% simple version: +% f = amplitude*(N - sum(cos(2*pi*(scale.*x)))) + sum((scale.*x).^2); + +% skew version: +y = repmat(scale, 1, size(x,2)) .* x; +idx = find(x > skewstart); +% idx = intersect(idx, 2:2:10); +if ~isempty(idx) y(idx) = skewfac*y(idx); - end - f = amplitude * (N-sum(cos(2*pi*y),1)) + sum(y.^2,1); - +end +f = amplitude * (N-sum(cos(2*pi*y),1)) + sum(y.^2,1); + function f=frastriginmax(x) - N = size(x,1); - f = (N/20)*807.06580387678 - (10 * (N-sum(cos(2*pi*x),1)) + sum(x.^2,1)); - f(any(abs(x) > 5.12)) = 1e2*N; +N = size(x,1); +f = (N/20)*807.06580387678 - (10 * (N-sum(cos(2*pi*x),1)) + sum(x.^2,1)); +f(any(abs(x) > 5.12)) = 1e2*N; function f = fschaffer(x) - % -100..100 - N = size(x,1); - s = x(1:N-1,:).^2 + x(2:N,:).^2; - f = sum(s.^0.25 .* (sin(50*s.^0.1).^2+1), 1); +% -100..100 +N = size(x,1); +s = x(1:N-1,:).^2 + x(2:N,:).^2; +f = sum(s.^0.25 .* (sin(50*s.^0.1).^2+1), 1); function f=fschwefelmult(x) - % -500..500 - % - N = size(x,1); - f = - sum(x.*sin(sqrt(abs(x))), 1); - f = 418.9829*N - 1.27275661e-5*N - sum(x.*sin(sqrt(abs(x))), 1); - % penalty term - f = f + 1e4*sum((abs(x)>500) .* (abs(x)-500).^2, 1); - +% -500..500 +% +N = size(x,1); +f = - sum(x.*sin(sqrt(abs(x))), 1); +f = 418.9829*N - 1.27275661e-5*N - sum(x.*sin(sqrt(abs(x))), 1); +% penalty term +f = f + 1e4*sum((abs(x)>500) .* (abs(x)-500).^2, 1); + function f=ftwomax(x) - % Boundaries at +/-5 - N = size(x,1); - f = -abs(sum(x)) + 5*N; +% Boundaries at +/-5 +N = size(x,1); +f = -abs(sum(x)) + 5*N; function f=ftwomaxtwo(x) - % Boundaries at +/-10 - N = size(x,1); - f = abs(sum(x)); - if f > 30 +% Boundaries at +/-10 +N = size(x,1); +f = abs(sum(x)); +if f > 30 f = f - 30; - end - f = -f; - +end +f = -f; + function f=frand(x) - f=1./(1-rand(1, size(x,2))) - 1; +f=1./(1-rand(1, size(x,2))) - 1; % CHANGES % 12/02/19: "future" setting of ccum, correcting for large mueff, is default now % 11/11/15: bug-fix: max value for ccovmu_sep setting corrected -% 10/11/11: (3.52.beta) boundary handling: replace max with min in change -% rate formula. Active CMA: check of pos.def. improved. -% Plotting: value of lambda appears in the title. +% 10/11/11: (3.52.beta) boundary handling: replace max with min in change +% rate formula. Active CMA: check of pos.def. improved. +% Plotting: value of lambda appears in the title. % 10/04/03: (3.51.beta) active CMA cleaned up. Equal fitness detection -% looks into history now. +% looks into history now. % 10/03/08: (3.50.beta) "active CMA" revised and bug-fix of ambiguous -% option Noise.alpha -> Noise.alphasigma. -% 09/10/12: (3.40.beta) a slightly modified version of "active CMA", +% option Noise.alpha -> Noise.alphasigma. +% 09/10/12: (3.40.beta) a slightly modified version of "active CMA", % that is a negative covariance matrix update, use option -% CMA.active. In 10;30;90-D the gain on ftablet is a factor -% of 1.6;2.5;4.4 (the scaling improves by sqrt(N)). On -% Rosenbrock the gain is about 25%. On sharp ridge the -% behavior is improved. Cigar is unchanged. -% 09/08/10: local plotcmaesdat remains in backround -% 09/08/10: bug-fix in time management for data writing, logtime was not -% considered properly (usually not at all). -% 09/07/05: V3.24: stagnation termination added +% CMA.active. In 10;30;90-D the gain on ftablet is a factor +% of 1.6;2.5;4.4 (the scaling improves by sqrt(N)). On +% Rosenbrock the gain is about 25%. On sharp ridge the +% behavior is improved. Cigar is unchanged. +% 09/08/10: local plotcmaesdat remains in backround +% 09/08/10: bug-fix in time management for data writing, logtime was not +% considered properly (usually not at all). +% 09/07/05: V3.24: stagnation termination added % 08/09/27: V3.23: momentum alignment is out-commented and de-preciated % 08/09/25: V3.22: re-alignment of sigma and C was buggy % 08/07/15: V3.20, CMA-parameters are options now. ccov and mucov were replaced % by ccov1 \approx ccov/mucov and ccovmu \approx (1-1/mucov)*ccov -% 08/06/30: file name xrecent was change to xrecentbest (compatible with other +% 08/06/30: file name xrecent was change to xrecentbest (compatible with other % versions) -% 08/06/29: time stamp added to output files -% 08/06/28: bug fixed with resume option, commentary did not work +% 08/06/29: time stamp added to output files +% 08/06/28: bug fixed with resume option, commentary did not work % 08/06/28: V3.10, uncertainty (noise) handling added (re-implemented), according % to reference "A Method for Handling Uncertainty..." from below. -% 08/06/28: bug fix: file xrecent was empty -% 08/06/01: diagonalonly clean up. >1 means some iterations. +% 08/06/28: bug fix: file xrecent was empty +% 08/06/01: diagonalonly clean up. >1 means some iterations. % 08/05/05: output is written to file preventing an increasing data -% array and ease long runs. -% 08/03/27: DiagonalOnly<0 learns for -DiagonalOnly iterations only the -% diagonal with a larger learning rate. -% 08/03 (2.60): option DiagonalOnly>=1 invokes a time- and space-linear -% variant with only diagonal elements of the covariance matrix -% updating. This can be useful for large dimensions, say > 100. +% array and ease long runs. +% 08/03/27: DiagonalOnly<0 learns for -DiagonalOnly iterations only the +% diagonal with a larger learning rate. +% 08/03 (2.60): option DiagonalOnly>=1 invokes a time- and space-linear +% variant with only diagonal elements of the covariance matrix +% updating. This can be useful for large dimensions, say > 100. % 08/02: diag(weights) * ... replaced with repmat(weights,1,N) .* ... -% in C update, implies O(mu*N^2) instead of O(mu^2*N + mu*N^2). +% in C update, implies O(mu*N^2) instead of O(mu^2*N + mu*N^2). % 07/09: tolhistfun as termination criterion added, "<" changed to -% "<=" also for TolFun to allow for stopping on zero difference. -% Name tolfunhist clashes with option tolfun. -% 07/07: hsig threshold made slighly smaller for large dimension, -% useful for lambda < lambda_default. +% "<=" also for TolFun to allow for stopping on zero difference. +% Name tolfunhist clashes with option tolfun. +% 07/07: hsig threshold made slighly smaller for large dimension, +% useful for lambda < lambda_default. % 07/06: boundary handling: scaling in the boundary handling % is omitted now, see bnd.flgscale. This seems not to % have a big impact. Using the scaling is worse on rotated -% functions, but better on separable ones. +% functions, but better on separable ones. % 07/05: boundary handling: weight i is not incremented anymore % if xmean(i) moves towards the feasible space. Increment -% factor changed to 1.2 instead of 1.1. +% factor changed to 1.2 instead of 1.1. % 07/05: boundary handling code simplified not changing the algorithm % 07/04: bug removed for saving in octave % 06/11/10: more testing of outcome of eig, fixed max(D) to max(diag(D)) -% 06/10/21: conclusive final bestever assignment in the end +% 06/10/21: conclusive final bestever assignment in the end % 06/10/21: restart and incpopsize option implemented for restarts -% with increasing population size, version 2.50. +% with increasing population size, version 2.50. % 06/09/16: output argument bestever inserted again for convenience and % backward compatibility -% 06/08: output argument out and struct out reorganized. +% 06/08: output argument out and struct out reorganized. % 06/01: Possible parallel evaluation included as option EvalParallel % 05/11: Compatibility to octave implemented, package octave-forge -% is needed. +% is needed. % 05/09: Raise of figure and waiting for first plots improved -% 05/01: Function coordinatesystem cleaned up. +% 05/01: Function coordinatesystem cleaned up. % 05/01: Function prctile, which requires the statistics toolbox, -% replaced by myprctile. -% 05/01: Option warnonequalfunctionvalues included. -% 04/12: Decrease of sigma removed. Problems on fsectorsphere can -% be addressed better by adding search space boundaries. -% 04/12: Boundary handling simpyfied. -% 04/12: Bug when stopping criteria tolx or tolupx are vectors. -% 04/11: Three input parameters are obligatory now. -% 04/11: Bug in boundary handling removed: Boundary weights can decrease now. -% 04/11: Normalization for boundary weights scale changed. -% 04/11: VerboseModulo option bug removed. Documentation improved. +% replaced by myprctile. +% 05/01: Option warnonequalfunctionvalues included. +% 04/12: Decrease of sigma removed. Problems on fsectorsphere can +% be addressed better by adding search space boundaries. +% 04/12: Boundary handling simpyfied. +% 04/12: Bug when stopping criteria tolx or tolupx are vectors. +% 04/11: Three input parameters are obligatory now. +% 04/11: Bug in boundary handling removed: Boundary weights can decrease now. +% 04/11: Normalization for boundary weights scale changed. +% 04/11: VerboseModulo option bug removed. Documentation improved. % 04/11: Condition for increasing boundary weights changed. % 04/10: Decrease of sigma when fitness is getting consistenly % worse. Addresses the problems appearing on fsectorsphere for % large population size. -% 04/10: VerboseModulo option included. +% 04/10: VerboseModulo option included. % 04/10: Bug for condition for increasing boundary weights removed. % 04/07: tolx depends on initial sigma to achieve scale invariance -% for this stopping criterion. +% for this stopping criterion. % 04/06: Objective function value NaN is not counted as function -% evaluation and invokes resampling of the search point. +% evaluation and invokes resampling of the search point. % 04/06: Error handling for eigenvalue beeing zero (never happens % with default parameter setting) -% 04/05: damps further tuned for large mueff -% o Details for stall of pc-adaptation added (variable hsig -% introduced). +% 04/05: damps further tuned for large mueff +% o Details for stall of pc-adaptation added (variable hsig +% introduced). % 04/05: Bug in boundary handling removed: A large initial SIGMA was % corrected not until *after* the first iteration, which could % lead to a complete failure. -% 04/05: Call of function range (works with stats toolbox only) -% changed to myrange. +% 04/05: Call of function range (works with stats toolbox only) +% changed to myrange. % 04/04: Parameter cs depends on mueff now and damps \propto sqrt(mueff) -% instead of \propto mueff. +% instead of \propto mueff. % o Initial stall to adapt C (flginiphase) is removed and % adaptation of pc is stalled for large norm(ps) instead. -% o Returned default options include documentation. +% o Returned default options include documentation. % o Resume part reorganized. -% 04/03: Stopflag becomes cell-array. +% 04/03: Stopflag becomes cell-array. % --------------------------------------------------------------- % CMA-ES: Evolution Strategy with Covariance Matrix Adaptation for % nonlinear function minimization. To be used under the terms of the % GNU General Public License (http://www.gnu.org/copyleft/gpl.html). -% Author (copyright): Nikolaus Hansen, 2001-2008. +% Author (copyright): Nikolaus Hansen, 2001-2008. % e-mail: nikolaus.hansen AT inria.fr % URL:http://www.bionik.tu-berlin.de/user/niko -% References: See below. +% References: See below. % --------------------------------------------------------------- % % GENERAL PURPOSE: The CMA-ES (Evolution Strategy with Covariance @@ -2999,7 +2999,7 @@ function f=frand(x) % expected to take at least 30*N^2 and up to 300*N^2 function % evaluations. % -% SOME MORE COMMENTS: +% SOME MORE COMMENTS: % The adaptation of the covariance matrix (e.g. by the CMA) is % equivalent to a general linear transformation of the problem % coding. Nevertheless every problem specific knowlegde about the best @@ -3022,13 +3022,13 @@ function f=frand(x) % --------------------------------------------------------------- %%% REFERENCES % -% The equation numbers refer to +% The equation numbers refer to % Hansen, N. and S. Kern (2004). Evaluating the CMA Evolution % Strategy on Multimodal Test Functions. Eighth International % Conference on Parallel Problem Solving from Nature PPSN VIII, -% Proceedings, pp. 282-291, Berlin: Springer. +% Proceedings, pp. 282-291, Berlin: Springer. % (http://www.bionik.tu-berlin.de/user/niko/ppsn2004hansenkern.pdf) -% +% % Further references: % Hansen, N. and A. Ostermeier (2001). Completely Derandomized % Self-Adaptation in Evolution Strategies. Evolutionary Computation, @@ -3050,6 +3050,3 @@ function f=frand(x) % Optimization with an Application to Feedback Control of % Combustion. To appear in IEEE Transactions on Evolutionary % Computation. - - - diff --git a/matlab/optimization/csminit1.m b/matlab/optimization/csminit1.m index 4184af2df6..0ad54a3a74 100644 --- a/matlab/optimization/csminit1.m +++ b/matlab/optimization/csminit1.m @@ -1,7 +1,7 @@ function [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,penalty,f0,g0,badg,H0,Verbose,varargin) % [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,penalty,f0,g0,badg,H0,Verbose,varargin) -% -% Inputs: +% +% Inputs: % fcn: [string] string naming the objective function to be minimized % x0: [npar by 1] initial value of the parameter vector % penalty: [scalar] variable penalty in case of failure of objective function @@ -20,7 +20,7 @@ function [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,penalty,f0,g0,badg,H0,Verb % retcode [scalar] 0: normal step % 1: zero gradient. % 5: largest step still improves too fast. -% 2,4: back and forth adjustment of stepsize didn't finish. +% 2,4: back and forth adjustment of stepsize didn't finish. % 3: smallest stepsize still improves too slow % 6: no improvement found %--------------------- @@ -33,10 +33,10 @@ function [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,penalty,f0,g0,badg,H0,Verb % % Fixed 7/19/93 to flip eigenvalues of H to get better performance when % it's not psd. -% +% % Original file downloaded from: % http://sims.princeton.edu/yftp/optimize/mfiles/csminit.m -% +% % Copyright (C) 1993-2007 Christopher Sims % Copyright (C) 2008-2016 Dynare Team % @@ -122,7 +122,7 @@ else disp_verbose(sprintf('Correct for low angle: %g',a),Verbose) end end - disp_verbose(sprintf('Predicted improvement: %18.9f',-dfhat/2),Verbose) + disp_verbose(sprintf('Predicted improvement: %18.9f',-dfhat/2),Verbose) % % Have OK dx, now adjust length of step (lambda) until min and % max improvement rate criteria are met. @@ -145,7 +145,7 @@ else %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_verbose(sprintf('lambda = %10.5g; f = %20.7f',lambda,f ),Verbose) + disp_verbose(sprintf('lambda = %10.5g; f = %20.7f',lambda,f ),Verbose) %debug %disp(sprintf('Improvement too great? f0-f: %g, criterion: %g',f0-f,-(1-THETA)*dfhat*lambda)) if f<fhat @@ -183,7 +183,7 @@ else if Verbose lambda = -lambda*factor^6 else - lambda = -lambda*factor^6; + lambda = -lambda*factor^6; end else if lambda < 0 diff --git a/matlab/optimization/csminwel1.m b/matlab/optimization/csminwel1.m index 7b067a0a81..33270c1178 100644 --- a/matlab/optimization/csminwel1.m +++ b/matlab/optimization/csminwel1.m @@ -14,13 +14,13 @@ function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel1(fcn,x0,H0,grad,crit,nit,m % epsilon: [scalar] scalar double, numerical differentiation increment % varargin: Optional additional inputs 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 % writes 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.) -% +% % Outputs: % fh: [scalar] function value at minimum % xh: [npar by 1] parameter vector at minimum @@ -30,17 +30,17 @@ function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel1(fcn,x0,H0,grad,crit,nit,m % fcount [scalar] function iteration count upon termination % retcodeh [scalar] return code: % 0: normal step -% 1: zero gradient +% 1: zero gradient % 2: back and forth on step length never finished % 3: smallest step still improving too slow % 4: back and forth on step length never finished % 5: largest step still improving too fast % 6: smallest step still improving too slow, reversed gradient % 7: warning: possible inaccuracy in H matrix -% +% % Original file downloaded from: % http://sims.princeton.edu/yftp/optimize/mfiles/csminwel.m -% +% % Copyright (C) 1993-2007 Christopher Sims % Copyright (C) 2006-2015 Dynare Team % @@ -59,7 +59,7 @@ function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel1(fcn,x0,H0,grad,crit,nit,m % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. -% initialize variable penalty +% initialize variable penalty penalty = 1e8; fh = []; xh = []; @@ -193,7 +193,7 @@ while ~done [f3, x3, fc, retcode3] = csminit1(fcn,x,penalty,f,gcliff,0,eye(nx),Verbose,varargin{:}); fcount = fcount+fc; % put by Jinill if retcode3==2 || retcode3==4 - wall3=1; + wall3=1; badg3=1; else if NumGrad @@ -302,7 +302,7 @@ while ~done error('Unaccounted Case, please contact the developers',Verbose) end end - + f=fh; x=xh; g=gh; @@ -312,18 +312,18 @@ end end function [g, badg]=get_num_grad(method,fcn,penalty,f0,x0,epsilon,varargin) - switch method - case 2 - [g,badg] = numgrad2(fcn, f0, x0, penalty, epsilon, varargin{:}); - case 3 - [g,badg] = numgrad3(fcn, f0, x0, penalty, epsilon, varargin{:}); - case 5 - [g,badg] = numgrad5(fcn, f0, x0, penalty, epsilon, varargin{:}); - case 13 - [g,badg] = numgrad3_(fcn, f0, x0, penalty, epsilon, varargin{:}); - case 15 - [g,badg] = numgrad5_(fcn, f0, x0, penalty, epsilon, varargin{:}); - otherwise - error('csminwel1: Unknown method for gradient evaluation!') - end +switch method + case 2 + [g,badg] = numgrad2(fcn, f0, x0, penalty, epsilon, varargin{:}); + case 3 + [g,badg] = numgrad3(fcn, f0, x0, penalty, epsilon, varargin{:}); + case 5 + [g,badg] = numgrad5(fcn, f0, x0, penalty, epsilon, varargin{:}); + case 13 + [g,badg] = numgrad3_(fcn, f0, x0, penalty, epsilon, varargin{:}); + case 15 + [g,badg] = numgrad5_(fcn, f0, x0, penalty, epsilon, varargin{:}); + otherwise + error('csminwel1: Unknown method for gradient evaluation!') +end end \ No newline at end of file diff --git a/matlab/optimization/dynare_minimize_objective.m b/matlab/optimization/dynare_minimize_objective.m index 54b84b84c8..025d411899 100644 --- a/matlab/optimization/dynare_minimize_objective.m +++ b/matlab/optimization/dynare_minimize_objective.m @@ -8,12 +8,12 @@ function [opt_par_values,fval,exitflag,hessian_mat,options_,Scale,new_rat_hess_i % minimizer_algorithm [scalar double, or string] code of the optimizer algorithm, or string for the name of a user defined optimization routine (not shipped with dynare). % options_ [matlab structure] Dynare options structure % bounds [n_params by 2] vector of doubles 2 row vectors containing lower and upper bound for parameters -% parameter_names [n_params by 1] cell array strings containing the parameters names +% parameter_names [n_params by 1] cell array strings containing the parameters names % prior_information [matlab structure] Dynare prior information structure (bayestopt_) provided for algorithm 6 % Initial_Hessian [n_params by n_params] matrix initial hessian matrix provided for algorithm 6 % new_rat_hess_info [matlab structure] step size info used by algorith 5 % varargin [cell array] Input arguments for objective function -% +% % OUTPUTS % opt_par_values [n_params by 1] vector of doubles optimal parameter values minimizing the objective % fval [scalar double] value of the objective function at the minimum @@ -21,11 +21,11 @@ function [opt_par_values,fval,exitflag,hessian_mat,options_,Scale,new_rat_hess_i % hessian_mat [n_params by n_params] matrix hessian matrix at the mode returned by optimizer % options_ [matlab structure] Dynare options structure (to return options set by algorithms 5) % Scale [scalar double] scaling parameter returned by algorith 6 -% +% % SPECIAL REQUIREMENTS % none. -% -% +% +% % Copyright (C) 2014-2017 Dynare Team % % This file is part of Dynare. @@ -188,16 +188,16 @@ switch minimizer_algorithm case 'verbosity' Verbose = options_list{i,2}; case 'SaveFiles' - Save_files = options_list{i,2}; + Save_files = options_list{i,2}; otherwise warning(['csminwel: Unknown option (' options_list{i,1} ')!']) end end end if options_.silent_optimizer - Save_files = 0; + Save_files = 0; Verbose = 0; - end + end % Set flag for analytical gradient. if options_.analytic_derivation analytic_grad=1; @@ -232,23 +232,23 @@ switch minimizer_algorithm if options_.analytic_derivation && flag~=0 error('newrat: analytic_derivation is incompatible with numerical Hessian. Using analytic Hessian') else - newratflag=flag; + newratflag=flag; end case 'TolFun' crit = options_list{i,2}; case 'verbosity' Verbose = options_list{i,2}; case 'SaveFiles' - Save_files = options_list{i,2}; + Save_files = options_list{i,2}; otherwise warning(['newrat: Unknown option (' options_list{i,1} ')!']) end end end if options_.silent_optimizer - Save_files = 0; + Save_files = 0; Verbose = 0; - end + end hess_info.gstep=options_.gstep; hess_info.htol = 1.e-4; hess_info.h1=options_.gradient_epsilon*ones(n_params,1); @@ -307,13 +307,13 @@ switch minimizer_algorithm end if options_.silent_optimizer simplexOptions.verbose = options_list{i,2}; - end + end [opt_par_values,fval,exitflag] = simplex_optimization_routine(objective_function,start_par_value,simplexOptions,parameter_names,varargin{:}); case 9 % Set defaults H0 = (bounds(:,2)-bounds(:,1))*0.2; H0(~isfinite(H0)) = 0.01; - while max(H0)/min(H0)>1e6 %make sure initial search volume (SIGMA) is not badly conditioned + while max(H0)/min(H0)>1e6 %make sure initial search volume (SIGMA) is not badly conditioned H0(H0==max(H0))=0.9*H0(H0==max(H0)); end cmaesOptions = options_.cmaes; @@ -339,14 +339,14 @@ switch minimizer_algorithm end case 'SaveFiles' if options_list{i,2}==0 - cmaesOptions.SaveVariables='off'; - cmaesOptions.LogModulo = '0'; % [0:Inf] if >1 record data less frequently after gen=100'; - cmaesOptions.LogTime = '0'; % [0:100] max. percentage of time for recording data'; + cmaesOptions.SaveVariables='off'; + cmaesOptions.LogModulo = '0'; % [0:Inf] if >1 record data less frequently after gen=100'; + cmaesOptions.LogTime = '0'; % [0:100] max. percentage of time for recording data'; end case 'CMAESResume' - if options_list{i,2}==1 + if options_list{i,2}==1 cmaesOptions.Resume = 'yes'; - end + end otherwise warning(['cmaes: Unknown option (' options_list{i,1} ')!']) end @@ -358,7 +358,7 @@ switch minimizer_algorithm cmaesOptions.SaveVariables='off'; cmaesOptions.LogModulo = '0'; % [0:Inf] if >1 record data less frequently after gen=100'; cmaesOptions.LogTime = '0'; % [0:100] max. percentage of time for recording data'; - end + end warning('off','CMAES:NonfinitenessRange'); warning('off','CMAES:InitialSigma'); [x, fval, COUNTEVAL, STOPFLAG, OUT, BESTEVER] = cmaes(func2str(objective_function),start_par_value,H0,cmaesOptions,varargin{:}); @@ -386,11 +386,11 @@ switch minimizer_algorithm case 'MaxFunEvals' simpsaOptions.MAX_FUN_EVALS = options_list{i,2}; case 'verbosity' - if options_list{i,2} == 0 + if options_list{i,2} == 0 simpsaOptions.DISPLAY = 'none'; - else + else simpsaOptions.DISPLAY = 'iter'; - end + end otherwise warning(['simpsa: Unknown option (' options_list{i,1} ')!']) end @@ -414,10 +414,10 @@ switch minimizer_algorithm if ~isempty(options_.optim_opt) options_list = read_key_value_string(options_.optim_opt); SupportedListOfOptions = {'CreationFcn', 'Display', 'DisplayInterval', 'FunctionTolerance', ... - 'FunValCheck', 'HybridFcn', 'InertiaRange', 'InitialSwarmMatrix', 'InitialSwarmSpan', ... - 'MaxIterations', 'MaxStallIterations', 'MaxStallTime', 'MaxTime', ... - 'MinNeighborsFraction', 'ObjectiveLimit', 'OutputFcn', 'PlotFcn', 'SelfAdjustmentWeight', ... - 'SocialAdjustmentWeight', 'SwarmSize', 'UseParallel', 'UseVectorized'}; + 'FunValCheck', 'HybridFcn', 'InertiaRange', 'InitialSwarmMatrix', 'InitialSwarmSpan', ... + 'MaxIterations', 'MaxStallIterations', 'MaxStallTime', 'MaxTime', ... + 'MinNeighborsFraction', 'ObjectiveLimit', 'OutputFcn', 'PlotFcn', 'SelfAdjustmentWeight', ... + 'SocialAdjustmentWeight', 'SwarmSize', 'UseParallel', 'UseVectorized'}; for i=1:rows(options_list) if ismember(options_list{i,1}, SupportedListOfOptions) particleswarmOptions = optimoptions(particleswarmOptions, options_list{i,1}, options_list{i,2}); @@ -514,8 +514,8 @@ end end function [LB, UB]=set_bounds_to_finite_values(bounds, huge_number) - LB=bounds(:,1); - LB(isinf(LB))=-huge_number; - UB=bounds(:,2); - UB(isinf(UB))=huge_number; +LB=bounds(:,1); +LB(isinf(LB))=-huge_number; +UB=bounds(:,2); +UB(isinf(UB))=huge_number; end diff --git a/matlab/optimization/gmhmaxlik.m b/matlab/optimization/gmhmaxlik.m index b26088a163..4f1db628d0 100644 --- a/matlab/optimization/gmhmaxlik.m +++ b/matlab/optimization/gmhmaxlik.m @@ -16,7 +16,7 @@ function [PostMode, HessianMatrix, Scale, ModeValue] = gmhmaxlik(fun, xinit, Hin % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - + % Set default options if ~isempty(Hinit) diff --git a/matlab/optimization/gmhmaxlik_core.m b/matlab/optimization/gmhmaxlik_core.m index 2d7a3cb814..eae0f931a4 100644 --- a/matlab/optimization/gmhmaxlik_core.m +++ b/matlab/optimization/gmhmaxlik_core.m @@ -1,8 +1,8 @@ -function [PostMod,PostVar,Scale,PostMean] = gmhmaxlik_core(ObjFun,xparam1,mh_bounds,options,iScale,info,MeanPar,VarCov,varargin) +function [PostMod,PostVar,Scale,PostMean] = gmhmaxlik_core(ObjFun,xparam1,mh_bounds,options,iScale,info,MeanPar,VarCov,varargin) -% (Dirty) Global minimization routine of (minus) a likelihood (or posterior density) function. -% -% INPUTS +% (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. @@ -10,29 +10,29 @@ function [PostMod,PostVar,Scale,PostMean] = gmhmaxlik_core(ObjFun,xparam1,mh_bou % 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 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 +% +% 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. +% 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 +% 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) -% \] +% \[ +% \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) +% \[ +% \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 @@ -43,7 +43,7 @@ function [PostMod,PostVar,Scale,PostMean] = gmhmaxlik_core(ObjFun,xparam1,mh_bou % \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. +% \right. % \] % % where $t$ is the iteration, $\mu_t$ the estimate of the posterior mean @@ -51,7 +51,7 @@ function [PostMod,PostVar,Scale,PostMean] = gmhmaxlik_core(ObjFun,xparam1,mh_bou % 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"). +% (specified by the user supplied function "fun"). % % SPECIAL REQUIREMENTS % None. @@ -94,7 +94,7 @@ isux = 0; jsux = 0; test = 0; ix2 = ModePar;% initial condition! ilogpo2 = - feval(ObjFun,ix2,varargin{:});% initial posterior density mlogpo2 = ilogpo2; -try +try dd = transpose(chol(CovJump)); catch dd = eye(length(CovJump)); @@ -108,7 +108,7 @@ while j<=MaxNumberOfTuningSimulations end % I move if the proposal is enough likely... if logpo2 > -inf && log(rand) < logpo2 - ilogpo2 - ix2 = proposal; + ix2 = proposal; if logpo2 > mlogpo2 ModePar = proposal; mlogpo2 = logpo2; @@ -165,7 +165,7 @@ while j<= NumberOfIterations ilogpo2 = logpo2; isux = isux + 1; jsux = jsux + 1; - end% ... otherwise I don't move. + end% ... otherwise I don't move. prtfrc = j/NumberOfIterations; if mod(j, 10)==0 dyn_waitbar(prtfrc,hh,sprintf('Acceptance ratio: %f',isux/j)); @@ -184,7 +184,7 @@ PostMean = MeanPar; %% this is the last call to the routine, and I climb the hill (without %% updating the covariance matrix)... if strcmpi(info,'LastCall') - + hh = dyn_waitbar(0,'Tuning of the scale parameter...'); set(hh,'Name','Tuning of the scale parameter.'), j = 1; jj = 1; @@ -214,8 +214,8 @@ if strcmpi(info,'LastCall') if mod(j, 10)==0 dyn_waitbar(prtfrc,hh,sprintf('Acceptance ratio [during last 1000]: %f [%f]',isux/j,jsux/jj)); end - if j/1000 == round(j/1000) - test1 = jsux/jj; + if j/1000 == round(j/1000) + test1 = jsux/jj; cfactor = test1/AcceptanceTarget; iScale = iScale*cfactor; jsux = 0; jj = 0; diff --git a/matlab/optimization/mr_gstep.m b/matlab/optimization/mr_gstep.m index 5850752714..0836a7a87e 100644 --- a/matlab/optimization/mr_gstep.m +++ b/matlab/optimization/mr_gstep.m @@ -103,5 +103,3 @@ inx = find(x<=bounds(:,1)); if ~isempty(inx) x(inx) = bounds(inx,1)+eps; end - - diff --git a/matlab/optimization/mr_hessian.m b/matlab/optimization/mr_hessian.m index 9b336c1225..b234df9b7c 100644 --- a/matlab/optimization/mr_hessian.m +++ b/matlab/optimization/mr_hessian.m @@ -33,7 +33,7 @@ function [hessian_mat, gg, htol1, ihh, hh_mat0, hh1, hess_info] = mr_hessian(x,f % varargin{6} --> BayesInfo % varargin{7} --> Bounds % varargin{8} --> DynareResults -% +% % Outputs % - hessian_mat hessian % - gg Jacobian @@ -223,7 +223,7 @@ if outer_product_gradient hh_mat=gga'*gga; % rescaled outer product hessian hh_mat0=ggh'*ggh; % outer product hessian A=diag(2.*hess_info.h1); % rescaling matrix - % igg=inv(hh_mat); % inverted rescaled outer product hessian + % igg=inv(hh_mat); % inverted rescaled outer product hessian ihh=A'*(hh_mat\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 @@ -244,12 +244,12 @@ if outer_product_gradient 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 + % 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(:); diff --git a/matlab/optimization/newrat.m b/matlab/optimization/newrat.m index 8dbdf5d330..c554a22dc1 100644 --- a/matlab/optimization/newrat.m +++ b/matlab/optimization/newrat.m @@ -11,14 +11,14 @@ function [xparam1, hh, gg, fval, igg, hess_info] = newrat(func0, x, bounds, anal % - analytic_derivation 1 if analytic derivatives, 0 otherwise % - ftol0 termination criterion for function change % - nit maximum number of iterations -% - flagg Indicator how to compute final Hessian (In each iteration, Hessian is computed with outer product gradient) +% - flagg Indicator how to compute final Hessian (In each iteration, Hessian is computed with outer product gradient) % 0: final Hessian computed with outer product gradient -% 1: final 'mixed' Hessian: diagonal elements computed with -% numerical second order derivatives with correlation structure +% 1: final 'mixed' Hessian: diagonal elements computed with +% numerical second order derivatives with correlation structure % as from outer product gradient % 2: full numerical Hessian % - Verbose 1 if explicit output is requested -% - Save_files 1 if intermediate output is to be saved +% - Save_files 1 if intermediate output is to be saved % - hess_info structure storing the step sizes for % computation of Hessian % - varargin other inputs: @@ -30,7 +30,7 @@ function [xparam1, hh, gg, fval, igg, hess_info] = newrat(func0, x, bounds, anal % varargin{6} --> BayesInfo % varargin{7} --> Bounds % varargin{8} --> DynareResults -% +% % Outputs % - xparam1 parameter vector at optimum % - hh hessian @@ -56,7 +56,7 @@ function [xparam1, hh, gg, fval, igg, hess_info] = newrat(func0, x, bounds, anal % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. -% initialize variable penalty +% initialize variable penalty penalty = 1e8; icount=0; @@ -200,21 +200,21 @@ while norm(gg)>gtol && check==0 && jit<nit hhg=hh; H = inv(hh); else - if flagit==2 - hh=hh0; - elseif flagg>0 - [dum, gg, htol0, igg, hhg, h1, hess_info]=mr_hessian(xparam1,func0,penalty,flagg,ftol0,hess_info,varargin{:}); - if flagg==2 - hh = reshape(dum,nx,nx); - ee=eig(hh); - if min(ee)<0 + if flagit==2 + hh=hh0; + elseif flagg>0 + [dum, gg, htol0, igg, hhg, h1, hess_info]=mr_hessian(xparam1,func0,penalty,flagg,ftol0,hess_info,varargin{:}); + if flagg==2 + hh = reshape(dum,nx,nx); + ee=eig(hh); + if min(ee)<0 + hh=hhg; + end + else hh=hhg; end - else - hh=hhg; end end - end disp_verbose(['Actual dxnorm ',num2str(norm(x(:,end)-x(:,end-1)))],Verbose) disp_verbose(['FVAL ',num2str(fval)],Verbose) disp_verbose(['Improvement ',num2str(fval0(icount)-fval)],Verbose) diff --git a/matlab/optimization/penalty_objective_function.m b/matlab/optimization/penalty_objective_function.m index c245800c2f..e0c2492512 100644 --- a/matlab/optimization/penalty_objective_function.m +++ b/matlab/optimization/penalty_objective_function.m @@ -2,13 +2,13 @@ function [fval, exit_flag, arg1, arg2] = penalty_objective_function(x, fcn, base % Encapsulates an objective function to be minimized, adding a penalty if necessary. % -% INPUTS +% INPUTS % - x [double] n*1 vector of instrument values. % - fcn [fhandle] objective function. % - base_penalty [double] scalar, base of the penality (typically the value of the objective at the previous iteration). % - varagin [cell] additional parameters for fcn. % -% OUTPUTS +% OUTPUTS % - fval [double] scalar, value of the objective function at x. % - exit_flag [integer] scalar, flag returned by fcn (third output). % - arg1, arg2 fourth and fifth output arguments of the objective function. diff --git a/matlab/optimization/simplex_optimization_routine.m b/matlab/optimization/simplex_optimization_routine.m index 465528d842..ccd81367eb 100644 --- a/matlab/optimization/simplex_optimization_routine.m +++ b/matlab/optimization/simplex_optimization_routine.m @@ -7,7 +7,7 @@ function [x,fval,exitflag] = simplex_optimization_routine(objective_function,x,o % % The routine automatically restarts from the current solution while amelioration is possible. % -% INPUTS +% INPUTS % o objective_function [string] Name of the objective function to be minimized. % o x [double] n*1 vector, starting guess of the optimization routine. % o options [structure] Options of this implementation of the simplex algorithm. @@ -23,7 +23,7 @@ function [x,fval,exitflag] = simplex_optimization_routine(objective_function,x,o % varargin{6} --> BayesInfo % varargin{1} --> DynareResults % -% OUTPUTS +% OUTPUTS % o x [double] n*1 vector, estimate of the optimal inputs. % o fval [double] scalar, value of the objective at the optimum. % o exitflag [integer] scalar equal to 0 or 1 (0 if the algorithm did not converge to @@ -251,7 +251,7 @@ while (func_count < max_func_calls) && (iter_count < max_iterations) && (simplex fxr = feval(objective_function,x,varargin{:}); func_count = func_count+1; if fxr < fv(1)% xr is better than previous best point v(:,1). - % Calculate the expansion point + % Calculate the expansion point xe = xbar + rho*chi*(xbar-v(:,end)); x = xe; fxe = feval(objective_function,x,varargin{:}); @@ -499,7 +499,7 @@ while (func_count < max_func_calls) && (iter_count < max_iterations) && (simplex else break end - end + end end% while loop. x(:) = v(:,1); @@ -520,43 +520,43 @@ end function [v,fv,delta] = simplex_initialization(objective_function,point,point_score,delta,zero_delta,check_delta,varargin) - n = length(point); - v = zeros(n,n+1); - v(:,1) = point; - fv = zeros(n+1,1); - fv(1) = point_score; - if length(delta)==1 - delta = repmat(delta,n,1); +n = length(point); +v = zeros(n,n+1); +v(:,1) = point; +fv = zeros(n+1,1); +fv(1) = point_score; +if length(delta)==1 + delta = repmat(delta,n,1); +end +for j = 1:n + y = point; + if y(j) ~= 0 + y(j) = (1 + delta(j))*y(j); + else + y(j) = zero_delta; end - for j = 1:n - y = point; - if y(j) ~= 0 - y(j) = (1 + delta(j))*y(j); - else - y(j) = zero_delta; - end - v(:,j+1) = y; - x = y; - [fv(j+1),junk1,junk2,nopenalty_flag] = feval(objective_function,x,varargin{:}); - if check_delta - while ~nopenalty_flag - if y(j)~=0 - delta(j) = delta(j)/1.1; - else - zero_delta = zero_delta/1.1; - end - y = point; - if y(j) ~= 0 - y(j) = (1 + delta(j))*y(j); - else - y(j) = zero_delta; - end - v(:,j+1) = y; - x = y; - [fv(j+1),junk1,junk2,nopenalty_flag] = feval(objective_function,x,varargin{:}); + v(:,j+1) = y; + x = y; + [fv(j+1),junk1,junk2,nopenalty_flag] = feval(objective_function,x,varargin{:}); + if check_delta + while ~nopenalty_flag + if y(j)~=0 + delta(j) = delta(j)/1.1; + else + zero_delta = zero_delta/1.1; end + y = point; + if y(j) ~= 0 + y(j) = (1 + delta(j))*y(j); + else + y(j) = zero_delta; + end + v(:,j+1) = y; + x = y; + [fv(j+1),junk1,junk2,nopenalty_flag] = feval(objective_function,x,varargin{:}); end end - % Sort by increasing order of the objective function values. - [fv,sort_idx] = sort(fv); - v = v(:,sort_idx); \ No newline at end of file +end +% Sort by increasing order of the objective function values. +[fv,sort_idx] = sort(fv); +v = v(:,sort_idx); \ No newline at end of file diff --git a/matlab/optimization/simpsa.m b/matlab/optimization/simpsa.m index b389b37bda..814618d415 100644 --- a/matlab/optimization/simpsa.m +++ b/matlab/optimization/simpsa.m @@ -1,8 +1,8 @@ function [X,FVAL,EXITFLAG,OUTPUT] = simpsa(FUN,X0,LB,UB,OPTIONS,varargin) -% Finds a minimum of a function of several variables using an algorithm -% that is based on the combination of the non-linear smplex and the simulated -% annealing algorithm (the SIMPSA algorithm, Cardoso et al., 1996). +% Finds a minimum of a function of several variables using an algorithm +% that is based on the combination of the non-linear smplex and the simulated +% annealing algorithm (the SIMPSA algorithm, Cardoso et al., 1996). % In this paper, the algorithm is shown to be adequate for the global optimi- % zation of an example set of unconstrained and constrained NLP functions. % @@ -11,48 +11,48 @@ function [X,FVAL,EXITFLAG,OUTPUT] = simpsa(FUN,X0,LB,UB,OPTIONS,varargin) % X % % Algorithm partly is based on paper of Cardoso et al, 1996. -% -% X=SIMPSA(FUN,X0) start at X0 and finds a minimum X to the function FUN. +% +% X=SIMPSA(FUN,X0) start at X0 and finds a minimum X to the function FUN. % FUN accepts input X and returns a scalar function value F evaluated at X. % X0 may be a scalar, vector, or matrix. -% -% X=SIMPSA(FUN,X0,LB,UB) defines a set of lower and upper bounds on the -% design variables, X, so that a solution is found in the range -% LB <= X <= UB. Use empty matrices for LB and UB if no bounds exist. -% Set LB(i) = -Inf if X(i) is unbounded below; set UB(i) = Inf if X(i) is +% +% X=SIMPSA(FUN,X0,LB,UB) defines a set of lower and upper bounds on the +% design variables, X, so that a solution is found in the range +% LB <= X <= UB. Use empty matrices for LB and UB if no bounds exist. +% Set LB(i) = -Inf if X(i) is unbounded below; set UB(i) = Inf if X(i) is % unbounded above. -% +% % X=SIMPSA(FUN,X0,LB,UB,OPTIONS) minimizes with the default optimization -% parameters replaced by values in the structure OPTIONS, an argument -% created with the SIMPSASET function. See SIMPSASET for details. +% parameters replaced by values in the structure OPTIONS, an argument +% created with the SIMPSASET function. See SIMPSASET for details. % Used options are TEMP_START, TEMP_END, COOL_RATE, INITIAL_ACCEPTANCE_RATIO, % MIN_COOLING_FACTOR, MAX_ITER_TEMP_FIRST, MAX_ITER_TEMP_LAST, MAX_ITER_TEMP, % MAX_ITER_TOTAL, MAX_TIME, MAX_FUN_EVALS, TOLX, TOLFUN, DISPLAY and OUTPUT_FCN. % Use OPTIONS = [] as a place holder if no options are set. -% -% X=SIMPSA(FUN,X0,LB,UB,OPTIONS,varargin) is used to supply a variable +% +% X=SIMPSA(FUN,X0,LB,UB,OPTIONS,varargin) is used to supply a variable % number of input arguments to the objective function FUN. -% -% [X,FVAL]=SIMPSA(FUN,X0,...) returns the value of the objective +% +% [X,FVAL]=SIMPSA(FUN,X0,...) returns the value of the objective % function FUN at the solution X. -% -% [X,FVAL,EXITFLAG]=SIMPSA(FUN,X0,...) returns an EXITFLAG that describes the -% exit condition of SIMPSA. Possible values of EXITFLAG and the corresponding +% +% [X,FVAL,EXITFLAG]=SIMPSA(FUN,X0,...) returns an EXITFLAG that describes the +% exit condition of SIMPSA. Possible values of EXITFLAG and the corresponding % exit conditions are: -% +% % 1 Change in the objective function value less than the specified tolerance. % 2 Change in X less than the specified tolerance. % 0 Maximum number of function evaluations or iterations reached. % -1 Maximum time exceeded. -% -% [X,FVAL,EXITFLAG,OUTPUT]=SIMPSA(FUN,X0,...) returns a structure OUTPUT with +% +% [X,FVAL,EXITFLAG,OUTPUT]=SIMPSA(FUN,X0,...) returns a structure OUTPUT with % the number of iterations taken in OUTPUT.nITERATIONS, the number of function % evaluations in OUTPUT.nFUN_EVALS, the temperature profile in OUTPUT.TEMPERATURE, -% the simplexes that were evaluated in OUTPUT.SIMPLEX and the best one in -% OUTPUT.SIMPLEX_BEST, the costs associated with each simplex in OUTPUT.COSTS and -% from the best simplex at that iteration in OUTPUT.COST_BEST, the amount of time +% the simplexes that were evaluated in OUTPUT.SIMPLEX and the best one in +% OUTPUT.SIMPLEX_BEST, the costs associated with each simplex in OUTPUT.COSTS and +% from the best simplex at that iteration in OUTPUT.COST_BEST, the amount of time % needed in OUTPUT.TIME and the options used in OUTPUT.OPTIONS. -% +% % See also SIMPSASET, SIMPSAGET @@ -122,20 +122,20 @@ NDIM = length(X0); % set default options DEFAULT_OPTIONS = simpsaset('TEMP_START',[],... % starting temperature (if none provided, an optimal one will be estimated) - 'TEMP_END',.1,... % end temperature - 'COOL_RATE',10,... % small values (<1) means slow convergence,large values (>1) means fast convergence - 'INITIAL_ACCEPTANCE_RATIO',0.95,... % when initial temperature is estimated, this will be the initial acceptance ratio in the first round - 'MIN_COOLING_FACTOR',0.9,... % minimum cooling factor (<1) - 'MAX_ITER_TEMP_FIRST',50,... % number of iterations in the preliminary temperature loop - 'MAX_ITER_TEMP_LAST',2000,... % number of iterations in the last temperature loop (pure simplex) - 'MAX_ITER_TEMP',10,... % number of iterations in the remaining temperature loops - 'MAX_ITER_TOTAL',2500,... % maximum number of iterations tout court - 'MAX_TIME',2500,... % maximum duration of optimization - 'MAX_FUN_EVALS',20000,... % maximum number of function evaluations - 'TOLX',1e-6,... % maximum difference between best and worst function evaluation in simplex - 'TOLFUN',1e-6,... % maximum difference between the coordinates of the vertices - 'DISPLAY','iter',... % 'iter' or 'none' indicating whether user wants feedback - 'OUTPUT_FCN',[]); % string with output function name + 'TEMP_END',.1,... % end temperature + 'COOL_RATE',10,... % small values (<1) means slow convergence,large values (>1) means fast convergence + 'INITIAL_ACCEPTANCE_RATIO',0.95,... % when initial temperature is estimated, this will be the initial acceptance ratio in the first round + 'MIN_COOLING_FACTOR',0.9,... % minimum cooling factor (<1) + 'MAX_ITER_TEMP_FIRST',50,... % number of iterations in the preliminary temperature loop + 'MAX_ITER_TEMP_LAST',2000,... % number of iterations in the last temperature loop (pure simplex) + 'MAX_ITER_TEMP',10,... % number of iterations in the remaining temperature loops + 'MAX_ITER_TOTAL',2500,... % maximum number of iterations tout court + 'MAX_TIME',2500,... % maximum duration of optimization + 'MAX_FUN_EVALS',20000,... % maximum number of function evaluations + 'TOLX',1e-6,... % maximum difference between best and worst function evaluation in simplex + 'TOLFUN',1e-6,... % maximum difference between the coordinates of the vertices + 'DISPLAY','iter',... % 'iter' or 'none' indicating whether user wants feedback + 'OUTPUT_FCN',[]); % string with output function name % update default options with supplied options @@ -196,25 +196,25 @@ nITERATIONS = 0; % ----------------------------------------------------------- while 1 - + % detect if termination criterium was met % --------------------------------------- - + % if a termination criterium was met, the value of EXITFLAG should have changed % from its default value of -2 to -1, 0, 1 or 2 - + if EXITFLAG ~= -2 break end - + % set MAXITERTEMP: maximum number of iterations at current temperature % -------------------------------------------------------------------- - + if TEMP_LOOP_NUMBER == 1 MAXITERTEMP = OPTIONS.MAX_ITER_TEMP_FIRST*NDIM; - % The initial temperature is estimated (is requested) as described in - % Cardoso et al. (1996). Therefore, we need to store the number of - % successful and unsuccessful moves, as well as the increase in cost + % The initial temperature is estimated (is requested) as described in + % Cardoso et al. (1996). Therefore, we need to store the number of + % successful and unsuccessful moves, as well as the increase in cost % for the unsuccessful moves. if isempty(OPTIONS.TEMP_START) [SUCCESSFUL_MOVES,UNSUCCESSFUL_MOVES,UNSUCCESSFUL_COSTS] = deal(0); @@ -225,19 +225,19 @@ while 1 else MAXITERTEMP = OPTIONS.MAX_ITER_TEMP*NDIM; end - + % construct initial simplex % ------------------------- - + % 1st vertex of initial simplex P(1,:) = PBEST; Y(1) = CALCULATE_COST(FUN,P(1,:),LB,UB,varargin{:}); - + % if output function given then run output function to plot intermediate result if ~isempty(OPTIONS.OUTPUT_FCN) feval(OPTIONS.OUTPUT_FCN,transpose(P(1,:)),Y(1)); end - + % remaining vertices of simplex for k = 1:NDIM % copy first vertex in new vertex @@ -247,17 +247,17 @@ while 1 % calculate value of objective function at new vertex Y(k+1) = CALCULATE_COST(FUN,P(k+1,:),LB,UB,varargin{:}); end - + % store information on what step the algorithm just did ALGOSTEP = 'initial simplex'; - + % add NDIM+1 to number of function evaluations nFUN_EVALS = nFUN_EVALS + NDIM; - + % note: % dimensions of matrix P: (NDIM+1) x NDIM % dimensions of vector Y: (NDIM+1) x 1 - + % give user feedback if requested if strcmp(OPTIONS.DISPLAY,'iter') if nITERATIONS == 0 @@ -269,67 +269,67 @@ while 1 % run full metropolis cycle at current temperature % ------------------------------------------------ - + % initialize vector COSTS, needed to calculate new temperature using cooling % schedule as described by Cardoso et al. (1996) COSTS = zeros((NDIM+1)*MAXITERTEMP,1); - + % initialize ITERTEMP to zero - + ITERTEMP = 0; - + % start for ITERTEMP = 1:MAXITERTEMP - + % add one to number of iterations nITERATIONS = nITERATIONS + 1; - + % Press and Teukolsky (1991) add a positive logarithmic distributed variable, - % proportional to the control temperature T to the function value associated with - % every vertex of the simplex. Likewise,they subtract a similar random variable + % proportional to the control temperature T to the function value associated with + % every vertex of the simplex. Likewise,they subtract a similar random variable % from the function value at every new replacement point. % Thus, if the replacement point corresponds to a lower cost, this method always - % accepts a true down hill step. If, on the other hand, the replacement point + % accepts a true down hill step. If, on the other hand, the replacement point % corresponds to a higher cost, an uphill move may be accepted, depending on the % relative COSTS of the perturbed values. % (taken from Cardoso et al.,1996) - + % add random fluctuations to function values of current vertices YFLUCT = Y+TEMP*abs(log(rand(NDIM+1,1))); - + % reorder YFLUCT, Y and P so that the first row corresponds to the lowest YFLUCT value help = sortrows([YFLUCT,Y,P],1); YFLUCT = help(:,1); Y = help(:,2); P = help(:,3:end); - + % store temperature at current iteration OUTPUT.TEMPERATURE(nITERATIONS) = TEMP; % store information about simplex at the current iteration OUTPUT.SIMPLEX(:,:,nITERATIONS) = P; OUTPUT.SIMPLEX_BEST(nITERATIONS,:) = PBEST; - + % store cost function value of best vertex in current iteration OUTPUT.COSTS(nITERATIONS,:) = Y; OUTPUT.COST_BEST(nITERATIONS) = YBEST; - + if strcmp(OPTIONS.DISPLAY,'iter') disp(sprintf('%5.0f %5.0f %12.6g %15.6g %12.6g %s',nITERATIONS,nFUN_EVALS,Y(1),YBEST,TEMP,ALGOSTEP)); end - + % if output function given then run output function to plot intermediate result if ~isempty(OPTIONS.OUTPUT_FCN) feval(OPTIONS.OUTPUT_FCN,transpose(P(1,:)),Y(1)); end - + % end the optimization if one of the stopping criteria is met - %% 1. difference between best and worst function evaluation in simplex is smaller than TOLFUN + %% 1. difference between best and worst function evaluation in simplex is smaller than TOLFUN %% 2. maximum difference between the coordinates of the vertices in simplex is less than TOLX %% 3. no convergence,but maximum number of iterations has been reached %% 4. no convergence,but maximum time has been reached - + if (abs(max(Y)-min(Y)) < OPTIONS.TOLFUN) && (TEMP_LOOP_NUMBER ~= 1) if strcmp(OPTIONS.DISPLAY,'iter') disp('Change in the objective function value less than the specified tolerance (TOLFUN).') @@ -337,7 +337,7 @@ while 1 EXITFLAG = 1; break end - + if (max(max(abs(P(2:NDIM+1,:)-P(1:NDIM,:)))) < OPTIONS.TOLX) && (TEMP_LOOP_NUMBER ~= 1) if strcmp(OPTIONS.DISPLAY,'iter') disp('Change in X less than the specified tolerance (TOLX).') @@ -345,7 +345,7 @@ while 1 EXITFLAG = 2; break end - + if (nITERATIONS >= OPTIONS.MAX_ITER_TOTAL*NDIM) || (nFUN_EVALS >= OPTIONS.MAX_FUN_EVALS*NDIM*(NDIM+1)) if strcmp(OPTIONS.DISPLAY,'iter') disp('Maximum number of function evaluations or iterations reached.'); @@ -353,7 +353,7 @@ while 1 EXITFLAG = 0; break end - + if toc/60 > OPTIONS.MAX_TIME if strcmp(OPTIONS.DISPLAY,'iter') disp('Exceeded maximum time.'); @@ -361,13 +361,13 @@ while 1 EXITFLAG = -1; break end - + % begin a new iteration - + %% first extrapolate by a factor -1 through the face of the simplex %% across from the high point,i.e.,reflect the simplex from the high point [YFTRY,YTRY,PTRY] = AMOTRY(FUN,P,-1,LB,UB,varargin{:}); - + %% check the result if YFTRY <= YFLUCT(1) %% gives a result better than the best point,so try an additional @@ -407,11 +407,11 @@ while 1 Y(end) = YTRY; ALGOSTEP = 'reflection'; end - - % the initial temperature is estimated in the first loop from - % the number of successfull and unsuccesfull moves, and the average + + % the initial temperature is estimated in the first loop from + % the number of successfull and unsuccesfull moves, and the average % increase in cost associated with the unsuccessful moves - + if TEMP_LOOP_NUMBER == 1 && isempty(OPTIONS.TEMP_START) if Y(1) > Y(end) SUCCESSFUL_MOVES = SUCCESSFUL_MOVES+1; @@ -427,14 +427,14 @@ while 1 if ITERTEMP < MAXITERTEMP break end - + % store cost function values in COSTS vector COSTS((ITERTEMP-1)*NDIM+1:ITERTEMP*NDIM+1) = Y; - - % calculated initial temperature or recalculate temperature + + % calculated initial temperature or recalculate temperature % using cooling schedule as proposed by Cardoso et al. (1996) % ----------------------------------------------------------- - + if TEMP_LOOP_NUMBER == 1 && isempty(OPTIONS.TEMP_START) TEMP = -(UNSUCCESSFUL_COSTS/(SUCCESSFUL_MOVES+UNSUCCESSFUL_MOVES))/log(((SUCCESSFUL_MOVES+UNSUCCESSFUL_MOVES)*OPTIONS.INITIAL_ACCEPTANCE_RATIO-SUCCESSFUL_MOVES)/UNSUCCESSFUL_MOVES); elseif TEMP_LOOP_NUMBER ~= 0 @@ -442,10 +442,10 @@ while 1 COOLING_FACTOR = 1/(1+TEMP*log(1+OPTIONS.COOL_RATE)/(3*STDEV_Y)); TEMP = TEMP*min(OPTIONS.MIN_COOLING_FACTOR,COOLING_FACTOR); end - + % add one to temperature loop number TEMP_LOOP_NUMBER = TEMP_LOOP_NUMBER+1; - + end % return solution @@ -476,8 +476,8 @@ return % --------------- function [YFTRY,YTRY,PTRY] = AMOTRY(FUN,P,fac,LB,UB,varargin) -% Extrapolates by a factor fac through the face of the simplex across from -% the high point, tries it, and replaces the high point if the new point is +% Extrapolates by a factor fac through the face of the simplex across from +% the high point, tries it, and replaces the high point if the new point is % better. global NDIM TEMP diff --git a/matlab/optimization/simpsaget.m b/matlab/optimization/simpsaget.m index e1c775495e..318ea43134 100644 --- a/matlab/optimization/simpsaget.m +++ b/matlab/optimization/simpsaget.m @@ -38,25 +38,25 @@ function o = simpsaget(options,name,default,flag) % undocumented usage for fast access with no error checking if (nargin == 4) && isequal(flag,'fast') - o = getknownfield(options,name,default); - return + o = getknownfield(options,name,default); + return end if nargin < 2 - error('MATLAB:odeget:NotEnoughInputs','Not enough input arguments.'); + error('MATLAB:odeget:NotEnoughInputs','Not enough input arguments.'); end if nargin < 3 - default = []; + default = []; end if ~isempty(options) && ~isa(options,'struct') - error('MATLAB:odeget:Arg1NotODESETstruct',... - 'First argument must be an options structure created with ODESET.'); + error('MATLAB:odeget:Arg1NotODESETstruct',... + 'First argument must be an options structure created with ODESET.'); end if isempty(options) - o = default; - return + o = default; + return end Names = [ @@ -75,39 +75,39 @@ Names = [ 'TOLFUN ' 'DISPLAY ' 'OUTPUT_FCN ' - ]; + ]; names = lower(Names); lowName = lower(name); j = strmatch(lowName,names); if isempty(j) % if no matches - error('MATLAB:odeget:InvalidPropName',... - ['Unrecognized property name ''%s''. ' ... - 'See ODESET for possibilities.'], name); + error('MATLAB:odeget:InvalidPropName',... + ['Unrecognized property name ''%s''. ' ... + 'See ODESET for possibilities.'], name); elseif length(j) > 1 % if more than one match - % Check for any exact matches (in case any names are subsets of others) - k = strmatch(lowName,names,'exact'); - if length(k) == 1 - j = k; - else - msg = sprintf('Ambiguous property name ''%s'' ', name); - msg = [msg '(' deblank(Names(j(1),:))]; - for k = j(2:length(j))' - msg = [msg ', ' deblank(Names(k,:))]; + % Check for any exact matches (in case any names are subsets of others) + k = strmatch(lowName,names,'exact'); + if length(k) == 1 + j = k; + else + msg = sprintf('Ambiguous property name ''%s'' ', name); + msg = [msg '(' deblank(Names(j(1),:))]; + for k = j(2:length(j))' + msg = [msg ', ' deblank(Names(k,:))]; + end + msg = sprintf('%s).', msg); + error('MATLAB:odeget:AmbiguousPropName', msg); end - msg = sprintf('%s).', msg); - error('MATLAB:odeget:AmbiguousPropName', msg); - end end if any(strcmp(fieldnames(options),deblank(Names(j,:)))) - o = options.(deblank(Names(j,:))); - if isempty(o) - o = default; - end + o = options.(deblank(Names(j,:))); + if isempty(o) + o = default; + end else - o = default; + o = default; end % -------------------------------------------------------------------------- @@ -115,11 +115,10 @@ function v = getknownfield(s, f, d) %GETKNOWNFIELD Get field f from struct s, or else yield default d. if isfield(s,f) % s could be empty. - v = subsref(s, struct('type','.','subs',f)); - if isempty(v) - v = d; - end + v = subsref(s, struct('type','.','subs',f)); + if isempty(v) + v = d; + end else - v = d; + v = d; end - diff --git a/matlab/optimization/simpsaset.m b/matlab/optimization/simpsaset.m index dc0aade4fa..16e1919c1f 100644 --- a/matlab/optimization/simpsaset.m +++ b/matlab/optimization/simpsaset.m @@ -64,7 +64,7 @@ if (nargin == 0) && (nargout == 0) fprintf(' DISPLAY: [ ''iter'' or ''none'' {''iter''} ]\n'); fprintf(' OUTPUT_FCN: [ function_handle ]\n'); fprintf('\n'); -return + return end Names = [ @@ -83,7 +83,7 @@ Names = [ 'TOLFUN ' 'DISPLAY ' 'OUTPUT_FCN ' - ]; + ]; m = size(Names,1); names = lower(Names); @@ -91,82 +91,82 @@ names = lower(Names); % Combine all leading options structures o1, o2, ... in odeset(o1,o2,...). options = []; for j = 1:m - options.(deblank(Names(j,:))) = []; + options.(deblank(Names(j,:))) = []; end i = 1; while i <= nargin - arg = varargin{i}; - if ischar(arg) % arg is an option name - break - end - if ~isempty(arg) % [] is a valid options argument - if ~isa(arg,'struct') - error('MATLAB:odeset:NoPropNameOrStruct',... - ['Expected argument %d to be a string property name ' ... - 'or an options structure\ncreated with SIMANSET.'], i); + arg = varargin{i}; + if ischar(arg) % arg is an option name + break end - for j = 1:m - if any(strcmp(fieldnames(arg),deblank(Names(j,:)))) - val = arg.(deblank(Names(j,:))); - else - val = []; - end - if ~isempty(val) - options.(deblank(Names(j,:))) = val; - end + if ~isempty(arg) % [] is a valid options argument + if ~isa(arg,'struct') + error('MATLAB:odeset:NoPropNameOrStruct',... + ['Expected argument %d to be a string property name ' ... + 'or an options structure\ncreated with SIMANSET.'], i); + end + for j = 1:m + if any(strcmp(fieldnames(arg),deblank(Names(j,:)))) + val = arg.(deblank(Names(j,:))); + else + val = []; + end + if ~isempty(val) + options.(deblank(Names(j,:))) = val; + end + end end - end - i = i + 1; + i = i + 1; end % A finite state machine to parse name-value pairs. if rem(nargin-i+1,2) ~= 0 - error('MATLAB:odeset:ArgNameValueMismatch',... - 'Arguments must occur in name-value pairs.'); + error('MATLAB:odeset:ArgNameValueMismatch',... + 'Arguments must occur in name-value pairs.'); end expectval = 0; % start expecting a name, not a value while i <= nargin - arg = varargin{i}; - - if ~expectval - if ~ischar(arg) - error('MATLAB:odeset:NoPropName',... - 'Expected argument %d to be a string property name.', i); - end - - lowArg = lower(arg); - j = strmatch(lowArg,names); - if isempty(j) % if no matches - error('MATLAB:odeset:InvalidPropName',... - 'Unrecognized property name ''%s''.', arg); - elseif length(j) > 1 % if more than one match - % Check for any exact matches (in case any names are subsets of others) - k = strmatch(lowArg,names,'exact'); - if length(k) == 1 - j = k; - else - msg = sprintf('Ambiguous property name ''%s'' ', arg); - msg = [msg '(' deblank(Names(j(1),:))]; - for k = j(2:length(j))' - msg = [msg ', ' deblank(Names(k,:))]; + arg = varargin{i}; + + if ~expectval + if ~ischar(arg) + error('MATLAB:odeset:NoPropName',... + 'Expected argument %d to be a string property name.', i); end - msg = sprintf('%s).', msg); - error('MATLAB:odeset:AmbiguousPropName', msg); - end + + lowArg = lower(arg); + j = strmatch(lowArg,names); + if isempty(j) % if no matches + error('MATLAB:odeset:InvalidPropName',... + 'Unrecognized property name ''%s''.', arg); + elseif length(j) > 1 % if more than one match + % Check for any exact matches (in case any names are subsets of others) + k = strmatch(lowArg,names,'exact'); + if length(k) == 1 + j = k; + else + msg = sprintf('Ambiguous property name ''%s'' ', arg); + msg = [msg '(' deblank(Names(j(1),:))]; + for k = j(2:length(j))' + msg = [msg ', ' deblank(Names(k,:))]; + end + msg = sprintf('%s).', msg); + error('MATLAB:odeset:AmbiguousPropName', msg); + end + end + expectval = 1; % we expect a value next + + else + options.(deblank(Names(j,:))) = arg; + expectval = 0; + end - expectval = 1; % we expect a value next - - else - options.(deblank(Names(j,:))) = arg; - expectval = 0; - - end - i = i + 1; + i = i + 1; end if expectval - error('MATLAB:odeset:NoValueForProp',... - 'Expected value for property ''%s''.', arg); + error('MATLAB:odeset:NoValueForProp',... + 'Expected value for property ''%s''.', arg); end end diff --git a/matlab/optimization/simulated_annealing.m b/matlab/optimization/simulated_annealing.m index 35f0240e00..9637e64e92 100644 --- a/matlab/optimization/simulated_annealing.m +++ b/matlab/optimization/simulated_annealing.m @@ -5,7 +5,7 @@ function [xopt, fopt,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_ % % Implements the continuous simulated annealing global optimization % algorithm described in Corana et al. (1987) -% +% % A very quick (perhaps too quick) overview of SA: % SA tries to find the global optimum of an N dimensional function. % It moves both up and downhill and as the optimization process @@ -49,17 +49,17 @@ function [xopt, fopt,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_ % Note: The suggested values generally come from Corana et al. To % drastically reduce runtime, see Goffe et al., pp. 90-1 for % suggestions on choosing the appropriate RT and NT. -% +% % fcn - function to be optimized. % x - The starting values for the variables of the function to be % optimized. (N) % optim: Options structure with fields -% +% % optim.maximizer_indicator - Denotes whether the function should be maximized or % minimized. A value =1 denotes maximization while a % value =0 denotes minimization. Intermediate output (see verbosity) % takes this into account. -% optim.RT - The temperature reduction factor +% optim.RT - The temperature reduction factor % optim.TolFun - Error tolerance for termination. If the final function % values from the last neps temperatures differ from the % corresponding value at the current temperature by less than @@ -104,11 +104,11 @@ function [xopt, fopt,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_ % of all points are accepted, the input value is not very % important (i.e. is the value is off, SA adjusts VM to the % correct value) -% -% lb - The lower bound for the allowable solution variables. -% ub - The upper bound for the allowable solution variables. +% +% lb - The lower bound for the allowable solution variables. +% ub - The upper bound for the allowable solution variables. % If the algorithm chooses X(I) < LB(I) or X(I) > UB(I), -% I = 1, N, a point is from inside is randomly selected. +% I = 1, N, a point is from inside is randomly selected. % This focuses the algorithm on the region inside UB and LB. % Unless the user wishes to concentrate the search to a par- % ticular region, UB and LB should be set to very large positive @@ -116,8 +116,8 @@ function [xopt, fopt,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_ % vector X should be inside this region. Also note that LB and % UB are fixed in position, while VM is centered on the last % accepted trial set of variables that optimizes the function. -% -% +% +% % Input/Output Parameters: % % Output Parameters: @@ -142,26 +142,26 @@ function [xopt, fopt,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_ % t: On output, the final temperature. % vm: Final step length vector % -% Algorithm: +% Algorithm: % This routine implements the continuous simulated annealing global % optimization algorithm described in Corana et al.'s article % "Minimizing Multimodal Functions of Continuous Variables with the % "Simulated Annealing" Algorithm" in the September 1987 (vol. 13, % no. 3, pp. 262-280) issue of the ACM Transactions on Mathematical % Software. -% +% % For modifications to the algorithm and many details on its use, % (particularly for econometric applications) see Goffe, Ferrier % and Rogers, "Global Optimization of Statistical Functions with % Simulated Annealing," Journal of Econometrics, vol. 60, no. 1/2, % Jan./Feb. 1994, pp. 65-100. -% +% % Based on the Matlab code written by Thomas Werner (Bundesbank December -% 2002), which in turn is based on the GAUSS version of Bill Goffe's simulated annealing +% 2002), which in turn is based on the GAUSS version of Bill Goffe's simulated annealing % program for global optimization, written by E.G.Tsionas (9/4/95). -% -% Copyright (C) 1995 E.G.Tsionas -% Copyright (C) 1995-2002 Thomas Werner +% +% Copyright (C) 1995 E.G.Tsionas +% Copyright (C) 1995-2002 Thomas Werner % Copyright (C) 2002-2015 Giovanni Lombardo % Copyright (C) 2015 Dynare Team % @@ -314,9 +314,9 @@ while (1>0) if(pp<p) if(optim.verbosity >=3) if(optim.maximizer_indicator) - fprintf('though lower, point accepted\n'); + fprintf('though lower, point accepted\n'); else - fprintf('though higher, point accepted\n'); + fprintf('though higher, point accepted\n'); end end x=xp; @@ -383,7 +383,7 @@ while (1>0) if(optim.verbosity >=1) fprintf('SA achieved termination criteria.exitflag=0\n'); end - return + return end %* If termination criteria are not met, prepare for another loop. * t=optim.rt*t; @@ -401,7 +401,7 @@ end function print_current_invalid_try(max,xp,x,fp,f) fprintf('\n'); - disp(['Current x ' num2str(x(:)')]); +disp(['Current x ' num2str(x(:)')]); if(max) disp(['Current f ' num2str(f)]); else diff --git a/matlab/optimization/solvopt.m b/matlab/optimization/solvopt.m index 9976ad8502..079a6d5b79 100644 --- a/matlab/optimization/solvopt.m +++ b/matlab/optimization/solvopt.m @@ -1,10 +1,10 @@ function [x,f,exitflag,n_f_evals,n_grad_evals,n_constraint_evals,n_constraint_gradient_evals]=solvopt(x,fun,grad,func,gradc,optim,varargin) % [x,f,options]=solvopt(x,fun,grad,func,gradc,options,varargin) -% -% The function SOLVOPT, developed by Alexei Kuntsevich and Franz Kappe, +% +% The function SOLVOPT, developed by Alexei Kuntsevich and Franz Kappe, % performs a modified version of Shor's r-algorithm in % order to find a local minimum resp. maximum of a nonlinear function -% defined on the n-dimensional Euclidean space or % a solution of a nonlinear +% defined on the n-dimensional Euclidean space or % a solution of a nonlinear % constrained problem: % min { f(x): g(x) (<)= 0, g(x) in R(m), x in R(n) } % @@ -41,7 +41,7 @@ function [x,f,exitflag,n_f_evals,n_grad_evals,n_constraint_evals,n_constraint_gr % *optim.LBGradientStep= lower bound for the stepsize used for the difference % approximation of gradients (1e-12 by default, see more in the manual). % (* ... changes should be done with care) -% +% % Outputs: % x optimal parameter vector (row resp. column), % f optimum function value @@ -51,13 +51,13 @@ function [x,f,exitflag,n_f_evals,n_grad_evals,n_constraint_evals,n_constraint_gr % n_grad_evals: number of gradient evaluations, % n_constraint_evals: number of constraint function evaluations, % n_constraint_gradient_evals number of constraint gradient evaluations. -% -% -% Algorithm: Kuntsevich, A.V., Kappel, F., SolvOpt - The solver for local nonlinear optimization problems -% (version 1.1, Matlab, C, FORTRAN). University of Graz, Graz, 1997. -% -% -% Copyright (C) 1997-2008, Alexei Kuntsevich and Franz Kappel +% +% +% Algorithm: Kuntsevich, A.V., Kappel, F., SolvOpt - The solver for local nonlinear optimization problems +% (version 1.1, Matlab, C, FORTRAN). University of Graz, Graz, 1997. +% +% +% Copyright (C) 1997-2008, Alexei Kuntsevich and Franz Kappel % Copyright (C) 2008-2015 Giovanni Lombardo % Copyright (C) 2015 Dynare Team % @@ -217,7 +217,7 @@ ajp=20; ajpp=ajp; % Start value for the power ajs=1.15; % Base II knorms=0; gnorms=zeros(1,10); % Gradient norms stored -%---} + %---} %Display control ---{ if optim.verbosity<=0, dispdata=0 @@ -243,7 +243,7 @@ else des=3.3; end mxtc=3; % Number of trial cycles (steep wall detect) -%---} + %---} termx=0; limxterm=50; % Counter and limit for x-criterion ddx =max(1e-11,optim.LBGradientStep); % stepsize for gradient approximation @@ -253,7 +253,7 @@ low_bound=-1+1e-4; % Lower bound cosine used to detect a ravine ZeroGrad=n*1.e-16; % Lower bound for a gradient norm nzero=0; % Zero-gradient events counter -% Lower bound for values of variables taking into account + % Lower bound for values of variables taking into account lowxbound=max([optim.TolX,1e-3]); % Lower bound for function values to be considered as making difference lowfbound=optim.TolFun^2; @@ -282,7 +282,7 @@ if isempty(f) disp(error30) end exitflag=-3; - if trx + if trx x=x'; end return @@ -310,7 +310,7 @@ elseif abs(f)==Inf return end xrec=x; frec=f; % record point and function value -% Constrained problem + % Constrained problem if constr, fp=f; kless=0 if trx fc=feval(func,x'); @@ -367,13 +367,13 @@ if app if trx g=apprgrdn(x',fp,fun,deltax',1,varargin{:}); else - g=apprgrdn(x ,fp,fun,deltax,1,varargin{:}); + g=apprgrdn(x ,fp,fun,deltax,1,varargin{:}); end else if trx g=apprgrdn(x',f,fun,deltax',1,varargin{:}); else - g=apprgrdn(x ,f,fun,deltax,1,varargin{:}); + g=apprgrdn(x ,f,fun,deltax,1,varargin{:}); end end n_f_evals=n_f_evals+n; @@ -381,7 +381,7 @@ else if trx g=feval(grad,x',varargin{:}); else - g=feval(grad,x,varargin{:}); + g=feval(grad,x,varargin{:}); end n_grad_evals=n_grad_evals+1; end @@ -395,7 +395,7 @@ if size(g,2)~=n exitflag=-4; if trx x=x'; - end + end return elseif isnan(ng) if dispwarn @@ -435,24 +435,24 @@ if constr if ~FP if appconstr deltax=sign(x); idx=find(deltax==0); - deltax(idx)=ones(size(idx)); + deltax(idx)=ones(size(idx)); deltax=ddx*deltax; if trx gc=apprgrdn(x',fc,func,deltax',0); else - gc=apprgrdn(x ,fc,func,deltax ,0); + gc=apprgrdn(x ,fc,func,deltax ,0); end n_constraint_evals=n_constraint_evals+n; else if trx gc=feval(gradc,x'); else - gc=feval(gradc,x); + gc=feval(gradc,x); end n_constraint_gradient_evals=n_constraint_gradient_evals+1; end if size(gc,2)==1 - gc=gc'; + gc=gc'; end ngc=norm(gc); if size(gc,2)~=n @@ -460,7 +460,7 @@ if constr disp(errmes) disp(error60) end - exitflag=-6; + exitflag=-6; if trx x=x'; end @@ -482,7 +482,7 @@ if constr disp(error62) disp(error6) end - exitflag=-6; + exitflag=-6; if trx x=x'; end @@ -492,7 +492,7 @@ if constr disp(errmes) disp(error63) end - exitflag=-6; + exitflag=-6; if trx x=x'; end @@ -519,13 +519,13 @@ while 1 B=eye(n); % re-set transf. matrix to identity fst=f; g1=g; dx=0; % ----} - + % MAIN ITERATIONS ----{ - + while 1 k=k+1;kcheck=kcheck+1; laststep=dx; - + % ADJUST GAMMA --{ gamma=1+max([ajb^((ajp-kcheck)*n),2*optim.TolFun]); gamma=min([gamma,ajs^max([1,log10(nng+1)])]); @@ -534,8 +534,8 @@ while 1 % JUMPING OVER A RAVINE ----{ if (gt/norm(gt))*(g1'/norm(g1))<low_bound if kj==2 - xx=x; - end + xx=x; + end if kj==0 kd=4 end @@ -561,8 +561,8 @@ while 1 z=z/nrmz; g1=gt+w*(z*gt')*z; B=B+w*(B*z')*z; else - z=zeros(1,n); - nrmz=0; + z=zeros(1,n); + nrmz=0; g1=gt; end d1=norm(g1); g0=(g1/d1)*B'; @@ -579,9 +579,9 @@ while 1 if abs(fst-f)<abs(f)*.01 ajp=ajp-10*n; else - ajp=ajpp; + ajp=ajpp; end - h=h1*dx/3; + h=h1*dx/3; k=k-1; break end @@ -603,15 +603,15 @@ while 1 if trx f=feval(fun,x',varargin{:}); else - f=feval(fun,x,varargin{:}); + f=feval(fun,x,varargin{:}); end n_f_evals=n_f_evals+1; if h1*f==Inf if dispwarn disp(errmes) - disp(error5) + disp(error5) end - exitflag=-7; + exitflag=-7; if trx x=x'; end @@ -648,7 +648,7 @@ while 1 return end if fc<=cnteps - FP=1; + FP=1; fc=0; else FP=0; @@ -669,7 +669,7 @@ while 1 if isnan(f) disp(error31) else - disp(error32) + disp(error32) end end if ksm || kc>=mxtc @@ -681,13 +681,13 @@ while 1 else k2=k2+1; k1=0; - hp=hp/dq; + hp=hp/dq; x=x1; - f=f1; + f=f1; knan=1; if constr - FP=FP1; - fp=fp1; + FP=FP1; + fp=fp1; end end % STEP SIZE IS ZERO TO THE EXTENT OF EPSNORM @@ -704,20 +704,20 @@ while 1 end return else - x=x1; - f=f1; - hp=hp*10; + x=x1; + f=f1; + hp=hp*10; ksm=1; if constr - FP=FP1; - fp=fp1; + FP=FP1; + fp=fp1; end end % USE SMALLER STEP elseif h1*f<h1*gamma^sign(f1)*f1 if ksm break - end + end k2=k2+1;k1=0; hp=hp/dq; x=x1;f=f1; if constr FP=FP1; @@ -725,12 +725,12 @@ while 1 end if kc>=mxtc, break, end % 1-D OPTIMIZER IS LEFT BEHIND - else + else if h1*f<=h1*f1 break end % USE LARGER STEP - k1=k1+1; + k1=k1+1; if k2>0 kc=kc+1; end @@ -759,12 +759,12 @@ while 1 if kg==1 h=h*(kk-des+1); else - h=h*sqrt(kk-des+1); + h=h*sqrt(kk-des+1); end elseif kk<des h=h*sqrt(kk/des); end - + stepvanish=stepvanish+ksm; % ----} % COMPUTE THE GRADIENT ----{ @@ -775,13 +775,13 @@ while 1 if trx g=apprgrdn(x',fp,fun,deltax',1,varargin{:}); else - g=apprgrdn(x ,fp,fun,deltax,1,varargin{:}); + g=apprgrdn(x ,fp,fun,deltax,1,varargin{:}); end else if trx g=apprgrdn(x',f,fun,deltax',1,varargin{:}); else - g=apprgrdn(x ,f,fun,deltax ,1,varargin{:}); + g=apprgrdn(x ,f,fun,deltax ,1,varargin{:}); end end n_f_evals=n_f_evals+n; @@ -789,7 +789,7 @@ while 1 if trx g=feval(grad,x',varargin{:}); else - g=feval(grad,x,varargin{:}); + g=feval(grad,x,varargin{:}); end n_grad_evals=n_grad_evals+1; end @@ -843,14 +843,14 @@ while 1 if trx gc=apprgrdn(x',fc,func,deltax',0); else - gc=apprgrdn(x ,fc,func,deltax ,0); + gc=apprgrdn(x ,fc,func,deltax ,0); end n_constraint_evals=n_constraint_evals+n; else if trx gc=feval(gradc,x'); else - gc=feval(gradc,x ); + gc=feval(gradc,x ); end n_constraint_gradient_evals=n_constraint_gradient_evals+1; end @@ -891,7 +891,7 @@ while 1 end g=g+PenCoef*gc; ng=norm(g); if Reset - if dispwarn + if dispwarn disp(wrnmes) disp(warn21) end @@ -915,7 +915,7 @@ while 1 gnorms(1)=ng; nng=(prod(gnorms(1:knorms)))^(1/knorms); end - + % DISPLAY THE CURRENT VALUES ----{ if k==ld disp('Iter.# ..... Function ... Step Value ... Gradient Norm '); @@ -954,20 +954,20 @@ while 1 disp(wrnmes) disp(warn09) end - x=xrec; - f=frec; - g=grec; - ng=norm(g); + x=xrec; + f=frec; + g=grec; + ng=norm(g); krerun=krerun+1; h=h1*max([dx,detxr*norm(x)])/krerun; - warnno=2; + warnno=2; break else h=h*10; end elseif abs(f-frec)> optim.TolFun*abs(f) && ... norm(x-xrec)<optim.TolX*norm(x) && constr - + elseif abs(f-fopt)<=optim.TolFun*abs(f) || ... abs(f)<=lowfbound || ... (abs(f-fopt)<=optim.TolFun && termx>=limxterm ) @@ -992,7 +992,7 @@ while 1 else exitflag=k; if dispwarn - disp(termwarn0); + disp(termwarn0); end end if trx @@ -1024,9 +1024,9 @@ while 1 end % ITERATIONS LIMIT if(k==optim.MaxIter) - exitflag=-9; + exitflag=-9; if trx - x=x'; + x=x'; end if dispwarn disp(wrnmes) @@ -1042,7 +1042,7 @@ while 1 disp(termwarn1) disp(warn1) end - exitflag=-8; + exitflag=-8; if trx x=x'; end @@ -1056,7 +1056,7 @@ while 1 disp(warn1) end if nzero>=3 - exitflag=-8; + exitflag=-8; if trx x=x'; end @@ -1068,13 +1068,13 @@ while 1 if trx f=feval(fun,x',varargin{:}); else - f=feval(fun,x,varargin{:}); + f=feval(fun,x,varargin{:}); end n_f_evals=n_f_evals+1; if abs(f)==Inf if dispwarn disp(errmes) - disp(error32) + disp(error32) end exitflag=-3; if trx @@ -1083,8 +1083,8 @@ while 1 return elseif isnan(f) if dispwarn - disp(errmes) - disp(error32) + disp(errmes) + disp(error32) end exitflag=-3; if trx @@ -1093,46 +1093,46 @@ while 1 return end if app - deltax=sign(g0); + deltax=sign(g0); idx=find(deltax==0); - deltax(idx)=ones(size(idx)); + deltax(idx)=ones(size(idx)); deltax=h1*ddx*deltax; - if trx + if trx g=apprgrdn(x',f,fun,deltax',1,varargin{:}); else g=apprgrdn(x,f,fun,deltax,1,varargin{:}); end n_f_evals=n_f_evals+n; else - if trx + if trx g=feval(grad,x',varargin{:}); else - g=feval(grad,x,varargin{:}); + g=feval(grad,x,varargin{:}); end n_grad_evals=n_grad_evals+1; end if size(g,2)==1 - g=g'; + g=g'; end ng=norm(g); if ng==Inf if dispwarn disp(errmes) - disp(error42) + disp(error42) end - exitflag=-4; + exitflag=-4; if trx - x=x'; + x=x'; end return elseif isnan(ng) if dispwarn - disp(errmes) - disp(error41) + disp(errmes) + disp(error41) end - exitflag=-4; + exitflag=-4; if trx - x=x'; + x=x'; end return end @@ -1142,23 +1142,23 @@ while 1 end if ng<=ZeroGrad if dispwarn - disp(termwarn1) + disp(termwarn1) disp(warn1) end - exitflag=-8; + exitflag=-8; if trx x=x'; end return end - h=h1*dx; + h=h1*dx; break end end % ----} % FUNCTION IS FLAT AT THE POINT ----{ if ~constr && abs(f-fopt)<abs(fopt)*optim.TolFun && kcheck>5 && ng<1 - idx=find(abs(g)<=epsnorm2); + idx=find(abs(g)<=epsnorm2); ni=size(idx,2); if ni>=1 && ni<=n/2 && kflat<=3 kflat=kflat+1; @@ -1174,7 +1174,7 @@ while 1 x1(j)=1; elseif abs(y)<1 x1(j)=sign(y); - else + else x1(j)=y; end for i=1:20 @@ -1182,12 +1182,12 @@ while 1 if trx f1=feval(fun,x1',varargin{:}); else - f1=feval(fun,x1,varargin{:}); + f1=feval(fun,x1,varargin{:}); end n_f_evals=n_f_evals+1; if abs(f1)~=Inf && ~isnan(f1) if h1*f1>h1*fm - y=x1(j); + y=x1(j); fm=f1; elseif h1*f2>h1*f1 break @@ -1205,19 +1205,19 @@ while 1 if trx gt=apprgrdn(x1',fm,fun,deltax',1,varargin{:}); else - gt=apprgrdn(x1 ,fm,fun,deltax ,1,varargin{:}); + gt=apprgrdn(x1 ,fm,fun,deltax ,1,varargin{:}); end n_f_evals=n_f_evals+n; else if trx gt=feval(grad,x1',varargin{:}); else - gt=feval(grad,x1,varargin{:}); + gt=feval(grad,x1,varargin{:}); end n_grad_evals=n_grad_evals+1; end if size(gt,2)==1 - gt=gt'; + gt=gt'; end ngt=norm(gt); if ~isnan(ngt) && ngt>epsnorm2 @@ -1225,11 +1225,11 @@ while 1 disp(warn32) end optim.TolFun=optim.TolFun/5; - x=x1; - g=gt; - ng=ngt; - f=fm; - h=h1*dx/3; + x=x1; + g=gt; + ng=ngt; + f=fm; + h=h1*dx/3; break end end @@ -1238,6 +1238,6 @@ while 1 % ----} end % iterations end % restart -% end of the function -% -end \ No newline at end of file + % end of the function + % + end \ No newline at end of file diff --git a/matlab/options2cell.m b/matlab/options2cell.m index 3ff8ef2274..dcf87748a6 100644 --- a/matlab/options2cell.m +++ b/matlab/options2cell.m @@ -2,10 +2,10 @@ function c = options2cell(o) % Converts an option structure as a cell of NAME and VALUE pairs. % -% INPUTS +% INPUTS % o o matlab's structure holding a set of options (each field name is the name of an option and the associated content is the value of the option). % -% OUTPUTS +% OUTPUTS % o c matlab's cell row array of the form {NAME1, VALUE1, NAME2, VALUE2, NAME3, VALUE3, ...}. % Copyright (C) 2013 Dynare Team. @@ -27,10 +27,10 @@ function c = options2cell(o) s = fieldnames(o); c = {}; -j = 1; - +j = 1; + for i=1:length(s) - c(j) = {s{i}}; - c(j+1) = {o.(s{i})}; - j = j+2; + c(j) = {s{i}}; + c(j+1) = {o.(s{i})}; + j = j+2; end \ No newline at end of file diff --git a/matlab/osr.m b/matlab/osr.m index d579c63ec9..a34df099ae 100644 --- a/matlab/osr.m +++ b/matlab/osr.m @@ -9,18 +9,18 @@ function osr_res = osr(var_list,params,i_var,W) % optimal simple rule % i_var [n_osr_vars by 1 double] indices of osr-variable in % specified in optim_weights in declaration order -% W [M_.endo_nbr by M_.endo_nbr sparse matrix] Weighting matrix for variance of endogenous variables -% +% W [M_.endo_nbr by M_.endo_nbr sparse matrix] Weighting matrix for variance of endogenous variables +% % OUTPUTS % osr_res: [structure] results structure containing: % - objective_function [scalar double] value of the objective % function at the optimum -% - optim_params [structure] parameter values at the optimum -% -% +% - optim_params [structure] parameter values at the optimum +% +% % SPECIAL REQUIREMENTS % none. -% +% % Copyright (C) 2001-2016 Dynare Team % % This file is part of Dynare. @@ -38,7 +38,7 @@ function osr_res = 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; diff --git a/matlab/osr1.m b/matlab/osr1.m index ae7c6afeab..bd19412ca3 100644 --- a/matlab/osr1.m +++ b/matlab/osr1.m @@ -9,13 +9,13 @@ function osr_res = osr1(i_params,i_var,weights) % osr_res: [structure] results structure containing: % - objective_function [scalar double] value of the objective % function at the optimum -% - optim_params [structure] parameter values at the optimum -% +% - optim_params [structure] parameter values at the optimum +% % Algorithm: -% +% % Uses Newton-type optimizer csminwel to directly solve quadratic % osr-problem -% +% % Copyright (C) 2005-2016 Dynare Team % % This file is part of Dynare. @@ -80,7 +80,7 @@ if isfield(options_.osr,'maxit') || isfield(options_.osr,'tolf') options_.optim_opt=[options_.optim_opt,',']; end options_.optim_opt=[options_.optim_opt,'''TolFun'',',num2str(options_.osr.tolf),'']; - end + end end end @@ -101,17 +101,17 @@ i_var=unique(i_var); %% do initial checks [loss,info,exit_flag,vx]=osr_obj(t0,i_params,inv_order_var(i_var),weights(i_var,i_var)); if info~=0 - print_info(info, options_.noprint, options_); - else - if ~options_.noprint - fprintf('\nOSR: Initial value of the objective function: %g \n\n',loss); - end + print_info(info, options_.noprint, options_); +else + if ~options_.noprint + fprintf('\nOSR: Initial value of the objective function: %g \n\n',loss); + end end -if ~options_.noprint && isinf(loss) - fprintf('\nOSR: The initial value of the objective function is infinite.\n'); - fprintf('\nOSR: Check whether the unconditional variance of a target variable is infinite\n'); - fprintf('\nOSR: due to the presence of a unit root.\n'); - error('OSR: Initial likelihood is infinite') +if ~options_.noprint && isinf(loss) + fprintf('\nOSR: The initial value of the objective function is infinite.\n'); + fprintf('\nOSR: Check whether the unconditional variance of a target variable is infinite\n'); + fprintf('\nOSR: due to the presence of a unit root.\n'); + error('OSR: Initial likelihood is infinite') end @@ -120,17 +120,17 @@ if isequal(options_.osr.opt_algo,5) elseif isequal(options_.osr.opt_algo,6) error('OSR: OSR does not support opt_algo=6.') elseif isequal(options_.osr.opt_algo,10) - error('OSR: OSR does not support opt_algo=10.') + error('OSR: OSR does not support opt_algo=10.') elseif isequal(options_.osr.opt_algo,11) - error('OSR: OSR does not support opt_algo=11.') + error('OSR: OSR does not support opt_algo=11.') else - -if ~isempty(M_.osr.param_bounds) && ~(ismember(options_.osr.opt_algo,[1,2,5,9]) || ischar(options_.osr.opt_algo)) - error('OSR: OSR with bounds on parameters requires a constrained optimizer, i.e. 1,2,5, or 9.') -end -%%do actual optimization -[p, f, exitflag] = dynare_minimize_objective(str2func('osr_obj'),t0,options_.osr.opt_algo,options_,M_.osr.param_bounds,cellstr(M_.param_names(i_params,:)),[],[], i_params,... - inv_order_var(i_var),weights(i_var,i_var)); + + if ~isempty(M_.osr.param_bounds) && ~(ismember(options_.osr.opt_algo,[1,2,5,9]) || ischar(options_.osr.opt_algo)) + error('OSR: OSR with bounds on parameters requires a constrained optimizer, i.e. 1,2,5, or 9.') + end + %%do actual optimization + [p, f, exitflag] = dynare_minimize_objective(str2func('osr_obj'),t0,options_.osr.opt_algo,options_,M_.osr.param_bounds,cellstr(M_.param_names(i_params,:)),[],[], i_params,... + inv_order_var(i_var),weights(i_var,i_var)); end osr_res.objective_function = f; diff --git a/matlab/osr_obj.m b/matlab/osr_obj.m index 67efbbbc08..d29c7e5307 100644 --- a/matlab/osr_obj.m +++ b/matlab/osr_obj.m @@ -51,14 +51,14 @@ it_ = M_.maximum_lag+1; if info(1) if info(1) == 3 || info(1) == 4 || info(1) == 5 || info(1)==6 ||info(1) == 19 ||... - info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ... - info(1) == 81 || info(1) == 84 || info(1) == 85 + info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ... + info(1) == 81 || info(1) == 84 || info(1) == 85 loss = 1e8; info(4)=info(2); return else loss = 1e8; - info(4)=0.1; + info(4)=0.1; return end end diff --git a/matlab/parallel/AnalyseComputationalEnvironment.m b/matlab/parallel/AnalyseComputationalEnvironment.m index e91e3b3e14..d00ca1b699 100644 --- a/matlab/parallel/AnalyseComputationalEnvironment.m +++ b/matlab/parallel/AnalyseComputationalEnvironment.m @@ -1,658 +1,658 @@ -function [ErrorCode] = AnalyseComputationalEnvironment(DataInput, DataInputAdd) -% PARALLEL CONTEXT -% In a parallel context, this function is used to check the cluster defined by the user. -% If no error happen the function returns 0. The function complies with -% Windows/Linux operating systems and Matlab/Octave software. -% -% -% INPUT/OUTPUT description: -% -% -% DataInput -% is the strcture option_.parallel, with the follow fields: -% -% Local 1 is on local machine, 0 remote -% ComputerName the computer name. -% CPUnbr the CPU's -% UserName the user name for the ComputerName. -% Password the password for the user name in ComputerName. -% RemoteDrive Drive used for Remote computation (data exchange, etc): must be contain 'RemoteFolder'. -% RemoteDirectory Folder in RemoteDrive used for Remote computation. -% MatlabOctavePath Path to MATLAB or Octave executable. -% DynarePath Path to matlab directory within the Dynare installation directory. -% -% This information is typed by the user in the DYNARE configuration file and is parsed by the preprocessor, -% the goal of this function is to check if configuration is correct and if dynare -% can be executed successfully in parallel mode. -% -% -% DataInputAdd -% it is the structure options_.parallel_info. Currently , only the string in the -% field RemoteTmpFolder (the temporary directory created/destroyed on remote -% computer) is used. - -if ispc - [tempo, MasterName]=system('hostname'); - MasterName=deblank(MasterName); -end - -RemoteTmpFolder=DataInputAdd.RemoteTmpFolder; -dynareParallelMkDir(RemoteTmpFolder,DataInput); - - -% The variable ErrorCode is initialized at 0. If there are non problems with -% Local, ComputerName 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 is detected, the values 1, 2, 3... are -% used to specify the type of error or warning. -% -% Value 1: The variable 'Local' has a bad value! -% -% Value 2: The variable 'CPUnbr' has a bad value. For more information -% see http://www.dynare.org/DynareWiki/ParallelDynare. -% 2.1 [warning] The user asks to use more CPU's than those available. -% 2.2 [warning] There are unused CPU's! -% 2.3 [error] NumberOfThreadsPerJob is not a divisor of CPUnbr -% -% -% Value 3: The remote computer is unreachable!!! -% -% Value 4: The fields user name and/or password are/is empty! -% -% Value 5: Remote Drive and/or Remote Folder do not exist! -% -% Value 6: It is impossible write/read files on the remote computer. -% -% Value 7: The values user and/or passwd are incorrect or the user has -% no permissions to execute a Matlab session. Or simply -% Matlab path (MatlabOctavePath) is incorrect! -% -% Value 8: Dynare path (DynarePath) is incorrect! -% -% Value 9: It is impossible delete remote computational temporary files! -% -% -% -% -% Currently when errors are detected execution simply stops and users can -% fix configuration errors according to the error type. - -% Copyright (C) 2009-2017 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; - - -for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' - % and use AnalyseComputationalEnvironment with differents input! - - - % Determine the operating system or software version when necessary - % for different command types. - - OScallerUnix=~ispc; - OScallerWindows=ispc; - OStargetUnix=strcmpi('unix',DataInput(Node).OperatingSystem); - if isempty(DataInput(Node).OperatingSystem) - OStargetUnix=OScallerUnix; - end - OStargetWindows=strcmpi('windows',DataInput(Node).OperatingSystem); - if isempty(DataInput(Node).OperatingSystem) - OStargetWindows=OScallerWindows; - end - - Environment= (OScallerUnix || OStargetUnix); - - skipline(2) - disp(['Testing computer -> ',DataInput(Node).ComputerName,' <- ...']); - skipline(2) - - % The function is composed by two main blocks, determined by the 'Local' - % variable. - - % This check can be removed ... according to the dynare parser - % strategy. - - if ((DataInput(Node).Local == 0) |(DataInput(Node).Local == 1)) - % Continue it is Ok! - disp('Check on Local Variable ..... Ok!'); - skipline() - else - disp('The variable "Local" has a bad value!'); - skipline() - disp('ErrorCode 1.'); - skipline() - ErrorCode=1; - return - end - - % %%%%%%%%%% Local (No Network) Computing %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Here only the multi-core, or multi-processor avaiable on local - % machine are involved in parallel computing. No network - % comunications are required! - - - % In this case we need to check only the variable 'CPUnbr'. - - % We run the parallel code on local computer, so the others fields are automatically - % fixed by Dynare parser. Then the user can also fill them with wrong values. - - - % %%%%%%%%%% Cluster Computing %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Here we can have many computer with multi-core, or multi-processor avaiable on the - % network and involved in parallel computing. - % So in this case we need more sophisticated check. - - - if (DataInput(Node).Local == 0) - - % Now we verify if it is possibile to be connected with the - % remote computer. - - si1=[]; - de1=[]; - - if Environment - if OScallerWindows - [si1 de1]=system(['ping ', DataInput(Node).ComputerName]); - else - [si1 de1]=system(['ping ', DataInput(Node).ComputerName, ' -c 4']); - end - else - [si1 de1]=system(['ping ', DataInput(Node).ComputerName]); - end - - if (si1) - disp(['It is impossibile to ping to the computer with name "',DataInput(Node).ComputerName,'" using the network!']) - skipline() - disp('ErrorCode 3.') - ErrorCode=3; - skipline(2) - else - disp('Check on ComputerName Variable ..... Ok!') - skipline(2) - end - - - % 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. - - if Environment - % This check can be removed ... according to the dynare parser - % strategy. - - if (isempty(DataInput(Node).UserName)) - disp('The fields UserName is empty!') - skipline() - disp('ErrorCode 4.') - skipline(2) - ErrorCode=4; - return - end - disp('Check on UserName Variable ..... Ok!') - skipline(2) - - % This check can be removed ... according to the dynare parser - % strategy. - if (~isempty(DataInput(Node).Password)) - disp('[WARNING] The field Password should be empty under unix or mac!'); - skipline() - disp(['Remove the string ',DataInput(Node).Password,' from this field!']) - skipline() - disp('ErrorCode 4.') - skipline(2) - ErrorCode=4; - else - disp('Check on Password Variable ..... Ok!') - skipline(2) - end - else - - % This check can be removed ... according to the dynare parser - % strategy. - - if (isempty(DataInput(Node).UserName)) || (isempty(DataInput(Node).Password)) - disp('The fields UserName and/or Password are/is empty!'); - skipline() - disp('ErrorCode 4.') - skipline(2) - ErrorCode=4; - return - end - disp('Check on UserName Variable ..... Ok!'); - skipline() - disp('Check on Password Variable ..... Ok!'); - skipline() - end - - % Now we very if RemoteDrive and/or RemoteDirectory exist on remote - % computer! - - if Environment - - % This check can be removed ... according to the dynare parser - % strategy. - - if isempty(DataInput(Node).RemoteDirectory) - disp('The field RemoteDirectory is empty!') - skipline() - disp('ErrorCode 5.') - skipline() - ErrorCode=5; - return - end - - % This check can be removed ... according to the dynare parser - % strategy. - - if (~isempty(DataInput(Node).RemoteDrive)) - disp('[WARNING] The fields RemoteDrive should be empty under unix or mac!') - skipline() - disp(['remove the string ',DataInput(Node).RemoteDrive,' from this field!']) - skipline() - disp('ErrorCode 5.') - skipline(2) - ErrorCode=5; - end - - si2=[]; - de2=[]; - if ~isempty(DataInput(Node).Port) - ssh_token = ['-p ',DataInput(Node).Port]; - else - ssh_token = ''; - end - - [si2 de2]=system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' ls ',DataInput(Node).RemoteDirectory,'/',RemoteTmpFolder,'/']); - - if (si2) - disp ('Remote Directory does not exist or is not reachable!') - skipline() - disp('ErrorCode 5.') - skipline(2) - ErrorCode=5; - return - end - - disp('Check on RemoteDirectory Variable ..... Ok!') - skipline(2) - disp('Check on RemoteDrive Variable ..... Ok!') - skipline(2) - - else - % This check can be removed ... according to the dynare parser - % strategy. - - if (isempty(DataInput(Node).RemoteDrive)||isempty(DataInput(Node).RemoteDirectory)) - disp('Remote RemoteDrive and/or RemoteDirectory is/are empty!') - skipline() - disp('ErrorCode 5.') - skipline(2) - ErrorCode=5; - return - end - - - si2=[]; - de2=[]; - [si2 de2]=system(['dir \\',DataInput(Node).ComputerName,'\',DataInput(Node).RemoteDrive,'$\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder]); - - if (si2) - disp ('Remote Directory does not exist or it is not reachable!') - skipline() - disp('ErrorCode 5.') - skipline(2) - ErrorCode=5; - return - end - - disp('Check on RemoteDirectory Variable ..... Ok!') - skipline(2) - disp('Check on RemoteDrive Variable ..... Ok!') - skipline(2) - - end - - - % Now we verify if it possible to exchange data with the remote - % computer: - - - % Build a command file to test the matlab execution and dynare path ... - - fid = fopen('Tracing.m', 'w+'); - s1=(['fT = fopen(''MatlabOctaveIsOk.txt'',''w+'');\n']); - s2='fclose(fT);\n'; - SBS=strfind(DataInput(Node).DynarePath,'\'); - DPStr=DataInput(Node).DynarePath; - if isempty(SBS) - DPStrNew=DPStr; - else - DPStrNew=[DPStr(1:SBS(1)),'\']; - for j=2:length(SBS) - DPStrNew=[DPStrNew,DPStr(SBS(j-1)+1:SBS(j)),'\']; - end - DPStrNew=[DPStrNew,DPStr(SBS(end)+1:end)]; - end - s3=['addpath(''',DPStrNew,'''),\n']; - s4=['try,\n dynareroot = dynare_config();\n']; - s41=([' fT = fopen(''DynareIsOk.txt'',''w+'');\n']); - s42=' fclose(fT);\n'; - s5=['catch,\n']; - s51=([' fT = fopen(''DynareFailed.txt'',''w+'');\n']); - s52=' fclose(fT);\n'; - s6=['end,\n']; - s7=['if ismac,\n']; - s71=([' fT = fopen(''IsMac.txt'',''w+'');\n']); - s72=' fclose(fT);\n'; - s8=['end,\n']; - send='exit'; - StrCommand=([s1,s2,s3,s4,s41,s42,s5,s51,s52,s6,s7,s71,s72,s8,send]); - - % Mettere controllo su NbW ... - % if isoctave - % NbW = fprintf(fid,StrCommand, '%s'); - % else - NbW = fprintf(fid,StrCommand, '%s'); - % end - fclose(fid); - - dynareParallelSendFiles('Tracing.m', RemoteTmpFolder,DataInput(Node)); - FindTracing = dynareParallelDir('Tracing.m', RemoteTmpFolder,DataInput(Node)); - - delete ('Tracing.m'); - - if (isempty(FindTracing)) - disp('It is impossible to exchange data with Remote Drive and/or Remote Directory! ErrorCode 6.') - skipline() - disp('ErrorCode 6.') - skipline(2) - ErrorCode=6; - return - else - disp('Check on Exchange File with Remote Computer ..... Ok!') - skipline(2) - end - - - % Now we verify if it is possible execute a matlab/octave section on remote - % machine when the user is .UserName with password .Password and - % the path is MatlabOctavePath. - - if Environment - if ~isempty(DataInput(Node).Port) - ssh_token = ['-p ',DataInput(Node).Port]; - else - ssh_token = ''; - end - if strfind([DataInput(Node).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa! - system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' "cd ',DataInput(Node).RemoteDirectory,'/',RemoteTmpFolder, '; ', DataInput(Node).MatlabOctavePath, ' Tracing.m;" &']); - else - system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' "cd ',DataInput(Node).RemoteDirectory,'/',RemoteTmpFolder, '; ', DataInput(Node).MatlabOctavePath, ' -nosplash -nodesktop -minimize -r Tracing;" &']); - end - else - if ~strcmp(DataInput(Node).ComputerName,MasterName) % run on remote machine - if strfind([DataInput(Node).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa! - [NonServeS NenServeD]=system(['start /B psexec \\',DataInput(Node).ComputerName,' -e -u ',DataInput(Node).UserName,' -p ',DataInput(Node).Password,' -W ',DataInput(Node).RemoteDrive,':\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder ' -low ',DataInput(Node).MatlabOctavePath,' Tracing.m']); - else - [NonServeS NenServeD]=system(['start /B psexec \\',DataInput(Node).ComputerName,' -e -u ',DataInput(Node).UserName,' -p ',DataInput(Node).Password,' -W ',DataInput(Node).RemoteDrive,':\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder ' -low ',DataInput(Node).MatlabOctavePath,' -nosplash -nodesktop -minimize -r Tracing']); - end - else % run on local machine via the network: user and passwd cannot be used! - if strfind([DataInput(Node).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa! - [NonServeS NenServeD]=system(['start /B psexec \\',DataInput(Node).ComputerName,' -e ',' -W ',DataInput(Node).RemoteDrive,':\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder ' -low ',DataInput(Node).MatlabOctavePath,' Tracing.m']); - else - [NonServeS NenServeD]=system(['start /B psexec \\',DataInput(Node).ComputerName,' -e ',' -W ',DataInput(Node).RemoteDrive,':\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder ' -low ',DataInput(Node).MatlabOctavePath,' -nosplash -nodesktop -minimize -r Tracing']); - end - end - - end - - % Timer da fissare, nei valori di attesa! - - t1=fix(clock); - - if t1(5)+1>60 - t2=2; - else - t2=t1(5)+1; - end - - Flag=0; - - while (1) - if Flag==0 - disp('Try to run matlab/octave on remote machine ... ') - skipline() - disp('please wait ... ') - skipline() - Flag=1; - end - nt=fix(clock); - nt(5)-t2; - - if (~isempty (dynareParallelDir('MatlabOctaveIsOk.txt',RemoteTmpFolder,DataInput(Node)))) || ((nt(5)-t2)>0) - if ((nt(5)-t2)>0) - ErrorCode=7; - end - break - end - - end - - if (ErrorCode==7) - - disp ('It is not possible execute a matlab session on remote machine!') - skipline() - disp('ErrorCode 7.') - skipline(2) - ErrorCode=7; - dynareParallelRmDir(RemoteTmpFolder,DataInput(Node)); - return - else - disp('Check on MatlabOctave Path and MatlabOctave Program Execution on remote machine ..... Ok!') - skipline(2) - - % Now we verify if the DynarePath is correct ... - disp('Check the Dynare path on remote machine ... ') - skipline() - disp('please wait ... ') - skipline(2) - pause(2) - - if isempty(dynareParallelDir('DynareIsOk.txt',RemoteTmpFolder,DataInput(Node))) - ErrorCode=8; - end - - if (ErrorCode==8) - disp ('The DynarePath is incorrect!') - skipline() - disp('ErrorCode 8.') - skipline(2) - ErrorCode=8; - dynareParallelRmDir(RemoteTmpFolder,DataInput(Node)); - return - else - disp('Check on Dynare Path remote machine ..... Ok!') - if isempty(dynareParallelDir('IsMac.txt',RemoteTmpFolder,DataInput(Node))) - RemoteEnvironment=Environment; - else - RemoteEnvironment=2; - end - skipline(2) - end - end - - - % Now we verify if it is possible delete remote computational traces! - - dynareParallelRmDir(RemoteTmpFolder,DataInput(Node)); - - si3=[]; - - si3=dynareParallelDir('Tracing.m', RemoteTmpFolder,DataInput(Node)); - - if (isempty(si3)) - disp ('Check on Delete Remote Computational Traces ..... Ok!') - skipline(2) - else - disp ('It is impossible to delete temporary files on remote machine!') - skipline() - disp('ErrorCode 9.') - skipline(2) - ErrorCode=9; - return - end - - - end - % Now we check the variable 'CPUnbr'. - - % This check can be removed ... according to the dynare parser - % strategy. - - yn=isempty(DataInput(Node).CPUnbr); - - if yn==1 - % The field is empty! - disp('The field "CPUnbr" is empty!') - skipline() - disp('ErrorCode 2.') - skipline(2) - ErrorCode=2; - return - end - - % This check can be removed ... according to the dynare parser - % strategy. - - - - % We look for the information on local computer hardware. - - si0=[]; - de0=[]; - - Environment1=Environment; - disp('Checking Hardware please wait ...'); - if (DataInput(Node).Local == 1) - if Environment - if ~ismac - [si0 de0]=system('grep processor /proc/cpuinfo'); - else - [si0 de0]=system('sysctl -n hw.ncpu'); - Environment1=2; - end - else - [si0 de0]=system(['psinfo \\']); - end - else - if Environment - if ~isempty(DataInput(Node).Port) - ssh_token = ['-p ',DataInput(Node).Port]; - else - ssh_token = ''; - end - if OStargetUnix - if RemoteEnvironment ==1 - [si0 de0]=system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' grep processor /proc/cpuinfo']); - else % it is MAC - [si0 de0]=system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' sysctl -n hw.ncpu']); - Environment1=2; - end - else - [si0 de0]=system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' psinfo']); - end - else - [si0 de0]=system(['psinfo \\',DataInput(Node).ComputerName,' -u ',DataInput(Node).UserName,' -p ',DataInput(Node).Password]); - end - end - - - RealCPUnbr=''; -% keyboard; - RealCPUnbr=GiveCPUnumber(de0,Environment1); - - % Questo controllo penso che si possa MIGLIORARE!!!!! - if isempty (RealCPUnbr) && Environment1==0 - [si0 de0]=system(['psinfo \\',DataInput(Node).ComputerName]); - end - RealCPUnbr=GiveCPUnumber(de0,Environment1); - - if isempty (RealCPUnbr) - % An error occurred when we try to know the Cpu/Cores - % numbers. - disp('It is impossible determine the number of Cpu/Processor avaiable on this machine!') - skipline() - disp('ErrorCode 2.') - skipline() - if Environment - disp('Check the command "$less /proc/cpuinfo" ... !') - else - disp('Check if the pstools are installed and are in machine path! And check the command "psinfo \\"') - end - skipline() - ErrorCode=2; - return - end - - - % Trasforming the input data provided in a form [n1:n2] in a single numerical - % value. - - - CPUnbrUser=length(DataInput(Node).CPUnbr); - maxCPUnbrUser=max(DataInput(Node).CPUnbr)+1; - - disp(['Hardware has ', num2str(RealCPUnbr),' Cpu/Cores!']) - disp(['User requires ',num2str(CPUnbrUser),' Cpu/Cores!']) - if CPUnbrUser==RealCPUnbr - % It is Ok! - disp('Check on CPUnbr Variable ..... Ok!') - skipline(3) - end - - if CPUnbrUser > RealCPUnbr - disp('Warning! The user asks to use more CPU''s than those available.') - skipline(2) - ErrorCode=2.1; - end - if CPUnbrUser < RealCPUnbr - disp('Warning! There are unused CPU''s!') - skipline(2) - ErrorCode=2.2; - end - - if mod(length(DataInput(Node).CPUnbr),DataInput(Node).NumberOfThreadsPerJob) - skipline() - disp(['NumberOfThreadsPerJob = ',int2str(DataInput(Node).NumberOfThreadsPerJob),' is not an exact divisor of number of CPUs = ',int2str(DataInput(Node).CPUnbr),'!']) - disp([' You must re-set properly NumberOfThreadsPerJob of node ' int2str(Node) ' ' DataInput(Node).ComputerName]) - disp(' in your configuration file') - skipline() - ErrorCode=2.3; - end - - disp(['Test for Cluster computation, computer ',DataInput(Node).ComputerName, ' ..... Passed!']) - skipline(2) +function [ErrorCode] = AnalyseComputationalEnvironment(DataInput, DataInputAdd) +% PARALLEL CONTEXT +% In a parallel context, this function is used to check the cluster defined by the user. +% If no error happen the function returns 0. The function complies with +% Windows/Linux operating systems and Matlab/Octave software. +% +% +% INPUT/OUTPUT description: +% +% +% DataInput +% is the strcture option_.parallel, with the follow fields: +% +% Local 1 is on local machine, 0 remote +% ComputerName the computer name. +% CPUnbr the CPU's +% UserName the user name for the ComputerName. +% Password the password for the user name in ComputerName. +% RemoteDrive Drive used for Remote computation (data exchange, etc): must be contain 'RemoteFolder'. +% RemoteDirectory Folder in RemoteDrive used for Remote computation. +% MatlabOctavePath Path to MATLAB or Octave executable. +% DynarePath Path to matlab directory within the Dynare installation directory. +% +% This information is typed by the user in the DYNARE configuration file and is parsed by the preprocessor, +% the goal of this function is to check if configuration is correct and if dynare +% can be executed successfully in parallel mode. +% +% +% DataInputAdd +% it is the structure options_.parallel_info. Currently , only the string in the +% field RemoteTmpFolder (the temporary directory created/destroyed on remote +% computer) is used. + +if ispc + [tempo, MasterName]=system('hostname'); + MasterName=deblank(MasterName); +end + +RemoteTmpFolder=DataInputAdd.RemoteTmpFolder; +dynareParallelMkDir(RemoteTmpFolder,DataInput); + + +% The variable ErrorCode is initialized at 0. If there are non problems with +% Local, ComputerName 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 is detected, the values 1, 2, 3... are +% used to specify the type of error or warning. +% +% Value 1: The variable 'Local' has a bad value! +% +% Value 2: The variable 'CPUnbr' has a bad value. For more information +% see http://www.dynare.org/DynareWiki/ParallelDynare. +% 2.1 [warning] The user asks to use more CPU's than those available. +% 2.2 [warning] There are unused CPU's! +% 2.3 [error] NumberOfThreadsPerJob is not a divisor of CPUnbr +% +% +% Value 3: The remote computer is unreachable!!! +% +% Value 4: The fields user name and/or password are/is empty! +% +% Value 5: Remote Drive and/or Remote Folder do not exist! +% +% Value 6: It is impossible write/read files on the remote computer. +% +% Value 7: The values user and/or passwd are incorrect or the user has +% no permissions to execute a Matlab session. Or simply +% Matlab path (MatlabOctavePath) is incorrect! +% +% Value 8: Dynare path (DynarePath) is incorrect! +% +% Value 9: It is impossible delete remote computational temporary files! +% +% +% +% +% Currently when errors are detected execution simply stops and users can +% fix configuration errors according to the error type. + +% Copyright (C) 2009-2017 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; + + +for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' + % and use AnalyseComputationalEnvironment with differents input! + + + % Determine the operating system or software version when necessary + % for different command types. + + OScallerUnix=~ispc; + OScallerWindows=ispc; + OStargetUnix=strcmpi('unix',DataInput(Node).OperatingSystem); + if isempty(DataInput(Node).OperatingSystem) + OStargetUnix=OScallerUnix; + end + OStargetWindows=strcmpi('windows',DataInput(Node).OperatingSystem); + if isempty(DataInput(Node).OperatingSystem) + OStargetWindows=OScallerWindows; + end + + Environment= (OScallerUnix || OStargetUnix); + + skipline(2) + disp(['Testing computer -> ',DataInput(Node).ComputerName,' <- ...']); + skipline(2) + + % The function is composed by two main blocks, determined by the 'Local' + % variable. + + % This check can be removed ... according to the dynare parser + % strategy. + + if ((DataInput(Node).Local == 0) |(DataInput(Node).Local == 1)) + % Continue it is Ok! + disp('Check on Local Variable ..... Ok!'); + skipline() + else + disp('The variable "Local" has a bad value!'); + skipline() + disp('ErrorCode 1.'); + skipline() + ErrorCode=1; + return + end + + % %%%%%%%%%% Local (No Network) Computing %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + % Here only the multi-core, or multi-processor avaiable on local + % machine are involved in parallel computing. No network + % comunications are required! + + + % In this case we need to check only the variable 'CPUnbr'. + + % We run the parallel code on local computer, so the others fields are automatically + % fixed by Dynare parser. Then the user can also fill them with wrong values. + + + % %%%%%%%%%% Cluster Computing %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + % Here we can have many computer with multi-core, or multi-processor avaiable on the + % network and involved in parallel computing. + % So in this case we need more sophisticated check. + + + if (DataInput(Node).Local == 0) + + % Now we verify if it is possibile to be connected with the + % remote computer. + + si1=[]; + de1=[]; + + if Environment + if OScallerWindows + [si1 de1]=system(['ping ', DataInput(Node).ComputerName]); + else + [si1 de1]=system(['ping ', DataInput(Node).ComputerName, ' -c 4']); + end + else + [si1 de1]=system(['ping ', DataInput(Node).ComputerName]); + end + + if (si1) + disp(['It is impossibile to ping to the computer with name "',DataInput(Node).ComputerName,'" using the network!']) + skipline() + disp('ErrorCode 3.') + ErrorCode=3; + skipline(2) + else + disp('Check on ComputerName Variable ..... Ok!') + skipline(2) + end + + + % 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. + + if Environment + % This check can be removed ... according to the dynare parser + % strategy. + + if (isempty(DataInput(Node).UserName)) + disp('The fields UserName is empty!') + skipline() + disp('ErrorCode 4.') + skipline(2) + ErrorCode=4; + return + end + disp('Check on UserName Variable ..... Ok!') + skipline(2) + + % This check can be removed ... according to the dynare parser + % strategy. + if (~isempty(DataInput(Node).Password)) + disp('[WARNING] The field Password should be empty under unix or mac!'); + skipline() + disp(['Remove the string ',DataInput(Node).Password,' from this field!']) + skipline() + disp('ErrorCode 4.') + skipline(2) + ErrorCode=4; + else + disp('Check on Password Variable ..... Ok!') + skipline(2) + end + else + + % This check can be removed ... according to the dynare parser + % strategy. + + if (isempty(DataInput(Node).UserName)) || (isempty(DataInput(Node).Password)) + disp('The fields UserName and/or Password are/is empty!'); + skipline() + disp('ErrorCode 4.') + skipline(2) + ErrorCode=4; + return + end + disp('Check on UserName Variable ..... Ok!'); + skipline() + disp('Check on Password Variable ..... Ok!'); + skipline() + end + + % Now we very if RemoteDrive and/or RemoteDirectory exist on remote + % computer! + + if Environment + + % This check can be removed ... according to the dynare parser + % strategy. + + if isempty(DataInput(Node).RemoteDirectory) + disp('The field RemoteDirectory is empty!') + skipline() + disp('ErrorCode 5.') + skipline() + ErrorCode=5; + return + end + + % This check can be removed ... according to the dynare parser + % strategy. + + if (~isempty(DataInput(Node).RemoteDrive)) + disp('[WARNING] The fields RemoteDrive should be empty under unix or mac!') + skipline() + disp(['remove the string ',DataInput(Node).RemoteDrive,' from this field!']) + skipline() + disp('ErrorCode 5.') + skipline(2) + ErrorCode=5; + end + + si2=[]; + de2=[]; + if ~isempty(DataInput(Node).Port) + ssh_token = ['-p ',DataInput(Node).Port]; + else + ssh_token = ''; + end + + [si2 de2]=system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' ls ',DataInput(Node).RemoteDirectory,'/',RemoteTmpFolder,'/']); + + if (si2) + disp ('Remote Directory does not exist or is not reachable!') + skipline() + disp('ErrorCode 5.') + skipline(2) + ErrorCode=5; + return + end + + disp('Check on RemoteDirectory Variable ..... Ok!') + skipline(2) + disp('Check on RemoteDrive Variable ..... Ok!') + skipline(2) + + else + % This check can be removed ... according to the dynare parser + % strategy. + + if (isempty(DataInput(Node).RemoteDrive)||isempty(DataInput(Node).RemoteDirectory)) + disp('Remote RemoteDrive and/or RemoteDirectory is/are empty!') + skipline() + disp('ErrorCode 5.') + skipline(2) + ErrorCode=5; + return + end + + + si2=[]; + de2=[]; + [si2 de2]=system(['dir \\',DataInput(Node).ComputerName,'\',DataInput(Node).RemoteDrive,'$\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder]); + + if (si2) + disp ('Remote Directory does not exist or it is not reachable!') + skipline() + disp('ErrorCode 5.') + skipline(2) + ErrorCode=5; + return + end + + disp('Check on RemoteDirectory Variable ..... Ok!') + skipline(2) + disp('Check on RemoteDrive Variable ..... Ok!') + skipline(2) + + end + + + % Now we verify if it possible to exchange data with the remote + % computer: + + + % Build a command file to test the matlab execution and dynare path ... + + fid = fopen('Tracing.m', 'w+'); + s1=(['fT = fopen(''MatlabOctaveIsOk.txt'',''w+'');\n']); + s2='fclose(fT);\n'; + SBS=strfind(DataInput(Node).DynarePath,'\'); + DPStr=DataInput(Node).DynarePath; + if isempty(SBS) + DPStrNew=DPStr; + else + DPStrNew=[DPStr(1:SBS(1)),'\']; + for j=2:length(SBS) + DPStrNew=[DPStrNew,DPStr(SBS(j-1)+1:SBS(j)),'\']; + end + DPStrNew=[DPStrNew,DPStr(SBS(end)+1:end)]; + end + s3=['addpath(''',DPStrNew,'''),\n']; + s4=['try,\n dynareroot = dynare_config();\n']; + s41=([' fT = fopen(''DynareIsOk.txt'',''w+'');\n']); + s42=' fclose(fT);\n'; + s5=['catch,\n']; + s51=([' fT = fopen(''DynareFailed.txt'',''w+'');\n']); + s52=' fclose(fT);\n'; + s6=['end,\n']; + s7=['if ismac,\n']; + s71=([' fT = fopen(''IsMac.txt'',''w+'');\n']); + s72=' fclose(fT);\n'; + s8=['end,\n']; + send='exit'; + StrCommand=([s1,s2,s3,s4,s41,s42,s5,s51,s52,s6,s7,s71,s72,s8,send]); + + % Mettere controllo su NbW ... + % if isoctave + % NbW = fprintf(fid,StrCommand, '%s'); + % else + NbW = fprintf(fid,StrCommand, '%s'); + % end + fclose(fid); + + dynareParallelSendFiles('Tracing.m', RemoteTmpFolder,DataInput(Node)); + FindTracing = dynareParallelDir('Tracing.m', RemoteTmpFolder,DataInput(Node)); + + delete ('Tracing.m'); + + if (isempty(FindTracing)) + disp('It is impossible to exchange data with Remote Drive and/or Remote Directory! ErrorCode 6.') + skipline() + disp('ErrorCode 6.') + skipline(2) + ErrorCode=6; + return + else + disp('Check on Exchange File with Remote Computer ..... Ok!') + skipline(2) + end + + + % Now we verify if it is possible execute a matlab/octave section on remote + % machine when the user is .UserName with password .Password and + % the path is MatlabOctavePath. + + if Environment + if ~isempty(DataInput(Node).Port) + ssh_token = ['-p ',DataInput(Node).Port]; + else + ssh_token = ''; + end + if strfind([DataInput(Node).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa! + system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' "cd ',DataInput(Node).RemoteDirectory,'/',RemoteTmpFolder, '; ', DataInput(Node).MatlabOctavePath, ' Tracing.m;" &']); + else + system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' "cd ',DataInput(Node).RemoteDirectory,'/',RemoteTmpFolder, '; ', DataInput(Node).MatlabOctavePath, ' -nosplash -nodesktop -minimize -r Tracing;" &']); + end + else + if ~strcmp(DataInput(Node).ComputerName,MasterName) % run on remote machine + if strfind([DataInput(Node).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa! + [NonServeS NenServeD]=system(['start /B psexec \\',DataInput(Node).ComputerName,' -e -u ',DataInput(Node).UserName,' -p ',DataInput(Node).Password,' -W ',DataInput(Node).RemoteDrive,':\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder ' -low ',DataInput(Node).MatlabOctavePath,' Tracing.m']); + else + [NonServeS NenServeD]=system(['start /B psexec \\',DataInput(Node).ComputerName,' -e -u ',DataInput(Node).UserName,' -p ',DataInput(Node).Password,' -W ',DataInput(Node).RemoteDrive,':\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder ' -low ',DataInput(Node).MatlabOctavePath,' -nosplash -nodesktop -minimize -r Tracing']); + end + else % run on local machine via the network: user and passwd cannot be used! + if strfind([DataInput(Node).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa! + [NonServeS NenServeD]=system(['start /B psexec \\',DataInput(Node).ComputerName,' -e ',' -W ',DataInput(Node).RemoteDrive,':\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder ' -low ',DataInput(Node).MatlabOctavePath,' Tracing.m']); + else + [NonServeS NenServeD]=system(['start /B psexec \\',DataInput(Node).ComputerName,' -e ',' -W ',DataInput(Node).RemoteDrive,':\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder ' -low ',DataInput(Node).MatlabOctavePath,' -nosplash -nodesktop -minimize -r Tracing']); + end + end + + end + + % Timer da fissare, nei valori di attesa! + + t1=fix(clock); + + if t1(5)+1>60 + t2=2; + else + t2=t1(5)+1; + end + + Flag=0; + + while (1) + if Flag==0 + disp('Try to run matlab/octave on remote machine ... ') + skipline() + disp('please wait ... ') + skipline() + Flag=1; + end + nt=fix(clock); + nt(5)-t2; + + if (~isempty (dynareParallelDir('MatlabOctaveIsOk.txt',RemoteTmpFolder,DataInput(Node)))) || ((nt(5)-t2)>0) + if ((nt(5)-t2)>0) + ErrorCode=7; + end + break + end + + end + + if (ErrorCode==7) + + disp ('It is not possible execute a matlab session on remote machine!') + skipline() + disp('ErrorCode 7.') + skipline(2) + ErrorCode=7; + dynareParallelRmDir(RemoteTmpFolder,DataInput(Node)); + return + else + disp('Check on MatlabOctave Path and MatlabOctave Program Execution on remote machine ..... Ok!') + skipline(2) + + % Now we verify if the DynarePath is correct ... + disp('Check the Dynare path on remote machine ... ') + skipline() + disp('please wait ... ') + skipline(2) + pause(2) + + if isempty(dynareParallelDir('DynareIsOk.txt',RemoteTmpFolder,DataInput(Node))) + ErrorCode=8; + end + + if (ErrorCode==8) + disp ('The DynarePath is incorrect!') + skipline() + disp('ErrorCode 8.') + skipline(2) + ErrorCode=8; + dynareParallelRmDir(RemoteTmpFolder,DataInput(Node)); + return + else + disp('Check on Dynare Path remote machine ..... Ok!') + if isempty(dynareParallelDir('IsMac.txt',RemoteTmpFolder,DataInput(Node))) + RemoteEnvironment=Environment; + else + RemoteEnvironment=2; + end + skipline(2) + end + end + + + % Now we verify if it is possible delete remote computational traces! + + dynareParallelRmDir(RemoteTmpFolder,DataInput(Node)); + + si3=[]; + + si3=dynareParallelDir('Tracing.m', RemoteTmpFolder,DataInput(Node)); + + if (isempty(si3)) + disp ('Check on Delete Remote Computational Traces ..... Ok!') + skipline(2) + else + disp ('It is impossible to delete temporary files on remote machine!') + skipline() + disp('ErrorCode 9.') + skipline(2) + ErrorCode=9; + return + end + + + end + % Now we check the variable 'CPUnbr'. + + % This check can be removed ... according to the dynare parser + % strategy. + + yn=isempty(DataInput(Node).CPUnbr); + + if yn==1 + % The field is empty! + disp('The field "CPUnbr" is empty!') + skipline() + disp('ErrorCode 2.') + skipline(2) + ErrorCode=2; + return + end + + % This check can be removed ... according to the dynare parser + % strategy. + + + + % We look for the information on local computer hardware. + + si0=[]; + de0=[]; + + Environment1=Environment; + disp('Checking Hardware please wait ...'); + if (DataInput(Node).Local == 1) + if Environment + if ~ismac + [si0 de0]=system('grep processor /proc/cpuinfo'); + else + [si0 de0]=system('sysctl -n hw.ncpu'); + Environment1=2; + end + else + [si0 de0]=system(['psinfo \\']); + end + else + if Environment + if ~isempty(DataInput(Node).Port) + ssh_token = ['-p ',DataInput(Node).Port]; + else + ssh_token = ''; + end + if OStargetUnix + if RemoteEnvironment ==1 + [si0 de0]=system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' grep processor /proc/cpuinfo']); + else % it is MAC + [si0 de0]=system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' sysctl -n hw.ncpu']); + Environment1=2; + end + else + [si0 de0]=system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' psinfo']); + end + else + [si0 de0]=system(['psinfo \\',DataInput(Node).ComputerName,' -u ',DataInput(Node).UserName,' -p ',DataInput(Node).Password]); + end + end + + + RealCPUnbr=''; + % keyboard; + RealCPUnbr=GiveCPUnumber(de0,Environment1); + + % Questo controllo penso che si possa MIGLIORARE!!!!! + if isempty (RealCPUnbr) && Environment1==0 + [si0 de0]=system(['psinfo \\',DataInput(Node).ComputerName]); + end + RealCPUnbr=GiveCPUnumber(de0,Environment1); + + if isempty (RealCPUnbr) + % An error occurred when we try to know the Cpu/Cores + % numbers. + disp('It is impossible determine the number of Cpu/Processor avaiable on this machine!') + skipline() + disp('ErrorCode 2.') + skipline() + if Environment + disp('Check the command "$less /proc/cpuinfo" ... !') + else + disp('Check if the pstools are installed and are in machine path! And check the command "psinfo \\"') + end + skipline() + ErrorCode=2; + return + end + + + % Trasforming the input data provided in a form [n1:n2] in a single numerical + % value. + + + CPUnbrUser=length(DataInput(Node).CPUnbr); + maxCPUnbrUser=max(DataInput(Node).CPUnbr)+1; + + disp(['Hardware has ', num2str(RealCPUnbr),' Cpu/Cores!']) + disp(['User requires ',num2str(CPUnbrUser),' Cpu/Cores!']) + if CPUnbrUser==RealCPUnbr + % It is Ok! + disp('Check on CPUnbr Variable ..... Ok!') + skipline(3) + end + + if CPUnbrUser > RealCPUnbr + disp('Warning! The user asks to use more CPU''s than those available.') + skipline(2) + ErrorCode=2.1; + end + if CPUnbrUser < RealCPUnbr + disp('Warning! There are unused CPU''s!') + skipline(2) + ErrorCode=2.2; + end + + if mod(length(DataInput(Node).CPUnbr),DataInput(Node).NumberOfThreadsPerJob) + skipline() + disp(['NumberOfThreadsPerJob = ',int2str(DataInput(Node).NumberOfThreadsPerJob),' is not an exact divisor of number of CPUs = ',int2str(DataInput(Node).CPUnbr),'!']) + disp([' You must re-set properly NumberOfThreadsPerJob of node ' int2str(Node) ' ' DataInput(Node).ComputerName]) + disp(' in your configuration file') + skipline() + ErrorCode=2.3; + end + + disp(['Test for Cluster computation, computer ',DataInput(Node).ComputerName, ' ..... Passed!']) + skipline(2) end \ No newline at end of file diff --git a/matlab/parallel/CreateTimeString.m b/matlab/parallel/CreateTimeString.m index 8b82b1cc6d..53251d4186 100644 --- a/matlab/parallel/CreateTimeString.m +++ b/matlab/parallel/CreateTimeString.m @@ -6,7 +6,7 @@ function [TiSt] = CreateTimeString() % None % % OUTPUTS -% o TiSt [] ... +% o TiSt [] ... % % Copyright (C) 2009-2010 Dynare Team % diff --git a/matlab/parallel/GiveCPUnumber.m b/matlab/parallel/GiveCPUnumber.m index 4d3988bece..cc2d45aa38 100644 --- a/matlab/parallel/GiveCPUnumber.m +++ b/matlab/parallel/GiveCPUnumber.m @@ -1,76 +1,76 @@ -function [nCPU]= GiveCPUnumber (ComputerInformations, Environment) -% PARALLEL CONTEXT -% In a parallel context this function return the CPUs or cores numer avaiable -% on the computer used for run parallel code. -% -% INPUTS -% an array contained several fields that describe the hardaware -% software enviroments of a generic computer. -% -% OUTPUTS -% The CPUs or Cores numbers of computer. -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2010-2017 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/>. - - -nCPU=''; - -if nargin < 2 -% Determine a specific operating system or software version when necessary -% for different command (sintax, name, ...). -Environment=~ispc; -end - -switch Environment - case 0 %WINDOWS OPERATING SYSTEM - - OffSet=27; - - SringPosition=strfind(ComputerInformations, 'Processors:'); - nCPU=ComputerInformations(SringPosition+OffSet); - - % We check if there are Processors/Cores more than 9. - - - t0=ComputerInformations(SringPosition+OffSet+1); - t1=str2num(t0); - t1=isempty(t1); - - % if t1 is 0 the machine have more than 9 CPU. - - if t1==0 - nCPU=strcat(nCPU,t0); - end - - nCPU=str2num(nCPU); - - return - case 1 %LIKE UNIX OPERATING SYSTEM - - % Da generalizzare a un numero di CPu maggiore di 9!!! - - nCPU=str2num(ComputerInformations(length(ComputerInformations)-1))+1; - - case 2 %MAC-OS OPERATING SYSTEM - - nCPU=str2num(ComputerInformations); - -end +function [nCPU]= GiveCPUnumber (ComputerInformations, Environment) +% PARALLEL CONTEXT +% In a parallel context this function return the CPUs or cores numer avaiable +% on the computer used for run parallel code. +% +% INPUTS +% an array contained several fields that describe the hardaware +% software enviroments of a generic computer. +% +% OUTPUTS +% The CPUs or Cores numbers of computer. +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2010-2017 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/>. + + +nCPU=''; + +if nargin < 2 + % Determine a specific operating system or software version when necessary + % for different command (sintax, name, ...). + Environment=~ispc; +end + +switch Environment + case 0 %WINDOWS OPERATING SYSTEM + + OffSet=27; + + SringPosition=strfind(ComputerInformations, 'Processors:'); + nCPU=ComputerInformations(SringPosition+OffSet); + + % We check if there are Processors/Cores more than 9. + + + t0=ComputerInformations(SringPosition+OffSet+1); + t1=str2num(t0); + t1=isempty(t1); + + % if t1 is 0 the machine have more than 9 CPU. + + if t1==0 + nCPU=strcat(nCPU,t0); + end + + nCPU=str2num(nCPU); + + return + case 1 %LIKE UNIX OPERATING SYSTEM + + % Da generalizzare a un numero di CPu maggiore di 9!!! + + nCPU=str2num(ComputerInformations(length(ComputerInformations)-1))+1; + + case 2 %MAC-OS OPERATING SYSTEM + + nCPU=str2num(ComputerInformations); + +end diff --git a/matlab/parallel/InitializeComputationalEnvironment.m b/matlab/parallel/InitializeComputationalEnvironment.m index 5a824cd72d..18ce19f113 100644 --- a/matlab/parallel/InitializeComputationalEnvironment.m +++ b/matlab/parallel/InitializeComputationalEnvironment.m @@ -37,7 +37,7 @@ function InitializeComputationalEnvironment() % Comment the line 'warning('off');' in order to view the warning message % in Octave! -if isoctave +if isoctave warning('off'); end diff --git a/matlab/parallel/closeSlave.m b/matlab/parallel/closeSlave.m index f6552e0e0c..49c14deb3e 100644 --- a/matlab/parallel/closeSlave.m +++ b/matlab/parallel/closeSlave.m @@ -10,7 +10,7 @@ function closeSlave(Parallel,TmpFolder,partial) % This directory is named using current date % and is used only one time and then deleted. % If islocal==1, TmpFolder=''. -% +% % % OUTPUTS % None @@ -45,7 +45,7 @@ if partial==1 dynareParallelSendFiles('slaveParallel_break.mat',TmpFolder,Parallel(indPC)); end end -% delete('slaveParallel_break') + % delete('slaveParallel_break') return end if partial==-1 @@ -55,7 +55,7 @@ if partial==-1 dynareParallelDelete( 'slaveParallel_break.mat',TmpFolder,Parallel(indPC)); end end -% delete('slaveParallel_break') + % delete('slaveParallel_break') return end @@ -63,14 +63,14 @@ for indPC=1:length(Parallel) if (Parallel(indPC).Local==0) dynareParallelDelete( 'slaveParallel_input*.mat',TmpFolder,Parallel(indPC)); end - - + + delete( 'slaveParallel_input*.mat'); delete( 'slaveJob*.mat'); pause(1) delete(['slaveParallel_*.log']); delete ConcurrentCommand1.bat; - + end while(1) @@ -81,7 +81,7 @@ while(1) end end break - + end end diff --git a/matlab/parallel/distributeJobs.m b/matlab/parallel/distributeJobs.m index b1276dd116..c0c41925f7 100644 --- a/matlab/parallel/distributeJobs.m +++ b/matlab/parallel/distributeJobs.m @@ -40,7 +40,7 @@ function [nCPU, totCPU, nBlockPerCPU, totSLAVES] = distributeJobs(Parallel, fBlo % The Parallel vector has already been sorted -% (in accord with the CPUWeight values) in DESCENDING order in +% (in accord with the CPUWeight values) in DESCENDING order in % InitializeComputationalEnvironment! totCPU=0; @@ -57,7 +57,7 @@ for j=1:lP error(['PARALLEL_ERROR:: NumberOfThreadsPerJob is not an exact divisor of CPUnbr']) end nCPU(j)=length(Parallel(j).CPUnbr)/Parallel(j).NumberOfThreadsPerJob; - totCPU=totCPU+nCPU(j); + totCPU=totCPU+nCPU(j); CPUWeight(j)=str2num(Parallel(j).NodeWeight); end @@ -85,15 +85,15 @@ CPUWeight=CPUWeight./sum(CPUWeight); % Redistributing the jobs among the cluster nodes according to the % CPUWeight. for i=1:nC - + JobsForNode(i)=CPUWeight(i)*NumbersOfJobs; - + % Many choices are possible: - + % JobsForNode(i)=round(JobsForNode(i)); % JobsForNode(i)=floor(JobsForNode(i)); - JobsForNode(i)=ceil(JobsForNode(i)); - + JobsForNode(i)=ceil(JobsForNode(i)); + end % Check if there are more (fewer) jobs. @@ -101,19 +101,19 @@ end SumOfJobs=sum(JobsForNode); if SumOfJobs~=NumbersOfJobs - + if SumOfJobs>NumbersOfJobs - + % Many choices are possible: - + % - Remove the excess works at the node that has the greatest % number of jobs. % - Remove the excess works at the node slower. - + VerySlow=nC; - + while SumOfJobs>NumbersOfJobs - + if JobsForNode(VerySlow)==0 VerySlow=VerySlow-1; continue @@ -121,21 +121,21 @@ if SumOfJobs~=NumbersOfJobs JobsForNode(VerySlow)=JobsForNode(VerySlow)-1; SumOfJobs=SumOfJobs-1; end - + end - + if SumOfJobs<NumbersOfJobs - + % Many choices are possible: % - ... (see above). - + [NonServe VeryFast]= min(CPUWeight); - + while SumOfJobs<NumbersOfJobs JobsForNode(VeryFast)=JobsForNode(VeryFast)+1; SumOfJobs=SumOfJobs+1; end - + end end @@ -148,36 +148,36 @@ JobAssignedCpu=0; RelativePosition=1; for i=1:nC - + % Many choices are possible: % - ... (see above). - + JobAssignedCpu=max(1,floor(JobsForNode(i)/nCPUoriginal(i))); - + ChekOverFlow=0; - + for j=RelativePosition:nCPU(i) JobsForCpu(j)=JobAssignedCpu; ChekOverFlow=ChekOverFlow+JobAssignedCpu; - + if ChekOverFlow>=JobsForNode(i) break end - + end - + % Check if there are more (fewer) jobs. % This can happen when we use ceil, round, ... functions. - + if ChekOverFlow ~=(JobsForNode(i)) - + if ChekOverFlow >(JobsForNode(i)) while ChekOverFlow>JobsForNode(i) JobsForCpu(nCPU(i))=JobsForCpu(nCPU(i))-1; ChekOverFlow=ChekOverFlow-1; end end - + if ChekOverFlow <(JobsForNode(i)) while ChekOverFlow<JobsForNode(i) JobsForCpu(nCPU(i))=JobsForCpu(nCPU(i))+1; @@ -185,9 +185,9 @@ for i=1:nC end end end - + RelativePosition=nCPU(i)+1; - + end % Reshape the variables totCPU,totSLAVES and nBlockPerCPU in accord with @@ -216,5 +216,3 @@ for i=1:nCPU(nC) RelativeCounter=RelativeCounter+1; end end - - diff --git a/matlab/parallel/dynareParallelDelete.m b/matlab/parallel/dynareParallelDelete.m index 7c02804367..478b8c8e46 100644 --- a/matlab/parallel/dynareParallelDelete.m +++ b/matlab/parallel/dynareParallelDelete.m @@ -4,8 +4,8 @@ function dynareParallelDelete(fname,pname,Parallel) % % INPUTS % o fname [] ... -% o pname [] ... -% o Parallel [] ... +% o pname [] ... +% o Parallel [] ... % % OUTPUTS % None @@ -53,5 +53,5 @@ for indPC=1:length(Parallel) delete(fname_temp); end end - + end diff --git a/matlab/parallel/dynareParallelDeleteNewFiles.m b/matlab/parallel/dynareParallelDeleteNewFiles.m index 9f88e65999..34fdab44be 100644 --- a/matlab/parallel/dynareParallelDeleteNewFiles.m +++ b/matlab/parallel/dynareParallelDeleteNewFiles.m @@ -36,7 +36,7 @@ NewFilesFromSlaves={}; % try for indPC=1:length(Parallel) - + if Parallel(indPC).Local==0 [NewFilesFromSlaves, PRCDirSnapshot{indPC}]=dynareParallelFindNewFiles(PRCDirSnapshot{indPC},Parallel(indPC), PRCDir); if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem) @@ -60,11 +60,11 @@ for indPC=1:length(Parallel) exception_flag=exception_flag+(~isempty(strfind(fileaddress{2},varargin{indexc}))); end if exception_flag==0 - dynareParallelDelete(fileaddress{2},[PRCDir,fS,fileaddress{1}],Parallel(indPC)); + dynareParallelDelete(fileaddress{2},[PRCDir,fS,fileaddress{1}],Parallel(indPC)); - disp('New file deleted in remote -->'); - disp(fileaddress{2}); - disp('<--'); + disp('New file deleted in remote -->'); + disp(fileaddress{2}); + disp('<--'); end end @@ -75,6 +75,3 @@ for indPC=1:length(Parallel) end end - - - diff --git a/matlab/parallel/dynareParallelDir.m b/matlab/parallel/dynareParallelDir.m index 8db2d6fe39..0625dd8e7b 100644 --- a/matlab/parallel/dynareParallelDir.m +++ b/matlab/parallel/dynareParallelDir.m @@ -37,10 +37,10 @@ for indPC=1:length(Parallel) ssh_token = ''; end if isoctave % Patch for peculiar behaviour of ssh-ls under Linux. - % It is necessary to capture the ls warning message. - % To do it under the ssh protocol it is necessary to redirect the ls message in a text file. - % The file is 'OctaveStandardOutputMessage.txt' and it is - % saved in the Model directory. + % It is necessary to capture the ls warning message. + % To do it under the ssh protocol it is necessary to redirect the ls message in a text file. + % The file is 'OctaveStandardOutputMessage.txt' and it is + % saved in the Model directory. [check, ax]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' ls ',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',filename, ' 2> OctaveStandardOutputMessage.txt']); else [check, ax]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' ls ',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',filename]); @@ -57,10 +57,10 @@ for indPC=1:length(Parallel) else if isoctave % Patch for peculiar behaviour of ls under Linux. - + % It is necessary to capture the ls warning message and properly manage the jolly char '*'! [check ax]=system(['ls ' ,filename, ' 2> OctaveStandardOutputMessage.txt']); - + if check ~= 0 || ~isempty(strfind(ax,'No such file or directory')) ax=[]; end diff --git a/matlab/parallel/dynareParallelFindNewFiles.m b/matlab/parallel/dynareParallelFindNewFiles.m index 4c6dabf36e..ba93d6245b 100644 --- a/matlab/parallel/dynareParallelFindNewFiles.m +++ b/matlab/parallel/dynareParallelFindNewFiles.m @@ -36,7 +36,7 @@ function [NewFilesFrom, NewFileList]=dynareParallelFindNewFiles(FileList,Paralle NewFilesFrom={}; LfL=length(FileList); - % The first call ... +% The first call ... NewFileList = dynareParallelListAllFiles('Root',PRCDir,Parallel); @@ -45,35 +45,34 @@ LnFl=length(NewFileList); RelativePosition=1; for i=1:LnFl - + % Exception Handling - + % If you comment the code below all new file will be copied! - + % 1. The comp_status* files are managed separately. - + FiCoS=strfind(NewFileList{i},'comp_status_'); if ~isempty(FiCoS) continue end - + % 2. For the time being is not necessary to always copy *.log % and *.txt files. - + nC1 = strfind(NewFileList{i}, '.log'); nC2 = strfind(NewFileList{i}, '.txt'); - + if (~isempty(nC1) || ~isempty(nC2)) continue end - + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - + + N=strmatch(NewFileList{i},FileList,'exact'); if isempty(N) NewFilesFrom{RelativePosition}=NewFileList{i}; RelativePosition=RelativePosition+1; end end - diff --git a/matlab/parallel/dynareParallelGetFiles.m b/matlab/parallel/dynareParallelGetFiles.m index 53e9c4ef0f..6669f21a85 100644 --- a/matlab/parallel/dynareParallelGetFiles.m +++ b/matlab/parallel/dynareParallelGetFiles.m @@ -55,10 +55,10 @@ for indPC=1:length(Parallel) for jfil=1:size(NamFileInput,1) if isoctave % Patch for peculiar behaviour of ls under Linux. - % It is necessary to manage the jolly char '*'! + % It is necessary to manage the jolly char '*'! FindAst=strfind(NamFileInput{jfil,2},'comp_status_posterior_sampler_core*'); - + if isempty (FindAst) [NonServeL NonServeR]= system(['scp ',scp_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,':',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',NamFileInput{jfil,1},NamFileInput{jfil,2},' ',NamFileInput{jfil,1}]); @@ -66,9 +66,9 @@ for indPC=1:length(Parallel) else filenameTemp=NamFileInput{jfil,2}; - + [NotUsed FlI]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' ls ',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',filenameTemp, ' 2> OctaveStandardOutputMessage.txt']); - + if isempty (FlI) return end diff --git a/matlab/parallel/dynareParallelGetNewFiles.m b/matlab/parallel/dynareParallelGetNewFiles.m index fb9b0ae917..8d42bd3759 100644 --- a/matlab/parallel/dynareParallelGetNewFiles.m +++ b/matlab/parallel/dynareParallelGetNewFiles.m @@ -37,7 +37,7 @@ NewFilesFromSlaves={}; % try for indPC=1:length(Parallel) - + if Parallel(indPC).Local==0 [NewFilesFromSlaves, PRCDirSnapshot{indPC}]=dynareParallelFindNewFiles(PRCDirSnapshot{indPC},Parallel(indPC), PRCDir); if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem) @@ -71,6 +71,3 @@ for indPC=1:length(Parallel) end end - - - diff --git a/matlab/parallel/dynareParallelListAllFiles.m b/matlab/parallel/dynareParallelListAllFiles.m index ebdbb78810..eab7134223 100644 --- a/matlab/parallel/dynareParallelListAllFiles.m +++ b/matlab/parallel/dynareParallelListAllFiles.m @@ -34,7 +34,7 @@ function fileList = dynareParallelListAllFiles(dirName,PRCDir,Parallel) if (~ispc || strcmpi('unix',Parallel.OperatingSystem)) - + fileList={}; currentPath=[]; if ~isempty(Parallel.Port) @@ -43,24 +43,24 @@ if (~ispc || strcmpi('unix',Parallel.OperatingSystem)) ssh_token = ''; end - % Get the data for the current remote directory. + % Get the data for the current remote directory. [Flag, fL]=system(['ssh ',ssh_token,' ',' ',Parallel.UserName,'@',Parallel.ComputerName,' ls ',Parallel.RemoteDirectory,'/',PRCDir, ' -R -p -1']); % Format the return value fL. - + nL=regexp(fL,'\n'); start=1; j=1; for (i=1:length(nL)) - + stringProcessed=fL(start:nL(i)-1); - + if isempty(stringProcessed) start=nL(i)+1; continue end - + if strfind(stringProcessed,'/') if strfind(stringProcessed,PRCDir) DD=strfind(stringProcessed,':'); @@ -70,11 +70,11 @@ if (~ispc || strcmpi('unix',Parallel.OperatingSystem)) start=nL(i)+1; continue end - + fileList{j,1}=[currentPath stringProcessed]; start=nL(i)+1; j=j+1; - end + end else @@ -92,7 +92,7 @@ else % Build the path files: if ~isempty(fileList) fileList = cellfun(@(x) fullfile(dirName,x),... - fileList,'UniformOutput',false); + fileList,'UniformOutput',false); end % Get a list of the subdirectories: @@ -112,5 +112,3 @@ else fileList = [fileList; dynareParallelListAllFiles(nextDir,PRCDir,Parallel)]; end end - - diff --git a/matlab/parallel/dynareParallelMkDir.m b/matlab/parallel/dynareParallelMkDir.m index 9cb0a41a56..e85d1af3a2 100644 --- a/matlab/parallel/dynareParallelMkDir.m +++ b/matlab/parallel/dynareParallelMkDir.m @@ -3,8 +3,8 @@ function dynareParallelMkDir(PRCDir,Parallel) % In a parallel context, this is a specialized version of rmdir() function. % % INPUTS -% o PRCDir [] ... -% o Parallel [] ... +% o PRCDir [] ... +% o Parallel [] ... % % OUTPUTS % None diff --git a/matlab/parallel/dynareParallelRmDir.m b/matlab/parallel/dynareParallelRmDir.m index 11b6e03608..64f3c4fdec 100644 --- a/matlab/parallel/dynareParallelRmDir.m +++ b/matlab/parallel/dynareParallelRmDir.m @@ -3,8 +3,8 @@ function dynareParallelRmDir(PRCDir,Parallel) % In a parallel context, this is a specialized version of rmdir() function. % % INPUTS -% o PRCDir [] ... -% o Parallel [] ... +% o PRCDir [] ... +% o Parallel [] ... % % OUTPUTS % None diff --git a/matlab/parallel/dynareParallelSendFiles.m b/matlab/parallel/dynareParallelSendFiles.m index 6a12a2328c..6a3c8904ce 100644 --- a/matlab/parallel/dynareParallelSendFiles.m +++ b/matlab/parallel/dynareParallelSendFiles.m @@ -62,15 +62,15 @@ for indPC=1:length(Parallel) for jfil=1:size(NamFileInput,1) if ~isempty(NamFileInput{jfil,1}) if isempty(dynareParallelDir(NamFileInput{jfil,1},PRCDir,Parallel(indPC))) - + if isoctave % Patch for peculiar behaviour of mkdir under Windows. - + % It is Necessary because Octave is not able to % create two nested directory at the same time. - - % Remove (if present) the '/' chars. Can be easily transformed - % in a function. - + + % Remove (if present) the '/' chars. Can be easily transformed + % in a function. + NamFileInputTemp=NamFileInput{jfil,1}; while(1) Bs=strfind(NamFileInputTemp,'/'); @@ -80,7 +80,7 @@ for indPC=1:length(Parallel) NamFileInputTemp(1,Bs)='\'; end end - + [NonServeL, NonServeR]=system(['mkdir \\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInputTemp]); else @@ -88,15 +88,15 @@ for indPC=1:length(Parallel) end end end - + if isoctave % Patch for peculiar behaviour copyfile ls under Windows. - + % It is Necessary because Octave is not able to % use the jolly char '*' with copyfile. - - % Remove (if present) the '/' chars. Can be easily transformed - % in a function. - + + % Remove (if present) the '/' chars. Can be easily transformed + % in a function. + NamFileInputTemp=NamFileInput{jfil,1}; while(1) Bs=strfind(NamFileInputTemp,'/'); @@ -106,9 +106,9 @@ for indPC=1:length(Parallel) NamFileInputTemp(1,Bs)='\'; end end - + [NonServeS, NonServeD]=system(['copy ',NamFileInputTemp, NamFileInput{jfil,2},' \\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInputTemp]); - + else copyfile([NamFileInput{jfil,1},NamFileInput{jfil,2}],['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInput{jfil,1}]); end diff --git a/matlab/parallel/dynareParallelSnapshot.m b/matlab/parallel/dynareParallelSnapshot.m index 522ffa989b..8566ebfe05 100644 --- a/matlab/parallel/dynareParallelSnapshot.m +++ b/matlab/parallel/dynareParallelSnapshot.m @@ -35,8 +35,8 @@ PRCDirSnapshot={}; for indPC=1:length(Parallel) if Parallel(indPC).Local==0 - % The first call ... + % The first call ... PRCDirSnapshot{indPC}=dynareParallelListAllFiles('Root',PRCDir,Parallel(indPC)); - + end end diff --git a/matlab/parallel/fMessageStatus.m b/matlab/parallel/fMessageStatus.m index 0d19960465..2c9f8ab5f4 100644 --- a/matlab/parallel/fMessageStatus.m +++ b/matlab/parallel/fMessageStatus.m @@ -3,16 +3,16 @@ function fMessageStatus(prtfrc, njob, waitbarString, waitbarTitle, Parallel) % In parallel context, this function is launched on slave % machines, and acts as a message passing device for the master machine. -% INPUTS +% INPUTS % o prtfrc [double] fraction of iteration performed % o njob [int] index number of this CPU among all CPUs in the % cluster -% o waitbarString [char] running message string to be displayed in the monitor window on master machine +% o waitbarString [char] running message string to be displayed in the monitor window on master machine % o waitbarTitle [char] title to be displayed in the monitor window on master machine % o Parallel [struct] options_.parallel(ThisMatlab), i.e. the parallel settings for this slave machine in the cluster. % -% OUTPUTS -% o None +% OUTPUTS +% o None % Copyright (C) 2006-2017 Dynare Team % @@ -39,7 +39,7 @@ end try save(['comp_status_',funcName,int2str(njob),'.mat'],'prtfrc','njob','waitbarString','waitbarTitle'); -catch +catch end fslave = dir( ['slaveParallel_input',int2str(njob),'.mat']); @@ -47,4 +47,3 @@ fbreak = dir( ['slaveParallel_break.mat']); if isempty(fslave) || ~isempty(fbreak) error('Master asked to break the job'); end - diff --git a/matlab/parallel/fParallel.m b/matlab/parallel/fParallel.m index 67752fe090..4bce410084 100644 --- a/matlab/parallel/fParallel.m +++ b/matlab/parallel/fParallel.m @@ -69,7 +69,7 @@ fInputVar.Parallel = Parallel; % Launch the routine to be run in parallel. try tic - + fOutputVar = feval(fname, fInputVar ,fblck, nblck, whoiam, ThisMatlab); toc if isfield(fOutputVar,'OutputFileName') @@ -87,7 +87,7 @@ try save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' ) save(['comp_status_',funcName,int2str(whoiam),'.mat'],'CloseAllSlaves'); end - + disp(['fParallel ',int2str(whoiam),' completed.']) catch theerror = lasterror; @@ -108,7 +108,7 @@ catch end fMessageStatus(NaN,whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab)); end - + end diary off; delete(['P_',fname,'_',int2str(whoiam),'End.txt']); diff --git a/matlab/parallel/masterParallel.m b/matlab/parallel/masterParallel.m index f9b47dea93..e51c6d0233 100644 --- a/matlab/parallel/masterParallel.m +++ b/matlab/parallel/masterParallel.m @@ -3,37 +3,37 @@ function [fOutVar,nBlockPerCPU, totCPU] = masterParallel(Parallel,fBlock,nBlock, % This is the most important function for the management of DYNARE parallel % computing. % It is the top-level function called on the master computer when parallelizing a task. -% +% % This function has two main computational strategies for managing the % matlab worker (slave process): -% +% % 0 Simple Close/Open Stategy: % In this case the new Matlab instances (slave process) are open when % necessary and then closed. This can happen many times during the % simulation of a model. -% +% % 1 Always Open Strategy: % In this case we have a more sophisticated management of slave processes, % which are no longer closed at the end of each job. The slave processes % wait for a new job (if it exists). If a slave does not receive a new job after a % fixed time it is destroyed. This solution removes the computational % time necessary to Open/Close new Matlab instances. -% +% % The first (point 0) is the default Strategy % i.e.(Parallel_info.leaveSlaveOpen=0). This value can be changed by the % user in xxx.mod file or it is changed by the programmer if it is necessary to % reduce the overall computational time. See for example the % prior_posterior_statistics.m. -% +% % The number of parallelized threads will be equal to (nBlock-fBlock+1). % % Treatment of global variables: -% Global variables used within the called function are wrapped and passed by storing their +% Global variables used within the called function are wrapped and passed by storing their % values at the start of the parallel computation in a file via % storeGlobalVars.m. This file is then loaded in the separate, % independent slave Matlab sessions. By keeping them separate, no -% interaction via global variables can take place. -% +% interaction via global variables can take place. +% % INPUTS % o Parallel [struct vector] copy of options_.parallel % o fBlock [int] index number of the first thread @@ -134,17 +134,17 @@ if isHybridMatlabOctave || isoctave fInputVar.(fInputNames{j})=TargetVar; end end - + if exist('fGlobalVar','var') && ~isempty(fGlobalVar) - fInputNames = fieldnames(fGlobalVar); - for j=1:length(fInputNames) - TargetVar = fGlobalVar.(fInputNames{j}); - if isa(TargetVar,'function_handle') - TargetVar=func2str(TargetVar); - fGlobalVar.(fInputNames{j})=TargetVar; + fInputNames = fieldnames(fGlobalVar); + for j=1:length(fInputNames) + TargetVar = fGlobalVar.(fInputNames{j}); + if isa(TargetVar,'function_handle') + TargetVar=func2str(TargetVar); + fGlobalVar.(fInputNames{j})=TargetVar; + end end end - end end if Strategy==1 @@ -165,18 +165,18 @@ end % Save input data for use by the slaves. switch Strategy - case 0 - storeGlobalVars([fname,'_input.mat']); - save([fname,'_input.mat'],'fInputVar','Parallel','-append') - - case 1 - if exist('fGlobalVar','var') - save(['temp_input.mat'],'fInputVar','fGlobalVar') - else - save(['temp_input.mat'],'fInputVar') - end - save(['temp_input.mat'],'Parallel','-append') - closeSlave(Parallel,PRCDir,-1); + case 0 + storeGlobalVars([fname,'_input.mat']); + save([fname,'_input.mat'],'fInputVar','Parallel','-append') + + case 1 + if exist('fGlobalVar','var') + save(['temp_input.mat'],'fInputVar','fGlobalVar') + else + save(['temp_input.mat'],'fInputVar') + end + save(['temp_input.mat'],'Parallel','-append') + closeSlave(Parallel,PRCDir,-1); end @@ -239,26 +239,26 @@ end % End for j=1:totCPU - + if Strategy==1 command1 = ' '; end - + indPC=min(find(nCPU>=j)); - + % According to the information contained in configuration file, compThread can limit MATLAB % to a single computational thread. By default, MATLAB makes use of the multithreading % capabilities of the computer on which it is running. Nevertheless % exsperimental results show as matlab native % multithreading limit the performaces when the parallel computing is active. - - + + if strcmp('true',Parallel(indPC).SingleCompThread) compThread = '-singleCompThread'; else compThread = ''; end - + nthreads=Parallel(indPC).NumberOfThreadsPerJob; if indPC>1 nCPU0 = nCPU(indPC-1); @@ -266,15 +266,15 @@ for j=1:totCPU nCPU0=0; end offset = sum(nBlockPerCPU(1:j-1))+offset0; - + % Create a file used to monitoring if a parallel block (core) % computation is finished or not. - + fid1=fopen(['P_',fname,'_',int2str(j),'End.txt'],'w+'); fclose(fid1); - + if Strategy==1 - + fblck = offset+1; nblck = sum(nBlockPerCPU(1:j)); save temp_input.mat fblck nblck fname -append; @@ -289,7 +289,7 @@ for j=1:totCPU % internal criteria. pause(1); newInstance = 0; - + % Check if j CPU is already alive. if isempty(dynareParallelDir(['P_slave_',int2str(j),'End.txt'],PRCDir,Parallel(indPC))) fid1=fopen(['P_slave_',int2str(j),'End.txt'],'w+'); @@ -298,66 +298,141 @@ for j=1:totCPU dynareParallelSendFiles(['P_slave_',int2str(j),'End.txt'],PRCDir,Parallel(indPC)); delete(['P_slave_',int2str(j),'End.txt']); end - + newInstance = 1; storeGlobalVars( ['slaveParallel_input',int2str(j),'.mat']); save( ['slaveParallel_input',int2str(j),'.mat'],'Parallel','-append'); % Prepare global vars for Slave. end else - + % If the computation is executed remotely all the necessary files % are created localy, then copied in remote directory and then % deleted (loacal)! - + save( ['slaveParallel_input',int2str(j),'.mat'],'j'); - + if Parallel(indPC).Local==0 dynareParallelSendFiles(['P_',fname,'_',int2str(j),'End.txt'],PRCDir,Parallel(indPC)); delete(['P_',fname,'_',int2str(j),'End.txt']); - + dynareParallelSendFiles(['slaveParallel_input',int2str(j),'.mat'],PRCDir,Parallel(indPC)); delete(['slaveParallel_input',int2str(j),'.mat']); - + end - + end - + % set affinity range on win CPU's affinity_range = [1:nthreads]+(j-1-nCPU0)*nthreads; my_affinity = int2str(Parallel(indPC).CPUnbr(affinity_range(1))); for jaff=2:length(affinity_range) my_affinity = [my_affinity ',' int2str(Parallel(indPC).CPUnbr(affinity_range(jaff)))]; end -% % % int2str(Parallel(indPC).CPUnbr(j-nCPU0)) + % % % int2str(Parallel(indPC).CPUnbr(j-nCPU0)) % DA SINTETIZZARE: - + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % The following 'switch - case' code is the core of this function! switch Strategy - case 0 - - if Parallel(indPC).Local == 1 % 0.1 Run on the local machine (localhost). - - if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem) % Hybrid computing Windows <-> Unix! - if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa! - command1=[Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')" &']; + case 0 + + if Parallel(indPC).Local == 1 % 0.1 Run on the local machine (localhost). + + if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem) % Hybrid computing Windows <-> Unix! + if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa! + command1=[Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')" &']; + else + command1=[Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')" &']; + end + else % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa! + if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') + command1=['psexec -d -W "',DyMo, '" -a ',my_affinity,' -low ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"']; + else + command1=['psexec -d -W "',DyMo, '" -a ',my_affinity,' -low ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"']; + end + end + else % 0.2 Parallel(indPC).Local==0: Run using network on remote machine or also on local machine. + if j==nCPU0+1 + dynareParallelSendFiles([fname,'_input.mat'],PRCDir,Parallel(indPC)); + dynareParallelSendFiles(NamFileInput,PRCDir,Parallel(indPC)); + end + + if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)) % Hybrid computing Windows <-> Unix! + if ispc + token='start /B '; + else + token = ''; + end + if ~isempty(Parallel(indPC).Port) + ssh_token = ['-p ',Parallel(indPC).Port]; + else + ssh_token = ''; + end + % To manage the diferences in Unix/Windows OS syntax. + remoteFile=['remoteDynare',int2str(j)]; + fidRemote=fopen([remoteFile,'.m'],'w+'); + if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa! + remoteString=['default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')']; + command1=[token, 'ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' "cd ',Parallel(indPC).RemoteDirectory,'/',PRCDir, '; ',Parallel(indPC).MatlabOctavePath,' -f --eval ',remoteFile,' " &']; + else + remoteString=['addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')']; + command1=[token, 'ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' "cd ',Parallel(indPC).RemoteDirectory,'/',PRCDir, '; ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r ',remoteFile,';" &']; + end + fprintf(fidRemote,'%s\n',remoteString); + fclose(fidRemote); + dynareParallelSendFiles([remoteFile,'.m'],PRCDir,Parallel(indPC)); + delete([remoteFile,'.m']); + else + if ~strcmpi(Parallel(indPC).ComputerName,MasterName) % 0.3 Run on a remote machine! + % Hybrid computing Matlab(Master)-> Octave(Slaves) and Vice Versa! + if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') + command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -u ',Parallel(indPC).UserName,' -p ',Parallel(indPC).Password,' -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ... + ' -low ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"']; else - command1=[Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')" &']; + + command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -u ',Parallel(indPC).UserName,' -p ',Parallel(indPC).Password,' -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ... + ' -low ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"']; end - else % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa! + else % 0.4 Run on the local machine via the network + % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa! if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') - command1=['psexec -d -W "',DyMo, '" -a ',my_affinity,' -low ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"']; + command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ... + ' -low ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"']; else - command1=['psexec -d -W "',DyMo, '" -a ',my_affinity,' -low ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"']; + command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ... + ' -low ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"']; end end - else % 0.2 Parallel(indPC).Local==0: Run using network on remote machine or also on local machine. - if j==nCPU0+1 - dynareParallelSendFiles([fname,'_input.mat'],PRCDir,Parallel(indPC)); - dynareParallelSendFiles(NamFileInput,PRCDir,Parallel(indPC)); + end + end + + + case 1 + if Parallel(indPC).Local == 1 && newInstance % 1.1 Run on the local machine. + if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)) % Hybrid computing Windows <-> Unix! + if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)-> Octave(Slaves) and Vice Versa! + command1=[Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')" &']; + else + command1=[Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')" &']; + end + else % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa! + if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') + command1=['psexec -d -W "',DyMo, '" -a ',my_affinity,' -low ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7'');addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"']; + else + command1=['psexec -d -W "',DyMo, '" -a ',my_affinity,' -low ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"']; end - + end + elseif Parallel(indPC).Local==0 % 1.2 Run using network on remote machine or also on local machine. + if j==nCPU0+1 + dynareParallelSendFiles(NamFileInput,PRCDir,Parallel(indPC)); + end + dynareParallelSendFiles(['P_',fname,'_',int2str(j),'End.txt'],PRCDir,Parallel(indPC)); + delete(['P_',fname,'_',int2str(j),'End.txt']); + if newInstance + dynareParallelSendFiles(['slaveJob',int2str(j),'.mat'],PRCDir,Parallel(indPC)); + delete(['slaveJob',int2str(j),'.mat']); + dynareParallelSendFiles(['slaveParallel_input',int2str(j),'.mat'],PRCDir,Parallel(indPC)) if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)) % Hybrid computing Windows <-> Unix! if ispc token='start /B '; @@ -372,134 +447,59 @@ for j=1:totCPU % To manage the diferences in Unix/Windows OS syntax. remoteFile=['remoteDynare',int2str(j)]; fidRemote=fopen([remoteFile,'.m'],'w+'); - if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa! - remoteString=['default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')']; - command1=[token, 'ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' "cd ',Parallel(indPC).RemoteDirectory,'/',PRCDir, '; ',Parallel(indPC).MatlabOctavePath,' -f --eval ',remoteFile,' " &']; + if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)-> Octave(Slaves) and Vice Versa! + remoteString=['default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),');']; + command1=[token, 'ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' "cd ',Parallel(indPC).RemoteDirectory,'/',PRCDir '; ',Parallel(indPC).MatlabOctavePath,' -f --eval ',remoteFile,' " &']; else - remoteString=['addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')']; - command1=[token, 'ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' "cd ',Parallel(indPC).RemoteDirectory,'/',PRCDir, '; ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r ',remoteFile,';" &']; + remoteString=['addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),');']; + command1=[token, 'ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' "cd ',Parallel(indPC).RemoteDirectory,'/',PRCDir '; ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r ',remoteFile,';" &']; end fprintf(fidRemote,'%s\n',remoteString); fclose(fidRemote); dynareParallelSendFiles([remoteFile,'.m'],PRCDir,Parallel(indPC)); delete([remoteFile,'.m']); else - if ~strcmpi(Parallel(indPC).ComputerName,MasterName) % 0.3 Run on a remote machine! - % Hybrid computing Matlab(Master)-> Octave(Slaves) and Vice Versa! + if ~strcmpi(Parallel(indPC).ComputerName,MasterName) % 1.3 Run on a remote machine. + % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa! if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -u ',Parallel(indPC).UserName,' -p ',Parallel(indPC).Password,' -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ... - ' -low ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"']; + ' -low ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7'');addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"']; else - command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -u ',Parallel(indPC).UserName,' -p ',Parallel(indPC).Password,' -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ... - ' -low ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"']; + ' -low ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"']; end - else % 0.4 Run on the local machine via the network - % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa! + else % 1.4 Run on the local machine via the network. + % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa! if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ... - ' -low ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"']; + ' -low ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"']; else command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ... - ' -low ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"']; + ' -low ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"']; end end end - end - - - case 1 - if Parallel(indPC).Local == 1 && newInstance % 1.1 Run on the local machine. - if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)) % Hybrid computing Windows <-> Unix! - if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)-> Octave(Slaves) and Vice Versa! - command1=[Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')" &']; - else - command1=[Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')" &']; - end - else % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa! - if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') - command1=['psexec -d -W "',DyMo, '" -a ',my_affinity,' -low ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7'');addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"']; - else - command1=['psexec -d -W "',DyMo, '" -a ',my_affinity,' -low ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"']; - end - end - elseif Parallel(indPC).Local==0 % 1.2 Run using network on remote machine or also on local machine. - if j==nCPU0+1 - dynareParallelSendFiles(NamFileInput,PRCDir,Parallel(indPC)); - end - dynareParallelSendFiles(['P_',fname,'_',int2str(j),'End.txt'],PRCDir,Parallel(indPC)); - delete(['P_',fname,'_',int2str(j),'End.txt']); - if newInstance - dynareParallelSendFiles(['slaveJob',int2str(j),'.mat'],PRCDir,Parallel(indPC)); - delete(['slaveJob',int2str(j),'.mat']); - dynareParallelSendFiles(['slaveParallel_input',int2str(j),'.mat'],PRCDir,Parallel(indPC)) - if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)) % Hybrid computing Windows <-> Unix! - if ispc - token='start /B '; - else - token = ''; - end - if ~isempty(Parallel(indPC).Port) - ssh_token = ['-p ',Parallel(indPC).Port]; - else - ssh_token = ''; - end - % To manage the diferences in Unix/Windows OS syntax. - remoteFile=['remoteDynare',int2str(j)]; - fidRemote=fopen([remoteFile,'.m'],'w+'); - if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)-> Octave(Slaves) and Vice Versa! - remoteString=['default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),');']; - command1=[token, 'ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' "cd ',Parallel(indPC).RemoteDirectory,'/',PRCDir '; ',Parallel(indPC).MatlabOctavePath,' -f --eval ',remoteFile,' " &']; - else - remoteString=['addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),');']; - command1=[token, 'ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' "cd ',Parallel(indPC).RemoteDirectory,'/',PRCDir '; ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r ',remoteFile,';" &']; - end - fprintf(fidRemote,'%s\n',remoteString); - fclose(fidRemote); - dynareParallelSendFiles([remoteFile,'.m'],PRCDir,Parallel(indPC)); - delete([remoteFile,'.m']); - else - if ~strcmpi(Parallel(indPC).ComputerName,MasterName) % 1.3 Run on a remote machine. - % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa! - if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') - command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -u ',Parallel(indPC).UserName,' -p ',Parallel(indPC).Password,' -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ... - ' -low ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7'');addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"']; - else - command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -u ',Parallel(indPC).UserName,' -p ',Parallel(indPC).Password,' -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ... - ' -low ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"']; - end - else % 1.4 Run on the local machine via the network. - % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa! - if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') - command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ... - ' -low ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"']; - else - command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ... - ' -low ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"']; - end - end - end + else + % When the user user strategy is equal to 1, you must + % do PRCDirSnapshot here to to avoid problems of + % synchronization. + + if isempty(PRCDirSnapshot{indPC}) + PRCDirSnapshot(indPC)=dynareParallelSnapshot(PRCDir,Parallel(indPC)); + PRCDirSnapshotInit(indPC) = PRCDirSnapshot(indPC); else - % When the user user strategy is equal to 1, you must - % do PRCDirSnapshot here to to avoid problems of - % synchronization. - - if isempty(PRCDirSnapshot{indPC}) - PRCDirSnapshot(indPC)=dynareParallelSnapshot(PRCDir,Parallel(indPC)); - PRCDirSnapshotInit(indPC) = PRCDirSnapshot(indPC); - else - PRCDirSnapshot(indPC)=dynareParallelGetNewFiles(PRCDir,Parallel(indPC),PRCDirSnapshot(indPC)); - end - dynareParallelSendFiles(['slaveJob',int2str(j),'.mat'],PRCDir,Parallel(indPC)); - delete(['slaveJob',int2str(j),'.mat']); - + PRCDirSnapshot(indPC)=dynareParallelGetNewFiles(PRCDir,Parallel(indPC),PRCDirSnapshot(indPC)); end + dynareParallelSendFiles(['slaveJob',int2str(j),'.mat'],PRCDir,Parallel(indPC)); + delete(['slaveJob',int2str(j),'.mat']); + end - + end + end - + fprintf(fid,'%s\n',command1); - + end % In This way we are sure that the file 'ConcurrentCommand1.bat' is @@ -518,13 +518,13 @@ end if Strategy==0 || newInstance % See above. PRCDirSnapshot=dynareParallelSnapshot(PRCDir,Parallel(1:totSlaves)); PRCDirSnapshotInit = PRCDirSnapshot; - + % Run the slaves. if ~ispc system('sh ConcurrentCommand1.bat &'); pause(1) else - + if isoctave % Redirect the standard output to the file 'OctaveStandardOutputMessage.txt'! % This file is saved in the Model directory. @@ -553,18 +553,18 @@ if isoctave || options_.console_mode end else hfigstatus = figure('name',['Parallel ',fname],... - 'DockControls','off', ... - 'IntegerHandle','off', ... - 'Interruptible','off', ... - 'MenuBar', 'none', ... - 'NumberTitle','off', ... - 'Renderer','Painters', ... - 'Resize','off'); - + 'DockControls','off', ... + 'IntegerHandle','off', ... + 'Interruptible','off', ... + 'MenuBar', 'none', ... + 'NumberTitle','off', ... + 'Renderer','Painters', ... + 'Resize','off'); + ncol = ceil(totCPU/10); hspace = 0.9/ncol; hstatus(1) = axes('position',[0.05/ncol 0.92 0.9/ncol 0.03], ... - 'box','on','xtick',[],'ytick',[],'xlim',[0 1],'ylim',[0 1]); + 'box','on','xtick',[],'ytick',[],'xlim',[0 1],'ylim',[0 1]); set(hstatus(1),'Units','pixels') hpixel = get(hstatus(1),'Position'); hfigure = get(hfigstatus,'Position'); @@ -577,12 +577,12 @@ else jrow = mod(j-1,10)+1; jcol = ceil(j/10); hstatus(j) = axes('position',[0.05/ncol+(jcol-1)/ncol vstart-vspace*(jrow-1) 0.9/ncol 0.3*vspace], ... - 'box','on','xtick',[],'ytick',[],'xlim',[0 1],'ylim',[0 1]); + 'box','on','xtick',[],'ytick',[],'xlim',[0 1],'ylim',[0 1]); hpat(j) = patch([0 0 0 0],[0 1 1 0],'r','EdgeColor','r'); htit(j) = title(['Initialize ...']); - + end - + cumBlockPerCPU = cumsum(nBlockPerCPU); end pcerdone = NaN(1,totCPU); @@ -596,20 +596,20 @@ idCPU = NaN(1,totCPU); % Caption for console mode computing ... if options_.console_mode || isoctave - + if ~isoctave if strcmpi([Parallel(indPC).MatlabOctavePath], 'octave') RjInformation='Hybrid Computing Is Active: Remote jobs are computed by Octave!'; fprintf([RjInformation,'\n\n']); end end - + fnameTemp=fname; - + L=length(fnameTemp); - + PoCo=strfind(fnameTemp,'_core'); - + for i=PoCo:L if i==PoCo fnameTemp(i)=' '; @@ -617,27 +617,27 @@ if options_.console_mode || isoctave fnameTemp(i)='.'; end end - + for i=1:L if fnameTemp(i)=='_' fnameTemp(i)=' '; end end - + fnameTemp(L)=''; - + Information=['Parallel ' fnameTemp ' Computing ...']; if isoctave if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)) && (Strategy==0) printf('\n'); pause(2); end - + printf([Information,'\n\n']); else fprintf([Information,'\n\n']); end - + end @@ -653,25 +653,25 @@ statusString = ''; flag_CloseAllSlaves=0; while (ForEver) - + waitbarString = ''; statusString0 = repmat('\b',1,length(sprintf(statusString, 100 .* pcerdone))); statusString = ''; - + pause(1) - + try if islocal ==0 dynareParallelGetFiles(['comp_status_',fname,'*.mat'],PRCDir,Parallel(1:totSlaves)); end catch end - + for j=1:totCPU try if ~isempty(['comp_status_',fname,int2str(j),'.mat']) load(['comp_status_',fname,int2str(j),'.mat']); -% whoCloseAllSlaves = who(['comp_status_',fname,int2str(j),'.mat','CloseAllSlaves']); + % whoCloseAllSlaves = who(['comp_status_',fname,int2str(j),'.mat','CloseAllSlaves']); if exist('CloseAllSlaves') && flag_CloseAllSlaves==0 flag_CloseAllSlaves=1; whoiamCloseAllSlaves=j; @@ -691,7 +691,7 @@ while (ForEver) status_Title{j} = waitbarTitle; end catch % ME - % To define! + % To define! if isoctave || options_.console_mode if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)) statusString = [statusString, int2str(j), ' %3.f%% done! ']; @@ -715,15 +715,15 @@ while (ForEver) set(hpat(j),'XData',[0 0 pcerdone(j) pcerdone(j)]); set(htit(j),'String',[status_Title{j},' - ',status_String{j}]); catch - + end end end - + % Check if the slave(s) has generated some new files remotely. % 1. The files .log and .txt are not copied. % 2. The comp_status_*.mat files are managed separately. - + if isoctave % to avoid synchronism problems try PRCDirSnapshot=dynareParallelGetNewFiles(PRCDir,Parallel(1:totSlaves),PRCDirSnapshot); @@ -732,11 +732,11 @@ while (ForEver) else PRCDirSnapshot=dynareParallelGetNewFiles(PRCDir,Parallel(1:totSlaves),PRCDirSnapshot); end - + if isempty(dynareParallelDir(['P_',fname,'_*End.txt'],PRCDir,Parallel(1:totSlaves))) HoTuttiGliOutput=0; for j=1:totCPU - + % Checking if the remote computation is finished and if we copied all the output here. if ~isempty(dir([fname,'_output_',int2str(j),'.mat'])) HoTuttiGliOutput=HoTuttiGliOutput+1; @@ -745,7 +745,7 @@ while (ForEver) dynareParallelGetFiles([fname,'_output_',int2str(j),'.mat'],PRCDir,Parallel(indPC)); end end - + if HoTuttiGliOutput==totCPU mydelete(['comp_status_',fname,'*.mat']); if isoctave || options_.console_mode @@ -760,13 +760,13 @@ while (ForEver) else close(hfigstatus) end - + break else disp('Waiting for output files from slaves ...') end end - + end @@ -780,7 +780,7 @@ for j=1:totCPU delete([fname,'_output_',int2str(j),'.mat']); if isfield(fOutputVar,'OutputFileName') && Parallel(indPC).Local==0 % Check if input files have been updated! - OutputFileName=fOutputVar.OutputFileName; + OutputFileName=fOutputVar.OutputFileName; tmp0=''; for i=1:size(NamFileInput,1) FileList = regexp(strrep(PRCDirSnapshot{indPC},'\','/'),strrep(strrep([NamFileInput{i,:}],'\','/'),'*','(\w*)'),'match'); @@ -808,7 +808,7 @@ for j=1:totCPU end end for k=1:size(tmp1,1) - dynareParallelGetFiles([OutputFileName(i,1) {tmp1(k,:)}],PRCDir,Parallel(indPC)); + dynareParallelGetFiles([OutputFileName(i,1) {tmp1(k,:)}],PRCDir,Parallel(indPC)); end end % check if some output file is missing! @@ -842,7 +842,7 @@ for j=1:totCPU elseif flag_CloseAllSlaves==0 fOutVar(j)=fOutputVar; elseif j==whoiamCloseAllSlaves - fOutVar=fOutputVar; + fOutVar=fOutputVar; end end @@ -860,46 +860,46 @@ pause(1) % Wait for all remote diary off completed dynareParallelGetFiles('*.log',PRCDir,Parallel(1:totSlaves)); switch Strategy - case 0 - for indPC=1:min(find(nCPU>=totCPU)) - if Parallel(indPC).Local == 0 - dynareParallelRmDir(PRCDir,Parallel(indPC)); - end - - if isempty(dir('dynareParallelLogFiles')) - [A B C]=rmdir('dynareParallelLogFiles'); - mkdir('dynareParallelLogFiles'); - end - try - copyfile('*.log','dynareParallelLogFiles'); - mydelete([fname,'*.log']); - catch - end - - mydelete(['*_core*_input*.mat']); - + case 0 + for indPC=1:min(find(nCPU>=totCPU)) + if Parallel(indPC).Local == 0 + dynareParallelRmDir(PRCDir,Parallel(indPC)); end - - delete ConcurrentCommand1.bat - case 1 - delete(['temp_input.mat']) - if newInstance - if isempty(dir('dynareParallelLogFiles')) - [A B C]=rmdir('dynareParallelLogFiles'); - mkdir('dynareParallelLogFiles'); - end + + if isempty(dir('dynareParallelLogFiles')) + [A B C]=rmdir('dynareParallelLogFiles'); + mkdir('dynareParallelLogFiles'); end - copyfile('*.log','dynareParallelLogFiles'); - if newInstance - delete ConcurrentCommand1.bat + try + copyfile('*.log','dynareParallelLogFiles'); + mydelete([fname,'*.log']); + catch end - dynareParallelDelete(['comp_status_',fname,'*.mat'],PRCDir,Parallel); - for indPC=1:min(find(nCPU>=totCPU)) - if Parallel(indPC).Local == 0 - dynareParallelDeleteNewFiles(PRCDir,Parallel(indPC),PRCDirSnapshotInit(indPC),'.log'); - for ifil=1:size(NamFileInput,1) - dynareParallelDelete([NamFileInput{ifil,:}],PRCDir,Parallel(indPC)); - end + + mydelete(['*_core*_input*.mat']); + + end + + delete ConcurrentCommand1.bat + case 1 + delete(['temp_input.mat']) + if newInstance + if isempty(dir('dynareParallelLogFiles')) + [A B C]=rmdir('dynareParallelLogFiles'); + mkdir('dynareParallelLogFiles'); + end + end + copyfile('*.log','dynareParallelLogFiles'); + if newInstance + delete ConcurrentCommand1.bat + end + dynareParallelDelete(['comp_status_',fname,'*.mat'],PRCDir,Parallel); + for indPC=1:min(find(nCPU>=totCPU)) + if Parallel(indPC).Local == 0 + dynareParallelDeleteNewFiles(PRCDir,Parallel(indPC),PRCDirSnapshotInit(indPC),'.log'); + for ifil=1:size(NamFileInput,1) + dynareParallelDelete([NamFileInput{ifil,:}],PRCDir,Parallel(indPC)); end end + end end \ No newline at end of file diff --git a/matlab/parallel/slaveParallel.m b/matlab/parallel/slaveParallel.m index 15b5351a17..5e3fe460ce 100644 --- a/matlab/parallel/slaveParallel.m +++ b/matlab/parallel/slaveParallel.m @@ -2,7 +2,7 @@ function slaveParallel(whoiam,ThisMatlab) % PARALLEL CONTEXT % In a parallelization context, this function is launched on slave % machines, to initialize MATLAB and DYNARE environment and waits for -% instructions sent by the Master. +% instructions sent by the Master. % This function is invoked by masterParallel only when the strategy (1), % i.e. always open, is actived. % @@ -12,8 +12,8 @@ function slaveParallel(whoiam,ThisMatlab) % cluster. % o ThisMatlab [int] index number of this slave machine in the cluster. % -% OUTPUTS -% None +% OUTPUTS +% None % Copyright (C) 2006-2017 Dynare Team % @@ -72,36 +72,36 @@ while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',in end % I wait for 20 min or while mater asks to exit (i.e. it cancels fslave file) pause(1) - + fjob = dir(['slaveJob',int2str(whoiam),'.mat']); - + if ~isempty(fjob) clear fGlobalVar fInputVar fblck nblck fname - + while(1) Go=0; - + Go=fopen(['slaveJob',int2str(whoiam),'.mat']); - - if Go>0 + + if Go>0 fclose(Go); pause(1) load(['slaveJob',int2str(whoiam),'.mat']); break else % Only for testing, will be remouved! - + % if isunix % E1=fopen('/home/ivano/Works/Errore-slaveParallel.txt','w+'); % fclose(E1); - % else + % else % E1=fopen('c:\dynare_calcs\Errore-slaveParallel.txt','w+'); % fclose(E1); % end - + end end - + funcName=fname; % Update global job name. if exist('fGlobalVar') && ~isempty (fGlobalVar) @@ -120,7 +120,7 @@ while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',in end delete(['slaveJob',int2str(whoiam),'.mat']); fInputVar.Parallel = Parallel; - + % Launch the routine to be run in parallel. try tic @@ -136,7 +136,7 @@ while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',in % Save the output result. save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' ); -% keyboard, + % keyboard, if isfield(fOutputVar,'CloseAllSlaves') CloseAllSlaves = 1; fOutputVar = rmfield(fOutputVar,'CloseAllSlaves'); @@ -171,7 +171,7 @@ while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',in delete(['P_',fname,'_',int2str(whoiam),'End.txt']); break end - + end end fslave = dir( ['slaveParallel_input',int2str(whoiam),'.mat']); % Check if Master asks to exit diff --git a/matlab/parallel/storeGlobalVars.m b/matlab/parallel/storeGlobalVars.m index 9d0426f221..79b86aa351 100644 --- a/matlab/parallel/storeGlobalVars.m +++ b/matlab/parallel/storeGlobalVars.m @@ -1,6 +1,6 @@ function storeGlobalVars(fname,append) % PARALLEL CONTEXT -% In a parallel context, this function stores all global vars in structure +% In a parallel context, this function stores all global vars in structure % fGlobalVar and saves it in the file fname.mat % % INPUTS diff --git a/matlab/parallel/struct2local.m b/matlab/parallel/struct2local.m index 16cbd7432f..d45bc12b8c 100644 --- a/matlab/parallel/struct2local.m +++ b/matlab/parallel/struct2local.m @@ -6,7 +6,7 @@ function struct2local(S) % % INPUTS % o S [struc] This structure possibly containing several fields ... -% +% % OUTPUTS % None % diff --git a/matlab/partial_information/PCL_Part_info_irf.m b/matlab/partial_information/PCL_Part_info_irf.m index f0b8ad6ee7..0c3c17c2be 100644 --- a/matlab/partial_information/PCL_Part_info_irf.m +++ b/matlab/partial_information/PCL_Part_info_irf.m @@ -1,9 +1,9 @@ function y=PCL_Part_info_irf( H, varobs, ivar, M_, dr, irfpers,ii) % sets up parameters and calls part-info kalman filter -% developed by G Perendia, July 2006 for implementation from notes by Prof. Joe Pearlman to -% suit partial information RE solution in accordance with, and based on, the +% developed by G Perendia, July 2006 for implementation from notes by Prof. Joe Pearlman to +% suit partial information RE solution in accordance with, and based on, the % Pearlman, Currie and Levine 1986 solution. -% 22/10/06 - Version 2 for new Riccati with 4 params instead 5 +% 22/10/06 - Version 2 for new Riccati with 4 params instead 5 % Copyright (C) 2006-2017 Dynare Team % @@ -23,8 +23,8 @@ function y=PCL_Part_info_irf( H, varobs, ivar, M_, dr, irfpers,ii) % along with Dynare. If not, see <http://www.gnu.org/licenses/>. -% Recall that the state space is given by the -% predetermined variables s(t-1), x(t-1) +% Recall that the state space is given by the +% predetermined variables s(t-1), x(t-1) % and the jump variables x(t). % The jump variables have dimension NETA @@ -66,7 +66,7 @@ U22=0; % determine K1 and K2 observation mapping matrices % This uses the fact that measurements are given by L1*s(t)+L2*x(t) % and s(t) is expressed in the dynamics as -% H1*eps(t)+G11*s(t-1)+G12*x(t-1)+G13*x(t). +% H1*eps(t)+G11*s(t-1)+G12*x(t-1)+G13*x(t). % Thus the observations o(t) can be written in the form % o(t)=K1*[eps(t)' s(t-1)' x(t-1)']' + K2*x(t) where % K1=[L1*H1 L1*G11 L1*G12] K2=L1*G13+L2 @@ -84,18 +84,18 @@ A21=G1(pd+1:end,1:pd); Lambda= nmat*A12+A22; I_L=inv(Lambda); BB=A12*inv(A22); -FF=K2*inv(A22); -QQ=BB*U22*BB' + U11; +FF=K2*inv(A22); +QQ=BB*U22*BB' + U11; UFT=U22*FF'; AA=A11-BB*A21; CCCC=A11-A12*nmat; % F in new notation DD=K1-FF*A21; % H in new notation EE=K1-K2*nmat; RR=FF*UFT+VV; -if ~any(RR) - % if zero add some dummy measurement err. variance-covariances +if ~any(RR) + % if zero add some dummy measurement err. variance-covariances % with diagonals 0.000001. This would not be needed if we used - % the slow solver, or the generalised eigenvalue approach, + % the slow solver, or the generalised eigenvalue approach, % but these are both slower. RR=eye(size(RR,1))*1.0e-6; end @@ -128,14 +128,14 @@ imp=[impact(1:ss-FL_RANK,:); impact(1:ss-FL_RANK,:)]; I_PD=(eye(ss-FL_RANK)-PDIDPDRD); LL0=[ EE (DD-EE)*I_PD]; VV = [ dr.PI_TT1 dr.PI_TT2]; -stderr=diag(M_.Sigma_e^0.5); +stderr=diag(M_.Sigma_e^0.5); irfmat=zeros(size(dr.PI_TT1 ,1),irfpers+1); -irfst=zeros(size(GG,1),irfpers+1); +irfst=zeros(size(GG,1),irfpers+1); irfst(:,1)=stderr(ii)*imp(:,ii); for jj=2:irfpers+1 irfst(:,jj)=GG*irfst(:,jj-1); irfmat(:,jj-1)=VV*irfst(NX+1:ss-FL_RANK,jj); -end +end y = irfmat(:,1:irfpers); save ([M_.fname '_PCL_PtInfoIRFs_' num2str(ii) '_' deblank(exo_names(ii,:))], 'irfmat','irfst'); diff --git a/matlab/partial_information/PCL_Part_info_moments.m b/matlab/partial_information/PCL_Part_info_moments.m index 67612f1587..bb16b66043 100644 --- a/matlab/partial_information/PCL_Part_info_moments.m +++ b/matlab/partial_information/PCL_Part_info_moments.m @@ -1,9 +1,9 @@ function AutoCOR_YRk=PCL_Part_info_moments( H, varobs, dr,ivar) % sets up parameters and calls part-info kalman filter -% developed by G Perendia, July 2006 for implementation from notes by Prof. Joe Pearlman to -% suit partial information RE solution in accordance with, and based on, the +% developed by G Perendia, July 2006 for implementation from notes by Prof. Joe Pearlman to +% suit partial information RE solution in accordance with, and based on, the % Pearlman, Currie and Levine 1986 solution. -% 22/10/06 - Version 2 for new Riccati with 4 params instead 5 +% 22/10/06 - Version 2 for new Riccati with 4 params instead 5 % Copyright (C) 2006-2017 Dynare Team % @@ -22,8 +22,8 @@ function AutoCOR_YRk=PCL_Part_info_moments( H, varobs, dr,ivar) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. -% Recall that the state space is given by the -% predetermined variables s(t-1), x(t-1) +% Recall that the state space is given by the +% predetermined variables s(t-1), x(t-1) % and the jump variables x(t). % The jump variables have dimension NETA @@ -54,7 +54,7 @@ if exist( 'irfpers')==1 end else irfpers=20; -end +end ss=size(G1,1); @@ -78,7 +78,7 @@ U22=0; % determine K1 and K2 observation mapping matrices % This uses the fact that measurements are given by L1*s(t)+L2*x(t) % and s(t) is expressed in the dynamics as -% H1*eps(t)+G11*s(t-1)+G12*x(t-1)+G13*x(t). +% H1*eps(t)+G11*s(t-1)+G12*x(t-1)+G13*x(t). % Thus the observations o(t) can be written in the form % o(t)=K1*[eps(t)' s(t-1)' x(t-1)']' + K2*x(t) where % K1=[L1*H1 L1*G11 L1*G12] K2=L1*G13+L2 @@ -96,8 +96,8 @@ A21=G1(pd+1:end,1:pd); Lambda= nmat*A12+A22; I_L=inv(Lambda); BB=A12*inv(A22); -FF=K2*inv(A22); -QQ=BB*U22*BB' + U11; +FF=K2*inv(A22); +QQ=BB*U22*BB' + U11; UFT=U22*FF'; % kf_param structure: AA=A11-BB*A21; @@ -105,10 +105,10 @@ CCCC=A11-A12*nmat; % F in new notation DD=K1-FF*A21; % H in new notation EE=K1-K2*nmat; RR=FF*UFT+VV; -if ~any(RR) - % if zero add some dummy measurement err. variance-covariances +if ~any(RR) + % if zero add some dummy measurement err. variance-covariances % with diagonals 0.000001. This would not be needed if we used - % the slow solver, or the generalised eigenvalue approach, + % the slow solver, or the generalised eigenvalue approach, % but these are both slower. RR=eye(size(RR,1))*1.0e-6; end @@ -150,7 +150,7 @@ diagCovYR0=diag(COV_YR0); labels = deblank(M_.endo_names(ivar,:)); if options_.nomoments == 0 - z = [ sqrt(diagCovYR0(ivar)) diagCovYR0(ivar) ]; + z = [ sqrt(diagCovYR0(ivar)) diagCovYR0(ivar) ]; title='THEORETICAL MOMENTS'; headers=char('VARIABLE','STD. DEV.','VARIANCE'); dyntable(options_,title,headers,labels,z,size(labels,2)+2,16,10); @@ -168,8 +168,8 @@ end ar = options_.ar; if ar > 0 - COV_YRk= zeros(nn,ar); - AutoCOR_YRk= zeros(nn,ar); + COV_YRk= zeros(nn,ar); + AutoCOR_YRk= zeros(nn,ar); for k=1:ar COV_P=GAM*COV_P; COV_OMEGA= COV_P( end-nn+1:end, end-nn+1:end); diff --git a/matlab/partial_information/PCL_resol.m b/matlab/partial_information/PCL_resol.m index 95b57a00d9..6bf4a7243a 100644 --- a/matlab/partial_information/PCL_resol.m +++ b/matlab/partial_information/PCL_resol.m @@ -17,7 +17,7 @@ function [dr,info]=PCL_resol(ys,check_flag) % info=6: The jacobian evaluated at the steady state is complex. % info=19: The steadystate file did not compute the steady state (inconsistent deep parameters). % info=20: can't find steady state info(2) contains sum of sqare residuals -% info=21: steady state is complex +% info=21: steady state is complex % info(2) contains sum of sqare of % imaginary part of steady state % info=30: Variance can't be computed @@ -45,7 +45,7 @@ function [dr,info]=PCL_resol(ys,check_flag) global M_ options_ oo_ global it_ -jacobian_flag = 0; +jacobian_flag = 0; info = 0; @@ -58,7 +58,7 @@ 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 +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 @@ -70,7 +70,7 @@ 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 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,... @@ -143,5 +143,5 @@ tempex = []; % 01/01/2003 MJ added dr_algo == 1 % 08/24/2001 MJ uses Schmitt-Grohe and Uribe (2001) constant correction -% in dr.ghs2 +% in dr.ghs2 % 05/26/2003 MJ added temporary values for oo_.exo_simul diff --git a/matlab/partial_information/PI_gensys.m b/matlab/partial_information/PI_gensys.m index eb8ba6a943..edc4e5da14 100644 --- a/matlab/partial_information/PI_gensys.m +++ b/matlab/partial_information/PI_gensys.m @@ -83,12 +83,12 @@ try end if singular == 1 || strcmp('MATLAB:nearlySingularMatrix',LastWarningID) == 1 || ... strcmp('MATLAB:illConditionedMatrix',LastWarningID)==1 || ... - strcmp('MATLAB:singularMatrix',LastWarningID)==1 + strcmp('MATLAB:singularMatrix',LastWarningID)==1 [C1,C2,C3,C4, C5, F1, F2, F3, F4, F5, M1, M2, UAVinv, FL_RANK, V01, V02] = PI_gensys_singularC(C1,C2,C3,C4, C5, F1, F2, F3, F4, F5, V01, V02, 0); end warning('on','MATLAB:singularMatrix'); warning('on','MATLAB:nearlySingularMatrix'); - if (any(any(isinf(UAVinv))) || any(any(isnan(UAVinv)))) + if (any(any(isinf(UAVinv))) || any(any(isnan(UAVinv)))) if(options_.ACES_solver==1) disp('ERROR! saving PI_gensys_data_dump'); save PI_gensys_data_dump @@ -131,8 +131,8 @@ G23=eye(FL_RANK); num_inst=0; % New Definitions -Ze11=zeros(NX,NX); -Ze12=zeros(NX,(n-FL_RANK)); +Ze11=zeros(NX,NX); +Ze12=zeros(NX,(n-FL_RANK)); Ze134=zeros(NX,FL_RANK); Ze31=zeros(FL_RANK,NX); @@ -149,7 +149,7 @@ impact=[eye(NX,NX); zeros(n+FL_RANK,NX)]; if(options_.ACES_solver==1) if isfield(lq_instruments,'names') num_inst=size(lq_instruments.names,1); - if num_inst>0 + if num_inst>0 i_var=lq_instruments.inst_var_indices; N1=UAVinv*U02'*lq_instruments.B1; N3=-FF*N1+Sinv*U01'*lq_instruments.B1; @@ -176,9 +176,9 @@ end G0pi=eye(n+FL_RANK+NX); try - % In Matlab: [aa bb q z v w] = qz(a,b) s.t. qaz = aa, qbz = bb % + % In Matlab: [aa bb q z v w] = qz(a,b) s.t. qaz = aa, qbz = bb % % In Octave: [aa bb q z v w] = qz(a,b) s.t. q'az = aa, q'bz=bb % - % and qzcomplex() extension based on lapack zgges produces same + % and qzcomplex() extension based on lapack zgges produces same % qz output for Octave as Matlab qz() does for Matlab thus: if isoctave [a b q z]=qzcomplex(G0pi,G1pi); @@ -192,12 +192,12 @@ catch disp(['PI_Gensys: ' lerror.message]); if 0==strcmp('MATLAB:qz:matrixWithNaNInf',lerror.identifier) disp '** Unexpected Error PI_Gensys:qz: ** :'; - button=questdlg('Continue Y/N?','Unexpected Error in qz','No','Yes','Yes'); - switch button - case 'No' + button=questdlg('Continue Y/N?','Unexpected Error in qz','No','Yes','Yes'); + switch button + case 'No' error ('Terminated') %case 'Yes' - + end end G1pi=[];impact=[];nmat=[]; gev=[]; @@ -206,11 +206,11 @@ catch catch disp '** Unexpected Error in qz ** :'; disp lerror.message; - button=questdlg('Continue Y/N?','Unexpected Error in qz','No','Yes','Yes'); - switch button - case 'No' - error ('Terminated') - case 'Yes' + button=questdlg('Continue Y/N?','Unexpected Error in qz','No','Yes','Yes'); + switch button + case 'No' + error ('Terminated') + case 'Yes' G1pi=[];impact=[];nmat=[]; gev=[]; eu=[-2;-2]; return @@ -257,7 +257,7 @@ if zxz end if (FL_RANK ~= nunstab && options_.ACES_solver~=1) disp(['Number of unstable variables ' num2str(nunstab)]); - disp( ['does not match number of expectational equations ' num2str(FL_RANK)]); + disp( ['does not match number of expectational equations ' num2str(FL_RANK)]); nmat=[];% gev=[]; eu=[-2;-2]; return diff --git a/matlab/partial_information/PI_gensys_singularC.m b/matlab/partial_information/PI_gensys_singularC.m index 5802346b97..b0c085fafc 100644 --- a/matlab/partial_information/PI_gensys_singularC.m +++ b/matlab/partial_information/PI_gensys_singularC.m @@ -1,9 +1,9 @@ function [C1,C2,C3,C4, C5, F1, F2, F3, F4, F5, M1, M2, UAVinv, FL_RANK, V01, V02]=PI_gensys_singularC(C1in, C2in, C3in, C4in, C5in, F1, F2, F3, F4, F5, V01, V02, level) % [C1,C2,C3,C4, C5, F1, F2, F3, F4, F5, M1, M2, UAVinv,FL_RANK, V01, V02]... % =PI_gensys_singularC(C1in, C2in, C3in, C4in, C5in, F1, F2, F3, F4, F5, V01, V02, level) -% +% % Recursive extension for PI_gensys function PCL general DSGE solver -% devised by Prof. Joseph Pearlman +% devised by Prof. Joseph Pearlman % developed by George Perendia % December 2010 diff --git a/matlab/partial_information/disc_riccati_fast.m b/matlab/partial_information/disc_riccati_fast.m index 4a0bd04018..c73adb5b2e 100644 --- a/matlab/partial_information/disc_riccati_fast.m +++ b/matlab/partial_information/disc_riccati_fast.m @@ -1,12 +1,12 @@ function Z=disc_riccati_fast(F,D,R,H,ch) % function Z=disc_riccati_fast(F,D,R,H,ch) -% -% Solves discrete Riccati Equation: +% +% Solves discrete Riccati Equation: % Z=FZF' - FZD'inv(DZD'+R)DZF' + H -% Using the Doubling Algorithm +% Using the Doubling Algorithm % -% George Perendia: based on the doubling algorithm for Riccati -% and the disclyap_fast function provided by Prof. Joe Pearlman +% George Perendia: based on the doubling algorithm for Riccati +% and the disclyap_fast function provided by Prof. Joe Pearlman % V.1 19/5/2006 % V.2 22/10/06 % ================================================================= @@ -28,16 +28,16 @@ function Z=disc_riccati_fast(F,D,R,H,ch) % 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 || isempty( ch ) == 1 - flag_ch = 0; -else - flag_ch = 1; -end +if nargin == 4 || isempty( ch ) == 1 + flag_ch = 0; +else + flag_ch = 1; +end % intialisation tol = 1e-10; % iteration convergence threshold -P0=H; +P0=H; X0=F; if ~any(R) % i.e. ==0 warning('Dangerously evading inversion of zero matrix!'); @@ -50,21 +50,21 @@ I=eye(size(POYO)); clear POYO; % iterate Riccati equation solution -matd=1; +matd=1; count=0; while matd > tol && count < 100 INVPY=inv(I+P0*Y0); - P1=X0*INVPY*P0*X0'+ P0; - Y1=X0'*Y0*INVPY*X0+ Y0; - X1=X0*INVPY*X0; - matd=sum( sum(abs( P1 - P0 ))); + P1=X0*INVPY*P0*X0'+ P0; + Y1=X0'*Y0*INVPY*X0+ Y0; + X1=X0*INVPY*X0; + matd=sum( sum(abs( P1 - P0 ))); % P0=(P1+P1')/2 - P0=P1; + P0=P1; X0=X1; Y0=Y1; count=count+1; % matd; -end +end Z=(P0+P0')/2; %Z=P0 @@ -75,17 +75,17 @@ if count==100 % error.identifier='Riccati not converged!' % error end -%if count >5 +%if count >5 % disp('Riccati count= '); % count %end -clear X0 X1 Y0 Y1 P1 I INVPY; +clear X0 X1 Y0 Y1 P1 I INVPY; -% Check that X is positive definite -if flag_ch==1 - [C,p]=chol(Z); - if p ~= 0 +% Check that X is positive definite +if flag_ch==1 + [C,p]=chol(Z); + if p ~= 0 error('Z is not positive definite') - end -end + end +end diff --git a/matlab/partial_information/disclyap_fast.m b/matlab/partial_information/disclyap_fast.m index fd4516f2b5..5dfcfe4b56 100644 --- a/matlab/partial_information/disclyap_fast.m +++ b/matlab/partial_information/disclyap_fast.m @@ -3,21 +3,21 @@ function [X,exitflag]=disclyap_fast(G,V,tol,check_flag) % Inputs: % - G [double] first input matrix % - V [double] second input matrix -% - tol [scalar] tolerance criterion +% - tol [scalar] tolerance criterion % - check_flag empty of non-empty if non-empty: check positive-definiteness % Outputs: % - X [double] solution matrix % - exitflag [scalar] 0 if solution is found, 1 otherwise % -% Solve the discrete Lyapunov Equation -% X=G*X*G'+V -% Using the Doubling Algorithm +% Solve the discrete Lyapunov Equation +% X=G*X*G'+V +% Using the Doubling Algorithm % -% If check_flag is defined then the code will check if the resulting X -% is positive definite and generate an error message if it is not -% -% Joe Pearlman and Alejandro Justiniano -% 3/5/2005 +% If check_flag is defined then the code will check if the resulting X +% is positive definite and generate an error message if it is not +% +% Joe Pearlman and Alejandro Justiniano +% 3/5/2005 % Copyright (C) 2010-2017 Dynare Team % @@ -36,40 +36,40 @@ function [X,exitflag]=disclyap_fast(G,V,tol,check_flag) % 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( check_flag ) == 1 - flag_ch = 0; -else - flag_ch = 1; -end +if nargin <= 3 || isempty( check_flag ) == 1 + flag_ch = 0; +else + flag_ch = 1; +end exitflag=0; -P0=V; -A0=G; +P0=V; +A0=G; -matd=1; +matd=1; iter=1; -while matd > tol && iter< 2000 - P1=P0+A0*P0*A0'; - A1=A0*A0; - matd=max( max( abs( P1 - P0 ) ) ); - P0=P1; - A0=A1; +while matd > tol && iter< 2000 + P1=P0+A0*P0*A0'; + A1=A0*A0; + matd=max( max( abs( P1 - P0 ) ) ); + P0=P1; + A0=A1; iter=iter+1; -end +end if iter==5000 X=NaN(P0); exitflag=1; return end -clear A0 A1 P1; +clear A0 A1 P1; -X=(P0+P0')/2; +X=(P0+P0')/2; -% Check that X is positive definite -if flag_ch==1 - [C,p]=chol(X); - if p ~= 0 +% Check that X is positive definite +if flag_ch==1 + [C,p]=chol(X); + if p ~= 0 exitflag=1; error('X is not positive definite') - end -end \ No newline at end of file + end +end \ No newline at end of file diff --git a/matlab/partial_information/dr1_PI.m b/matlab/partial_information/dr1_PI.m index 8ae7ff2ff1..04fe8d9267 100644 --- a/matlab/partial_information/dr1_PI.m +++ b/matlab/partial_information/dr1_PI.m @@ -6,7 +6,7 @@ function [dr,info,M_,options_,oo_] = dr1_PI(dr,task,M_,options_,oo_) % Prepares System as % A0*E_t[y(t+1])+A1*y(t)=A2*y(t-1)+c+psi*eps(t) % with z an exogenous variable process. -% and calls PI_Gensys.m solver +% and calls PI_Gensys.m solver % based on Pearlman et al 1986 paper and derived from % C.Sims' gensys linear solver. % to return solution in format @@ -16,29 +16,29 @@ function [dr,info,M_,options_,oo_] = dr1_PI(dr,task,M_,options_,oo_) % dr [matlab structure] Decision rules for stochastic simulations. % task [integer] if task = 0 then dr1 computes decision rules. % if task = 1 then dr1 computes eigenvalues. -% M_ [matlab structure] Definition of the model. +% M_ [matlab structure] Definition of the model. % options_ [matlab structure] Global options. -% oo_ [matlab structure] Results -% +% oo_ [matlab structure] Results +% % OUTPUTS % dr [matlab structure] Decision rules for stochastic simulations. % info [integer] info=1: the model doesn't define current variables uniquely -% info=2: problem in mjdgges.dll info(2) contains error code. +% info=2: problem in mjdgges.dll info(2) contains error code. % info=3: BK order condition not satisfied info(2) contains "distance" % absence of stable trajectory. % info=4: BK order condition not satisfied info(2) contains "distance" % indeterminacy. % info=5: BK rank condition not satisfied. -% M_ [matlab structure] +% M_ [matlab structure] % options_ [matlab structure] % oo_ [matlab structure] -% +% % ALGORITHM % ... -% +% % SPECIAL REQUIREMENTS % none. -% +% % Copyright (C) 1996-2017 Dynare Team % @@ -66,9 +66,9 @@ xlen = M_.maximum_endo_lead + M_.maximum_endo_lag + 1; if (options_.aim_solver == 1) options_.aim_solver == 0; - warning('You can not use AIM with Part Info solver. AIM ignored'); + warning('You can not use AIM with Part Info solver. AIM ignored'); end -if (options_.order > 1) +if (options_.order > 1) warning('You can not use order higher than 1 with Part Info solver. Order 1 assumed'); options_.order =1; end @@ -101,11 +101,11 @@ else iyv = iyv(:); iyr0 = find(iyv) ; it_ = M_.maximum_lag + 1 ; - + if M_.exo_nbr == 0 oo_.exo_steady_state = [] ; end - + if options_.ACES_solver == 1 sim_ruleids=[]; @@ -172,15 +172,15 @@ 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),:); -if (options_.aim_solver == 1) +if (options_.aim_solver == 1) error('Anderson and Moore AIM solver is not compatible with Partial Information models'); end % end if useAIM and... % If required, try PCL86 solver, that is, if not the check being - % performed only and if it is 1st order + % performed only and if it is 1st order % create sparse, extended jacobia AA: nendo=M_.endo_nbr; % = size(aa,1) - + if(options_.ACES_solver==1) %if ~isfield(lq_instruments,'names') @@ -239,8 +239,8 @@ end % end if useAIM and... % E_t z(t) % E_t z(t+1) % E_t z(t+2) - % E_t z(t+3) - + % E_t z(t+3) + % partition jacobian: jlen=M_.nspred+M_.nsfwrd+M_.endo_nbr+M_.exo_nbr; % length of jacobian PSI=-jacobia_(:, jlen-M_.exo_nbr+1:end); % exog @@ -253,12 +253,12 @@ end % end if useAIM and... AA2=AA0; % empty A2 and A3 AA3=AA0; if xlen==nendo % && M_.maximum_lag <=1 && M_.maximum_lead <=1 % apply a shortcut - AA1=jacobia_(:,nspred+1:nspred+nendo); + AA1=jacobia_(:,nspred+1:nspred+nendo); if M_.maximum_lead ==1 fnd = find(lead_lag(:,M_.maximum_lag+2)); AA0(:, fnd)= jacobia_(:,nonzeros(lead_lag(:,M_.maximum_lag+2))); %forwd jacobian end - if nspred>0 && M_.maximum_lag ==1 + if nspred>0 && M_.maximum_lag ==1 fnd = find(lead_lag(:,1)); AA2(:, fnd)= jacobia_(:,nonzeros(lead_lag(:,1))); %backward end @@ -266,7 +266,7 @@ end % end if useAIM and... if nendo-xlen==num_inst PSI=[PSI;zeros(num_inst, M_.exo_nbr)]; % AA1 contemporary - AA_all=jacobia_(:,nspred+1:nspred+nendo); + AA_all=jacobia_(:,nspred+1:nspred+nendo); AA1=AA_all(:,lq_instruments.m_var); % endo without instruments lq_instruments.ij1=AA_all(:,lq_instruments.inst_var_indices); % instruments only lq_instruments.B1=-[lq_instruments.ij1; eye(num_inst)]; @@ -281,7 +281,7 @@ end % end if useAIM and... lq_instruments.B0=[lq_instruments.ij0; eye(num_inst)]; AA0=[AA0, zeros(xlen,num_inst); zeros(num_inst,xlen+num_inst)]; end - if nspred>0 && M_.maximum_lag ==1 + if nspred>0 && M_.maximum_lag ==1 AA_all(:,:)=0.0; fnd = find(lead_lag(:,1)); AA_all(:, fnd)= jacobia_(:,nonzeros(lead_lag(:,1))); %backward @@ -312,7 +312,7 @@ end % end if useAIM and... NX=M_.exo_nbr; % no of exogenous varexo shock variables. NETA=nfwrd+nboth; % total no of exp. errors set to no of forward looking equations FL_RANK=rank(AA0); % nfwrd+nboth; % min total no of forward looking equations and vars - + try % call [G1pi,C,impact,nmat,TT1,TT2,gev,eu]=PI_gensys(a0,a1,a2,c,PSI,NX,NETA,NO_FL_EQS) % System given as @@ -348,13 +348,13 @@ end % end if useAIM and... [G1pi,CC,impact,nmat,TT1,TT2,gev,eu, DD, E2,E5, GAMMA, FL_RANK]=PI_gensys(AA0,AA1,-AA2,AA3,cc,PSI,NX,NETA,FL_RANK, M_, options_); end - % reuse some of the bypassed code and tests that may be needed + % reuse some of the bypassed code and tests that may be needed if (eu(1) ~= 1 || eu(2) ~= 1) && options_.ACES_solver==0 info(1) = abs(eu(1)+eu(2)); info(2) = 1.0e+8; % return end - + dr.PI_ghx=G1pi; dr.PI_ghu=impact; dr.PI_TT1=TT1; @@ -369,7 +369,7 @@ end % end if useAIM and... dr.ghu=impact; dr.eigval = eig(G1pi); dr.rank=FL_RANK; - + if options_.ACES_solver==1 betap=options_.planner_discount; sigma_cov=M_.Sigma_e; @@ -390,8 +390,8 @@ end % end if useAIM and... ACES.Q=DYN_Q; ACES.W=W; NY=nendo-num_inst; - - % save the followings in a subdirectory - BY + + % save the followings in a subdirectory - BY save ([ACES_DirectoryName,'/',M_.fname '_ACESLQ_Matrices'], 'ACES'); save ([ACES_DirectoryName,'/',M_.fname '_ACESLQ_GAMMA'], 'GAMMA'); save ([ACES_DirectoryName,'/',M_.fname '_ACESLQ_A.txt'], 'G1pi', '-ascii', '-double', '-tabs'); @@ -449,6 +449,6 @@ end % end if useAIM and... end end - % TODO: + % TODO: % if options_.loglinear == 1 % if exogenous deterministic variables \ No newline at end of file diff --git a/matlab/perfect-foresight-models/det_cond_forecast.m b/matlab/perfect-foresight-models/det_cond_forecast.m index ac2a86c033..ee177d8306 100644 --- a/matlab/perfect-foresight-models/det_cond_forecast.m +++ b/matlab/perfect-foresight-models/det_cond_forecast.m @@ -34,9 +34,9 @@ pp = 2; initial_conditions = oo_.steady_state; verbosity = options_.verbosity; if options_.periods == 0 - options_.periods = 25; + options_.periods = 25; end -%We have to get an initial guess for the conditional forecast +%We have to get an initial guess for the conditional forecast % and terminal conditions for the non-stationary variables, we % use the first order approximation of the rational expectation solution. if ~isfield(oo_,'dr') || (isempty(oo_.dr)) @@ -82,7 +82,7 @@ if length(varargin) > 3 error(['Unknown exogenous variable ' controlled_varexo(i,:)]); end end - + else % alternative way to call: plan, dset, dates_of_frcst plan = varargin{1}; @@ -102,10 +102,10 @@ else s2 = strings(range(range.ndat)); error(['the dseries ' inputname(2) ' finish at time ' s1{1} ' before the last period of forecast ' s2{1}]); end - + sym_dset = dset(dates(-range(1)):dates(range(range.ndat))); periods = options_.periods + M_.maximum_lag + M_.maximum_lead; - total_periods = periods + range.ndat; + total_periods = periods + range.ndat; if isfield(oo_, 'exo_simul') if size(oo_.exo_simul, 1) ~= total_periods oo_.exo_simul = repmat(oo_.exo_steady_state',total_periods,1); @@ -113,22 +113,22 @@ else else oo_.exo_simul = repmat(oo_.exo_steady_state',total_periods,1); end - + oo_.endo_simul = repmat(oo_.steady_state, 1, total_periods); - + for i = 1:sym_dset.vobs iy = find(strcmp(strtrim(sym_dset.name{i}), strtrim(plan.endo_names))); if ~isempty(iy) oo_.endo_simul(iy,1:sym_dset.nobs) = sym_dset.data(:, i); initial_conditions(iy) = sym_dset.data(1, i); - else - ix = find(strcmp(strtrim(sym_dset.name{i}), strtrim(plan.exo_names))); - if ~isempty(ix) - oo_.exo_simul(1, ix) = sym_dset.data(1, i)'; + else + ix = find(strcmp(strtrim(sym_dset.name{i}), strtrim(plan.exo_names))); + if ~isempty(ix) + oo_.exo_simul(1, ix) = sym_dset.data(1, i)'; else %warning(['The variable ' sym_dset.name{i} ' in the dataset ' inputname(2) ' is not a endogenous neither an exogenous variable!!']); end - end + end end for i = 1:length(M_.aux_vars) if M_.aux_vars(i).type == 1 %lag variable @@ -146,8 +146,8 @@ else %Compute the initial path using the the steady-state % steady-state %for jj = 2 : (options_.periods + 2) - for jj = 2 : (range.ndat + 2) - oo_.endo_simul(:, jj) = oo_.steady_state; + for jj = 2 : (range.ndat + 2) + oo_.endo_simul(:, jj) = oo_.steady_state; end missings = isnan(oo_.endo_simul(:,1)); if any(missings) @@ -165,11 +165,11 @@ else options_.dynatol.f = save_options_dynatol_f; if Info == 0 - oo_.endo_simul = endo; - oo_.exo_simul = exo; + oo_.endo_simul = endo; + oo_.exo_simul = exo; end endo = endo'; - endo_l = size(endo(1+M_.maximum_lag:end,:),1); + endo_l = size(endo(1+M_.maximum_lag:end,:),1); jrng = dates(plan.date(1)):dates(plan.date(1)+endo_l); data_set = dseries(nan(endo_l, dset.vobs), plan.date(1), dset.name); for i = 1:length(dset.name) @@ -179,7 +179,7 @@ else else pos = find(strcmp(dset.name{i},plan.exo_names)); if ~isempty(pos) - data_set{dset.name{i}} = dseries(exo(1+M_.maximum_lag:end,pos), plan.date(1),dset.name{i}); + data_set{dset.name{i}} = dseries(exo(1+M_.maximum_lag:end,pos), plan.date(1),dset.name{i}); end end end @@ -209,14 +209,14 @@ else return end else - error('impossible case'); + error('impossible case'); end - + else oo_.exo_simul = repmat(oo_.exo_steady_state',options_.periods+2,1); oo_.endo_simul = repmat(oo_.steady_state, 1, options_.periods+2); end - + direct_mode = 1; constrained_paths = plan.constrained_paths_; constrained_vars = plan.constrained_vars_; @@ -232,16 +232,16 @@ else else shocks_present = 0; end - + total_periods = plan.date; - + end if ~isfield(options_cond_fcst,'periods') || isempty(options_cond_fcst.periods) options_cond_fcst.periods = 100; end -options_.periods = 10; +options_.periods = 10; if direct_mode == 1 n_periods = length(constrained_periods); @@ -272,7 +272,7 @@ if direct_mode == 1 tp = tp + 1; j = j + 1; end - if tp - tp0 > max_periods_simulation + if tp - tp0 > max_periods_simulation max_periods_simulation = tp - tp0; end end @@ -311,7 +311,7 @@ if direct_mode == 1 tp = tp + 1; j = j + 1; end - if tp - tp0 > max_periods_simulation + if tp - tp0 > max_periods_simulation max_periods_simulation = tp - tp0; end end @@ -336,7 +336,7 @@ ny = size(ys,1); xs = [oo_.exo_steady_state ; oo_.exo_det_steady_state]; nx = size(xs,1); -constrained_periods = max_periods_simulation; +constrained_periods = max_periods_simulation; n_endo_constrained = size(constrained_vars,1); if isfield(options_cond_fcst,'controlled_varexo') n_control_exo = size(options_cond_fcst.controlled_varexo, 1); @@ -453,7 +453,7 @@ if pf && ~surprise not_achieved = 0; end end - + per = 30; z = oo_.endo_simul(:, 1 : per + 2 ); zx = oo_.exo_simul(1: per + 2,:); @@ -485,7 +485,7 @@ if pf && ~surprise end mexErrCheck('bytecode', chck); end - if k == 1 + if k == 1 g1(1:M_.endo_nbr,-M_.endo_nbr + [cur_indx lead_indx]) = data1.g1(:,M_.nspred + 1:end); elseif k == per g1(M_.endo_nbr * (k - 1) + 1 :M_.endo_nbr * k,M_.endo_nbr * (k -2) + [lag_indx cur_indx]) = data1.g1(:,1:M_.nspred + M_.endo_nbr); @@ -514,7 +514,7 @@ if pf && ~surprise end end end - + d_y_x = - g1 \ g1_x; cum_l1 = 0; @@ -534,24 +534,24 @@ if pf && ~surprise end cum_l1 = cum_l1 + length(constrained_vars(j1)); end - - -% col_count = 1; -% for j = controlled_varexo' -% for time = time_index_constraint -% saved = oo_.exo_simul(time,j); -% oo_.exo_simul(time,j) = oo_.exo_simul(time,j) + eps1; -% simul(); -% J1(:,col_count) = (oo_.endo_simul(indx_endo) - ys) / eps1; -% oo_.exo_simul(time,j) = saved; -% col_count = col_count + 1; -% end -% end -% J1 -% sdfmlksdf; - + + + % col_count = 1; + % for j = controlled_varexo' + % for time = time_index_constraint + % saved = oo_.exo_simul(time,j); + % oo_.exo_simul(time,j) = oo_.exo_simul(time,j) + eps1; + % simul(); + % J1(:,col_count) = (oo_.endo_simul(indx_endo) - ys) / eps1; + % oo_.exo_simul(time,j) = saved; + % col_count = col_count + 1; + % end + % end + % J1 + % sdfmlksdf; + disp(['iteration ' int2str(it) ' error = ' num2str(normr)]); - + if normr <= eps convg = 1; disp('convergence achieved'); @@ -573,8 +573,8 @@ if pf && ~surprise exo = oo_.exo_simul; else for t = 1:constrained_periods - - if direct_mode && ~isempty(is_constraint) + + if direct_mode && ~isempty(is_constraint) [pos_constrained_pf, junk] = find(constrained_perfect_foresight .* is_constraint(t, :)'); indx_endo_solve_pf = constrained_vars(pos_constrained_pf); if isempty(indx_endo_solve_pf) @@ -582,7 +582,7 @@ else else pf = length(indx_endo_solve_pf); end - + [pos_constrained_surprise, junk] = find((1-constrained_perfect_foresight) .* is_constraint(t, :)'); indx_endo_solve_surprise = constrained_vars(pos_constrained_surprise); @@ -592,8 +592,8 @@ else surprise = length(indx_endo_solve_surprise); end end - - if direct_mode && ~isempty(is_shock) + + if direct_mode && ~isempty(is_shock) [pos_shock_pf, junk] = find(shock_perfect_foresight .* is_shock(t, :)'); indx_endo_solve_pf = shock_vars(pos_shock_pf); if isempty(indx_endo_solve_pf) @@ -601,7 +601,7 @@ else else b_pf = length(indx_endo_solve_pf); end - + [pos_shock_surprise, junk] = find((1-shock_perfect_foresight) .* is_shock(t, :)'); indx_endo_solve_surprise = shock_vars(pos_shock_surprise); @@ -611,7 +611,7 @@ else b_surprise = length(indx_endo_solve_surprise); end end - + disp('==============================================================================================='); disp(['t=' int2str(t) ' conditional (surprise=' int2str(surprise) ' perfect foresight=' int2str(pf) ') unconditional (surprise=' int2str(b_surprise) ' perfect foresight=' int2str(b_pf) ')']); disp('==============================================================================================='); @@ -627,16 +627,16 @@ else %exo_init oo_.exo_simul = exo_init; oo_.endo_simul(:,1) = initial_conditions; - + time_index_constraint = maximum_lag + 1:maximum_lag + constrained_periods - t + 1; - + if direct_mode nb_shocks = length(plan.shock_vars_); if nb_shocks > 0 shock_index_t = shock_index{t}; shock_vars_t = shock_vars(shock_index_t); for shock_indx = shock_index_t - if shock_perfect_foresight(shock_indx) + if shock_perfect_foresight(shock_indx) oo_.exo_simul(time_index_constraint,shock_vars_t(shock_indx)) = shock_paths(shock_indx,t:constrained_periods); else oo_.exo_simul(maximum_lag + 1,shock_vars_t(shock_indx)) = shock_paths(shock_indx,t); @@ -653,11 +653,11 @@ else for jj = 1 : (options_.periods + 2) oo_.endo_simul(:,jj) = oo_.steady_state + oo_.endo_simul(:,jj); end - + constraint_index_t = constraint_index{t}; controlled_varexo_t = controlled_varexo(constraint_index_t); constrained_vars_t = constrained_vars(constraint_index_t); - + second_system_size = surprise + pf * (constrained_periods - t + 1); indx_endo = zeros(second_system_size,1); col_count = 1; @@ -670,9 +670,9 @@ else col_count = col_count + 1; end end - + r = zeros(second_system_size,1); - + convg = 0; it = 1; while ~convg && it <= maxit @@ -709,7 +709,7 @@ else end yc = oo_.endo_simul(:,maximum_lag + 1); ys = oo_.endo_simul(indx_endo); - + col_count = 1; for j = constraint_index_t if constrained_perfect_foresight(j) @@ -722,7 +722,7 @@ else col_count = col_count + 1; end end - + disp('computation of derivatives w.r. to exogenous shocks'); per = 30; @@ -757,14 +757,14 @@ else end mexErrCheck('bytecode', chck); end - if k == 1 + if k == 1 g1(1:M_.endo_nbr,-M_.endo_nbr + [cur_indx lead_indx]) = data1.g1(:,M_.nspred + 1:end); elseif k == per g1(M_.endo_nbr * (k - 1) + 1 :M_.endo_nbr * k,M_.endo_nbr * (k -2) + [lag_indx cur_indx]) = data1.g1(:,1:M_.nspred + M_.endo_nbr); else g1(M_.endo_nbr * (k - 1) + 1 :M_.endo_nbr * k, M_.endo_nbr * (k -2) + [lag_indx cur_indx lead_indx]) = data1.g1; end - + l2 = 1; pf_c = 1; if t + k - 1 <= constrained_periods @@ -794,10 +794,10 @@ else end end end - + d_y_x = - g1 \ g1_x; - + cum_l1 = 0; count_col = 1; cum_index_J = 1:length(cum_index_d_y_x(indx_x)); @@ -821,39 +821,39 @@ else cum_l1 = cum_l1 + length(constrained_vars_t(j1)); end - -% % Numerical computation of the derivatives in the second systme -% J1 = []; -% col_count = 1; -% for j = constraint_index_t -% j_pos = controlled_varexo(j); -% if constrained_perfect_foresight(j) -% for time = time_index_constraint -% saved = oo_.exo_simul(time,j_pos); -% oo_.exo_simul(time,j_pos) = oo_.exo_simul(time,j_pos) + eps1; -% simul(); -% J1(:,col_count) = (oo_.endo_simul(indx_endo) - ys) / eps1; -% oo_.exo_simul(time,j_pos) = saved; -% col_count = col_count + 1; -% end -% else -% saved = oo_.exo_simul(maximum_lag+1,j_pos); -% oo_.exo_simul(maximum_lag+1,j_pos) = oo_.exo_simul(maximum_lag+1,j_pos) + eps1; -% simul(); -% % indx_endo -% J1(:,col_count) = (oo_.endo_simul(indx_endo) - ys) / eps1; -% % J(:,col_count) = (oo_.endo_simul((pp - 1) * M_.endo_nbr + 1: pp * M_.endo_nbr) - ys) / eps1; -% oo_.exo_simul(maximum_lag+1,j_pos) = saved; -% col_count = col_count + 1; -% end -% end -% disp('J1'); -% disp(full(J1)); -% sdfmlk; - + + % % Numerical computation of the derivatives in the second systme + % J1 = []; + % col_count = 1; + % for j = constraint_index_t + % j_pos = controlled_varexo(j); + % if constrained_perfect_foresight(j) + % for time = time_index_constraint + % saved = oo_.exo_simul(time,j_pos); + % oo_.exo_simul(time,j_pos) = oo_.exo_simul(time,j_pos) + eps1; + % simul(); + % J1(:,col_count) = (oo_.endo_simul(indx_endo) - ys) / eps1; + % oo_.exo_simul(time,j_pos) = saved; + % col_count = col_count + 1; + % end + % else + % saved = oo_.exo_simul(maximum_lag+1,j_pos); + % oo_.exo_simul(maximum_lag+1,j_pos) = oo_.exo_simul(maximum_lag+1,j_pos) + eps1; + % simul(); + % % indx_endo + % J1(:,col_count) = (oo_.endo_simul(indx_endo) - ys) / eps1; + % % J(:,col_count) = (oo_.endo_simul((pp - 1) * M_.endo_nbr + 1: pp * M_.endo_nbr) - ys) / eps1; + % oo_.exo_simul(maximum_lag+1,j_pos) = saved; + % col_count = col_count + 1; + % end + % end + % disp('J1'); + % disp(full(J1)); + % sdfmlk; + normr = norm(r, 1); - + disp(['iteration ' int2str(it) ' error = ' num2str(normr) ' at time ' int2str(t)]); if normr <= eps @@ -862,7 +862,7 @@ else else % Newton update on exogenous shocks try - D_exo = - J \ r; + D_exo = - J \ r; catch [V, D] = eig(full(J)); ev = diag(D); diff --git a/matlab/perfect-foresight-models/linear_approximation_accuracy.m b/matlab/perfect-foresight-models/linear_approximation_accuracy.m index e3f9eb5215..552310a691 100644 --- a/matlab/perfect-foresight-models/linear_approximation_accuracy.m +++ b/matlab/perfect-foresight-models/linear_approximation_accuracy.m @@ -2,12 +2,12 @@ function err = linear_approximation_accuracy(options_, M_, oo_) % Evaluates the accuracy of the linear approximation when solving perfect foresight models, by % reporting the max absolute value of the dynamic residuals. % -% INPUTS +% INPUTS % - options_ [struct] contains various options. % - M_ [struct] contains a description of the model. % - oo_ [struct] contains results. % -% OUTPUTS +% OUTPUTS % - err [double] n*1 vector, evaluation of the accuracy (n is the number of equations). % Copyright (C) 2015 Dynare Team diff --git a/matlab/perfect-foresight-models/linear_perfect_foresight_problem.m b/matlab/perfect-foresight-models/linear_perfect_foresight_problem.m index 8361ffcb97..78d9fed418 100644 --- a/matlab/perfect-foresight-models/linear_perfect_foresight_problem.m +++ b/matlab/perfect-foresight-models/linear_perfect_foresight_problem.m @@ -1,11 +1,11 @@ function [residuals,JJacobian] = linear_perfect_foresight_problem(y, dynamicjacobian, Y0, YT, ... - exo_simul, params, steady_state, ... - maximum_lag, T, ny, i_cols, ... - i_cols_J1, i_cols_1, i_cols_T, ... - i_cols_j,nnzJ,jendo,jexog) + exo_simul, params, steady_state, ... + maximum_lag, T, ny, i_cols, ... + i_cols_J1, i_cols_1, i_cols_T, ... + i_cols_j,nnzJ,jendo,jexog) % function [residuals,JJacobian] = perfect_foresight_problem(x, model_dynamic, Y0, YT,exo_simul, % params, steady_state, maximum_lag, periods, ny, i_cols,i_cols_J1, i_cols_1, -% i_cols_T, i_cols_j, nnzA) +% i_cols_T, i_cols_j, nnzA) % computes the residuals and th Jacobian matrix % for a perfect foresight problem over T periods. % diff --git a/matlab/perfect-foresight-models/make_ex_.m b/matlab/perfect-foresight-models/make_ex_.m index 73ab28f436..1eec29ac54 100644 --- a/matlab/perfect-foresight-models/make_ex_.m +++ b/matlab/perfect-foresight-models/make_ex_.m @@ -5,14 +5,14 @@ function oo_=make_ex_(M_,options_,oo_) % M_: Dynare model structure % options_: Dynare options structure % oo_: Dynare results structure -% +% % OUTPUTS % oo_: Dynare results structure % % ALGORITHM -% +% % SPECIAL REQUIREMENTS -% +% % Copyright (C) 1996-2016 Dynare Team % @@ -53,7 +53,7 @@ else else error('histval and endval cannot be used simultaneously') end -end +end % Initialize oo_.exo_det_simul if M_.exo_det_nbr > 0 diff --git a/matlab/perfect-foresight-models/make_y_.m b/matlab/perfect-foresight-models/make_y_.m index f3c8f686f6..bbe41db716 100644 --- a/matlab/perfect-foresight-models/make_y_.m +++ b/matlab/perfect-foresight-models/make_y_.m @@ -1,20 +1,20 @@ function oo_=make_y_(M_,options_,oo_) % function oo_=make_y_(M_,options_,oo_) % forms oo_.endo_simul as guess values for deterministic simulations -% +% % INPUTS % M_: Dynare model structure % options_: Dynare options structure % oo_: Dynare results structure -% +% % OUTPUTS % oo_: Dynare results structure -% +% % ALGORITHM % ... % SPECIAL REQUIREMENTS % none -% +% % Copyright (C) 1996-2016 Dynare Team % @@ -33,7 +33,7 @@ function oo_=make_y_(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 ys0_ +global ys0_ if options_.steadystate_flag [oo_.steady_state,M_.params,check] = ... diff --git a/matlab/perfect-foresight-models/perfect_foresight_mcp_problem.m b/matlab/perfect-foresight-models/perfect_foresight_mcp_problem.m index d4b4193086..5160ce71f6 100644 --- a/matlab/perfect-foresight-models/perfect_foresight_mcp_problem.m +++ b/matlab/perfect-foresight-models/perfect_foresight_mcp_problem.m @@ -1,8 +1,8 @@ function [residuals,JJacobian] = perfect_foresight_mcp_problem(y, dynamic_function, Y0, YT, ... - exo_simul, params, steady_state, ... - maximum_lag, T, ny, i_cols, ... - i_cols_J1, i_cols_1, i_cols_T, ... - i_cols_j,nnzJ,eq_index) + exo_simul, params, steady_state, ... + maximum_lag, T, ny, i_cols, ... + i_cols_J1, i_cols_1, i_cols_T, ... + i_cols_j,nnzJ,eq_index) % function [residuals,JJacobian] = perfect_foresight_mcp_problem(y, dynamic_function, Y0, YT, ... % exo_simul, params, steady_state, ... % maximum_lag, T, ny, i_cols, ... @@ -17,7 +17,7 @@ function [residuals,JJacobian] = perfect_foresight_mcp_problem(y, dynamic_functi % Y0 [double] N*1 array, initial conditions for the endogenous variables % YT [double] N*1 array, terminal conditions for the endogenous variables % exo_simul [double] nperiods*M_.exo_nbr matrix of exogenous variables (in declaration order) -% for all simulation periods +% for all simulation periods % params [double] nparams*1 array, parameter values % steady_state [double] endo_nbr*1 vector of steady state values % maximum_lag [scalar] maximum lag present in the model @@ -25,7 +25,7 @@ function [residuals,JJacobian] = perfect_foresight_mcp_problem(y, dynamic_functi % ny [scalar] number of endogenous variables % i_cols [double] indices of variables appearing in M.lead_lag_incidence % and that need to be passed to _dynamic-file -% i_cols_J1 [double] indices of contemporaneous and forward looking variables +% i_cols_J1 [double] indices of contemporaneous and forward looking variables % appearing in M.lead_lag_incidence % i_cols_1 [double] indices of contemporaneous and forward looking variables in % M.lead_lag_incidence in dynamic Jacobian (relevant in first period) @@ -33,8 +33,8 @@ function [residuals,JJacobian] = perfect_foresight_mcp_problem(y, dynamic_functi % variables (relevant in last period) % i_cols_j [double] indices of variables in M.lead_lag_incidence % in dynamic Jacobian (relevant in intermediate periods) -% nnzJ [scalar] number of non-zero elements in Jacobian -% eq_index [double] N*1 array, index vector describing residual mapping resulting +% nnzJ [scalar] number of non-zero elements in Jacobian +% eq_index [double] N*1 array, index vector describing residual mapping resulting % from complementarity setup % OUTPUTS % residuals [double] (N*T)*1 array, residuals of the stacked problem @@ -77,11 +77,11 @@ i_cols_J = i_cols; for it = 2:(T+1) if nargout == 1 res = dynamic_function(YY(i_cols),exo_simul, params, ... - steady_state,it); + steady_state,it); residuals(i_rows) = res(eq_index); elseif nargout == 2 [res,jacobian] = dynamic_function(YY(i_cols),exo_simul, params, ... - steady_state,it); + steady_state,it); residuals(i_rows) = res(eq_index); if it == 2 [rows,cols,vals] = find(jacobian(eq_index,i_cols_1)); @@ -96,7 +96,7 @@ for it = 2:(T+1) end offset = offset + ny; end - + i_rows = i_rows + ny; i_cols = i_cols + ny; end @@ -104,5 +104,5 @@ end if nargout == 2 iJacobian = cat(1,iJacobian{:}); JJacobian = sparse(iJacobian(:,1),iJacobian(:,2),iJacobian(:,3),T* ... - ny,T*ny); + ny,T*ny); end \ No newline at end of file diff --git a/matlab/perfect-foresight-models/perfect_foresight_problem.m b/matlab/perfect-foresight-models/perfect_foresight_problem.m index 9561190945..a853d65149 100644 --- a/matlab/perfect-foresight-models/perfect_foresight_problem.m +++ b/matlab/perfect-foresight-models/perfect_foresight_problem.m @@ -1,8 +1,8 @@ function [residuals,JJacobian] = perfect_foresight_problem(y, dynamic_function, Y0, YT, ... - exo_simul, params, steady_state, ... - maximum_lag, T, ny, i_cols, ... - i_cols_J1, i_cols_1, i_cols_T, ... - i_cols_j,nnzJ) + exo_simul, params, steady_state, ... + maximum_lag, T, ny, i_cols, ... + i_cols_J1, i_cols_1, i_cols_T, ... + i_cols_j,nnzJ) % function [residuals,JJacobian] = perfect_foresight_problem(y, dynamic_function, Y0, YT, ... % exo_simul, params, steady_state, ... % maximum_lag, T, ny, i_cols, ... @@ -16,7 +16,7 @@ function [residuals,JJacobian] = perfect_foresight_problem(y, dynamic_function, % Y0 [double] N*1 array, initial conditions for the endogenous variables % YT [double] N*1 array, terminal conditions for the endogenous variables % exo_simul [double] nperiods*M_.exo_nbr matrix of exogenous variables (in declaration order) -% for all simulation periods +% for all simulation periods % params [double] nparams*1 array, parameter values % steady_state [double] endo_nbr*1 vector of steady state values % maximum_lag [scalar] maximum lag present in the model @@ -24,7 +24,7 @@ function [residuals,JJacobian] = perfect_foresight_problem(y, dynamic_function, % ny [scalar] number of endogenous variables % i_cols [double] indices of variables appearing in M.lead_lag_incidence % and that need to be passed to _dynamic-file -% i_cols_J1 [double] indices of contemporaneous and forward looking variables +% i_cols_J1 [double] indices of contemporaneous and forward looking variables % appearing in M.lead_lag_incidence % i_cols_1 [double] indices of contemporaneous and forward looking variables in % M.lead_lag_incidence in dynamic Jacobian (relevant in first period) @@ -32,7 +32,7 @@ function [residuals,JJacobian] = perfect_foresight_problem(y, dynamic_function, % variables (relevant in last period) % i_cols_j [double] indices of variables in M.lead_lag_incidence % in dynamic Jacobian (relevant in intermediate periods) -% nnzJ [scalar] number of non-zero elements in Jacobian +% nnzJ [scalar] number of non-zero elements in Jacobian % OUTPUTS % residuals [double] (N*T)*1 array, residuals of the stacked problem % JJacobian [double] (N*T)*(N*T) array, Jacobian of the stacked problem @@ -60,44 +60,44 @@ function [residuals,JJacobian] = perfect_foresight_problem(y, dynamic_function, % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - YY = [Y0; y; YT]; - - residuals = zeros(T*ny,1); - if nargout == 2 - iJacobian = cell(T,1); - end +YY = [Y0; y; YT]; - i_rows = 1:ny; - i_cols_J = i_cols; - offset = 0; - - for it = 2:(T+1) - if nargout == 1 - residuals(i_rows) = dynamic_function(YY(i_cols),exo_simul, params, ... - steady_state,it); - elseif nargout == 2 - [residuals(i_rows),jacobian] = dynamic_function(YY(i_cols),exo_simul, params, ... - steady_state,it); - if it == 2 - [rows,cols,vals] = find(jacobian(:,i_cols_1)); - iJacobian{1} = [offset+rows, i_cols_J1(cols), vals]; - elseif it == T + 1 - [rows,cols,vals] = find(jacobian(:,i_cols_T)); - iJacobian{T} = [offset+rows, i_cols_J(i_cols_T(cols)), vals]; - else - [rows,cols,vals] = find(jacobian(:,i_cols_j)); - iJacobian{it-1} = [offset+rows, i_cols_J(cols), vals]; - i_cols_J = i_cols_J + ny; - end - offset = offset + ny; - end +residuals = zeros(T*ny,1); +if nargout == 2 + iJacobian = cell(T,1); +end + +i_rows = 1:ny; +i_cols_J = i_cols; +offset = 0; - i_rows = i_rows + ny; - i_cols = i_cols + ny; +for it = 2:(T+1) + if nargout == 1 + residuals(i_rows) = dynamic_function(YY(i_cols),exo_simul, params, ... + steady_state,it); + elseif nargout == 2 + [residuals(i_rows),jacobian] = dynamic_function(YY(i_cols),exo_simul, params, ... + steady_state,it); + if it == 2 + [rows,cols,vals] = find(jacobian(:,i_cols_1)); + iJacobian{1} = [offset+rows, i_cols_J1(cols), vals]; + elseif it == T + 1 + [rows,cols,vals] = find(jacobian(:,i_cols_T)); + iJacobian{T} = [offset+rows, i_cols_J(i_cols_T(cols)), vals]; + else + [rows,cols,vals] = find(jacobian(:,i_cols_j)); + iJacobian{it-1} = [offset+rows, i_cols_J(cols), vals]; + i_cols_J = i_cols_J + ny; + end + offset = offset + ny; end - if nargout == 2 - iJacobian = cat(1,iJacobian{:}); - JJacobian = sparse(iJacobian(:,1),iJacobian(:,2),iJacobian(:,3),T* ... - ny,T*ny); - end \ No newline at end of file + i_rows = i_rows + ny; + i_cols = i_cols + ny; +end + +if nargout == 2 + iJacobian = cat(1,iJacobian{:}); + JJacobian = sparse(iJacobian(:,1),iJacobian(:,2),iJacobian(:,3),T* ... + ny,T*ny); +end \ No newline at end of file diff --git a/matlab/perfect-foresight-models/perfect_foresight_setup.m b/matlab/perfect-foresight-models/perfect_foresight_setup.m index 3b28254326..a9cddb0e59 100644 --- a/matlab/perfect-foresight-models/perfect_foresight_setup.m +++ b/matlab/perfect-foresight-models/perfect_foresight_setup.m @@ -1,14 +1,14 @@ function perfect_foresight_setup() % Prepares a deterministic simulation, by filling oo_.exo_simul and oo_.endo_simul -% +% % INPUTS % None -% +% % OUTPUTS % none -% +% % ALGORITHM -% +% % SPECIAL REQUIREMENTS % none @@ -35,14 +35,14 @@ test_for_deep_parameters_calibration(M_); if size(M_.lead_lag_incidence,2)-nnz(M_.lead_lag_incidence(M_.maximum_endo_lag+1,:)) > 0 mess = ['PERFECT_FORESIGHT_SETUP: error in model specification : the variable(s) ']; - var_list=M_.endo_names(find(M_.lead_lag_incidence(M_.maximum_lag+1,:)==0),:); - for i=1:size(var_list,1) - if i<size(var_list,1) - mess = [mess, deblank(var_list(i,:)) ', ']; - else - mess = [mess, deblank(var_list(i,:)) ]; - end + var_list=M_.endo_names(find(M_.lead_lag_incidence(M_.maximum_lag+1,:)==0),:); + for i=1:size(var_list,1) + if i<size(var_list,1) + mess = [mess, deblank(var_list(i,:)) ', ']; + else + mess = [mess, deblank(var_list(i,:)) ]; end + end mess = [mess ' don''t appear as current period variables.']; error(mess) end diff --git a/matlab/perfect-foresight-models/perfect_foresight_solver.m b/matlab/perfect-foresight-models/perfect_foresight_solver.m index b5fc7e4f21..8bf52c28b2 100644 --- a/matlab/perfect-foresight-models/perfect_foresight_solver.m +++ b/matlab/perfect-foresight-models/perfect_foresight_solver.m @@ -184,20 +184,20 @@ if ~isreal(oo_.endo_simul(:)) %can only happen without bytecode [i_cols_J1,junk,i_cols_1] = find(illi(:)); i_cols_T = nonzeros(M_.lead_lag_incidence(1:2,:)'); residuals = perfect_foresight_problem(yy(:),str2func([M_.fname '_dynamic']), y0, yT, ... - oo_.exo_simul,M_.params,oo_.steady_state, ... - M_.maximum_lag,options_.periods,M_.endo_nbr,i_cols, ... - i_cols_J1, i_cols_1, i_cols_T, i_cols_j, ... - M_.NNZDerivatives(1)); + oo_.exo_simul,M_.params,oo_.steady_state, ... + M_.maximum_lag,options_.periods,M_.endo_nbr,i_cols, ... + i_cols_J1, i_cols_1, i_cols_T, i_cols_j, ... + M_.NNZDerivatives(1)); if max(abs(residuals))< options_.dynatol.f oo_.deterministic_simulation.status = 1; oo_.endo_simul=real(oo_.endo_simul); else - oo_.deterministic_simulation.status = 0; + oo_.deterministic_simulation.status = 0; disp('Simulation terminated with imaginary parts in the residuals or endogenous variables.') - end + end end -if oo_.deterministic_simulation.status == 1 +if oo_.deterministic_simulation.status == 1 disp('Perfect foresight solution found.') else disp('Failed to solve perfect foresight model') diff --git a/matlab/perfect-foresight-models/perfect_foresight_solver_core.m b/matlab/perfect-foresight-models/perfect_foresight_solver_core.m index da267b7dae..94e978316e 100644 --- a/matlab/perfect-foresight-models/perfect_foresight_solver_core.m +++ b/matlab/perfect-foresight-models/perfect_foresight_solver_core.m @@ -2,12 +2,12 @@ function [oo_, maxerror] = perfect_foresight_solver_core(M_, options_, oo_) %function [oo_, maxerror] = perfect_foresight_solver_core(M_, options_, oo_) % Core function calling solvers for perfect foresight model % -% INPUTS +% INPUTS % - M_ [struct] contains a description of the model. % - options_ [struct] contains various options. % - oo_ [struct] contains results % -% OUTPUTS +% OUTPUTS % - oo_ [struct] contains results % - maxerror [double] contains the maximum absolute error @@ -81,8 +81,8 @@ else [oo_.endo_simul, oo_.deterministic_simulation] = ... sim1_purely_backward(oo_.endo_simul, oo_.exo_simul, oo_.steady_state, M_, options_); elseif M_.maximum_endo_lag == 0 % Purely forward model - [oo_.endo_simul, oo_.deterministic_simulation] = ... - sim1_purely_forward(oo_.endo_simul, oo_.exo_simul, oo_.steady_state, M_, options_); + [oo_.endo_simul, oo_.deterministic_simulation] = ... + sim1_purely_forward(oo_.endo_simul, oo_.exo_simul, oo_.steady_state, M_, options_); else % General case switch options_.stack_solve_algo case 0 @@ -143,5 +143,3 @@ if nargout>1 maxerror = max(max(abs(residuals))); end end - - diff --git a/matlab/perfect-foresight-models/private/check_input_arguments.m b/matlab/perfect-foresight-models/private/check_input_arguments.m index affb808e08..81c3da8ce4 100644 --- a/matlab/perfect-foresight-models/private/check_input_arguments.m +++ b/matlab/perfect-foresight-models/private/check_input_arguments.m @@ -43,7 +43,7 @@ end if isempty(DynareResults.endo_simul) || any(size(DynareResults.endo_simul) ~= [ DynareModel.endo_nbr, DynareModel.maximum_lag+DynareOptions.periods+DynareModel.maximum_lead ]) - + if DynareOptions.initval_file fprintf('PERFECT_FORESIGHT_SOLVER: ''oo_.endo_simul'' has wrong size. Check whether your initval-file provides %d periods.',DynareModel.maximum_endo_lag+DynareOptions.periods+DynareModel.maximum_endo_lead) error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: ''oo_.endo_simul'' has wrong size. Did you run ''perfect_foresight_setup'' ?') diff --git a/matlab/perfect-foresight-models/private/initialize_stacked_problem.m b/matlab/perfect-foresight-models/private/initialize_stacked_problem.m index 64beba34e2..3d6c9abdc0 100644 --- a/matlab/perfect-foresight-models/private/initialize_stacked_problem.m +++ b/matlab/perfect-foresight-models/private/initialize_stacked_problem.m @@ -4,19 +4,19 @@ function [options, y0, yT, z, i_cols, i_cols_J1, i_cols_T, i_cols_j, i_cols_1, . % dynamicmodel] = initialize_stacked_problem(endogenousvariables, options, M, steadystate_y) % Sets up the stacked perfect foresight problem for use with dynare_solve.m % -% INPUTS +% INPUTS % - endogenousvariables [double] N*T array, paths for the endogenous variables (initial guess). % - options [struct] contains various options. % - M [struct] contains a description of the model. % - steadystate_y [double] N*1 array, steady state for the endogenous variables. -% OUTPUTS +% OUTPUTS % - options [struct] contains various options. % - y0 [double] N*1 array, initial conditions for the endogenous variables % - yT [double] N*1 array, terminal conditions for the endogenous variables % - z [double] T*M array, paths for the exogenous variables. % - i_cols [double] indices of variables appearing in M.lead_lag_incidence % and that need to be passed to _dynamic-file -% - i_cols_J1 [double] indices of contemporaneous and forward looking variables +% - i_cols_J1 [double] indices of contemporaneous and forward looking variables % appearing in M.lead_lag_incidence % - i_cols_T [double] columns of dynamic Jacobian related to % contemporaneous and backward-looking @@ -43,7 +43,7 @@ function [options, y0, yT, z, i_cols, i_cols_J1, i_cols_T, i_cols_j, i_cols_1, . % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - + periods = options.periods; if (options.solve_algo == 10) if ~isfield(options.lmmcp,'lb') diff --git a/matlab/perfect-foresight-models/private/simulation_core.m b/matlab/perfect-foresight-models/private/simulation_core.m index 3c8f126046..947ebd9a59 100644 --- a/matlab/perfect-foresight-models/private/simulation_core.m +++ b/matlab/perfect-foresight-models/private/simulation_core.m @@ -66,8 +66,8 @@ else [oo_.endo_simul, oo_.deterministic_simulation] = ... sim1_purely_backward(oo_.endo_simul, oo_.exo_simul, oo_.steady_state, M_, options_); elseif M_.maximum_endo_lag == 0 % Purely forward model - [oo_.endo_simul, oo_.deterministic_simulation] = ... - sim1_purely_forward(oo_.endo_simul, oo_.exo_simul, oo_.steady_state, M_, options_); + [oo_.endo_simul, oo_.deterministic_simulation] = ... + sim1_purely_forward(oo_.endo_simul, oo_.exo_simul, oo_.steady_state, M_, options_); else % General case if options_.stack_solve_algo == 0 if options_.linear_approximation diff --git a/matlab/perfect-foresight-models/sim1.m b/matlab/perfect-foresight-models/sim1.m index 1a173b2115..b8d09a8086 100644 --- a/matlab/perfect-foresight-models/sim1.m +++ b/matlab/perfect-foresight-models/sim1.m @@ -154,13 +154,13 @@ for iter = 1:options.simul.maxit if endogenous_terminal_period && iter>1 dy = ZERO; if options.simul.robust_lin_solve - dy(1:i_rows(end)) = -lin_solve_robust( A(1:i_rows(end),1:i_rows(end)), res(1:i_rows(end)),verbose ); + dy(1:i_rows(end)) = -lin_solve_robust( A(1:i_rows(end),1:i_rows(end)), res(1:i_rows(end)),verbose ); else dy(1:i_rows(end)) = -lin_solve( A(1:i_rows(end),1:i_rows(end)), res(1:i_rows(end)), verbose ); end else if options.simul.robust_lin_solve - dy = -lin_solve_robust( A, res, verbose ); + dy = -lin_solve_robust( A, res, verbose ); else dy = -lin_solve( A, res, verbose ); end @@ -228,108 +228,106 @@ if verbose end function x = lin_solve( A, b,verbose) - if norm( b ) < sqrt( eps ) % then x = 0 is a solution - x = 0; - return - end - - x = A\b; - x( ~isfinite( x ) ) = 0; - relres = norm( b - A * x ) / norm( b ); - if relres > 1e-6 && verbose - fprintf( 'WARNING : Failed to find a solution to the linear system.\n' ); - end - +if norm( b ) < sqrt( eps ) % then x = 0 is a solution + x = 0; + return +end + +x = A\b; +x( ~isfinite( x ) ) = 0; +relres = norm( b - A * x ) / norm( b ); +if relres > 1e-6 && verbose + fprintf( 'WARNING : Failed to find a solution to the linear system.\n' ); +end + function [ x, flag, relres ] = lin_solve_robust( A, b , verbose) - if norm( b ) < sqrt( eps ) % then x = 0 is a solution - x = 0; - flag = 0; - relres = 0; - return - end - - x = A\b; - x( ~isfinite( x ) ) = 0; - [ x, flag, relres ] = bicgstab( A, b, [], [], [], [], x ); % returns immediately if x is a solution - if flag == 0 - return - end +if norm( b ) < sqrt( eps ) % then x = 0 is a solution + x = 0; + flag = 0; + relres = 0; + return +end - disp( relres ); +x = A\b; +x( ~isfinite( x ) ) = 0; +[ x, flag, relres ] = bicgstab( A, b, [], [], [], [], x ); % returns immediately if x is a solution +if flag == 0 + return +end - if verbose - fprintf( 'Initial bicgstab failed, trying alternative start point.\n' ); - end - old_x = x; - old_relres = relres; - [ x, flag, relres ] = bicgstab( A, b ); - if flag == 0 - return - end +disp( relres ); - if verbose - fprintf( 'Alternative start point also failed with bicgstab, trying gmres.\n' ); - end - if old_relres < relres - x = old_x; - end - [ x, flag, relres ] = gmres( A, b, [], [], [], [], [], x ); - if flag == 0 - return - end +if verbose + fprintf( 'Initial bicgstab failed, trying alternative start point.\n' ); +end +old_x = x; +old_relres = relres; +[ x, flag, relres ] = bicgstab( A, b ); +if flag == 0 + return +end - if verbose - fprintf( 'Initial gmres failed, trying alternative start point.\n' ); - end - old_x = x; - old_relres = relres; - [ x, flag, relres ] = gmres( A, b ); - if flag == 0 - return - end +if verbose + fprintf( 'Alternative start point also failed with bicgstab, trying gmres.\n' ); +end +if old_relres < relres + x = old_x; +end +[ x, flag, relres ] = gmres( A, b, [], [], [], [], [], x ); +if flag == 0 + return +end - if verbose - fprintf( 'Alternative start point also failed with gmres, using the (SLOW) Moore-Penrose Pseudo-Inverse.\n' ); - end - if old_relres < relres - x = old_x; - relres = old_relres; - end - old_x = x; - old_relres = relres; - x = pinv( full( A ) ) * b; - relres = norm( b - A * x ) / norm( b ); - if old_relres < relres - x = old_x; - relres = old_relres; - end - flag = relres > 1e-6; - if flag ~= 0 && verbose - fprintf( 'WARNING : Failed to find a solution to the linear system\n' ); - end - -function display_critical_variables(dyy, M) +if verbose + fprintf( 'Initial gmres failed, trying alternative start point.\n' ); +end +old_x = x; +old_relres = relres; +[ x, flag, relres ] = gmres( A, b ); +if flag == 0 + return +end - if any(isnan(dyy)) - indx = find(any(isnan(dyy))); - endo_names=cellstr(M.endo_names(indx,:)); - disp('Last iteration provided NaN for the following variables:') - fprintf('%s, ',endo_names{:}), - fprintf('\n'), - end - if any(isinf(dyy)) - indx = find(any(isinf(dyy))); - endo_names=cellstr(M.endo_names(indx,:)); - disp('Last iteration diverged (Inf) for the following variables:') - fprintf('%s, ',endo_names{:}), - fprintf('\n'), - end - if any(~isreal(dyy)) - indx = find(any(~isreal(dyy))); - endo_names=cellstr(M.endo_names(indx,:)); - disp('Last iteration provided complex number for the following variables:') - fprintf('%s, ',endo_names{:}), - fprintf('\n'), - end +if verbose + fprintf( 'Alternative start point also failed with gmres, using the (SLOW) Moore-Penrose Pseudo-Inverse.\n' ); +end +if old_relres < relres + x = old_x; + relres = old_relres; +end +old_x = x; +old_relres = relres; +x = pinv( full( A ) ) * b; +relres = norm( b - A * x ) / norm( b ); +if old_relres < relres + x = old_x; + relres = old_relres; +end +flag = relres > 1e-6; +if flag ~= 0 && verbose + fprintf( 'WARNING : Failed to find a solution to the linear system\n' ); +end + +function display_critical_variables(dyy, M) - \ No newline at end of file +if any(isnan(dyy)) + indx = find(any(isnan(dyy))); + endo_names=cellstr(M.endo_names(indx,:)); + disp('Last iteration provided NaN for the following variables:') + fprintf('%s, ',endo_names{:}), + fprintf('\n'), +end +if any(isinf(dyy)) + indx = find(any(isinf(dyy))); + endo_names=cellstr(M.endo_names(indx,:)); + disp('Last iteration diverged (Inf) for the following variables:') + fprintf('%s, ',endo_names{:}), + fprintf('\n'), +end +if any(~isreal(dyy)) + indx = find(any(~isreal(dyy))); + endo_names=cellstr(M.endo_names(indx,:)); + disp('Last iteration provided complex number for the following variables:') + fprintf('%s, ',endo_names{:}), + fprintf('\n'), +end diff --git a/matlab/perfect-foresight-models/sim1_lbj.m b/matlab/perfect-foresight-models/sim1_lbj.m index 50bcbc6fd6..4ff1cf9639 100644 --- a/matlab/perfect-foresight-models/sim1_lbj.m +++ b/matlab/perfect-foresight-models/sim1_lbj.m @@ -122,7 +122,7 @@ if ~stop end info.status = 0;% more iterations are needed. info.error = err; - info.errors = c/abs(err); + info.errors = c/abs(err); info.iterations = options.simul.maxit; end diff --git a/matlab/perfect-foresight-models/sim1_linear.m b/matlab/perfect-foresight-models/sim1_linear.m index 152c5933bd..e5a2d19ac9 100644 --- a/matlab/perfect-foresight-models/sim1_linear.m +++ b/matlab/perfect-foresight-models/sim1_linear.m @@ -2,7 +2,7 @@ function [endogenousvariables, info] = sim1_linear(endogenousvariables, exogenou % Solves a linear approximation of a perfect foresight model using sparse matrix. % -% INPUTS +% INPUTS % - endogenousvariables [double] N*T array, paths for the endogenous variables (initial guess). % - exogenousvariables [double] T*M array, paths for the exogenous variables. % - steadystate_y [double] N*1 array, steady state for the endogenous variables. @@ -10,16 +10,16 @@ function [endogenousvariables, info] = sim1_linear(endogenousvariables, exogenou % - M [struct] contains a description of the model. % - options [struct] contains various options. % -% OUTPUTS +% OUTPUTS % - endogenousvariables [double] N*T array, paths for the endogenous variables (solution of the perfect foresight model). % - info [struct] contains informations about the results. % -% NOTATIONS +% NOTATIONS % - N is the number of endogenous variables. % - M is the number of innovations. % - T is the number of periods (including initial and/or terminal conditions). % -% REMARKS +% REMARKS % - The structure `M` describing the structure of the model, must contain the % following informations: % + lead_lag_incidence, incidence matrix (given by the preprocessor). diff --git a/matlab/perfect-foresight-models/sim1_purely_backward.m b/matlab/perfect-foresight-models/sim1_purely_backward.m index 48ac6e9862..1c9d041794 100644 --- a/matlab/perfect-foresight-models/sim1_purely_backward.m +++ b/matlab/perfect-foresight-models/sim1_purely_backward.m @@ -28,12 +28,12 @@ else nyb = 0; iyb = []; end - + if ny0 ~= M.endo_nbr error('All endogenous variables must appear at the current period!') end - + dynamicmodel = str2func([M.fname,'_dynamic']); info.status = 1; diff --git a/matlab/perfect-foresight-models/sim1_purely_forward.m b/matlab/perfect-foresight-models/sim1_purely_forward.m index fbb3e9ace7..a1af211174 100644 --- a/matlab/perfect-foresight-models/sim1_purely_forward.m +++ b/matlab/perfect-foresight-models/sim1_purely_forward.m @@ -24,7 +24,7 @@ iyf = find(M.lead_lag_incidence(2,:)>0); % Indices of variables at next period if ny0 ~= M.endo_nbr error('All endogenous variables must appear at the current period!') end - + dynamicmodel = str2func([M.fname,'_dynamic']); info.status = 1; diff --git a/matlab/perfect-foresight-models/solve_stacked_linear_problem.m b/matlab/perfect-foresight-models/solve_stacked_linear_problem.m index 9a2d2d3fc8..2ddc51a21c 100644 --- a/matlab/perfect-foresight-models/solve_stacked_linear_problem.m +++ b/matlab/perfect-foresight-models/solve_stacked_linear_problem.m @@ -42,11 +42,11 @@ z = bsxfun(@minus, z, steadystate_y); x = bsxfun(@minus, exogenousvariables, steadystate_x'); [y, check] = dynare_solve(@linear_perfect_foresight_problem,z(:), options, ... - jacobian, y0-steadystate_y, yT-steadystate_y, ... - x, M.params, steadystate_y, ... - M.maximum_lag, options.periods, M.endo_nbr, i_cols, ... - i_cols_J1, i_cols_1, i_cols_T, i_cols_j, ... - M.NNZDerivatives(1), jendo, jexog); + jacobian, y0-steadystate_y, yT-steadystate_y, ... + x, M.params, steadystate_y, ... + M.maximum_lag, options.periods, M.endo_nbr, i_cols, ... + i_cols_J1, i_cols_1, i_cols_T, i_cols_j, ... + M.NNZDerivatives(1), jendo, jexog); if all(imag(y)<.1*options.dynatol.x) if ~isreal(y) diff --git a/matlab/perfect-foresight-models/solve_stacked_problem.m b/matlab/perfect-foresight-models/solve_stacked_problem.m index 66fa99ffe8..2e0885367f 100644 --- a/matlab/perfect-foresight-models/solve_stacked_problem.m +++ b/matlab/perfect-foresight-models/solve_stacked_problem.m @@ -2,14 +2,14 @@ function [endogenousvariables, info] = solve_stacked_problem(endogenousvariables % [endogenousvariables, info] = solve_stacked_problem(endogenousvariables, exogenousvariables, steadystate, M, options); % Solves the perfect foresight model using dynare_solve % -% INPUTS +% INPUTS % - endogenousvariables [double] N*T array, paths for the endogenous variables (initial guess). % - exogenousvariables [double] T*M array, paths for the exogenous variables. % - steadystate [double] N*1 array, steady state for the endogenous variables. % - M [struct] contains a description of the model. % - options [struct] contains various options. % -% OUTPUTS +% OUTPUTS % - endogenousvariables [double] N*T array, paths for the endogenous variables (solution of the perfect foresight model). % - info [struct] contains informations about the results. @@ -29,7 +29,7 @@ function [endogenousvariables, info] = solve_stacked_problem(endogenousvariables % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - + [options, y0, yT, z, i_cols, i_cols_J1, i_cols_T, i_cols_j, i_cols_1, dynamicmodel] = ... initialize_stacked_problem(endogenousvariables, options, M, steadystate); @@ -74,6 +74,6 @@ endogenousvariables = [y0 reshape(y, M.endo_nbr, options.periods) yT]; if check info.status = false; else - + info.status = true; end \ No newline at end of file diff --git a/matlab/plot_icforecast.m b/matlab/plot_icforecast.m index 1d4b61eb75..c4e3c2b2b9 100644 --- a/matlab/plot_icforecast.m +++ b/matlab/plot_icforecast.m @@ -1,12 +1,12 @@ function plot_icforecast(Variables,periods,options_) % Build plots for the conditional forecasts. % -% INPUTS -% o Variables [char] m*x array holding the names of the endogenous variables to be plotted. +% INPUTS +% o Variables [char] m*x array holding the names of the endogenous variables to be plotted. % % OUTPUTS % None. -% +% % SPECIAL REQUIREMENTS % This routine has to be called after imcforecast.m. diff --git a/matlab/plot_identification.m b/matlab/plot_identification.m index 116909bb23..12da568048 100644 --- a/matlab/plot_identification.m +++ b/matlab/plot_identification.m @@ -8,14 +8,14 @@ function plot_identification(params,idemoments,idehess,idemodel, idelre, advance % o idemodel [structure] identification results for the reduced form solution % o idelre [structure] identification results for the LRE model % o advanced [integer] flag for advanced identification checks -% o tittxt [char] name of the results to plot +% o tittxt [char] name of the results to plot % o name [char] list of names % o IdentifDirectoryName [char] directory name -% o tittxt [char] TeX-name of the results to plot +% o tittxt [char] TeX-name of the results to plot % o name_tex [char] TeX-names of the parameters % OUTPUTS % None -% +% % SPECIAL REQUIREMENTS % None @@ -41,8 +41,8 @@ global M_ options_ if nargin <10 || isempty(tit_TeX) tit_TeX=tittxt; end - -if nargin <11 + +if nargin <11 name_TeX=name; end @@ -85,7 +85,7 @@ if SampleSize == 1 else title('Identification strength with moments Information matrix (log-scale)') end - + subplot(212) if ~all(isnan(idehess.deltaM_prior)) bar(log([idehess.deltaM(is) idehess.deltaM_prior(is)])) @@ -123,7 +123,7 @@ if SampleSize == 1 fclose(fidTeX); end dyn_saveas(hh,[IdentifDirectoryName '/' M_.fname '_ident_strength_' tittxt1],options_.nodisplay,options_.graph_format); - + if advanced if ~options_.nodisplay skipline() @@ -169,9 +169,9 @@ if SampleSize == 1 % identificaton patterns for j=1:size(idemoments.cosnJ,2) pax=NaN(nparam,nparam); -% fprintf('\n') -% disp(['Collinearity patterns with ', int2str(j) ,' parameter(s)']) -% fprintf('%-15s [%-*s] %10s\n','Parameter',(15+1)*j,' Expl. params ','cosn') + % fprintf('\n') + % disp(['Collinearity patterns with ', int2str(j) ,' parameter(s)']) + % fprintf('%-15s [%-*s] %10s\n','Parameter',(15+1)*j,' Expl. params ','cosn') for i=1:nparam namx=''; for in=1:j @@ -183,7 +183,7 @@ if SampleSize == 1 pax(i,dumpindx)=idemoments.cosnJ(i,j); end end -% fprintf('%-15s [%s] %10.3f\n',name{i},namx,idemoments.cosnJ(i,j)) + % fprintf('%-15s [%s] %10.3f\n',name{i},namx,idemoments.cosnJ(i,j)) end hh = dyn_figure(options_.nodisplay,'Name',[tittxt,' - Collinearity patterns with ', int2str(j) ,' parameter(s)']); imagesc(pax,[0 1]); @@ -234,8 +234,8 @@ if SampleSize == 1 tex_tit_2=[tittxt,' - Identification patterns (Information matrix): HIGHEST SV']; end else -% S = idemoments.S; -% V = idemoments.V; + % S = idemoments.S; + % V = idemoments.V; if nparam<5 f1 = dyn_figure(options_.nodisplay,'Name',[tittxt,' - Identification patterns (moments Information matrix)']); tex_tit_1=[tittxt,' - Identification patterns (moments Information matrix)']; @@ -301,7 +301,7 @@ if SampleSize == 1 end end end - + else hh = dyn_figure(options_.nodisplay,'Name',['MC sensitivities']); subplot(211) @@ -316,8 +316,8 @@ else offset=size(siHnorm,2)-size(siLREnorm,2); mmm1 = [NaN(offset,1); mmm1./max(mmm1)]; mmm=[mmm mmm1]; - end - + end + bar(mmm(is,:)) set(gca,'xlim',[0 nparam+1]) set(gca,'xticklabel','') @@ -343,13 +343,13 @@ else fprintf(fidTeX,'%% End Of TeX file. \n'); fclose(fidTeX); end - + if advanced if ~options_.nodisplay, skipline() disp('Press ENTER to display advanced diagnostics'), pause(5), end -% options_.nograph=1; + % options_.nograph=1; hh = dyn_figure(options_.nodisplay,'Name','MC Condition Number'); subplot(221) hist(log10(idemodel.cond)) @@ -386,16 +386,16 @@ else options_mcf.title = 'MC Highest Condition Number Model Moments'; [dum,is]=sort(idemoments.cond); mcf_analysis(params, is(1:ncut), is(ncut+1:end), options_mcf, options_); -% [proba, dproba] = stab_map_1(idemoments.Mco', is(1:ncut), is(ncut+1:end), 'HighestCondNumberMoments_vs_Mco', 1, [], IdentifDirectoryName); -% for j=1:nparam, -% % ibeh=find(idemoments.Mco(j,:)<0.9); -% % inonbeh=find(idemoments.Mco(j,:)>=0.9); -% % if ~isempty(ibeh) && ~isempty(inonbeh) -% % [proba, dproba] = stab_map_1(params, ibeh, inonbeh, ['HighestMultiCollinearity_',name{j}], 1, [], IdentifDirectoryName); -% % end -% [~,is]=sort(idemoments.Mco(:,j)); -% [proba, dproba] = stab_map_1(params, is(1:ncut), is(ncut+1:end), ['MC_HighestMultiCollinearity_',name{j}], 1, [], IdentifDirectoryName, 0.15); -% end + % [proba, dproba] = stab_map_1(idemoments.Mco', is(1:ncut), is(ncut+1:end), 'HighestCondNumberMoments_vs_Mco', 1, [], IdentifDirectoryName); + % for j=1:nparam, + % % ibeh=find(idemoments.Mco(j,:)<0.9); + % % inonbeh=find(idemoments.Mco(j,:)>=0.9); + % % if ~isempty(ibeh) && ~isempty(inonbeh) + % % [proba, dproba] = stab_map_1(params, ibeh, inonbeh, ['HighestMultiCollinearity_',name{j}], 1, [], IdentifDirectoryName); + % % end + % [~,is]=sort(idemoments.Mco(:,j)); + % [proba, dproba] = stab_map_1(params, is(1:ncut), is(ncut+1:end), ['MC_HighestMultiCollinearity_',name{j}], 1, [], IdentifDirectoryName, 0.15); + % end if nparam<5 f1 = dyn_figure(options_.nodisplay,'Name',[tittxt,' - MC Identification patterns (moments): HIGHEST SV']); diff --git a/matlab/plot_shock_decomposition.m b/matlab/plot_shock_decomposition.m index b7d3675fc3..78488d6c60 100644 --- a/matlab/plot_shock_decomposition.m +++ b/matlab/plot_shock_decomposition.m @@ -77,7 +77,7 @@ if vintage_ end initial_date = options_.initial_date; - + if isfield(options_.plot_shock_decomp,'q2a') % private trap for aoa calls q2a=options_.plot_shock_decomp.q2a; if isstruct(q2a) && isempty(fieldnames(q2a)) @@ -88,60 +88,60 @@ else end switch realtime_ - - case 0 - z = oo_.shock_decomposition; - fig_name1=fig_name; - - case 1 % realtime - if vintage_ - z = oo_.realtime_shock_decomposition.(['time_' int2str(vintage_)]); - fig_name1=[fig_name ' realtime (vintage ' char(initial_date+vintage_-1) ')']; - else - z = oo_.realtime_shock_decomposition.pool; - fig_name1=[fig_name ' realtime (rolling)']; - end - - case 2 % conditional - if vintage_ - z = oo_.realtime_conditional_shock_decomposition.(['time_' int2str(vintage_)]); - initial_date = options_.initial_date+vintage_-1; - fig_name1=[fig_name ' ' int2str(forecast_) '-step ahead conditional forecast (given ' char(initial_date) ')']; - else - z = oo_.conditional_shock_decomposition.pool; - fig_name1=[fig_name ' 1-step ahead conditional forecast (rolling)']; - end - - case 3 % forecast - if vintage_ - z = oo_.realtime_forecast_shock_decomposition.(['time_' int2str(vintage_)]); - initial_date = options_.initial_date+vintage_-1; - fig_name1=[fig_name ' ' int2str(forecast_) '-step ahead forecast (given ' char(initial_date) ')']; - else - z = oo_.realtime_forecast_shock_decomposition.pool; - fig_name1=[fig_name ' 1-step ahead forecast (rolling)']; - end + + case 0 + z = oo_.shock_decomposition; + fig_name1=fig_name; + + case 1 % realtime + if vintage_ + z = oo_.realtime_shock_decomposition.(['time_' int2str(vintage_)]); + fig_name1=[fig_name ' realtime (vintage ' char(initial_date+vintage_-1) ')']; + else + z = oo_.realtime_shock_decomposition.pool; + fig_name1=[fig_name ' realtime (rolling)']; + end + + case 2 % conditional + if vintage_ + z = oo_.realtime_conditional_shock_decomposition.(['time_' int2str(vintage_)]); + initial_date = options_.initial_date+vintage_-1; + fig_name1=[fig_name ' ' int2str(forecast_) '-step ahead conditional forecast (given ' char(initial_date) ')']; + else + z = oo_.conditional_shock_decomposition.pool; + fig_name1=[fig_name ' 1-step ahead conditional forecast (rolling)']; + end + + case 3 % forecast + if vintage_ + z = oo_.realtime_forecast_shock_decomposition.(['time_' int2str(vintage_)]); + initial_date = options_.initial_date+vintage_-1; + fig_name1=[fig_name ' ' int2str(forecast_) '-step ahead forecast (given ' char(initial_date) ')']; + else + z = oo_.realtime_forecast_shock_decomposition.pool; + fig_name1=[fig_name ' 1-step ahead forecast (rolling)']; + end end steady_state = oo_.steady_state; if isequal(type,'aoa') && isstruct(q2a) && realtime_ - if isempty(initial_date) + if isempty(initial_date) + t0=1; + initial_date = dates('1Y'); + else + initial_date0 = dates([int2str(initial_date.time(1)) 'Y']); + if initial_date.time(2)==1 t0=1; - initial_date = dates('1Y'); + initial_date1=initial_date0; else - initial_date0 = dates([int2str(initial_date.time(1)) 'Y']); - if initial_date.time(2)==1 - t0=1; - initial_date1=initial_date0; - else - t0=(4-initial_date.time(2)+2); - initial_date1=initial_date0+1; - end + t0=(4-initial_date.time(2)+2); + initial_date1=initial_date0+1; end - t0=min(options_.plot_shock_decomp.save_realtime); - ini1 = initial_date+t0-1; - t0=t0+(4-ini1.time(2)); + end + t0=min(options_.plot_shock_decomp.save_realtime); + ini1 = initial_date+t0-1; + t0=t0+(4-ini1.time(2)); if ~isfield(q2a,'var_type') % private trap for aoa calls q2a.var_type=1; end @@ -160,21 +160,21 @@ if isequal(type,'aoa') && isstruct(q2a) && realtime_ if ~isfield(q2a,'plot') % private trap for aoa calls q2a.plot=1; % growth rate end - -% if isstruct(q2a.aux) && ischar(q2a.aux.y) -% opts=options_; -% opts.plot_shock_decomp.type='qoq'; -% [y_aux, steady_state_aux] = plot_shock_decomposition(M_,oo_,opts,q2a.aux.y); -% q2a.aux.y=y_aux; -% q2a.aux.yss=steady_state_aux; -% end + + % if isstruct(q2a.aux) && ischar(q2a.aux.y) + % opts=options_; + % opts.plot_shock_decomp.type='qoq'; + % [y_aux, steady_state_aux] = plot_shock_decomposition(M_,oo_,opts,q2a.aux.y); + % q2a.aux.y=y_aux; + % q2a.aux.yss=steady_state_aux; + % end [za, endo_names, endo_names_tex, steady_state, i_var, oo_] = ... annualized_shock_decomposition(oo_,M_, options_, i_var, t0, options_.nobs, realtime_, vintage_, steady_state,q2a); -% if realtime_<2 -% initial_date = initial_date1; -% else -% initial_date = initial_date0; -% end + % if realtime_<2 + % initial_date = initial_date1; + % else + % initial_date = initial_date0; + % end end @@ -190,7 +190,7 @@ if options_.plot_shock_decomp.use_shock_groups fig_name=[fig_name ' group ' options_.plot_shock_decomp.use_shock_groups]; shock_names = shock_ind; for i=1:ngroups - shock_names{i} = (shock_groups.(shock_ind{i}).label); + shock_names{i} = (shock_groups.(shock_ind{i}).label); end zz = zeros(endo_nbr,ngroups+2,gend); kcum=[]; @@ -208,7 +208,7 @@ if options_.plot_shock_decomp.use_shock_groups M_.shock_groups.(options_.plot_shock_decomp.use_shock_groups)=shock_groups; if any(any(zothers)) shock_names = [shock_names; {'Others + Initial Values'}]; - end + end zz(:,ngroups+1,:) = sum(z(:,1:nshocks+1,:),2); zz(:,ngroups+2,:) = z(:,nshocks+2,:); z = zz; @@ -216,10 +216,10 @@ else shock_names = M_.exo_names; end - func = @(x) colorspace('RGB->Lab',x); - MAP = distinguishable_colors(size(z,2)-1,'w',func); +func = @(x) colorspace('RGB->Lab',x); +MAP = distinguishable_colors(size(z,2)-1,'w',func); % MAP = [MAP; MAP(end,:)]; - MAP(end,:) = [0.7 0.7 0.7]; +MAP(end,:) = [0.7 0.7 0.7]; % MAP = [MAP; [0.7 0.7 0.7]; [0.3 0.3 0.3]]; if isempty(options_.plot_shock_decomp.colormap) @@ -228,36 +228,36 @@ end switch type - case '' % default + case '' % default - case 'qoq' + case 'qoq' - case 'yoy' - z=z(:,:,1:end-3)+z(:,:,2:end-2)+z(:,:,3:end-1)+z(:,:,4:end); - if ~isempty(initial_date), - initial_date = initial_date+3; - else - initial_date = dates('1Q4'); - end - steady_state = 4*steady_state; - - case 'aoa' + case 'yoy' + z=z(:,:,1:end-3)+z(:,:,2:end-2)+z(:,:,3:end-1)+z(:,:,4:end); + if ~isempty(initial_date), + initial_date = initial_date+3; + else + initial_date = dates('1Q4'); + end + steady_state = 4*steady_state; + + case 'aoa' - if isempty(initial_date) - t0=4; - initial_date = dates('1Y'); + if isempty(initial_date) + t0=4; + initial_date = dates('1Y'); + else + initial_date0 = dates([int2str(initial_date.time(1)) 'Y']); + if initial_date.time(2)==1 + t0=1; + initial_date1=initial_date0; else - initial_date0 = dates([int2str(initial_date.time(1)) 'Y']); - if initial_date.time(2)==1 - t0=1; - initial_date1=initial_date0; - else - t0=(4-initial_date.time(2)+2); - initial_date1=initial_date0+1; - end + t0=(4-initial_date.time(2)+2); + initial_date1=initial_date0+1; end - if isstruct(q2a) - if realtime_ == 0 + end + if isstruct(q2a) + if realtime_ == 0 if ~isfield(q2a,'var_type') % private trap for aoa calls q2a.var_type=1; end @@ -276,7 +276,7 @@ switch type if ~isfield(q2a,'plot') % private trap for aoa calls q2a.plot=1; % growth rate end - + if isstruct(q2a.aux) && ischar(q2a.aux.y) opts=options_; opts.plot_shock_decomp.type='qoq'; @@ -286,33 +286,33 @@ switch type end [za, endo_names, endo_names_tex, steady_state, i_var, oo_] = ... annualized_shock_decomposition(z,M_, options_, i_var, t0, options_.nobs, realtime_, vintage_, steady_state,q2a); - end - z = za; - M_.endo_names = endo_names; - M_.endo_names_tex = endo_names_tex; -% endo_nbr = size(z,1); - if realtime_<2 - initial_date = initial_date1; - else - initial_date = initial_date0; - end + end + z = za; + M_.endo_names = endo_names; + M_.endo_names_tex = endo_names_tex; + % endo_nbr = size(z,1); + if realtime_<2 + initial_date = initial_date1; else - t0=4-initial_date.time(2)+1; initial_date = initial_date0; - z=z(:,:,t0:4:end); - end - - if ~isempty(options_.plot_shock_decomp.plot_init_date) - options_.plot_shock_decomp.plot_init_date = dates([int2str(options_.plot_shock_decomp.plot_init_date.time(1)) 'Y']); - end - if ~isempty(options_.plot_shock_decomp.plot_end_date) - options_.plot_shock_decomp.plot_end_date = dates([int2str(options_.plot_shock_decomp.plot_end_date.time(1)) 'Y']); end - - - otherwise + else + t0=4-initial_date.time(2)+1; + initial_date = initial_date0; + z=z(:,:,t0:4:end); + end + + if ~isempty(options_.plot_shock_decomp.plot_init_date) + options_.plot_shock_decomp.plot_init_date = dates([int2str(options_.plot_shock_decomp.plot_init_date.time(1)) 'Y']); + end + if ~isempty(options_.plot_shock_decomp.plot_end_date) + options_.plot_shock_decomp.plot_end_date = dates([int2str(options_.plot_shock_decomp.plot_end_date.time(1)) 'Y']); + end + + + otherwise - error('plot_shock_decomposition:: Wrong type') + error('plot_shock_decomposition:: Wrong type') end if steadystate diff --git a/matlab/pltorg.m b/matlab/pltorg.m index 7f100e4b2f..dca9e66f1b 100644 --- a/matlab/pltorg.m +++ b/matlab/pltorg.m @@ -48,11 +48,11 @@ elseif number == 5 elseif number == 6 nbplt = 1; nr = 3; - nc = 2; + nc = 2; elseif number == 7 nbplt = 1; nr = 3; - nc = 3; + nc = 3; elseif number == 8 nbplt = 1; nr = 3; @@ -67,7 +67,7 @@ else nr = nrstar; nc = ncstar; lr = nr; - lc = nc; + lc = nc; else nbplt = ceil(number/nstar); nr = nrstar; @@ -90,10 +90,10 @@ else lc = 2; elseif reste == 6 lr = 3; - lc = 2; + lc = 2; elseif reste == 7 lr = 3; - lc = 3; + lc = 3; elseif reste == 8 lr = 3; lc = 3; diff --git a/matlab/pm3.m b/matlab/pm3.m index f1d9a4483f..242df77c26 100644 --- a/matlab/pm3.m +++ b/matlab/pm3.m @@ -7,7 +7,7 @@ function pm3(n1,n2,ifil,B,tit1,tit2,tit3,tit_tex,names1,names2,name3,DirectoryNa % n2 [scalar] size of second dimension of moment matrix % ifil [scalar] number of moment files to load % B [scalar] number of subdraws -% tit1 [string] Figure title +% tit1 [string] Figure title % tit2 [string] not used % tit3 [string] Save name for figure % tit_tex [cell array] TeX-Names for Variables @@ -63,7 +63,7 @@ if options_.TeX if isempty(tit_tex) tit_tex=names1; end - + varlist_TeX = []; for i=1:nvar if i==1 @@ -92,7 +92,7 @@ for file = 1:ifil stock=loaded_file.stock; if strcmp(var_type,'_filter_step_ahead') if file==1 %on first run, initialize variable for storing filter_step_ahead - stock1_filter_step_ahead=NaN(n1,n2,B,length(options_.filter_step_ahead)); + stock1_filter_step_ahead=NaN(n1,n2,B,length(options_.filter_step_ahead)); stock1 = zeros(n1,n2,B); end filter_step_ahead_indicator=1; @@ -289,112 +289,112 @@ if strcmp(var_type,'_trend_coeff') || max(max(abs(Mean(:,:))))<=10^(-6) || all(a return %not do plots end %% -%% Finally I build the plots. +%% Finally I build the plots. %% if ~options_.nograph && ~options_.no_graph.posterior -% Block of code executed in parallel, with the exception of file -% .tex generation always run sequentially. This portion of code is execute in parallel by -% pm3_core1.m function. + % Block of code executed in parallel, with the exception of file + % .tex generation always run sequentially. This portion of code is execute in parallel by + % pm3_core1.m function. -% %%%%%%%%% PARALLEL BLOCK % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% -% %%% The file .TeX! are not saved in parallel. + % %%%%%%%%% PARALLEL BLOCK % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + % + % %%% The file .TeX! are not saved in parallel. -% Store the variable mandatory for local/remote parallel computing. + % Store the variable mandatory for local/remote parallel computing. -localVars=[]; + localVars=[]; -localVars.tit1=tit1; -localVars.nn=nn; -localVars.n2=n2; -localVars.Distrib=Distrib; -localVars.varlist=varlist; -localVars.MaxNumberOfPlotsPerFigure=MaxNumberOfPlotsPerFigure; -localVars.name3=name3; -localVars.tit3=tit3; -localVars.Mean=Mean; -% Like sequential execution! -nvar0=nvar; + localVars.tit1=tit1; + localVars.nn=nn; + localVars.n2=n2; + localVars.Distrib=Distrib; + localVars.varlist=varlist; + localVars.MaxNumberOfPlotsPerFigure=MaxNumberOfPlotsPerFigure; + localVars.name3=name3; + localVars.tit3=tit3; + localVars.Mean=Mean; + % Like sequential execution! + nvar0=nvar; -if ~isoctave - % Commenting for testing! - if isnumeric(options_.parallel) || ceil(size(varlist,1)/MaxNumberOfPlotsPerFigure)<4 - fout = pm3_core(localVars,1,nvar,0); - - % Parallel execution! - else - isRemoteOctave = 0; - for indPC=1:length(options_.parallel) - isRemoteOctave = isRemoteOctave + (findstr(options_.parallel(indPC).MatlabOctavePath, 'octave')); - end - if isRemoteOctave + if ~isoctave + % Commenting for testing! + if isnumeric(options_.parallel) || ceil(size(varlist,1)/MaxNumberOfPlotsPerFigure)<4 fout = pm3_core(localVars,1,nvar,0); + + % Parallel execution! else - globalVars = struct('M_',M_, ... - 'options_', options_, ... - 'oo_', oo_); - [fout, nvar0, totCPU] = masterParallel(options_.parallel, 1, nvar, [],'pm3_core', localVars,globalVars, options_.parallel_info); + isRemoteOctave = 0; + for indPC=1:length(options_.parallel) + isRemoteOctave = isRemoteOctave + (findstr(options_.parallel(indPC).MatlabOctavePath, 'octave')); + end + if isRemoteOctave + fout = pm3_core(localVars,1,nvar,0); + else + globalVars = struct('M_',M_, ... + 'options_', options_, ... + 'oo_', oo_); + [fout, nvar0, totCPU] = masterParallel(options_.parallel, 1, nvar, [],'pm3_core', localVars,globalVars, options_.parallel_info); + end end + else + % For the time being in Octave enviroment the pm3.m is executed only in + % serial modality, to avoid problem with the plots. + + fout = pm3_core(localVars,1,nvar,0); end -else - % For the time being in Octave enviroment the pm3.m is executed only in - % serial modality, to avoid problem with the plots. - - fout = pm3_core(localVars,1,nvar,0); -end -subplotnum = 0; + subplotnum = 0; -if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) - 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'); - nvar0=cumsum(nvar0); + if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) + 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'); + nvar0=cumsum(nvar0); + + i=0; + for j=1:length( - i=0; - for j=1:length( - - NAMES = []; - TEXNAMES = []; - nvar=nvar0(j); - while i<nvar - i=i+1; - if max(abs(Mean(:,i))) > 10^(-6) - subplotnum = subplotnum+1; - name = deblank(varlist(i,:)); - texname = deblank(varlist_TeX(i,:)); - if subplotnum==1 - NAMES = name; - TEXNAMES = ['$' texname '$']; - else - NAMES = char(NAMES,name); - TEXNAMES = char(TEXNAMES,['$' texname '$']); - end - end - if subplotnum == MaxNumberOfPlotsPerFigure || i == nvar - 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[width=%2.2f\\textwidth]{%s/Output/%s_' name3 '_%s}\n'],options_.figures.textwidth*min(subplotnum/nn,1),M_.dname,M_.fname,deblank(tit3(i,:))); - fprintf(fidTeX,'\\label{Fig:%s:%s}\n',name3,deblank(tit3(i,:))); - fprintf(fidTeX,'\\caption{%s}\n',tit1); - fprintf(fidTeX,'\\end{figure}\n'); - fprintf(fidTeX,' \n'); - subplotnum = 0; NAMES = []; TEXNAMES = []; + nvar=nvar0(j); + while i<nvar + i=i+1; + if max(abs(Mean(:,i))) > 10^(-6) + subplotnum = subplotnum+1; + name = deblank(varlist(i,:)); + texname = deblank(varlist_TeX(i,:)); + if subplotnum==1 + NAMES = name; + TEXNAMES = ['$' texname '$']; + else + NAMES = char(NAMES,name); + TEXNAMES = char(TEXNAMES,['$' texname '$']); + end + end + if subplotnum == MaxNumberOfPlotsPerFigure || i == nvar + 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[width=%2.2f\\textwidth]{%s/Output/%s_' name3 '_%s}\n'],options_.figures.textwidth*min(subplotnum/nn,1),M_.dname,M_.fname,deblank(tit3(i,:))); + fprintf(fidTeX,'\\label{Fig:%s:%s}\n',name3,deblank(tit3(i,:))); + fprintf(fidTeX,'\\caption{%s}\n',tit1); + fprintf(fidTeX,'\\end{figure}\n'); + fprintf(fidTeX,' \n'); + subplotnum = 0; + NAMES = []; + TEXNAMES = []; + end + end end + fprintf(fidTeX,'%% End of TeX file.\n'); + fclose(fidTeX); end - end - fprintf(fidTeX,'%% End of TeX file.\n'); - fclose(fidTeX); -end end fprintf(['Estimation::mcmc: ' tit1 ', done!\n']); diff --git a/matlab/pm3_core.m b/matlab/pm3_core.m index e484304a82..881c4b4235 100644 --- a/matlab/pm3_core.m +++ b/matlab/pm3_core.m @@ -3,7 +3,7 @@ function myoutput=pm3_core(myinputs,fpar,nvar,whoiam, ThisMatlab) % PARALLEL CONTEXT % Core functionality for pm3.m function, which can be parallelized. -% INPUTS +% INPUTS % See the comment in posterior_sampler_core.m funtion. % OUTPUTS @@ -100,13 +100,13 @@ for i=fpar:nvar set(gca,'yticklabel',yticklabels_new) end end - + if whoiam if Parallel(ThisMatlab).Local==0 DirectoryName = CheckPath('Output',M_.dname); end end - + if subplotnum == MaxNumberOfPlotsPerFigure || i == nvar dyn_saveas(hh,[M_.dname '/Output/' M_.fname '_' name3 '_' deblank(tit3(i,:))],options_.nodisplay,options_.graph_format); if RemoteFlag==1 @@ -118,14 +118,14 @@ for i=fpar:nvar hh = dyn_figure(options_.nodisplay,'Name',[name3 ' ' int2str(figunumber+1)]); end end - + if whoiam -% waitbarString = [ 'Variable ' int2str(i) '/' int2str(nvar) ' done.']; -% fMessageStatus((i-fpar+1)/(nvar-fpar+1),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab)); + % waitbarString = [ 'Variable ' int2str(i) '/' int2str(nvar) ' done.']; + % fMessageStatus((i-fpar+1)/(nvar-fpar+1),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab)); dyn_waitbar((i-fpar+1)/(nvar-fpar+1),h); end - - + + end if whoiam diff --git a/matlab/posterior_analysis.m b/matlab/posterior_analysis.m index ca8459c2fc..7e13059bf1 100644 --- a/matlab/posterior_analysis.m +++ b/matlab/posterior_analysis.m @@ -1,4 +1,4 @@ -function oo_ = posterior_analysis(type,arg1,arg2,arg3,options_,M_,oo_) +function oo_ = posterior_analysis(type,arg1,arg2,arg3,options_,M_,oo_) % Copyright (C) 2008-2015 Dynare Team % % This file is part of Dynare. @@ -55,14 +55,14 @@ switch type 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_,options_); + vartan,nvar,arg1,arg2,options_.mh_conf_sig,oo_,options_); 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_,options_); + M_.exo_names,arg2,vartan,arg1,options_.mh_conf_sig,oo_,options_); case 'correlation' if nargin==narg1 [nvar,vartan,NumberOfFiles] = ... @@ -76,7 +76,7 @@ switch type 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_,options_); + arg3,M_.exo_names,arg2,vartan,arg1,options_.mh_conf_sig,oo_,options_); 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 75fd7a287d..e16992a08c 100644 --- a/matlab/posterior_moments.m +++ b/matlab/posterior_moments.m @@ -11,13 +11,13 @@ function [post_mean, post_median, post_var, hpd_interval, post_deciles, density] % post_mean [double] Scalar, posterior mean. % post_median [double] Scalar, posterior median. % post_var [double] Scalar, posterior variance. -% hpd_interval [double] Vector (1*2), Highest Probability Density interval +% hpd_interval [double] Vector (1*2), Highest Probability Density interval % post_deciles [double] Vector (9*1), deciles of the posterior distribution. -% density [double] Matrix (n*2), non parametric estimate of the posterior density. First and second -% columns are respectively abscissa and ordinate coordinates. -% +% density [double] Matrix (n*2), non parametric estimate of the posterior density. First and second +% columns are respectively abscissa and ordinate coordinates. +% % SPECIAL REQUIREMENTS -% Other matlab routines distributed with Dynare: mh_optimal_bandwidth.m +% Other matlab routines distributed with Dynare: mh_optimal_bandwidth.m % kernel_density_estimate.m. % @@ -41,7 +41,7 @@ function [post_mean, post_median, post_var, hpd_interval, post_deciles, density] if nargin<4 number_of_grid_points = 2^9; % 2^9 = 512 !... Must be a power of two. bandwidth = 0; % Rule of thumb optimal bandwidth parameter. - kernel_function = 'gaussian'; % Gaussian kernel for Fast Fourrier Transform approximaton. + kernel_function = 'gaussian'; % Gaussian kernel for Fast Fourrier Transform approximaton. else number_of_grid_points = kernel_options.gridpoints; bandwidth = kernel_options.bandwidth; @@ -69,7 +69,7 @@ if hpd_draws>2 [kmin,idx] = min(kk); hpd_interval = [xx(idx) xx(idx)+kmin]; else - hpd_interval=NaN(1,2); + hpd_interval=NaN(1,2); end if length(xx)>9 post_deciles = xx([round(0.1*number_of_draws) ... diff --git a/matlab/posterior_sampler.m b/matlab/posterior_sampler.m index 5d8b9cdbe7..70f7b5de9f 100644 --- a/matlab/posterior_sampler.m +++ b/matlab/posterior_sampler.m @@ -1,8 +1,8 @@ function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_) % function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_) -% Random Walk Metropolis-Hastings algorithm. -% -% INPUTS +% Random Walk Metropolis-Hastings algorithm. +% +% INPUTS % o TargetFun [char] string specifying the name of the objective % function (posterior kernel). % o ProposalFun [char] string specifying the name of the proposal @@ -10,7 +10,7 @@ function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_boun % o xparam1 [double] (p*1) vector of parameters to be estimated (initial values). % o sampler_options structure % .invhess [double] (p*p) matrix, posterior covariance matrix (at the mode). -% o mh_bounds [double] (p*2) matrix defining lower and upper bounds for the parameters. +% o mh_bounds [double] (p*2) matrix defining lower and upper bounds for the parameters. % o dataset_ data structure % o dataset_info dataset info structure % o options_ options structure @@ -27,7 +27,7 @@ function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_boun % in parallel. The code suitable to be executed in % parallel on multi core or cluster machine (in general a 'for' cycle) % has been removed from this function and been placed in the posterior_sampler_core.m funtion. -% +% % The DYNARE parallel packages comprise a i) set of pairs of Matlab functions that can be executed in % parallel and called name_function.m and name_function_core.m and ii) a second set of functions used % to manage the parallel computations. @@ -120,8 +120,8 @@ end if isnumeric(options_.parallel) || (nblck-fblck)==0 fout = posterior_sampler_core(localVars, fblck, nblck, 0); record = fout.record; - % Parallel in Local or remote machine. -else + % Parallel in Local or remote machine. +else % Global variables for parallel routines. globalVars = struct(); % which files have to be copied to run remotely diff --git a/matlab/posterior_sampler_core.m b/matlab/posterior_sampler_core.m index cd140c52c4..b753391b46 100644 --- a/matlab/posterior_sampler_core.m +++ b/matlab/posterior_sampler_core.m @@ -31,7 +31,7 @@ function myoutput = posterior_sampler_core(myinputs,fblck,nblck,whoiam, ThisMatl % % SPECIAL REQUIREMENTS. % None. -% +% % PARALLEL CONTEXT % See the comments in the posterior_sampler.m funtion. @@ -132,9 +132,9 @@ for curr_block = fblck:nblck set_dynare_seed(options_.DynareRandomStreams.seed+curr_block); end % Set the state of the RNG - set_dynare_random_generator_state(record.InitialSeeds(curr_block).Unifor, record.InitialSeeds(curr_block).Normal); + set_dynare_random_generator_state(record.InitialSeeds(curr_block).Unifor, record.InitialSeeds(curr_block).Normal); catch - % If the state set by master is incompatible with the slave, we only reseed + % If the state set by master is incompatible with the slave, we only reseed set_dynare_seed(options_.DynareRandomStreams.seed+curr_block); end if (options_.load_mh_file~=0) && (fline(curr_block)>1) && OpenOldFile(curr_block) %load previous draws and likelihood @@ -164,9 +164,9 @@ for curr_block = fblck:nblck feval_this_file = 0; draw_index_current_file = fline(curr_block); %get location of first draw in current block draw_iter = 1; - + while draw_iter <= nruns(curr_block) - + [par, logpost, accepted, neval] = posterior_sampler_iteration(TargetFun, last_draw(curr_block,:), last_posterior(curr_block), sampler_options,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_); x2(draw_index_current_file,:) = par; diff --git a/matlab/posterior_sampler_initialization.m b/matlab/posterior_sampler_initialization.m index ed98fc96d0..b8b65e8b8d 100644 --- a/matlab/posterior_sampler_initialization.m +++ b/matlab/posterior_sampler_initialization.m @@ -3,13 +3,13 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa % function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npar, NumberOfBlocks, nruns, NewFile, MAX_nruns, d, bayestopt_] = ... % metropolis_hastings_initialization(TargetFun, xparam1, vv, mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_) % Metropolis-Hastings initialization. -% -% INPUTS +% +% INPUTS % o TargetFun [char] string specifying the name of the objective % function (posterior kernel). % o xparam1 [double] (p*1) vector of parameters to be estimated (initial values). % o vv [double] (p*p) matrix, posterior covariance matrix (at the mode). -% o mh_bounds [double] (p*2) matrix defining lower and upper bounds for the parameters. +% o mh_bounds [double] (p*2) matrix defining lower and upper bounds for the parameters. % o dataset_ data structure % o dataset_info dataset info structure % o options_ options structure @@ -17,17 +17,17 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa % o estim_params_ estimated parameters structure % o bayestopt_ estimation options structure % o oo_ outputs structure -% -% OUTPUTS +% +% OUTPUTS % o ix2 [double] (NumberOfBlocks*npar) vector of starting points for different chains % o ilogpo2 [double] (NumberOfBlocks*1) vector of initial posterior values for different chains % o ModelName [string] name of the mod-file % o MetropolisFolder [string] path to the Metropolis subfolder -% o FirstBlock [scalar] number of the first MH chain to be run (not equal to 1 in case of recovery) -% o FirstLine [double] (NumberOfBlocks*1) vector of first draw in each chain (not equal to 1 in case of recovery) +% o FirstBlock [scalar] number of the first MH chain to be run (not equal to 1 in case of recovery) +% o FirstLine [double] (NumberOfBlocks*1) vector of first draw in each chain (not equal to 1 in case of recovery) % o npar [scalar] number of parameters estimated -% o NumberOfBlocks [scalar] Number of MCM chains requested -% o nruns [double] (NumberOfBlocks*1) number of draws in each chain +% o NumberOfBlocks [scalar] Number of MCM chains requested +% o nruns [double] (NumberOfBlocks*1) number of draws in each chain % o NewFile [scalar] (NumberOfBlocks*1) vector storing the number % of the first MH-file to created for each chain when saving additional % draws @@ -58,7 +58,7 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa %Initialize outputs ix2 = []; ilogpo2 = []; -ModelName = []; +ModelName = []; MetropolisFolder = []; FirstBlock = []; FirstLine = []; @@ -132,7 +132,7 @@ if ~options_.load_mh_file && ~options_.mh_recover else candidate = rand_multivariate_normal( transpose(xparam1), d * options_.mh_init_scale, npar); end - if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub) + if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub) ix2(j,:) = candidate; ilogpo2(j) = - feval(TargetFun,ix2(j,:)',dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_); if ~isfinite(ilogpo2(j)) % if returned log-density is @@ -175,7 +175,7 @@ if ~options_.load_mh_file && ~options_.mh_recover else% Case 2: one chain (we start from the posterior mode) fprintf(fidlog,[' Initial values of the parameters:\n']); candidate = transpose(xparam1(:));% - if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub) + if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub) ix2 = candidate; ilogpo2 = - feval(TargetFun,ix2',dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_); disp('Estimation::mcmc: Initialization at the posterior mode.') @@ -293,7 +293,7 @@ elseif options_.load_mh_file && ~options_.mh_recover NumberOfDrawsWrittenInThePastLastFile = MAX_nruns - LastLineNumber; NumberOfDrawsToBeSaved = nruns(1) - NumberOfDrawsWrittenInThePastLastFile; AnticipatedNumberOfFiles = ceil(NumberOfDrawsToBeSaved/MAX_nruns); - AnticipatedNumberOfLinesInTheLastFile = NumberOfDrawsToBeSaved - (AnticipatedNumberOfFiles-1)*MAX_nruns; + AnticipatedNumberOfLinesInTheLastFile = NumberOfDrawsToBeSaved - (AnticipatedNumberOfFiles-1)*MAX_nruns; record.LastFileNumber = LastFileNumber + AnticipatedNumberOfFiles; record.LastLineNumber = AnticipatedNumberOfLinesInTheLastFile; record.MhDraws(end,1) = nruns(1); @@ -312,15 +312,15 @@ elseif options_.mh_recover load_last_mh_history_file(MetropolisFolder, ModelName); NumberOfBlocks = record.Nblck;% Number of "parallel" mcmc chains. options_.mh_nblck = NumberOfBlocks; - + %% check consistency of options if record.MhDraws(end,1)~=options_.mh_replic fprintf('\nEstimation::mcmc: You cannot specify a different mh_replic than in the chain you are trying to recover\n') fprintf('Estimation::mcmc: I am resetting mh_replic to %u\n',record.MhDraws(end,1)) options_.mh_replic=record.MhDraws(end,1); nruns = ones(NumberOfBlocks,1)*options_.mh_replic; - end - + end + if ~isnan(record.MAX_nruns(end,1)) %field exists if record.MAX_nruns(end,1)~=MAX_nruns fprintf('\nEstimation::mcmc: You cannot specify a different MaxNumberOfBytes than in the chain you are trying to recover\n') @@ -347,9 +347,9 @@ elseif options_.mh_recover if OldMhExists LastLineNumberInThePreviousMh = record.MhDraws(end-1,3);% Number of lines in the last mh files of the previous session. LastFileNumberInThePreviousMh = sum(record.MhDraws(1:end-1,2),1);% Number of mh files in the the previous sessions. - %Test if the last mh files of the previous session were not full yet - if LastLineNumberInThePreviousMh < MAX_nruns%not full - %store starting point if whole chain needs to be redone + %Test if the last mh files of the previous session were not full yet + if LastLineNumberInThePreviousMh < MAX_nruns%not full + %store starting point if whole chain needs to be redone NewFile = ones(NumberOfBlocks,1)*LastFileNumberInThePreviousMh; FirstLine = ones(NumberOfBlocks,1)*(LastLineNumberInThePreviousMh+1); LastFileFullIndicator=0; @@ -368,7 +368,7 @@ elseif options_.mh_recover end [d,bayestopt_]=set_proposal_density_to_previous_value(record,options_,bayestopt_); %% Now find out what exactly needs to be redone - % 1. Check if really something needs to be done + % 1. Check if really something needs to be done % How many mh files should we have ? ExpectedNumberOfMhFilesPerBlock = sum(record.MhDraws(:,2),1); ExpectedNumberOfMhFiles = ExpectedNumberOfMhFilesPerBlock*NumberOfBlocks; @@ -378,7 +378,7 @@ elseif options_.mh_recover % Quit if no crashed mcmc chain can be found as there are as many files as expected if (TotalNumberOfMhFiles==ExpectedNumberOfMhFiles) disp('Estimation::mcmc: It appears that you don''t need to use the mh_recover option!') - disp(' You have to edit the mod file and remove the mh_recover option') + disp(' You have to edit the mod file and remove the mh_recover option') disp(' in the estimation command') error('Estimation::mcmc: mh_recover option not required!') end @@ -401,15 +401,15 @@ elseif options_.mh_recover end FirstBlock = FirstBlock+1; end - - %% 3. Overwrite default settings for + + %% 3. Overwrite default settings for % How many mh-files are saved in this block? NumberOfSavedMhFilesInTheCrashedBlck = NumberOfMhFilesPerBlock(FirstBlock); ExistingDrawsInLastMCFile=0; %initialize: no MCMC draws of current MCMC are in file from last run - % Check whether last present file is a file included in the last MCMC run - if ~LastFileFullIndicator + % Check whether last present file is a file included in the last MCMC run + if ~LastFileFullIndicator if NumberOfSavedMhFilesInTheCrashedBlck==NewFile(FirstBlock) %only that last file exists, but no files from current MCMC - loaded_results=load([BaseName '_mh' int2str(NewFile(FirstBlock)) '_blck' int2str(FirstBlock) '.mat']); + loaded_results=load([BaseName '_mh' int2str(NewFile(FirstBlock)) '_blck' int2str(FirstBlock) '.mat']); %check whether that last file was filled if size(loaded_results.x2,1)==MAX_nruns %file is full NewFile(FirstBlock)=NewFile(FirstBlock)+1; %set first file to be created to next one @@ -419,20 +419,20 @@ elseif options_.mh_recover ExistingDrawsInLastMCFile=0; end end - elseif LastFileFullIndicator + elseif LastFileFullIndicator ExistingDrawsInLastMCFile=0; if NumberOfSavedMhFilesInTheCrashedBlck==NewFile(FirstBlock) %only the last file exists, but no files from current MCMC NewFile(FirstBlock)=NewFile(FirstBlock)+1; %set first file to be created to next one end end -% % Correct the number of saved mh files if the crashed Metropolis was not the first session (so -% % that NumberOfSavedMhFilesInTheCrashedBlck is the number of saved mh files in the crashed chain -% % of the current session). -% if OldMhExists -% NumberOfSavedMhFilesInTheCrashedBlck = NumberOfSavedMhFilesInTheCrashedBlck - LastFileNumberInThePreviousMh; -% end -% NumberOfSavedMhFiles = NumberOfSavedMhFilesInTheCrashedBlck+LastFileNumberInThePreviousMh; - + % % Correct the number of saved mh files if the crashed Metropolis was not the first session (so + % % that NumberOfSavedMhFilesInTheCrashedBlck is the number of saved mh files in the crashed chain + % % of the current session). + % if OldMhExists + % NumberOfSavedMhFilesInTheCrashedBlck = NumberOfSavedMhFilesInTheCrashedBlck - LastFileNumberInThePreviousMh; + % end + % NumberOfSavedMhFiles = NumberOfSavedMhFilesInTheCrashedBlck+LastFileNumberInThePreviousMh; + % Correct initial conditions. if NumberOfSavedMhFilesInTheCrashedBlck<ExpectedNumberOfMhFilesPerBlock loaded_results=load([BaseName '_mh' int2str(NumberOfSavedMhFilesInTheCrashedBlck) '_blck' int2str(FirstBlock) '.mat']); @@ -452,19 +452,19 @@ elseif options_.mh_recover end function [d,bayestopt_]=set_proposal_density_to_previous_value(record,options_,bayestopt_,d) - if isfield(record,'ProposalCovariance') && isfield(record,'ProposalCovariance') - if isfield(record,'MCMC_sampler') - if ~strcmp(record.MCMC_sampler,options_.posterior_sampler_options.posterior_sampling_method) - error(fprintf('Estimation::mcmc: The posterior_sampling_method differs from the one of the original chain. Please reset it to %s',record.MCMC_sampler)) - end - end - fprintf('Estimation::mcmc: Recovering the previous proposal density.\n') - d=record.ProposalCovariance; - bayestopt_.jscale=record.ProposalScaleVec; - else - if options_.mode_compute~=0 - fprintf('Estimation::mcmc: No stored previous proposal density found, continuing with the one implied by mode_compute\n.'); - elseif ~isempty(options_.mode_file) - fprintf('Estimation::mcmc: No stored previous proposal density found, continuing with the one implied by the mode_file\n.'); +if isfield(record,'ProposalCovariance') && isfield(record,'ProposalCovariance') + if isfield(record,'MCMC_sampler') + if ~strcmp(record.MCMC_sampler,options_.posterior_sampler_options.posterior_sampling_method) + error(fprintf('Estimation::mcmc: The posterior_sampling_method differs from the one of the original chain. Please reset it to %s',record.MCMC_sampler)) end end + fprintf('Estimation::mcmc: Recovering the previous proposal density.\n') + d=record.ProposalCovariance; + bayestopt_.jscale=record.ProposalScaleVec; +else + if options_.mode_compute~=0 + fprintf('Estimation::mcmc: No stored previous proposal density found, continuing with the one implied by mode_compute\n.'); + elseif ~isempty(options_.mode_file) + fprintf('Estimation::mcmc: No stored previous proposal density found, continuing with the one implied by the mode_file\n.'); + end +end diff --git a/matlab/posterior_sampler_iteration.m b/matlab/posterior_sampler_iteration.m index 09e5d88510..5b54e785ef 100644 --- a/matlab/posterior_sampler_iteration.m +++ b/matlab/posterior_sampler_iteration.m @@ -1,173 +1,173 @@ -function [par, logpost, accepted, neval] = posterior_sampler_iteration(TargetFun,last_draw, last_posterior, sampler_options,varargin) - -% function [par, logpost, accepted, neval] = posterior_sampler_iteration(TargetFun,last_draw, last_posterior, sampler_options,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_) -% posterior samplers -% -% INPUTS -% posterior_sampler_options: posterior sampler options -% options_: structure storing the options - -% OUTPUTS -% posterior_sampler_options: checked posterior sampler options -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2015-16 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/>. - - -posterior_sampling_method = sampler_options.posterior_sampling_method; -mh_bounds = sampler_options.bounds; - -switch posterior_sampling_method - case 'slice' - - [par, logpost, neval] = slice_sampler(TargetFun,last_draw, [mh_bounds.lb mh_bounds.ub], sampler_options,varargin{:}); - accepted = 1; - case 'random_walk_metropolis_hastings' - neval = 1; - ProposalFun = sampler_options.proposal_distribution; - proposal_covariance_Cholesky_decomposition = sampler_options.proposal_covariance_Cholesky_decomposition; - n = sampler_options.n; - - par = feval(ProposalFun, last_draw, proposal_covariance_Cholesky_decomposition, n); - if all( par(:) > mh_bounds.lb ) && all( par(:) < mh_bounds.ub ) - try - logpost = - feval(TargetFun, par(:),varargin{:}); - catch - logpost = -inf; - end - else - logpost = -inf; - end - r = logpost-last_posterior; - if (logpost > -inf) && (log(rand) < r) - accepted = 1; - else - accepted = 0; - par = last_draw; - logpost = last_posterior; - end - case 'tailored_random_block_metropolis_hastings' - options_=varargin{3}; - bayestopt_=varargin{6}; - npar=length(last_draw); - %% randomize indices for blocking in this iteration - indices=randperm(npar)'; - blocks=[1; (1+cumsum((rand(length(indices)-1,1)>(1-sampler_options.new_block_probability))))]; - nblocks=blocks(end,1); %get number of blocks this iteration - current_draw=last_draw'; %get starting point for current draw for updating - blocked_draws_counter=0; - accepted_draws_counter=0; - for block_iter=1:nblocks - blocked_draws_counter=blocked_draws_counter+1; - nxopt=length(indices(blocks==block_iter,1)); %get size of current block - par_start_current_block=current_draw(indices(blocks==block_iter,1)); - [xopt_current_block, fval, exitflag, hess_mat_optimizer, options_, Scale] = dynare_minimize_objective(@TaRB_optimizer_wrapper,par_start_current_block,sampler_options.mode_compute,options_,[mh_bounds.lb(indices(blocks==block_iter,1),1) mh_bounds.ub(indices(blocks==block_iter,1),1)],bayestopt_.name,bayestopt_,[],... - current_draw,indices(blocks==block_iter,1),TargetFun,...% inputs for wrapper - varargin{:}); %inputs for objective - %% covariance for proposal density - hessian_mat = reshape(hessian('TaRB_optimizer_wrapper',xopt_current_block, ... - options_.gstep,... - current_draw,indices(blocks==block_iter,1),TargetFun,...% inputs for wrapper - varargin{:}),nxopt,nxopt); - - if any(any(isnan(hessian_mat))) || any(any(isinf(hessian_mat))) - inverse_hessian_mat=eye(nxopt)*1e-4; %use diagonal - else - inverse_hessian_mat=inv(hessian_mat); %get inverse Hessian - if any(any((isnan(inverse_hessian_mat)))) || any(any((isinf(inverse_hessian_mat)))) - inverse_hessian_mat=eye(nxopt)*1e-4; %use diagonal - end - end - [proposal_covariance_Cholesky_decomposition_upper,negeigenvalues]=chol(inverse_hessian_mat); - %if not positive definite, use generalized Cholesky of Eskow/Schnabel - if negeigenvalues~=0 - proposal_covariance_Cholesky_decomposition_upper=chol_SE(inverse_hessian_mat,0); - end - proposal_covariance_Cholesky_decomposition_upper=proposal_covariance_Cholesky_decomposition_upper*diag(bayestopt_.jscale(indices(blocks==block_iter,1),:)); - %get proposal draw - if strcmpi(sampler_options.proposal_distribution,'rand_multivariate_normal') - n = nxopt; - elseif strcmpi(sampler_options.proposal_distribution,'rand_multivariate_student') - n = options_.student_degrees_of_freedom; - end - - proposed_par = feval(sampler_options.proposal_distribution, xopt_current_block', proposal_covariance_Cholesky_decomposition_upper, n); - % check whether draw is valid and compute posterior - if all( proposed_par(:) > mh_bounds.lb(indices(blocks==block_iter,1),:) ) && all( proposed_par(:) < mh_bounds.ub(indices(blocks==block_iter,1),:) ) - try - logpost = - feval('TaRB_optimizer_wrapper', proposed_par(:),... - current_draw,indices(blocks==block_iter,1),TargetFun,...% inputs for wrapper - varargin{:}); - catch - logpost = -inf; - end - else - logpost = -inf; - end - %get ratio of proposal densities, required because proposal depends - %on current mode via Hessian and is thus not symmetric anymore - if strcmpi(sampler_options.proposal_distribution,'rand_multivariate_normal') - proposal_density_proposed_move_forward=multivariate_normal_pdf(proposed_par,xopt_current_block',proposal_covariance_Cholesky_decomposition_upper,n); - proposal_density_proposed_move_backward=multivariate_normal_pdf(par_start_current_block',xopt_current_block',proposal_covariance_Cholesky_decomposition_upper,n); - elseif strcmpi(sampler_options.proposal_distribution,'rand_multivariate_student') - proposal_density_proposed_move_forward=multivariate_student_pdf(proposed_par,xopt_current_block',proposal_covariance_Cholesky_decomposition_upper,n); - proposal_density_proposed_move_backward=multivariate_student_pdf(par_start_current_block',xopt_current_block',proposal_covariance_Cholesky_decomposition_upper,n); - end - accprob=logpost-last_posterior+ log(proposal_density_proposed_move_backward)-log(proposal_density_proposed_move_forward); %Formula (6), Chib/Ramamurthy - - if (logpost > -inf) && (log(rand) < accprob) - current_draw(indices(blocks==block_iter,1))=proposed_par; - last_posterior=logpost; - accepted_draws_counter =accepted_draws_counter +1; - else %no updating - %do nothing, keep old value - end - end - accepted=accepted_draws_counter/blocked_draws_counter; - par = current_draw; - neval=1; - case 'independent_metropolis_hastings' - neval = 1; - ProposalFun = sampler_options.proposal_distribution; - ProposalDensity = sampler_options.ProposalDensity; - proposal_covariance_Cholesky_decomposition = sampler_options.proposal_covariance_Cholesky_decomposition; - n = sampler_options.n; - xparam1 = sampler_options.xparam1'; - par = feval(ProposalFun, xparam1, proposal_covariance_Cholesky_decomposition, n); - if all( par(:) > mh_bounds.lb ) && all( par(:) < mh_bounds.ub ) - try - logpost = - feval(TargetFun, par(:),varargin{:}); - catch - logpost = -inf; - end - else - logpost = -inf; - end - r = logpost - last_posterior + ... - log(feval(ProposalDensity, last_draw, xparam1, proposal_covariance_Cholesky_decomposition, n)) - ... - log(feval(ProposalDensity, par, xparam1, proposal_covariance_Cholesky_decomposition, n)); - if (logpost > -inf) && (log(rand) < r) - accepted = 1; - else - accepted = 0; - par = last_draw; - logpost = last_posterior; - end +function [par, logpost, accepted, neval] = posterior_sampler_iteration(TargetFun,last_draw, last_posterior, sampler_options,varargin) + +% function [par, logpost, accepted, neval] = posterior_sampler_iteration(TargetFun,last_draw, last_posterior, sampler_options,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_) +% posterior samplers +% +% INPUTS +% posterior_sampler_options: posterior sampler options +% options_: structure storing the options + +% OUTPUTS +% posterior_sampler_options: checked posterior sampler options +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2015-16 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/>. + + +posterior_sampling_method = sampler_options.posterior_sampling_method; +mh_bounds = sampler_options.bounds; + +switch posterior_sampling_method + case 'slice' + + [par, logpost, neval] = slice_sampler(TargetFun,last_draw, [mh_bounds.lb mh_bounds.ub], sampler_options,varargin{:}); + accepted = 1; + case 'random_walk_metropolis_hastings' + neval = 1; + ProposalFun = sampler_options.proposal_distribution; + proposal_covariance_Cholesky_decomposition = sampler_options.proposal_covariance_Cholesky_decomposition; + n = sampler_options.n; + + par = feval(ProposalFun, last_draw, proposal_covariance_Cholesky_decomposition, n); + if all( par(:) > mh_bounds.lb ) && all( par(:) < mh_bounds.ub ) + try + logpost = - feval(TargetFun, par(:),varargin{:}); + catch + logpost = -inf; + end + else + logpost = -inf; + end + r = logpost-last_posterior; + if (logpost > -inf) && (log(rand) < r) + accepted = 1; + else + accepted = 0; + par = last_draw; + logpost = last_posterior; + end + case 'tailored_random_block_metropolis_hastings' + options_=varargin{3}; + bayestopt_=varargin{6}; + npar=length(last_draw); + %% randomize indices for blocking in this iteration + indices=randperm(npar)'; + blocks=[1; (1+cumsum((rand(length(indices)-1,1)>(1-sampler_options.new_block_probability))))]; + nblocks=blocks(end,1); %get number of blocks this iteration + current_draw=last_draw'; %get starting point for current draw for updating + blocked_draws_counter=0; + accepted_draws_counter=0; + for block_iter=1:nblocks + blocked_draws_counter=blocked_draws_counter+1; + nxopt=length(indices(blocks==block_iter,1)); %get size of current block + par_start_current_block=current_draw(indices(blocks==block_iter,1)); + [xopt_current_block, fval, exitflag, hess_mat_optimizer, options_, Scale] = dynare_minimize_objective(@TaRB_optimizer_wrapper,par_start_current_block,sampler_options.mode_compute,options_,[mh_bounds.lb(indices(blocks==block_iter,1),1) mh_bounds.ub(indices(blocks==block_iter,1),1)],bayestopt_.name,bayestopt_,[],... + current_draw,indices(blocks==block_iter,1),TargetFun,...% inputs for wrapper + varargin{:}); %inputs for objective + %% covariance for proposal density + hessian_mat = reshape(hessian('TaRB_optimizer_wrapper',xopt_current_block, ... + options_.gstep,... + current_draw,indices(blocks==block_iter,1),TargetFun,...% inputs for wrapper + varargin{:}),nxopt,nxopt); + + if any(any(isnan(hessian_mat))) || any(any(isinf(hessian_mat))) + inverse_hessian_mat=eye(nxopt)*1e-4; %use diagonal + else + inverse_hessian_mat=inv(hessian_mat); %get inverse Hessian + if any(any((isnan(inverse_hessian_mat)))) || any(any((isinf(inverse_hessian_mat)))) + inverse_hessian_mat=eye(nxopt)*1e-4; %use diagonal + end + end + [proposal_covariance_Cholesky_decomposition_upper,negeigenvalues]=chol(inverse_hessian_mat); + %if not positive definite, use generalized Cholesky of Eskow/Schnabel + if negeigenvalues~=0 + proposal_covariance_Cholesky_decomposition_upper=chol_SE(inverse_hessian_mat,0); + end + proposal_covariance_Cholesky_decomposition_upper=proposal_covariance_Cholesky_decomposition_upper*diag(bayestopt_.jscale(indices(blocks==block_iter,1),:)); + %get proposal draw + if strcmpi(sampler_options.proposal_distribution,'rand_multivariate_normal') + n = nxopt; + elseif strcmpi(sampler_options.proposal_distribution,'rand_multivariate_student') + n = options_.student_degrees_of_freedom; + end + + proposed_par = feval(sampler_options.proposal_distribution, xopt_current_block', proposal_covariance_Cholesky_decomposition_upper, n); + % check whether draw is valid and compute posterior + if all( proposed_par(:) > mh_bounds.lb(indices(blocks==block_iter,1),:) ) && all( proposed_par(:) < mh_bounds.ub(indices(blocks==block_iter,1),:) ) + try + logpost = - feval('TaRB_optimizer_wrapper', proposed_par(:),... + current_draw,indices(blocks==block_iter,1),TargetFun,...% inputs for wrapper + varargin{:}); + catch + logpost = -inf; + end + else + logpost = -inf; + end + %get ratio of proposal densities, required because proposal depends + %on current mode via Hessian and is thus not symmetric anymore + if strcmpi(sampler_options.proposal_distribution,'rand_multivariate_normal') + proposal_density_proposed_move_forward=multivariate_normal_pdf(proposed_par,xopt_current_block',proposal_covariance_Cholesky_decomposition_upper,n); + proposal_density_proposed_move_backward=multivariate_normal_pdf(par_start_current_block',xopt_current_block',proposal_covariance_Cholesky_decomposition_upper,n); + elseif strcmpi(sampler_options.proposal_distribution,'rand_multivariate_student') + proposal_density_proposed_move_forward=multivariate_student_pdf(proposed_par,xopt_current_block',proposal_covariance_Cholesky_decomposition_upper,n); + proposal_density_proposed_move_backward=multivariate_student_pdf(par_start_current_block',xopt_current_block',proposal_covariance_Cholesky_decomposition_upper,n); + end + accprob=logpost-last_posterior+ log(proposal_density_proposed_move_backward)-log(proposal_density_proposed_move_forward); %Formula (6), Chib/Ramamurthy + + if (logpost > -inf) && (log(rand) < accprob) + current_draw(indices(blocks==block_iter,1))=proposed_par; + last_posterior=logpost; + accepted_draws_counter =accepted_draws_counter +1; + else %no updating + %do nothing, keep old value + end + end + accepted=accepted_draws_counter/blocked_draws_counter; + par = current_draw; + neval=1; + case 'independent_metropolis_hastings' + neval = 1; + ProposalFun = sampler_options.proposal_distribution; + ProposalDensity = sampler_options.ProposalDensity; + proposal_covariance_Cholesky_decomposition = sampler_options.proposal_covariance_Cholesky_decomposition; + n = sampler_options.n; + xparam1 = sampler_options.xparam1'; + par = feval(ProposalFun, xparam1, proposal_covariance_Cholesky_decomposition, n); + if all( par(:) > mh_bounds.lb ) && all( par(:) < mh_bounds.ub ) + try + logpost = - feval(TargetFun, par(:),varargin{:}); + catch + logpost = -inf; + end + else + logpost = -inf; + end + r = logpost - last_posterior + ... + log(feval(ProposalDensity, last_draw, xparam1, proposal_covariance_Cholesky_decomposition, n)) - ... + log(feval(ProposalDensity, par, xparam1, proposal_covariance_Cholesky_decomposition, n)); + if (logpost > -inf) && (log(rand) < r) + accepted = 1; + else + accepted = 0; + par = last_draw; + logpost = last_posterior; + end end \ No newline at end of file diff --git a/matlab/print_bytecode_dynamic_model.m b/matlab/print_bytecode_dynamic_model.m index f4e381ed15..688f9cadb9 100644 --- a/matlab/print_bytecode_dynamic_model.m +++ b/matlab/print_bytecode_dynamic_model.m @@ -1,10 +1,10 @@ function print_bytecode_dynamic_model() % function print_bytecode_dynamic_model() % print the model and jacobian from the bytecode format for the dynamic model -% +% % INPUTS % none -% +% % OUTPUTS % none % diff --git a/matlab/print_bytecode_static_model.m b/matlab/print_bytecode_static_model.m index bc216c70da..6ddc67fe2a 100644 --- a/matlab/print_bytecode_static_model.m +++ b/matlab/print_bytecode_static_model.m @@ -1,10 +1,10 @@ function print_bytecode_static_model() % function print_bytecode_static_model() % print the model and jacobian from the bytecode format for the static model -% +% % INPUTS % none -% +% % OUTPUTS % none % diff --git a/matlab/print_info.m b/matlab/print_info.m index 29ef302d7a..76ec1d115f 100644 --- a/matlab/print_info.m +++ b/matlab/print_info.m @@ -2,7 +2,7 @@ function print_info(info, noprint, DynareOptions) % Prints error messages % % INPUTS -% info [double] vector returned by resol.m +% info [double] vector returned by resol.m % noprint [integer] equal to 0 if the error message has to be printed. % DynareOptions [structure] --> options_ % OUTPUTS @@ -54,15 +54,15 @@ if ~noprint error('One of the eigenvalues is close to 0/0 (the absolute value of numerator and denominator is smaller than %s!\n If you believe that the model has a unique solution you can try to reduce the value of qz_zero_threshold.',num2str(DynareOptions.qz_zero_threshold)) case 8 if size(info,2)>=2 - global M_; + global M_; disp_string=deblank(M_.param_names(info(2),:)); - for ii=1:length(info)-2 - disp_string=[disp_string,', ',deblank(M_.param_names(info(2+ii),:))]; - end - error(['The Jacobian contains NaNs because the following parameters are NaN: '... - disp_string]) + for ii=1:length(info)-2 + disp_string=[disp_string,', ',deblank(M_.param_names(info(2+ii),:))]; + end + error(['The Jacobian contains NaNs because the following parameters are NaN: '... + disp_string]) else - error(['The Jacobian contains NaNs. For more information, use options_.debug.']) + error(['The Jacobian contains NaNs. For more information, use options_.debug.']) end case 9 error(['k_order_pert was unable to compute the solution']) @@ -78,7 +78,7 @@ if ~noprint if DynareOptions.linear error(['Impossible to find the steady state. Either the model' ... ' doesn''t have a steady state or there are an infinity of steady states.' ... - ' Check whether your model is truly linear or whether there is a mistake in linearization.']) + ' Check whether your model is truly linear or whether there is a mistake in linearization.']) else error(['Impossible to find the steady state. Either the model' ... ' doesn''t have a steady state, there are an infinity of steady states,' ... @@ -117,7 +117,7 @@ if ~noprint case 49 error('The model violates one (many) endogenous prior restriction(s)') case 50 - error('Likelihood is Inf') + error('Likelihood is Inf') case 51 fprintf('\n The dsge_prior_weight is dsge_var=%5.4f, but must be at least %5.4f for the prior to be proper.\n',info(2),info(3)); error('You are estimating a DSGE-VAR model, but the value of the dsge prior weight is too low!') diff --git a/matlab/print_moments_implied_prior.m b/matlab/print_moments_implied_prior.m index 496e3bf865..56dc069b1d 100644 --- a/matlab/print_moments_implied_prior.m +++ b/matlab/print_moments_implied_prior.m @@ -1,7 +1,7 @@ function print_moments_implied_prior(ModelInfo, mm, vm, mv, vv) % This routine prints in the command window some descriptive statistics -% about the endogenous variables implied prior moments. +% about the endogenous variables implied prior moments. % Copyright (C) 2016 Dynare Team % diff --git a/matlab/print_table_prior.m b/matlab/print_table_prior.m index 605adfabf7..c12c2fd313 100644 --- a/matlab/print_table_prior.m +++ b/matlab/print_table_prior.m @@ -1,6 +1,6 @@ function print_table_prior(lb, ub, DynareOptions, ModelInfo, BayesInfo, EstimationInfo) -% This routine prints in the command window some descriptive statistics about the prior distribution. +% This routine prints in the command window some descriptive statistics about the prior distribution. % Copyright (C) 2015 Dynare Team % @@ -111,7 +111,7 @@ for i=1:size(BayesInfo.name,1) UpperBound, ... PriorIntervals.lb(i), ... PriorIntervals.ub(i) ); - T2 = strvcat(T2, str); + T2 = strvcat(T2, str); end T1 = strvcat(T1, l1); @@ -134,25 +134,25 @@ skipline(2) function format_string = build_format_string(PriorMode,PriorStandardDeviation,LowerBound,UpperBound) - format_string = ['%s \t %6.4f \t']; - if isnan(PriorMode) - format_string = [ format_string , ' %s \t']; - else - format_string = [ format_string , ' %6.4f \t']; - end - if ~isnumeric(PriorStandardDeviation) - format_string = [ format_string , ' %s \t']; - else - format_string = [ format_string , ' %6.4f \t']; - end - if ~isnumeric(LowerBound) - format_string = [ format_string , ' %s \t']; - else - format_string = [ format_string , ' %6.4f \t']; - end - if ~isnumeric(UpperBound) - format_string = [ format_string , ' %s \t']; - else - format_string = [ format_string , ' %6.4f \t']; - end - format_string = [ format_string , ' %6.4f \t %6.4f']; \ No newline at end of file +format_string = ['%s \t %6.4f \t']; +if isnan(PriorMode) + format_string = [ format_string , ' %s \t']; +else + format_string = [ format_string , ' %6.4f \t']; +end +if ~isnumeric(PriorStandardDeviation) + format_string = [ format_string , ' %s \t']; +else + format_string = [ format_string , ' %6.4f \t']; +end +if ~isnumeric(LowerBound) + format_string = [ format_string , ' %s \t']; +else + format_string = [ format_string , ' %6.4f \t']; +end +if ~isnumeric(UpperBound) + format_string = [ format_string , ' %s \t']; +else + format_string = [ format_string , ' %6.4f \t']; +end +format_string = [ format_string , ' %6.4f \t %6.4f']; \ No newline at end of file diff --git a/matlab/printline.m b/matlab/printline.m index c60d0906a9..85bb44e0f7 100644 --- a/matlab/printline.m +++ b/matlab/printline.m @@ -1,13 +1,13 @@ function varargout = printline(n, s, fid) % This function print a line formed by replicating a symbol s. % -% INPUTS +% INPUTS % % n [integer] Length of the printed line % s [char] Symbol used to draw the line (+, -, =, ...) % f [integer] file id returned by fopen -% -% OUTPUTS +% +% OUTPUTS % None % Copyright (C) 2015 Dynare Team @@ -25,7 +25,7 @@ function varargout = printline(n, s, fid) % 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/>. +% along with Dynare. If not, see <http://www.gnu.org/licenses/>. if nargin<3 f = 1; diff --git a/matlab/prior_analysis.m b/matlab/prior_analysis.m index c152aaa588..41b43ffa34 100644 --- a/matlab/prior_analysis.m +++ b/matlab/prior_analysis.m @@ -56,7 +56,7 @@ switch type 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_,options_); + vartan,nvar,arg1,arg2,options_.mh_conf_sig,oo_,options_); case 'decomposition' if nargin==narg1 [nvar,vartan,NumberOfFiles] = ... diff --git a/matlab/prior_bounds.m b/matlab/prior_bounds.m index cd11fdfaba..83127f7aaf 100644 --- a/matlab/prior_bounds.m +++ b/matlab/prior_bounds.m @@ -40,10 +40,10 @@ function bounds = prior_bounds(bayestopt, prior_trunc) % % INPUTS % bayestopt [structure] characterizing priors (shape, mean, p1..p4) -% +% % OUTPUTS % bounds [double] structure specifying prior bounds (lb and ub fields) -% +% % SPECIAL REQUIREMENTS % none diff --git a/matlab/prior_draw.m b/matlab/prior_draw.m index 4e9ca2ba2c..c97eaeefd4 100644 --- a/matlab/prior_draw.m +++ b/matlab/prior_draw.m @@ -2,10 +2,10 @@ function pdraw = prior_draw(BayesInfo, prior_trunc, uniform) % --*-- Unitary tes % This function generate one draw from the joint prior distribution and % allows sampling uniformly from the prior support (uniform==1 when called with init==1) -% -% INPUTS -% o init [integer] scalar equal to: -% 1: first call to set up persistent variables +% +% INPUTS +% o init [integer] scalar equal to: +% 1: first call to set up persistent variables % describing the prior % 0: subsequent call to get prior % draw @@ -13,8 +13,8 @@ function pdraw = prior_draw(BayesInfo, prior_trunc, uniform) % --*-- Unitary tes % 1: sample uniformly from prior % support (overwrites prior shape used for sampling within this function) % 0: sample from joint prior distribution -% -% OUTPUTS +% +% OUTPUTS % o pdraw [double] 1*npar vector, draws from the joint prior density. % % @@ -25,7 +25,7 @@ function pdraw = prior_draw(BayesInfo, prior_trunc, uniform) % --*-- Unitary tes % NOTE 2. A given draw from the joint prior distribution does not satisfy BK conditions a priori. % NOTE 3. This code relies on bayestopt_ as created in the base workspace % by the preprocessor (or as updated in subsequent pieces of code and handed to the base workspace) -% +% % Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. @@ -108,7 +108,7 @@ if nargin>0 end if uniform_draws - pdraw(uniform_index) = rand(length(uniform_index),1).*(p4(uniform_index)-p3(uniform_index)) + p3(uniform_index); + pdraw(uniform_index) = rand(length(uniform_index),1).*(p4(uniform_index)-p3(uniform_index)) + p3(uniform_index); out_of_bound = find( (pdraw(uniform_index)'>ub(uniform_index)) | (pdraw(uniform_index)'<lb(uniform_index))); while ~isempty(out_of_bound) pdraw(uniform_index) = rand(length(uniform_index),1).*(p4(uniform_index)-p3(uniform_index)) + p3(uniform_index); diff --git a/matlab/prior_posterior_statistics.m b/matlab/prior_posterior_statistics.m index 6aa9797f18..064e7874ae 100644 --- a/matlab/prior_posterior_statistics.m +++ b/matlab/prior_posterior_statistics.m @@ -14,11 +14,11 @@ function prior_posterior_statistics(type,dataset,dataset_info) % % SPECIAL REQUIREMENTS % none -% +% % PARALLEL CONTEXT % See the comments in the posterior_sampler.m funtion. -% -% +% +% % Copyright (C) 2005-2017 Dynare Team % % This file is part of Dynare. @@ -117,7 +117,7 @@ if options_.filter_covariance MAX_filter_covariance = min(B,ceil(MaxNumberOfBytes/(endo_nbr^2*(gend+1))/8)); end -if options_.smoothed_state_uncertainty +if options_.smoothed_state_uncertainty MAX_n_smoothed_state_uncertainty = min(B,ceil(MaxNumberOfBytes/((endo_nbr*endo_nbr)*gend)/8)); end @@ -196,7 +196,7 @@ end if options_.filter_covariance localVars.MAX_filter_covariance = MAX_filter_covariance; end -if options_.smoothed_state_uncertainty +if options_.smoothed_state_uncertainty localVars.MAX_n_smoothed_state_uncertainty = MAX_n_smoothed_state_uncertainty ; end localVars.MAX_n_smoothed_constant=MAX_n_smoothed_constant; @@ -211,9 +211,9 @@ if strcmpi(type,'posterior') BaseName = [DirectoryName filesep M_.fname]; load_last_mh_history_file(DirectoryName, M_.fname); FirstMhFile = record.KeepedDraws.FirstMhFile; - FirstLine = record.KeepedDraws.FirstLine; - TotalNumberOfMhFiles = sum(record.MhDraws(:,2)); - LastMhFile = TotalNumberOfMhFiles; + FirstLine = record.KeepedDraws.FirstLine; + TotalNumberOfMhFiles = sum(record.MhDraws(:,2)); + LastMhFile = TotalNumberOfMhFiles; TotalNumberOfMhDraws = sum(record.MhDraws(:,1)); NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws); mh_nblck = options_.mh_nblck; @@ -274,14 +274,14 @@ else end if run_smoother nfiles = ceil(nBlockPerCPU(j)/MAX_n_trend_coeff); - ifil(9,j+1) =ifil(9,j)+nfiles; + ifil(9,j+1) =ifil(9,j)+nfiles; nfiles = ceil(nBlockPerCPU(j)/MAX_n_smoothed_constant); - ifil(10,j+1) =ifil(10,j)+nfiles; + ifil(10,j+1) =ifil(10,j)+nfiles; nfiles = ceil(nBlockPerCPU(j)/MAX_n_smoothed_trend); - ifil(11,j+1) =ifil(11,j)+nfiles; + ifil(11,j+1) =ifil(11,j)+nfiles; if smoothed_state_uncertainty nfiles = ceil(nBlockPerCPU(j)/MAX_n_smoothed_state_uncertainty); - ifil(13,j+1) =ifil(13,j)+nfiles; + ifil(13,j+1) =ifil(13,j)+nfiles; end end end @@ -331,7 +331,7 @@ if options_.smoother '',M_.exo_names,M_.exo_names_tex,M_.exo_names,... M_.exo_names,'SmoothedShocks',DirectoryName,'_inno'); pm3(endo_nbr,1,ifil(9),B,'Trend_coefficients',... - '',varlist,M_.endo_names_tex,M_.endo_names,... + '',varlist,M_.endo_names_tex,M_.endo_names,... varlist,'TrendCoeff',DirectoryName,'_trend_coeff'); pm3(endo_nbr,gend,ifil(10),B,'Smoothed constant',... '',varlist,M_.endo_names_tex,M_.endo_names,... @@ -348,17 +348,17 @@ if options_.smoother '',varlist,M_.endo_names_tex,M_.endo_names,... varlist,'StateUncertainty',DirectoryName,'_state_uncert'); end - + if nvn - for obs_iter=1:length(options_.varobs) + for obs_iter=1:length(options_.varobs) meas_error_names{obs_iter,1}=['SE_EOBS_' M_.endo_names(strmatch(options_.varobs{obs_iter},M_.endo_names,'exact'),:)]; texnames{obs_iter,1}=['SE_EOBS_' M_.endo_names_tex(strmatch(options_.varobs{obs_iter},M_.endo_names,'exact'),:)]; end meas_error_names=char(meas_error_names); texnames=char(texnames); pm3(meas_err_nbr,gend,ifil(3),B,'Smoothed measurement errors',... - '',meas_error_names,texnames,meas_error_names,... - meas_error_names,'SmoothedMeasurementErrors',DirectoryName,'_error') + '',meas_error_names,texnames,meas_error_names,... + meas_error_names,'SmoothedMeasurementErrors',DirectoryName,'_error') end end @@ -377,7 +377,7 @@ if options_.forecast varlist,'PointForecast',DirectoryName,'_forc_point'); if ~isequal(M_.H,0) && ~isempty(intersect(options_.varobs,varlist)) texnames=[]; - for obs_iter=1:length(options_.varobs) + for obs_iter=1:length(options_.varobs) obs_names{obs_iter,1}=M_.endo_names(strmatch(options_.varobs{obs_iter},M_.endo_names,'exact'),:); texnames{obs_iter,1}=M_.endo_names_tex(strmatch(options_.varobs{obs_iter},M_.endo_names,'exact'),:); end @@ -385,8 +385,8 @@ if options_.forecast texnames=char(texnames); varlist_forecast_ME=intersect(options_.varobs,varlist); pm3(meas_err_nbr,horizon,ifil(12),B,'Forecasted variables (point) with ME',... - '',char(varlist_forecast_ME),texnames,obs_names,... - char(varlist_forecast_ME),'PointForecastME',DirectoryName,'_forc_point_ME') + '',char(varlist_forecast_ME),texnames,obs_names,... + char(varlist_forecast_ME),'PointForecastME',DirectoryName,'_forc_point_ME') end end diff --git a/matlab/prior_posterior_statistics_core.m b/matlab/prior_posterior_statistics_core.m index 904eb7afad..03cc43a3e0 100644 --- a/matlab/prior_posterior_statistics_core.m +++ b/matlab/prior_posterior_statistics_core.m @@ -157,22 +157,22 @@ end %initialize arrays if run_smoother - stock_smooth=NaN(endo_nbr,gend,MAX_nsmoo); - stock_update=NaN(endo_nbr,gend,MAX_nsmoo); - stock_innov=NaN(M_.exo_nbr,gend,MAX_ninno); - stock_smoothed_constant=NaN(endo_nbr,gend,MAX_n_smoothed_constant); - stock_smoothed_trend=NaN(endo_nbr,gend,MAX_n_smoothed_trend); - stock_trend_coeff = zeros(endo_nbr,MAX_n_trend_coeff); - if horizon - stock_forcst_mean= NaN(endo_nbr,horizon,MAX_nforc1); - stock_forcst_point = NaN(endo_nbr,horizon,MAX_nforc2); - if ~isequal(M_.H,0) - stock_forcst_point_ME = NaN(length(varobs),horizon,MAX_nforc_ME); - end - end + stock_smooth=NaN(endo_nbr,gend,MAX_nsmoo); + stock_update=NaN(endo_nbr,gend,MAX_nsmoo); + stock_innov=NaN(M_.exo_nbr,gend,MAX_ninno); + stock_smoothed_constant=NaN(endo_nbr,gend,MAX_n_smoothed_constant); + stock_smoothed_trend=NaN(endo_nbr,gend,MAX_n_smoothed_trend); + stock_trend_coeff = zeros(endo_nbr,MAX_n_trend_coeff); + if horizon + stock_forcst_mean= NaN(endo_nbr,horizon,MAX_nforc1); + stock_forcst_point = NaN(endo_nbr,horizon,MAX_nforc2); + if ~isequal(M_.H,0) + stock_forcst_point_ME = NaN(length(varobs),horizon,MAX_nforc_ME); + end + end end if nvn - stock_error = NaN(length(varobs),gend,MAX_nerro); + stock_error = NaN(length(varobs),gend,MAX_nerro); end if naK stock_filter_step_ahead =NaN(length(options_.filter_step_ahead),endo_nbr,gend+max(options_.filter_step_ahead),MAX_naK); @@ -206,7 +206,7 @@ for b=fpar:B [dr,info,M_,options_,oo_] = resol(0,M_,options_,oo_); [alphahat,etahat,epsilonhat,alphatilde,SteadyState,trend_coeff,aK,junk1,junk2,P,junk4,junk5,trend_addition,state_uncertainty,M_,oo_,options_,bayestopt_] = ... DsgeSmoother(deep,gend,Y,data_index,missing_value,M_,oo_,options_,bayestopt_,estim_params_); - + stock_trend_coeff(options_.varobs_id,irun(9))=trend_coeff; stock_smoothed_trend(IdObs,:,irun(11))=trend_addition; if options_.loglinear %reads values from smoother results, which are in dr-order and put them into declaration order @@ -221,7 +221,7 @@ for b=fpar:B constant_part; stock_update(dr.order_var,:,irun(1)) = alphatilde(1:endo_nbr,:)+ ... constant_part; - end + end stock_smoothed_constant(dr.order_var,:,irun(10))=constant_part; %% Compute constant for observables if options_.prefilter == 1 %as mean is taken after log transformation, no distinction is needed here @@ -243,10 +243,10 @@ for b=fpar:B %smoothed variables are E_T(y_t) so no trend shift is required stock_smooth(IdObs,:,irun(1))=stock_smooth(IdObs,:,irun(1))+trend_addition+mean_correction; %updated variables are E_t(y_t) so no trend shift is required - stock_update(IdObs,:,irun(1))=stock_update(IdObs,:,irun(1))+trend_addition+mean_correction; + stock_update(IdObs,:,irun(1))=stock_update(IdObs,:,irun(1))+trend_addition+mean_correction; else stock_smooth(IdObs,:,irun(1))=stock_smooth(IdObs,:,irun(1))+trend_addition; - stock_update(IdObs,:,irun(1))=stock_update(IdObs,:,irun(1))+trend_addition; + stock_update(IdObs,:,irun(1))=stock_update(IdObs,:,irun(1))+trend_addition; end stock_innov(:,:,irun(2)) = etahat; if nvn @@ -259,11 +259,11 @@ for b=fpar:B constant_part=repmat(log(SteadyState(dr.order_var))',[length(options_.filter_step_ahead),1,gend+max(options_.filter_step_ahead)]); else constant_part=repmat(SteadyState(dr.order_var)',[length(options_.filter_step_ahead),1,gend+max(options_.filter_step_ahead)]); - end + end stock_filter_step_ahead(:,dr.order_var,:,irun(4)) = aK(options_.filter_step_ahead,1:endo_nbr,:) + ... constant_part; - + %now add trend to observables for ii=1:length(options_.filter_step_ahead) if options_.prefilter @@ -280,16 +280,16 @@ for b=fpar:B if horizon yyyy = alphahat(iendo,i_last_obs); yf = forcst2a(yyyy,dr,zeros(horizon,exo_nbr)); - if options_.prefilter + if options_.prefilter % add mean yf(:,IdObs) = yf(:,IdObs)+repmat(mean_varobs, ... horizon+maxlag,1); % add trend, taking into account that last point of sample is still included in forecasts and only cut off later yf(:,IdObs) = yf(:,IdObs)+((options_.first_obs-1)+gend+[1-maxlag:horizon]')*trend_coeff'-... - repmat(mean(trend_coeff*[options_.first_obs:options_.first_obs+gend-1],2)',length(1-maxlag:horizon),1); %center trend + repmat(mean(trend_coeff*[options_.first_obs:options_.first_obs+gend-1],2)',length(1-maxlag:horizon),1); %center trend else % add trend, taking into account that last point of sample is still included in forecasts and only cut off later - yf(:,IdObs) = yf(:,IdObs)+((options_.first_obs-1)+gend+[1-maxlag:horizon]')*trend_coeff'; + yf(:,IdObs) = yf(:,IdObs)+((options_.first_obs-1)+gend+[1-maxlag:horizon]')*trend_coeff'; end if options_.loglinear yf = yf+repmat(log(SteadyState'),horizon+maxlag,1); @@ -303,10 +303,10 @@ for b=fpar:B repmat(mean_varobs,[horizon+maxlag,1,1]); % add trend, taking into account that last point of sample is still included in forecasts and only cut off later yf1(:,IdObs) = yf1(:,IdObs)+((options_.first_obs-1)+gend+[1-maxlag:horizon]')*trend_coeff'-... - repmat(mean(trend_coeff*[options_.first_obs:options_.first_obs+gend-1],2)',length(1-maxlag:horizon),1); %center trend + repmat(mean(trend_coeff*[options_.first_obs:options_.first_obs+gend-1],2)',length(1-maxlag:horizon),1); %center trend else - % add trend, taking into account that last point of sample is still included in forecasts and only cut off later - yf1(:,IdObs,:) = yf1(:,IdObs,:)+repmat(((options_.first_obs-1)+gend+[1-maxlag:horizon]')* ... + % add trend, taking into account that last point of sample is still included in forecasts and only cut off later + yf1(:,IdObs,:) = yf1(:,IdObs,:)+repmat(((options_.first_obs-1)+gend+[1-maxlag:horizon]')* ... trend_coeff',[1,1,1]); end if options_.loglinear @@ -420,7 +420,7 @@ for b=fpar:B end irun(7) = 1; end - + if run_smoother && filter_covariance && (irun(8) > MAX_filter_covariance || b == B) stock = stock_filter_covariance(:,:,:,1:irun(8)-1); ifil(8) = ifil(8) + 1; @@ -430,7 +430,7 @@ for b=fpar:B end irun(8) = 1; end - + irun_index=9; if run_smoother && (irun(irun_index) > MAX_n_trend_coeff || b == B) stock = stock_trend_coeff(:,1:irun(irun_index)-1); @@ -441,7 +441,7 @@ for b=fpar:B end irun(irun_index) = 1; end - + irun_index=10; if run_smoother && (irun(irun_index) > MAX_n_smoothed_constant || b == B) stock = stock_smoothed_constant(:,:,1:irun(irun_index)-1); @@ -463,7 +463,7 @@ for b=fpar:B end irun(irun_index) = 1; end - + irun_index=12; if run_smoother && horizon && ~isequal(M_.H,0) && (irun(irun_index) > MAX_nforc_ME || b == B) stock = stock_forcst_point_ME(:,:,1:irun(irun_index)-1); @@ -474,7 +474,7 @@ for b=fpar:B end irun(irun_index) = 1; end - + irun_index=13; if run_smoother && smoothed_state_uncertainty && (irun(irun_index) > MAX_n_smoothed_state_uncertainty || b == B) stock = stock_smoothed_uncert(:,:,:,1:irun(irun_index)-1); @@ -508,4 +508,3 @@ if RemoteFlag==1 end dyn_waitbar_close(h); - diff --git a/matlab/priordens.m b/matlab/priordens.m index ce1e5bb854..b988e7ea1a 100644 --- a/matlab/priordens.m +++ b/matlab/priordens.m @@ -1,7 +1,7 @@ function [logged_prior_density, dlprior, d2lprior, info] = priordens(x, pshape, p6, p7, p3, p4, initialization) % --*-- Unitary tests --*-- % Computes a prior density for the structural parameters of DSGE models % -% INPUTS +% INPUTS % x [double] vector with n elements. % pshape [integer] vector with n elements (bayestopt_.pshape). % p6: [double] vector with n elements, first parameter of the prior distribution (bayestopt_.p6). @@ -9,8 +9,8 @@ function [logged_prior_density, dlprior, d2lprior, info] = priordens(x, pshape, % p3: [double] vector with n elements, lower bounds of the untruncated standard or generalized distribution % p4: [double] vector with n elements, upper bound of the untruncated standard or generalized distribution % initialization [integer] if 1: initialize persistent variables -% -% OUTPUTS +% +% OUTPUTS % logged_prior_density [double] scalar, log of the prior density evaluated at x. % info [double] error code for index of Inf-prior parameter % @@ -89,7 +89,7 @@ d2lprior = 0.0; if tt1 logged_prior_density = logged_prior_density + sum(lpdfgbeta(x(id1),p6(id1),p7(id1),p3(id1),p4(id1))) ; if isinf(logged_prior_density) - if nargout ==4 + if nargout ==4 info=id1(isinf(lpdfgbeta(x(id1),p6(id1),p7(id1),p3(id1),p4(id1)))); end return @@ -104,7 +104,7 @@ end if tt2 logged_prior_density = logged_prior_density + sum(lpdfgam(x(id2)-p3(id2),p6(id2),p7(id2))) ; if isinf(logged_prior_density) - if nargout ==4 + if nargout ==4 info=id2(isinf(lpdfgam(x(id2)-p3(id2),p6(id2),p7(id2)))); end return @@ -128,7 +128,7 @@ end if tt4 logged_prior_density = logged_prior_density + sum(lpdfig1(x(id4)-p3(id4),p6(id4),p7(id4))) ; if isinf(logged_prior_density) - if nargout ==4 + if nargout ==4 info=id4(isinf(lpdfig1(x(id4)-p3(id4),p6(id4),p7(id4)))); end return @@ -143,7 +143,7 @@ end if tt5 if any(x(id5)-p3(id5)<0) || any(x(id5)-p4(id5)>0) logged_prior_density = -Inf ; - if nargout ==4 + if nargout ==4 info=id5((x(id5)-p3(id5)<0) || (x(id5)-p4(id5)>0)); end return @@ -160,7 +160,7 @@ end if tt6 logged_prior_density = logged_prior_density + sum(lpdfig2(x(id6)-p3(id6),p6(id6),p7(id6))) ; if isinf(logged_prior_density) - if nargout ==4 + if nargout ==4 info=id6(isinf(lpdfig2(x(id6)-p3(id6),p6(id6),p7(id6)))); end return @@ -175,7 +175,7 @@ end if tt8 logged_prior_density = logged_prior_density + sum(lpdfgweibull(x(id8),p6(id8),p7(id8))); if isinf(logged_prior_density) - if nargout ==4 + if nargout ==4 info=id8(isinf(log(lpdfgweibull(x(id8),p6(id8),p7(id8))))); end return diff --git a/matlab/qr2.m b/matlab/qr2.m index 3c84db9960..2d00e1c2c9 100644 --- a/matlab/qr2.m +++ b/matlab/qr2.m @@ -1,18 +1,18 @@ function [Q,R] = qr2(varargin) % This routine performs a qr decomposition of matrix X such that the -% diagonal scalars of the upper-triangular matrix R are positive. If X +% 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 +% factorization of X'X. This property is needed for the Del Negro % & Schorfheides's identification scheme. -% -% INPUTS +% +% INPUTS % See matlab's documentation for QR decomposition. -% -% OUTPUTS +% +% OUTPUTS % See matlab's documentation for QR decomposition. % % ALGORITHM -% None. +% None. % % SPECIAL REQUIREMENTS % None. diff --git a/matlab/quadratic_matrix_equation_solver.m b/matlab/quadratic_matrix_equation_solver.m index d74f5e12f7..3ecfe25282 100644 --- a/matlab/quadratic_matrix_equation_solver.m +++ b/matlab/quadratic_matrix_equation_solver.m @@ -106,34 +106,34 @@ end function f = eval_quadratic_matrix_equation(A,B,C,X) - f = C + (B + A*X)*X; +f = C + (B + A*X)*X; function [p0,p1] = merit_polynomial(A,H,F) - AHH = A*H*H; - gamma = norm(AHH,'fro')^2; - alpha = norm(F,'fro')^2; - beta = trace(F*AHH*AHH*F); - p0 = [gamma, -beta, alpha+beta, -2*alpha, alpha]; - p1 = [4*gamma, -3*beta, 2*(alpha+beta), -2*alpha]; +AHH = A*H*H; +gamma = norm(AHH,'fro')^2; +alpha = norm(F,'fro')^2; +beta = trace(F*AHH*AHH*F); +p0 = [gamma, -beta, alpha+beta, -2*alpha, alpha]; +p1 = [4*gamma, -3*beta, 2*(alpha+beta), -2*alpha]; function t = line_search(A,H,F) - [p0,p1] = merit_polynomial(A,H,F); - if any(isnan(p0)) || any(isinf(p0)) - t = 1.0; - return - end - r = roots(p1); - s = [Inf(3,1),r]; - for i = 1:3 - if isreal(r(i)) - s(i,1) = p0(1)*r(i)^4 + p0(2)*r(i)^3 + p0(3)*r(i)^2 + p0(4)*r(i) + p0(5); - end - end - s = sortrows(s,1); - t = s(1,2); - if t<=1e-12 || t>=2 - t = 1; +[p0,p1] = merit_polynomial(A,H,F); +if any(isnan(p0)) || any(isinf(p0)) + t = 1.0; + return +end +r = roots(p1); +s = [Inf(3,1),r]; +for i = 1:3 + if isreal(r(i)) + s(i,1) = p0(1)*r(i)^4 + p0(2)*r(i)^3 + p0(3)*r(i)^2 + p0(4)*r(i) + p0(5); end +end +s = sortrows(s,1); +t = s(1,2); +if t<=1e-12 || t>=2 + t = 1; +end %@test:1 %$ addpath ../matlab diff --git a/matlab/qz/mjdgges.m b/matlab/qz/mjdgges.m index 58e4b6513b..12c91d8016 100644 --- a/matlab/qz/mjdgges.m +++ b/matlab/qz/mjdgges.m @@ -6,16 +6,16 @@ function [err,ss,tt,w,sdim,eigval,info] = mjdgges(e,d,qz_criterium, fake) % e [double] real square (n*n) matrix. % d [double] real square (n*n) matrix. % qz_criterium [double] scalar (1+epsilon). -% +% % OUTPUTS % err [double] scalar: 1 indicates failure, 0 indicates success % ss [complex] (n*n) matrix. % tt [complex] (n*n) matrix. % w [complex] (n*n) matrix. -% sdim [integer] scalar. -% eigval [complex] (n*1) vector. +% sdim [integer] scalar. +% eigval [complex] (n*1) vector. % info [integer] scalar. -% +% % ALGORITHM % Sims's qzdiv routine is used. % @@ -54,7 +54,7 @@ end % Set default value of qz_criterium. if nargin <3 - qz_criterium = 1 + 1e-6; + qz_criterium = 1 + 1e-6; end info = 0; diff --git a/matlab/qzdiv.m b/matlab/qzdiv.m index 3641808a12..8b6e58a585 100644 --- a/matlab/qzdiv.m +++ b/matlab/qzdiv.m @@ -2,7 +2,7 @@ function [A,B,Q,Z] = qzdiv(stake,A,B,Q,Z) %function [A,B,Q,Z] = qzdiv(stake,A,B,Q,Z) % % Takes U.T. matrices A, B, orthonormal matrices Q,Z, rearranges them -% so that all cases of abs(B(i,i)/A(i,i))>stake are in lower right +% so that all cases of abs(B(i,i)/A(i,i))>stake are in lower right % corner, while preserving U.T. and orthonormal properties and Q'AZ' and % Q'BZ'. @@ -34,13 +34,13 @@ 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) + if (root(j,2) > stake || root(j,2) < -.1) m=j; break end end - if (m==0) - return + if (m==0) + return end for k=m:1:i-1 [A, B, Q, Z] = qzswitch(k,A,B,Q,Z); @@ -48,4 +48,4 @@ for i = n:-1:1 root(k,2) = root(k+1,2); root(k+1,2) = tmp; end -end +end diff --git a/matlab/ramsey_policy.m b/matlab/ramsey_policy.m index fe162eca43..2ca9079fe4 100644 --- a/matlab/ramsey_policy.m +++ b/matlab/ramsey_policy.m @@ -38,7 +38,7 @@ else error('You have specified a steady state file, but not provided an instrument. Either delete the steady state file or provide an instrument') end end - + info = stoch_simul(var_list); oo_.steady_state = oo_.dr.ys; diff --git a/matlab/read_data_.m b/matlab/read_data_.m index 7ad6b4228a..32c61ea810 100644 --- a/matlab/read_data_.m +++ b/matlab/read_data_.m @@ -1,6 +1,6 @@ function read_data_() % function read_data_ -% reads endogenous and exogenous variables from a text file +% reads endogenous and exogenous variables from a text file % Used by datafile option in simulate % % INPUT diff --git a/matlab/read_key_value_string.m b/matlab/read_key_value_string.m index d6b7124ed6..d92fb26985 100644 --- a/matlab/read_key_value_string.m +++ b/matlab/read_key_value_string.m @@ -40,7 +40,7 @@ iComma = strfind(s,','); %delete commata in sublists from further checks for sublist_iter=length(i_begin_sublist):-1:1 - iComma(iComma>=i_begin_sublist(sublist_iter) & iComma<=i_end_sublist(sublist_iter))=[]; + iComma(iComma>=i_begin_sublist(sublist_iter) & iComma<=i_end_sublist(sublist_iter))=[]; end nComma = length(iComma); @@ -85,10 +85,10 @@ end function j = comma2opt(i) - if isodd(i) - % The comma is a separator between a Key and a Value (returned j is minus the option number). - j = - (i+1)/2; - else - % The comma is a separator between two options (returned j is the option number). - j = i/2; - end \ No newline at end of file +if isodd(i) + % The comma is a separator between a Key and a Value (returned j is minus the option number). + j = - (i+1)/2; +else + % The comma is a separator between two options (returned j is the option number). + j = i/2; +end \ No newline at end of file diff --git a/matlab/read_variables.m b/matlab/read_variables.m index 47373c4101..34a50c9eb4 100644 --- a/matlab/read_variables.m +++ b/matlab/read_variables.m @@ -6,7 +6,7 @@ function dyn_data_01=read_variables(file_name_01,var_names_01,dyn_data_01,xls_sh % INPUTS % file_name_01: file name % var_names_01: variables name -% dyn_data_01: +% dyn_data_01: % xls_sheet: Excel sheet name % xls_range: Excel range specification % @@ -65,64 +65,64 @@ fullname = [basename extension]; if ~exist(fullname) error(['Can''t find datafile: ' fullname ]); -end +end switch (extension) - case '.m' - eval(basename); - for dyn_i_01=1:var_size_01 - dyn_tmp_01 = eval(var_names_01{dyn_i_01}); + case '.m' + eval(basename); + 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 + case '.mat' + s = load(basename); + for dyn_i_01=1:var_size_01 + dyn_tmp_01 = s.(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 + case { '.xls', '.xlsx' } + [freq,init,data,varlist] = load_xls_file_data(fullname,xls_sheet,xls_range); + for dyn_i_01=1:var_size_01 + iv = strmatch(strtrim(var_names_01(dyn_i_01,:)),varlist,'exact'); + if ~isempty(iv) + dyn_tmp_01 = [data(:,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; + else + cd(old_pwd) + error([strtrim(var_names_01(dyn_i_01,:)) ' not found in ' fullname]) end - case '.mat' - s = load(basename); - for dyn_i_01=1:var_size_01 - dyn_tmp_01 = s.(var_names_01{dyn_i_01}); + end + case '.csv' + [freq,init,data,varlist] = load_csv_file_data(fullname); + for dyn_i_01=1:var_size_01 + iv = strmatch(var_names_01{dyn_i_01},varlist,'exact'); + if ~isempty(iv) + dyn_tmp_01 = [data(:,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; + else + cd(old_pwd) + error([var_names_01{dyn_i_01} ' not found in ' fullname]) end - case { '.xls', '.xlsx' } - [freq,init,data,varlist] = load_xls_file_data(fullname,xls_sheet,xls_range); - for dyn_i_01=1:var_size_01 - iv = strmatch(strtrim(var_names_01(dyn_i_01,:)),varlist,'exact'); - if ~isempty(iv) - dyn_tmp_01 = [data(:,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; - else - cd(old_pwd) - error([strtrim(var_names_01(dyn_i_01,:)) ' not found in ' fullname]) - end - end - case '.csv' - [freq,init,data,varlist] = load_csv_file_data(fullname); - for dyn_i_01=1:var_size_01 - iv = strmatch(var_names_01{dyn_i_01},varlist,'exact'); - if ~isempty(iv) - dyn_tmp_01 = [data(:,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; - else - cd(old_pwd) - error([var_names_01{dyn_i_01} ' not found in ' fullname]) - end - end - otherwise - cd(old_pwd) - error(['Unsupported extension for datafile: ' extension]) + end + otherwise + cd(old_pwd) + error(['Unsupported extension for datafile: ' extension]) end cd(old_pwd) diff --git a/matlab/realtime_shock_decomposition.m b/matlab/realtime_shock_decomposition.m index d160f767a5..64bf96c6f7 100644 --- a/matlab/realtime_shock_decomposition.m +++ b/matlab/realtime_shock_decomposition.m @@ -1,11 +1,11 @@ function oo_ = realtime_shock_decomposition(M_,oo_,options_,varlist,bayestopt_,estim_params_) % function oo_ = realtime_shock_decomposition(M_,oo_,options_,varlist,bayestopt_,estim_params_) % Computes shocks contribution to a simulated trajectory. The fields set are -% oo_.realtime_shock_decomposition, oo_.conditional_shock_decomposition and oo_.realtime_forecast_shock_decomposition. +% oo_.realtime_shock_decomposition, oo_.conditional_shock_decomposition and oo_.realtime_forecast_shock_decomposition. % Subfields are arrays n_var by nshock+2 by nperiods. The % first nshock columns store the respective shock contributions, column n+1 % stores the role of the initial conditions, while column n+2 stores the -% value of the smoothed variables. Both the variables and shocks are stored +% value of the smoothed variables. Both the variables and shocks are stored % in the order of declaration, i.e. M_.endo_names and M_.exo_names, respectively. % % INPUTS @@ -64,7 +64,7 @@ if isempty(parameter_set) parameter_set = 'posterior_mode'; else error(['realtime_shock_decomposition: option parameter_set is not specified ' ... - 'and posterior mode is not available']) + 'and posterior mode is not available']) end end @@ -104,22 +104,22 @@ if forecast_ && any(forecast_params) end for j=presample+1:nobs -% evalin('base',['options_.nobs=' int2str(j) ';']) + % evalin('base',['options_.nobs=' int2str(j) ';']) options_.nobs=j; [oo, M_, junk2, junk3, Smoothed_Variables_deviation_from_mean] = evaluate_smoother(parameter_set,varlist,M_,oo_,options_,bayestopt_,estim_params_); - + % 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; - + if forecast_ if any(forecast_params) Af = oo1.dr.ghx; @@ -137,20 +137,20 @@ for j=presample+1:nobs epsilon(i,:) = oo.SmoothedShocks.(deblank(M_.exo_names(i,:))); end epsilon=[epsilon zeros(nshocks,forecast_)]; - + z = zeros(endo_nbr,nshocks+2,gend+forecast_); - + z(:,end,1:gend) = Smoothed_Variables_deviation_from_mean; - + maximum_lag = M_.maximum_lag; - + 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+forecast_ 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); @@ -165,16 +165,16 @@ for j=presample+1:nobs lags = lags+1; z(:,1:nshocks,i) = z(:,1:nshocks,i) + B(inv_order_var,:).*repmat(epsilon(:,i)',endo_nbr,1); end - -% z(:,1:nshocks,i) = z(:,1:nshocks,i) + B(inv_order_var,:).*repmat(epsilon(:,i)',endo_nbr,1); + + % 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 - + %% conditional shock decomp 1 step ahead z1 = zeros(endo_nbr,nshocks+2); z1(:,end) = Smoothed_Variables_deviation_from_mean(:,gend); for i=gend - + z1(:,1:nshocks) = z1(:,1:nshocks) + B(inv_order_var,:).*repmat(epsilon(:,i)',endo_nbr,1); z1(:,nshocks+1) = z1(:,nshocks+2) - sum(z1(:,1:nshocks),2); end @@ -188,7 +188,7 @@ for j=presample+1:nobs if i > 1 && i <= maximum_lag+1 lags = min(i-1,maximum_lag):-1:1; end - + if i > 1 tempx = permute(zn(:,1:nshocks,lags),[1 3 2]); m = min(i-1,maximum_lag); @@ -197,14 +197,14 @@ for j=presample+1:nobs lags = lags+1; zn(:,1:nshocks,i) = zn(:,1:nshocks,i) + B(inv_order_var,:).*repmat(epsilon(:,i+gend-forecast_-1)',endo_nbr,1); end - -% zn(:,1:nshocks,i) = zn(:,1:nshocks,i) + B(inv_order_var,:).*repmat(epsilon(:,i+gend-forecast_-1)',endo_nbr,1); + + % zn(:,1:nshocks,i) = zn(:,1:nshocks,i) + B(inv_order_var,:).*repmat(epsilon(:,i+gend-forecast_-1)',endo_nbr,1); zn(:,nshocks+1,i) = zn(:,nshocks+2,i) - sum(zn(:,1:nshocks,i),2); end oo_.conditional_shock_decomposition.(['time_' int2str(j-forecast_)])=zn; end %% - + if init zreal(:,:,1:j) = z(:,:,1:j); else @@ -214,12 +214,12 @@ for j=presample+1:nobs if ismember(j,save_realtime) oo_.realtime_shock_decomposition.(['time_' int2str(j)])=z; end - + if forecast_ zfrcst(:,:,j+1) = z(:,:,gend+1); oo_.realtime_forecast_shock_decomposition.(['time_' int2str(j)])=z(:,:,gend:end); if j>forecast_+presample - %% realtime conditional shock decomp k step ahead + %% realtime conditional shock decomp k step ahead oo_.realtime_conditional_shock_decomposition.(['time_' int2str(j-forecast_)]) = ... zreal(:,:,j-forecast_:j) - ... oo_.realtime_forecast_shock_decomposition.(['time_' int2str(j-forecast_)]); @@ -227,7 +227,7 @@ for j=presample+1:nobs oo_.realtime_forecast_shock_decomposition.(['time_' int2str(j-forecast_)])(:,end,:); oo_.realtime_conditional_shock_decomposition.(['time_' int2str(j-forecast_)])(:,end,:) = ... zreal(:,end,j-forecast_:j); - + if j==nobs for my_forecast_=(forecast_-1):-1:1 oo_.realtime_conditional_shock_decomposition.(['time_' int2str(j-my_forecast_)]) = ... @@ -239,10 +239,10 @@ for j=presample+1:nobs zreal(:,end,j-my_forecast_:j); end end - + end end - + prctdone=(j-presample)/(nobs-presample); if isoctave printf([running_text,' %3.f%% done\r'], prctdone*100); diff --git a/matlab/recursive_moments.m b/matlab/recursive_moments.m index 712a4b5978..e446c86bfd 100644 --- a/matlab/recursive_moments.m +++ b/matlab/recursive_moments.m @@ -1,20 +1,20 @@ function [mu,sigma,offset] = recursive_moments(m0,s0,data,offset) % Recursive estimation of order one and two moments (expectation and -% covariance matrix). -% -% INPUTS +% 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 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. +% 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. +% ALGORITHM +% None. % % SPECIAL REQUIREMENTS % None. @@ -47,6 +47,6 @@ for t = 1:T s0 = s1; end -mu = m1; +mu = m1; sigma = s1; offset = offset+T; \ No newline at end of file diff --git a/matlab/reduced_rank_cholesky.m b/matlab/reduced_rank_cholesky.m index c1870e96cf..fe9edbacef 100644 --- a/matlab/reduced_rank_cholesky.m +++ b/matlab/reduced_rank_cholesky.m @@ -51,8 +51,8 @@ function T = reduced_rank_cholesky(X) % 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/>. - +% along with Dynare. If not, see <http://www.gnu.org/licenses/>. + [T,X_is_not_positive_definite] = chol(X); if X_is_not_positive_definite diff --git a/matlab/resid.m b/matlab/resid.m index 58e421bc9e..817544f8f2 100644 --- a/matlab/resid.m +++ b/matlab/resid.m @@ -2,13 +2,13 @@ function z = resid(junk) % function z = resid(junk) % % Computes static residuals associated with the guess values. -% +% % INPUTS % junk: dummy value for backward compatibility -% +% % OUTPUTS % z: residuals -% +% % SPECIAL REQUIREMENTS % none @@ -58,9 +58,9 @@ if any(imag(oo_.steady_state)) for iter=1:length(imagrow) fprintf('%s\n',M_.endo_names(imagrow(iter),:)); end - end + end end - + if options_.steadystate_flag [oo_.steady_state,M_.params,info] = ... evaluate_steady_state(oo_.steady_state,M_,options_,oo_,0); diff --git a/matlab/rotated_slice_sampler.m b/matlab/rotated_slice_sampler.m index d249cb0c61..6dbfded0f4 100644 --- a/matlab/rotated_slice_sampler.m +++ b/matlab/rotated_slice_sampler.m @@ -1,184 +1,183 @@ -function [theta, fxsim, neval] = rotated_slice_sampler(objective_function,theta,thetaprior,sampler_options,varargin) -% ---------------------------------------------------------- -% ROTATED SLICE SAMPLER - with stepping out (Neal, 2003) -% extension of the orthogonal univarite sampler (slice_sampler.m) -% copyright M. Ratto (European Commission) -% -% objective_function(theta,varargin): -log of any unnormalized pdf -% with varargin (optional) a vector of auxiliaty parameters -% to be passed to f( ). -% ---------------------------------------------------------- -% -% INPUTS -% objective_function: objective function (expressed as minus the log of a density) -% theta: last value of theta -% thetaprior: bounds of the theta space -% sampler_options: posterior sampler options -% varargin: optional input arguments to objective function -% -% OUTPUTS -% theta: new theta sample -% fxsim: value of the objective function for the new sample -% neval: number of function evaluations -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2015-2017 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/>. - -theta=theta(:); -npar = length(theta); -neval = zeros(npar,1); -W1=[]; -if isfield(sampler_options,'WR') - W1 = sampler_options.WR; -end -if ~isempty(sampler_options.mode) - mm = sampler_options.mode; - n = length(mm); - for j=1:n - distance(j)=sqrt(sum((theta-mm(j).m).^2)); - end - [m, im] = min(distance); - - r=im; - V1 = mm(r).m; - jj=0; - for j=1:n - if j~=r - jj=jj+1; - tmp=mm(j).m-mm(r).m; - %tmp=mm(j).m-theta; - V1(:,jj)=tmp/norm(tmp); - end - end - resul=randperm(n-1,n-1); - V1 = V1(:,resul); - - %V1 = V1(:, randperm(n-1)); -% %d = chol(mm(r).invhess); -% %V1 = transpose(feval(sampler_options.proposal_distribution, transpose(mm(r).m), d, npar)); -% -% V1=eye(npar); -% V1=V1(:,randperm(npar)); -% for j=1:2, -% V1(:,j)=mm(r(j)).m-theta; -% V1(:,j)=V1(:,j)/norm(V1(:,j)); -% end -% % Gram-Schmidt -% for j=2:npar, -% for k=1:j-1, -% V1(:,j)=V1(:,j)-V1(:,k)'*V1(:,j)*V1(:,k); -% end -% V1(:,j)=V1(:,j)/norm(V1(:,j)); -% end -% for j=1:n, -% distance(j)=sqrt(sum((theta-mm(j).m).^2)); -% end -% [m, im] = min(distance); -% if im==r, -% fxsim=[]; -% return, -% else -% theta1=theta; -% end -else - V1 = sampler_options.V1; -end -npar=size(V1,2); - -for it=1:npar - theta0 = theta; - neval(it) = 0; - xold = 0; - % XLB = thetaprior(3); - % XUB = thetaprior(4); - tb=sort([(thetaprior(:,1)-theta)./V1(:,it) (thetaprior(:,2)-theta)./V1(:,it)],2); - XLB=max(tb(:,1)); - XUB=min(tb(:,2)); - if isempty(W1) - W = (XUB-XLB); %*0.8; - else - W = W1(it); - end - - % ------------------------------------------------------- - % 1. DRAW Z = ln[f(X0)] - EXP(1) where EXP(1)=-ln(U(0,1)) - % THIS DEFINES THE SLICE S={x: z < ln(f(x))} - % ------------------------------------------------------- - - fxold = -feval(objective_function,theta,varargin{:}); - %I have to be sure that the rotation is for L,R or for Fxold, theta(it) - neval(it) = neval(it) + 1; - Z = fxold + log(rand(1,1)); - % ------------------------------------------------------------- - % 2. FIND I=(L,R) AROUND X0 THAT CONTAINS S AS MUCH AS POSSIBLE - % STEPPING-OUT PROCEDURE - % ------------------------------------------------------------- - u = rand(1,1); - L = max(XLB,xold-W*u); - R = min(XUB,L+W); - - %[L R]=slice_rotation(L, R, alpha); - while(L > XLB) - xsim = L; - theta = theta0+xsim*V1(:,it); - fxl = -feval(objective_function,theta,varargin{:}); - neval(it) = neval(it) + 1; - if (fxl <= Z) - break - end - L = max(XLB,L-W); - end - while(R < XUB) - xsim = R; - theta = theta0+xsim*V1(:,it); - fxr = -feval(objective_function,theta,varargin{:}); - neval(it) = neval(it) + 1; - if (fxr <= Z) - break - end - R = min(XUB,R+W); - end - % ------------------------------------------------------ - % 3. SAMPLING FROM THE SET A = (I INTERSECT S) = (LA,RA) - % ------------------------------------------------------ - fxsim = Z-1; - while (fxsim < Z) - u = rand(1,1); - xsim = L + u*(R - L); - theta = theta0+xsim*V1(:,it); - fxsim = -feval(objective_function,theta,varargin{:}); - neval(it) = neval(it) + 1; - if (xsim > xold) - R = xsim; - else - L = xsim; - end - end -end - -% if ~isempty(sampler_options.mode), -% dist1=sqrt(sum((theta-mm(r).m).^2)); -% if dist1>distance(r), -% theta=theta1; -% fxsim=[]; -% end -% end -end - +function [theta, fxsim, neval] = rotated_slice_sampler(objective_function,theta,thetaprior,sampler_options,varargin) +% ---------------------------------------------------------- +% ROTATED SLICE SAMPLER - with stepping out (Neal, 2003) +% extension of the orthogonal univarite sampler (slice_sampler.m) +% copyright M. Ratto (European Commission) +% +% objective_function(theta,varargin): -log of any unnormalized pdf +% with varargin (optional) a vector of auxiliaty parameters +% to be passed to f( ). +% ---------------------------------------------------------- +% +% INPUTS +% objective_function: objective function (expressed as minus the log of a density) +% theta: last value of theta +% thetaprior: bounds of the theta space +% sampler_options: posterior sampler options +% varargin: optional input arguments to objective function +% +% OUTPUTS +% theta: new theta sample +% fxsim: value of the objective function for the new sample +% neval: number of function evaluations +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2015-2017 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/>. + +theta=theta(:); +npar = length(theta); +neval = zeros(npar,1); +W1=[]; +if isfield(sampler_options,'WR') + W1 = sampler_options.WR; +end +if ~isempty(sampler_options.mode) + mm = sampler_options.mode; + n = length(mm); + for j=1:n + distance(j)=sqrt(sum((theta-mm(j).m).^2)); + end + [m, im] = min(distance); + + r=im; + V1 = mm(r).m; + jj=0; + for j=1:n + if j~=r + jj=jj+1; + tmp=mm(j).m-mm(r).m; + %tmp=mm(j).m-theta; + V1(:,jj)=tmp/norm(tmp); + end + end + resul=randperm(n-1,n-1); + V1 = V1(:,resul); + + %V1 = V1(:, randperm(n-1)); + % %d = chol(mm(r).invhess); + % %V1 = transpose(feval(sampler_options.proposal_distribution, transpose(mm(r).m), d, npar)); + % + % V1=eye(npar); + % V1=V1(:,randperm(npar)); + % for j=1:2, + % V1(:,j)=mm(r(j)).m-theta; + % V1(:,j)=V1(:,j)/norm(V1(:,j)); + % end + % % Gram-Schmidt + % for j=2:npar, + % for k=1:j-1, + % V1(:,j)=V1(:,j)-V1(:,k)'*V1(:,j)*V1(:,k); + % end + % V1(:,j)=V1(:,j)/norm(V1(:,j)); + % end + % for j=1:n, + % distance(j)=sqrt(sum((theta-mm(j).m).^2)); + % end + % [m, im] = min(distance); + % if im==r, + % fxsim=[]; + % return, + % else + % theta1=theta; + % end +else + V1 = sampler_options.V1; +end +npar=size(V1,2); + +for it=1:npar + theta0 = theta; + neval(it) = 0; + xold = 0; + % XLB = thetaprior(3); + % XUB = thetaprior(4); + tb=sort([(thetaprior(:,1)-theta)./V1(:,it) (thetaprior(:,2)-theta)./V1(:,it)],2); + XLB=max(tb(:,1)); + XUB=min(tb(:,2)); + if isempty(W1) + W = (XUB-XLB); %*0.8; + else + W = W1(it); + end + + % ------------------------------------------------------- + % 1. DRAW Z = ln[f(X0)] - EXP(1) where EXP(1)=-ln(U(0,1)) + % THIS DEFINES THE SLICE S={x: z < ln(f(x))} + % ------------------------------------------------------- + + fxold = -feval(objective_function,theta,varargin{:}); + %I have to be sure that the rotation is for L,R or for Fxold, theta(it) + neval(it) = neval(it) + 1; + Z = fxold + log(rand(1,1)); + % ------------------------------------------------------------- + % 2. FIND I=(L,R) AROUND X0 THAT CONTAINS S AS MUCH AS POSSIBLE + % STEPPING-OUT PROCEDURE + % ------------------------------------------------------------- + u = rand(1,1); + L = max(XLB,xold-W*u); + R = min(XUB,L+W); + + %[L R]=slice_rotation(L, R, alpha); + while(L > XLB) + xsim = L; + theta = theta0+xsim*V1(:,it); + fxl = -feval(objective_function,theta,varargin{:}); + neval(it) = neval(it) + 1; + if (fxl <= Z) + break + end + L = max(XLB,L-W); + end + while(R < XUB) + xsim = R; + theta = theta0+xsim*V1(:,it); + fxr = -feval(objective_function,theta,varargin{:}); + neval(it) = neval(it) + 1; + if (fxr <= Z) + break + end + R = min(XUB,R+W); + end + % ------------------------------------------------------ + % 3. SAMPLING FROM THE SET A = (I INTERSECT S) = (LA,RA) + % ------------------------------------------------------ + fxsim = Z-1; + while (fxsim < Z) + u = rand(1,1); + xsim = L + u*(R - L); + theta = theta0+xsim*V1(:,it); + fxsim = -feval(objective_function,theta,varargin{:}); + neval(it) = neval(it) + 1; + if (xsim > xold) + R = xsim; + else + L = xsim; + end + end +end + +% if ~isempty(sampler_options.mode), +% dist1=sqrt(sum((theta-mm(r).m).^2)); +% if dist1>distance(r), +% theta=theta1; +% fxsim=[]; +% end +% end +end diff --git a/matlab/row_header_width.m b/matlab/row_header_width.m index c3132e261b..2ad7dee285 100644 --- a/matlab/row_header_width.m +++ b/matlab/row_header_width.m @@ -1,13 +1,13 @@ function w=row_header_width(M_,estim_params_,bayestopt_) % This function computes the width of the row headers for % the estimation results -% -% INPUTS -% estim_params_ [structure] +% +% INPUTS +% estim_params_ [structure] % M_ [structure] % bayestopt_ [structure] -% -% OUTPUTS +% +% OUTPUTS % w integer % % SPECIAL REQUIREMENTS @@ -44,13 +44,13 @@ if np end if nvx for i=1:nvx - k = estim_params_.var_exo(i,1); + k = estim_params_.var_exo(i,1); w = max(w,length(deblank(M_.exo_names(k,:)))); end end if nvn for i=1:nvn - k = estim_params_.var_endo(i,1); + k = estim_params_.var_endo(i,1); w = max(w,length(deblank(M_.endo_names(k,:)))); end end @@ -72,4 +72,3 @@ if ncn end end - diff --git a/matlab/rplot.m b/matlab/rplot.m index 5f19018941..cc7f30515c 100644 --- a/matlab/rplot.m +++ b/matlab/rplot.m @@ -52,11 +52,11 @@ ix = [1 - M_.maximum_lag:size(oo_.endo_simul,2)-M_.maximum_lag]' ; y = []; for k=1:size(s1,1) - if isempty(strmatch(deblank(s1(k,:)),M_.endo_names,'exact')) - if isempty(strmatch(deblank(s1(k,:)),M_.exo_names,'exact')) + if isempty(strmatch(deblank(s1(k,:)),M_.endo_names,'exact')) + if isempty(strmatch(deblank(s1(k,:)),M_.exo_names,'exact')) error (['rplot: One of the variables specified does not exist']) ; else - y = [y; oo_.exo_simul(:,strmatch(deblank(s1(k,:)),M_.exo_names,'exact'))'] ; + y = [y; oo_.exo_simul(:,strmatch(deblank(s1(k,:)),M_.exo_names,'exact'))'] ; end else y = [y; oo_.endo_simul(strmatch(deblank(s1(k,:)),M_.endo_names,'exact'),:)] ; @@ -140,16 +140,16 @@ if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) end function []=create_TeX_loader(fidTeX,options,figpath,caption,label_name,label_type,scale_factor) - if nargin<6 - scale_factor=1; - end - fprintf(fidTeX,' \n'); - fprintf(fidTeX,'\\begin{figure}[H]\n'); - fprintf(fidTeX,'\\centering \n'); - fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s}\n',0.8*scale_factor,strrep(figpath,'\','/')); - fprintf(fidTeX,'\\caption{%s.}',caption); - fprintf(fidTeX,'\\label{Fig:%s:%s}\n',label_name,label_type); - fprintf(fidTeX,'\\end{figure}\n\n'); +if nargin<6 + scale_factor=1; +end +fprintf(fidTeX,' \n'); +fprintf(fidTeX,'\\begin{figure}[H]\n'); +fprintf(fidTeX,'\\centering \n'); +fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s}\n',0.8*scale_factor,strrep(figpath,'\','/')); +fprintf(fidTeX,'\\caption{%s.}',caption); +fprintf(fidTeX,'\\label{Fig:%s:%s}\n',label_name,label_type); +fprintf(fidTeX,'\\end{figure}\n\n'); % 02/28/01 MJ replaced bseastr by MATLAB's strmatch % 06/19/01 MJ added 'exact' to strmatch calls diff --git a/matlab/sample_autocovariance.m b/matlab/sample_autocovariance.m index 12bd34e86f..67f1f9b592 100644 --- a/matlab/sample_autocovariance.m +++ b/matlab/sample_autocovariance.m @@ -1,14 +1,14 @@ function [autocov,autocor] = sample_autocovariance(data,q) % Computes the autocovariance function associated to a time series. -% % -% INPUTS +% +% INPUTS % % data [double] T*1 vector of data. -% q [integer] Order of the autocovariance function. -% -% OUTPUTS -% autocov [double] (q+1)*1 vector, autocovariance function (first scalar is the variance). +% q [integer] Order of the autocovariance function. +% +% OUTPUTS +% autocov [double] (q+1)*1 vector, autocovariance function (first scalar is the variance). % autocor [double] (q+1)*1 vector, autocorrelation function (first scalar is equal to one). % % SPECIAL REQUIREMENTS diff --git a/matlab/sample_hp_filter.m b/matlab/sample_hp_filter.m index 00aae0e020..911d0aabda 100644 --- a/matlab/sample_hp_filter.m +++ b/matlab/sample_hp_filter.m @@ -1,16 +1,16 @@ function [hptrend,hpcycle] = sample_hp_filter(y,s) % HP filters a collection of time series. -% -% INPUTS +% +% INPUTS % y [double] T*n matrix of data (n is the number of variables) % s [double] scalar, smoothing parameter. -% -% OUTPUTS +% +% OUTPUTS % hptrend [double] T*n matrix, trend component of y. -% hpcycle [double] T*n matrix, cycle component of y. -% +% hpcycle [double] T*n matrix, cycle component of y. +% % SPECIAL REQUIREMENTS -% +% % Copyright (C) 2010-2013 Dynare Team % diff --git a/matlab/save_params_and_steady_state.m b/matlab/save_params_and_steady_state.m index 0f8dbfe1a4..bbfee51a6c 100644 --- a/matlab/save_params_and_steady_state.m +++ b/matlab/save_params_and_steady_state.m @@ -12,10 +12,10 @@ function save_params_and_steady_state(filename) % Note that no variable type is stored in the file, so that the values % can be reloaded (with load_params_and_steady_state) in a setup where % the variable types are different. -% +% % INPUTS % filename: where to store the saved values -% +% % OUTPUTS % none % diff --git a/matlab/score.m b/matlab/score.m index 273ca63953..112be53457 100644 --- a/matlab/score.m +++ b/matlab/score.m @@ -25,95 +25,95 @@ function [DLIK] = score(T,R,Q,H,P,Y,DT,DYss,DOm,DH,DP,start,mf,kalman_tol,riccat % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licen - k = size(DT,3); % number of structural parameters - smpl = size(Y,2); % Sample size. - mm = size(T,2); % Number of state variables. - a = zeros(mm,1); % State vector. - Om = R*Q*transpose(R); % Variance of R times the vector of structural innovations. - t = 0; % Initialization of the time index. - oldK = 0; - notsteady = 1; % Steady state flag. - F_singular = 1; - - DLIK = zeros(k,1); % Initialization of the score. - Da = zeros(mm,k); % State vector. - Dv = zeros(length(mf),k); % observation vector. - +k = size(DT,3); % number of structural parameters +smpl = size(Y,2); % Sample size. +mm = size(T,2); % Number of state variables. +a = zeros(mm,1); % State vector. +Om = R*Q*transpose(R); % Variance of R times the vector of structural innovations. +t = 0; % Initialization of the time index. +oldK = 0; +notsteady = 1; % Steady state flag. +F_singular = 1; + +DLIK = zeros(k,1); % Initialization of the score. +Da = zeros(mm,k); % State vector. +Dv = zeros(length(mf),k); % observation vector. + % for ii = 1:k -% DOm = DR(:,:,ii)*Q*transpose(R) + R*DQ(:,:,ii)*transpose(R) + R*Q*transpose(DR(:,:,ii)); +% DOm = DR(:,:,ii)*Q*transpose(R) + R*DQ(:,:,ii)*transpose(R) + R*Q*transpose(DR(:,:,ii)); % 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 - a = T*a; - P = T*P*transpose(T)+Om; - 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; - iF = inv(F); - K = P(:,mf)*iF; - - [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K); - for ii = 1:k - Dv(:,ii) = -Da(mf,ii)-DYss(mf,ii); - Da(:,ii) = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii)); - if t>=start - DLIK(ii,1) = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v; - end + a = T*a; + P = T*P*transpose(T)+Om; + end + else + F_singular = 0; + iF = inv(F); + K = P(:,mf)*iF; + + [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K); + for ii = 1:k + Dv(:,ii) = -Da(mf,ii)-DYss(mf,ii); + Da(:,ii) = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii)); + if t>=start + DLIK(ii,1) = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v; end - a = T*(a+K*v); - P = T*(P-K*P(mf,:))*transpose(T)+Om; - DP = DP1; end - notsteady = max(max(abs(K-oldK))) > riccati_tol; - oldK = K; + a = T*(a+K*v); + P = T*(P-K*P(mf,:))*transpose(T)+Om; + DP = DP1; 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') - end +if F_singular + error('The variance of the forecast error remains singular until the end of the sample') +end - for ii = 1:k - tmp0(:,:,ii) = iF*DF(:,:,ii)*iF; - end - - if t < smpl - t0 = t+1; - while t < smpl - t = t+1; - v = Y(:,t)-a(mf); - for ii = 1:k - Dv(:,ii) = -Da(mf,ii)-DYss(mf,ii); - Da(:,ii) = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii)); - if t>=start - DLIK(ii,1) = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v; - end - end - a = T*(a+K*v); - end +for ii = 1:k + tmp0(:,:,ii) = iF*DF(:,:,ii)*iF; +end + +if t < smpl + t0 = t+1; + while t < smpl + t = t+1; + v = Y(:,t)-a(mf); for ii = 1:k -% DLIK(ii,1) = DLIK(ii,1) + (smpl-t0+1)*trace( iF*DF(:,:,ii) ); + Dv(:,ii) = -Da(mf,ii)-DYss(mf,ii); + Da(:,ii) = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii)); + if t>=start + DLIK(ii,1) = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v; + end end - - end - - DLIK = DLIK/2; - -% end of main function - + a = T*(a+K*v); + end + for ii = 1:k + % DLIK(ii,1) = DLIK(ii,1) + (smpl-t0+1)*trace( iF*DF(:,:,ii) ); + end + +end + +DLIK = DLIK/2; + +% end of main function + function [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K) - k = size(DT,3); - tmp = P-K*P(mf,:); +k = size(DT,3); +tmp = P-K*P(mf,:); for ii = 1:k - DF(:,:,ii) = DP(mf,mf,ii) + DH(:,:,ii); + DF(:,:,ii) = DP(mf,mf,ii) + DH(:,:,ii); DiF(:,:,ii) = -iF*DF(:,:,ii)*iF; DK(:,:,ii) = DP(:,mf,ii)*iF + P(:,mf)*DiF(:,:,ii); Dtmp = DP(:,:,ii) - DK(:,:,ii)*P(mf,:) - K*DP(mf,:,ii); @@ -121,6 +121,3 @@ for ii = 1:k end % end of computeDKalman - - - \ No newline at end of file diff --git a/matlab/selif.m b/matlab/selif.m index 752143aa5c..452adcc391 100644 --- a/matlab/selif.m +++ b/matlab/selif.m @@ -18,10 +18,9 @@ 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),:) ; return ; - diff --git a/matlab/set_all_parameters.m b/matlab/set_all_parameters.m index e4daafc37e..3b52d3da43 100644 --- a/matlab/set_all_parameters.m +++ b/matlab/set_all_parameters.m @@ -95,7 +95,7 @@ if ncx end %build covariance matrix from correlation matrix and variances already on %diagonal -Sigma_e = diag(sqrt(diag(Sigma_e)))*Correlation_matrix*diag(sqrt(diag(Sigma_e))); +Sigma_e = diag(sqrt(diag(Sigma_e)))*Correlation_matrix*diag(sqrt(diag(Sigma_e))); %if calibrated covariances, set them now to their stored value if isfield(estim_params,'calibrated_covariances') Sigma_e(estim_params.calibrated_covariances.position)=estim_params.calibrated_covariances.cov_value; @@ -136,5 +136,5 @@ if nvx || ncx end if nvn || ncn M.H = H; - M.Correlation_matrix_ME=Correlation_matrix_ME; + M.Correlation_matrix_ME=Correlation_matrix_ME; end \ No newline at end of file diff --git a/matlab/set_default_option.m b/matlab/set_default_option.m index 0ece729afc..94e41c4757 100644 --- a/matlab/set_default_option.m +++ b/matlab/set_default_option.m @@ -1,16 +1,16 @@ function options=set_default_option(options,field,default) % function options=set_default_option(options,field,default) -% Sets the option value -% +% Sets the option value +% % INPUTS % options % field: option name % default: assigns a value -% +% % OUTPUTS % options -% +% % SPECIAL REQUIREMENTS % none diff --git a/matlab/set_dynare_random_generator_state.m b/matlab/set_dynare_random_generator_state.m index f5561b2e9f..0cfda7dd2e 100644 --- a/matlab/set_dynare_random_generator_state.m +++ b/matlab/set_dynare_random_generator_state.m @@ -1,11 +1,11 @@ function [state_u,state_n] = set_dynare_random_generator_state(state_u,state_n) % Wet state of Matlab/Octave random generator depending on matlab -% (octave) version. +% (octave) version. % In older versions, Matlab kept one generator for uniformly distributed numbers and -% one for normally distributed numbers. +% one for normally distributed numbers. % For backward compatibility, we return two vectors, but, in recent % versions of Matlab and in Octave, we return two identical vectors. -% +% % Copyright (C) 2010-2013 Dynare Team % % This file is part of Dynare. @@ -23,37 +23,37 @@ function [state_u,state_n] = set_dynare_random_generator_state(state_u,state_n) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - matlab_random_streams = ~(isoctave || matlab_ver_less_than('7.7')); +matlab_random_streams = ~(isoctave || matlab_ver_less_than('7.7')); - if matlab_random_streams% Use new matlab interface. +if matlab_random_streams% Use new matlab interface. + if matlab_ver_less_than('7.12') + s = RandStream.getDefaultStream(); + else + s = RandStream.getGlobalStream(); + end + if isequal(s.Type,'legacy') + rand('state',state_u); + randn('state',state_n); + else + if ~isequal(state_u,state_n) + error(['You are using the new Matlab RandStream mechanism ' ... + 'with a single random generator, but the values ' ... + 'of the state of the uniformly ' ... + 'distributed numbers and of the state of the ' ... + 'normally distributed numbers are different. Something must be ' ... + 'wrong, such as reloading old Metropolis runs, ' ... + 'computed on a different version of Matlab. If you ' ... + 'don''t understand the origin of the problem, ' ... + 'please, contact Dynare''s development team.']) + end + s.State = state_u; if matlab_ver_less_than('7.12') - s = RandStream.getDefaultStream(); + RandStream.setDefaultStream(s); else - s = RandStream.getGlobalStream(); + RandStream.setGlobalStream(s); end - if isequal(s.Type,'legacy') - rand('state',state_u); - randn('state',state_n); - else - if ~isequal(state_u,state_n) - error(['You are using the new Matlab RandStream mechanism ' ... - 'with a single random generator, but the values ' ... - 'of the state of the uniformly ' ... - 'distributed numbers and of the state of the ' ... - 'normally distributed numbers are different. Something must be ' ... - 'wrong, such as reloading old Metropolis runs, ' ... - 'computed on a different version of Matlab. If you ' ... - 'don''t understand the origin of the problem, ' ... - 'please, contact Dynare''s development team.']) - end - s.State = state_u; - if matlab_ver_less_than('7.12') - RandStream.setDefaultStream(s); - else - RandStream.setGlobalStream(s); - end - end - else% Use old matlab interface. - rand('state',state_u); - randn('state',state_n); - end \ No newline at end of file + end +else% Use old matlab interface. + rand('state',state_u); + randn('state',state_n); +end \ No newline at end of file diff --git a/matlab/set_dynare_seed.m b/matlab/set_dynare_seed.m index 3a71d7236c..e79dadef99 100644 --- a/matlab/set_dynare_seed.m +++ b/matlab/set_dynare_seed.m @@ -1,7 +1,7 @@ function set_dynare_seed(a,b) -% Set seeds depending on matlab (octave) version. This routine is called in dynare_config and can be called by the +% Set seeds depending on matlab (octave) version. This routine is called in dynare_config and can be called by the % user in the mod file. -% +% % Copyright (C) 2010-2014 Dynare Team % % This file is part of Dynare. diff --git a/matlab/set_parameters.m b/matlab/set_parameters.m index c183bb3d31..932e94c1ef 100644 --- a/matlab/set_parameters.m +++ b/matlab/set_parameters.m @@ -4,13 +4,13 @@ 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 @@ -66,7 +66,7 @@ if ncx end %build covariance matrix from correlation matrix and variances already on %diagonal -Sigma_e = diag(sqrt(diag(Sigma_e)))*Correlation_matrix*diag(sqrt(diag(Sigma_e))); +Sigma_e = diag(sqrt(diag(Sigma_e)))*Correlation_matrix*diag(sqrt(diag(Sigma_e))); if isfield(estim_params_,'calibrated_covariances') Sigma_e(estim_params_.calibrated_covariances.position)=estim_params_.calibrated_covariances.cov_value; end diff --git a/matlab/set_prior.m b/matlab/set_prior.m index b2402d0cc1..dc7922916e 100644 --- a/matlab/set_prior.m +++ b/matlab/set_prior.m @@ -4,17 +4,17 @@ function [xparam1, estim_params_, bayestopt_, lb, ub, M_]=set_prior(estim_params % % INPUTS % o estim_params_ [structure] characterizing parameters to be estimated. -% o M_ [structure] characterizing the model. -% o options_ [structure] -% +% o M_ [structure] characterizing the model. +% o options_ [structure] +% % OUTPUTS % o xparam1 [double] vector of parameters to be estimated (initial values) % o estim_params_ [structure] characterizing parameters to be estimated % o bayestopt_ [structure] characterizing priors -% o lb [double] vector of lower bounds for the estimated parameters. +% o lb [double] vector of lower bounds for the estimated parameters. % o ub [double] vector of upper bounds for the estimated parameters. % o M_ [structure] characterizing the model. -% +% % SPECIAL REQUIREMENTS % None @@ -64,7 +64,7 @@ bayestopt_.name = {}; if nvx xparam1 = estim_params_.var_exo(:,2); ub = estim_params_.var_exo(:,4); - lb = estim_params_.var_exo(:,3); + 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); @@ -88,8 +88,8 @@ if nvn estim_params_.nvn_observable_correspondence(i,1)=obsi_; end xparam1 = [xparam1; estim_params_.var_endo(:,2)]; - ub = [ub; estim_params_.var_endo(:,4)]; - lb = [lb; estim_params_.var_endo(:,3)]; + 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)]; @@ -158,7 +158,7 @@ bayestopt_.p7 = bayestopt_.p6 ; %% check for point priors and disallow them as they do not work with MCMC if any(bayestopt_.p2 ==0) error(sprintf(['Error in prior for %s: you cannot use a point prior in estimation. Either increase the prior standard deviation',... - ' or fix the parameter completely.'], bayestopt_.name{bayestopt_.p2 ==0})) + ' or fix the parameter completely.'], bayestopt_.name{bayestopt_.p2 ==0})) end % generalized location parameters by default for beta distribution @@ -170,14 +170,14 @@ bayestopt_.p4(k(k1)) = ones(length(k1),1); for i=1:length(k) [bayestopt_.p6(k(i)), bayestopt_.p7(k(i))] = beta_specification(bayestopt_.p1(k(i)), bayestopt_.p2(k(i))^2, bayestopt_.p3(k(i)), bayestopt_.p4(k(i)), bayestopt_.name{k(i)}); if bayestopt_.p6(k(i))<1 || bayestopt_.p7(k(i))<1 - fprintf('Prior distribution for parameter %s has unbounded density!\n',bayestopt_.name{k(i)}) + fprintf('Prior distribution for parameter %s has unbounded density!\n',bayestopt_.name{k(i)}) end 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 ' bayestopt_.name{k(i)} ' has two modes!']) - bayestopt_.p5(k(i)) = m(1); + bayestopt_.p5(k(i)) = m(1); end end @@ -190,7 +190,7 @@ bayestopt_.p4(k(k2)) = Inf(length(k2),1); for i=1:length(k) [bayestopt_.p6(k(i)), bayestopt_.p7(k(i))] = gamma_specification(bayestopt_.p1(k(i)), bayestopt_.p2(k(i))^2, bayestopt_.p3(k(i)), bayestopt_.name{k(i)}); if bayestopt_.p6(k(i))<1 - fprintf('Prior distribution for parameter %s has unbounded density!\n',bayestopt_.name{k(i)}) + fprintf('Prior distribution for parameter %s has unbounded density!\n',bayestopt_.name{k(i)}) end bayestopt_.p5(k(i)) = compute_prior_mode([ bayestopt_.p6(k(i)) , bayestopt_.p7(k(i)) , bayestopt_.p3(k(i)) ], 2) ; end diff --git a/matlab/shock_decomposition.m b/matlab/shock_decomposition.m index 19601cee55..1785e8c089 100644 --- a/matlab/shock_decomposition.m +++ b/matlab/shock_decomposition.m @@ -4,7 +4,7 @@ function [oo_,M_] = shock_decomposition(M_,oo_,options_,varlist,bayestopt_,estim % oo_.shock_decomposition. It is a n_var by nshock+2 by nperiods array. The % first nshock columns store the respective shock contributions, column n+1 % stores the role of the initial conditions, while column n+2 stores the -% value of the smoothed variables. Both the variables and shocks are stored +% value of the smoothed variables. Both the variables and shocks are stored % in the order of declaration, i.e. M_.endo_names and M_.exo_names, respectively. % % INPUTS @@ -59,9 +59,9 @@ parameter_set = options_.parameter_set; if isempty(parameter_set) if isfield(oo_,'posterior_mean') parameter_set = 'posterior_mean'; - elseif isfield(oo_,'mle_mode') + elseif isfield(oo_,'mle_mode') parameter_set = 'mle_mode'; - elseif isfield(oo_,'posterior') + elseif isfield(oo_,'posterior') parameter_set = 'posterior_mode'; else error(['shock_decomposition: option parameter_set is not specified ' ... @@ -105,7 +105,7 @@ 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); @@ -115,7 +115,7 @@ for i=1:gend end if i > options_.shock_decomp.init_state - z(:,1:nshocks,i) = z(:,1:nshocks,i) + B(inv_order_var,:).*repmat(epsilon(:,i)',endo_nbr,1); + z(:,1:nshocks,i) = z(:,1:nshocks,i) + B(inv_order_var,:).*repmat(epsilon(:,i)',endo_nbr,1); end z(:,nshocks+1,i) = z(:,nshocks+2,i) - sum(z(:,1:nshocks,i),2); end diff --git a/matlab/simul_backward_linear_model.m b/matlab/simul_backward_linear_model.m index c4ed4fe264..bb2b979697 100644 --- a/matlab/simul_backward_linear_model.m +++ b/matlab/simul_backward_linear_model.m @@ -84,9 +84,9 @@ A0inv = inv(jacob(:,jdx)); A1 = jacob(:,nonzeros(DynareModel.lead_lag_incidence(1,:))); B = jacob(:,end-number_of_shocks+1:end); -% Simulations +% Simulations for it = 2:sample_size+1 - Y(:,it) = -A0inv*(cst + A1*Y(iy1,it-1) + B*DynareOutput.exo_simul(it,:)'); + Y(:,it) = -A0inv*(cst + A1*Y(iy1,it-1) + B*DynareOutput.exo_simul(it,:)'); end DynareOutput.endo_simul = Y; \ No newline at end of file diff --git a/matlab/simul_backward_model.m b/matlab/simul_backward_model.m index 90c0f5c746..edc705a4cb 100644 --- a/matlab/simul_backward_model.m +++ b/matlab/simul_backward_model.m @@ -1,4 +1,4 @@ -function DynareOutput = simul_backward_linear_model(initial_conditions, sample_size, DynareOptions, DynareModel, DynareOutput, innovations) +function DynareOutput = simul_backward_model(initial_conditions, sample_size, DynareOptions, DynareModel, DynareOutput, innovations) %@info: %! @deftypefn {Function File} {@var{DynareOutput} =} simul_backward_nonlinear_model (@var{sample_size},@var{DynareOptions}, @var{DynareModel}, @var{DynareOutput}) @@ -87,9 +87,8 @@ end if DynareOptions.linear DynareOutput = simul_backward_linear_model(initial_conditions, sample_size, DynareOptions, ... - DynareModel, DynareOutput, innovations); + DynareModel, DynareOutput, innovations); else DynareOutput = simul_backward_nonlinear_model(initial_conditions, sample_size, DynareOptions, ... - DynareModel, DynareOutput, innovations); -end - \ No newline at end of file + DynareModel, DynareOutput, innovations); +end diff --git a/matlab/simul_backward_nonlinear_model.m b/matlab/simul_backward_nonlinear_model.m index fbd6241d11..e644e2f1c2 100644 --- a/matlab/simul_backward_nonlinear_model.m +++ b/matlab/simul_backward_nonlinear_model.m @@ -2,7 +2,7 @@ function DynareOutput = simul_backward_nonlinear_model(initial_conditions, sampl % Simulates a stochastic non linear backward looking model with arbitrary precision (a deterministic solver is used). % -% INPUTS +% INPUTS % - initial_conditions [double] n*1 vector, initial conditions for the endogenous variables. % - sample_size [integer] scalar, number of periods for the simulation. % - DynareOptions [struct] Dynare's options_ global structure. @@ -10,10 +10,10 @@ function DynareOutput = simul_backward_nonlinear_model(initial_conditions, sampl % - DynareOutput [struct] Dynare's oo_ global structure. % - innovations [double] T*q matrix, innovations to be used for the simulation. % -% OUTPUTS +% OUTPUTS % - DynareOutput [struct] Dynare's oo_ global structure. % -% REMARKS +% REMARKS % [1] The innovations used for the simulation are saved in DynareOutput.exo_simul, and the resulting paths for the endogenous % variables are saved in DynareOutput.endo_simul. % [2] The last input argument is not mandatory. If absent we use random draws and rescale them with the informations provided diff --git a/matlab/simulated_moment_uncertainty.m b/matlab/simulated_moment_uncertainty.m index ef9358a75c..14ca704296 100644 --- a/matlab/simulated_moment_uncertainty.m +++ b/matlab/simulated_moment_uncertainty.m @@ -11,7 +11,7 @@ function [cmm, mm] = simulated_moment_uncertainty(indx, periods, replic,options_ % Outputs: % - cmm: [n_moments by n_moments] covariance matrix of simulated moments % - mm: [n_moments by replic] matrix of moments -% +% % Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. @@ -67,7 +67,7 @@ if options_.logged_steady_state %if steady state was previously logged, undo thi options_.logged_steady_state=0; logged_steady_state_indicator=1; evalin('base','options_.logged_steady_state=0;') -else +else logged_steady_state_indicator=0; end diff --git a/matlab/simulated_moments_estimation.m b/matlab/simulated_moments_estimation.m index a7c9c3422d..b01e5e9d3a 100644 --- a/matlab/simulated_moments_estimation.m +++ b/matlab/simulated_moments_estimation.m @@ -2,12 +2,12 @@ function [param,sigma] = simulated_moments_estimation(dataset,options,parallel) % Performs estimation by Simulated Moments Method. % % INPUTS: -% xparam [double] p*1 vector of initial values for the estimated parameters. +% xparam [double] p*1 vector of initial values for the estimated parameters. % dataset [ ] Structure describing the data set. % options [ ] Structure defining options for SMM. -% parallel [ ] Structure defining the parallel mode settings (optional). +% parallel [ ] Structure defining the parallel mode settings (optional). % -% OUTPUTS: +% OUTPUTS: % param [double] p*1 vector of point estimates for the parameters. % sigma [double] p*p covariance matrix of the SMM estimates. % @@ -87,7 +87,7 @@ options.estimated_parameters.upper_bound = [options.estimated_parameters.upper_b options.number_of_simulated_sample = 0; for i=1:length(parallel) - options.number_of_simulated_sample = options.number_of_simulated_sample + parallel(i).number_of_jobs*parallel(i).number_of_simulations; + options.number_of_simulated_sample = options.number_of_simulated_sample + parallel(i).number_of_jobs*parallel(i).number_of_simulations; end options.observed_variables_idx = dataset.observed_variables_idx; @@ -97,7 +97,7 @@ if nargin>2 if ~isunix error('The parallel version of SMM estimation is not implemented for non unix platforms!') end - [junk,hostname] = unix('hostname --fqdn'); + [junk,hostname] = unix('hostname --fqdn'); hostname = deblank(hostname); master_is_running_a_job = 0; for i=1:length(parallel) @@ -204,7 +204,7 @@ end skipline() if options.optimization_routine==1 - % Set options for csminwel. + % Set options for csminwel. H0 = 1e-4*eye(options.estimated_parameters.nb); ct = 1e-4; it = 1000; @@ -212,7 +212,7 @@ if options.optimization_routine==1 % Minimization of the objective function. if nargin==2 [fval,param,grad,hessian_csminwel,itct,fcount,retcodehat] = ... - csminwel1('smm_objective',xparam,H0,[],ct,it,2,options_.gradient_epsilon,sample_moments,weighting_matrix,options); + csminwel1('smm_objective',xparam,H0,[],ct,it,2,options_.gradient_epsilon,sample_moments,weighting_matrix,options); elseif nargin>2 [fval,param,grad,hessian_csminwel,itct,fcount,retcodehat] = ... csminwel1('smm_objective',xparam,H0,[],ct,it,2,options_.gradient_epsilon,sample_moments,weighting_matrix,options,parallel); @@ -236,7 +236,7 @@ elseif options.optimization_routine==0% Compute the variance of the SMM estimato V = (1+1/options.number_of_simulated_sample)*G'*long_run_covariance*G; [param,diag(V)] elseif options.optimization_routine<0 - T = -options.optimization_routine;% length of the simulated time series. + T = -options.optimization_routine;% length of the simulated time series. time_series = extended_path(oo_.steady_state,T,1); save time_series.mat; end @@ -248,7 +248,7 @@ fid = fopen(['job' int2str(slave_number) '.m'],'w'); fprintf(fid,['% Generated by ' hostname '.\n\n']); -if ( strcmpi(hostname,remotename) && (job_number>1) ) || ~strcmpi(hostname,remotename) +if ( strcmpi(hostname,remotename) && (job_number>1) ) || ~strcmpi(hostname,remotename) fprintf(fid,'load(''master_variables'');\n'); fprintf(fid,'assignin(''base'',''M_'',M_);\n'); fprintf(fid,'assignin(''base'',''oo_'',oo_);\n'); @@ -270,9 +270,9 @@ fprintf(fid,'M_.Sigma_e = diag(tmp);') fprintf(fid,['stream=RandStream(''mt19937ar'',''Seed'',' int2str(slave_number) ');\n']); if matlab_ver_less_than('7.12') - fprintf(fid,['RandStream.setDefaultStream(stream);\n\n']); + fprintf(fid,['RandStream.setDefaultStream(stream);\n\n']); else - fprintf(fid,['RandStream.setGlobalStream(stream);\n\n']); + fprintf(fid,['RandStream.setGlobalStream(stream);\n\n']); end fprintf(fid,['maxNumCompThreads(' int2str(threads_per_job) ');\n\n']); @@ -295,7 +295,7 @@ else fprintf(fid,['unix(''rm simulated_moments_slave_' int2str(slave_number) '.dat'');\n']); end -if ((job_number>1) && strcmpi(hostname,remotename)) || ~strcmpi(hostname,remotename) +if ((job_number>1) && strcmpi(hostname,remotename)) || ~strcmpi(hostname,remotename) fprintf(fid,'exit'); end diff --git a/matlab/simult_.m b/matlab/simult_.m index 02b95cebf1..381bfaf1be 100644 --- a/matlab/simult_.m +++ b/matlab/simult_.m @@ -3,7 +3,7 @@ function y_=simult_(y0,dr,ex_,iorder) % decision rules. % % INPUTS -% y0 [double] n*1 vector, initial value (n is the number of declared endogenous variables plus the number +% y0 [double] n*1 vector, initial value (n is the number of declared endogenous variables plus the number % of auxilliary variables for lags and leads); must be in declaration order, i.e. as in M_.endo_names % dr [struct] matlab's structure where the reduced form solution of the model is stored. % ex_ [double] T*q matrix of innovations. @@ -85,7 +85,7 @@ else k2 = k2(:,1)+(M_.maximum_lag+1-k2(:,2))*endo_nbr; order_var = dr.order_var; end - + switch iorder case 1 if isempty(dr.ghu)% For (linearized) deterministic models. @@ -134,7 +134,7 @@ else y_(dr.order_var,i) = constant + dr.ghx*yhat + dr.ghu*epsilon ... + abcOut1 + abcOut2 + abcOut3; end - end + end case 3 % only with pruning % the third moments of the shocks are assumed null. We don't have @@ -176,7 +176,7 @@ else mexErrCheck('A_times_B_kronecker_C', err); [gy2u, err] = A_times_B_kronecker_C(ghxu,yhat2,u,threads); mexErrCheck('A_times_B_kronecker_C', err); - %construct terms of order 3, all based on first order component yhat1 + %construct terms of order 3, all based on first order component yhat1 y2a = kron(yhat1,yhat1); [gyyy, err] = A_times_B_kronecker_C(ghxxx,y2a,yhat1,threads); mexErrCheck('A_times_B_kronecker_C', err); @@ -199,6 +199,6 @@ else yhat1 = yhat1(ipred); yhat2 = yhat2(ipred); yhat3 = yhat3(ipred); - end + end end end diff --git a/matlab/simultxdet.m b/matlab/simultxdet.m index 032f20588c..7de335e062 100644 --- a/matlab/simultxdet.m +++ b/matlab/simultxdet.m @@ -88,7 +88,7 @@ if iorder == 1 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 elseif iorder == 2 @@ -153,7 +153,7 @@ end int_width = zeros(iter,nvar); for i=1:nvar int_width(:,i) = fact*sqrt(var_yf(:,i)); - if nargout==3 + if nargout==3 int_width_ME(:,i) = -fact*sqrt(var_yf_ME(:,i)); - end + end end diff --git a/matlab/skipline.m b/matlab/skipline.m index 51dbd79125..b9ecaac148 100644 --- a/matlab/skipline.m +++ b/matlab/skipline.m @@ -1,12 +1,12 @@ function skipline(n, fid) % This function prints n newlines to fid % -% INPUTS +% INPUTS % % n [integer] Number of newlines to print % fid [integer] file id returned by fopen -% -% OUTPUTS +% +% OUTPUTS % None % @@ -25,7 +25,7 @@ function skipline(n, fid) % 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/>. +% along with Dynare. If not, see <http://www.gnu.org/licenses/>. if nargin < 2 fid = 1; diff --git a/matlab/slice_sampler.m b/matlab/slice_sampler.m index 68ec48439d..8aa18fb1d4 100644 --- a/matlab/slice_sampler.m +++ b/matlab/slice_sampler.m @@ -1,123 +1,123 @@ -function [theta, fxsim, neval] = slice_sampler(objective_function,theta,thetaprior,sampler_options,varargin) -% function [theta, fxsim, neval] = slice_sampler(objective_function,theta,thetaprior,sampler_options,varargin) -% ---------------------------------------------------------- -% UNIVARIATE SLICE SAMPLER - stepping out (Neal, 2003) -% W: optimal value in the range (3,10)*std(x) -% - see C.Planas and A.Rossi (2014) -% objective_function(theta,varargin): -log of any unnormalized pdf -% with varargin (optional) a vector of auxiliaty parameters -% to be passed to f( ). -% ---------------------------------------------------------- -% -% INPUTS -% objective_function: objective function (expressed as minus the log of a density) -% theta: last value of theta -% thetaprior: bounds of the theta space -% sampler_options: posterior sampler options -% varargin: optional input arguments to objective function -% -% OUTPUTS -% theta: new theta sample -% fxsim: value of the objective function for the new sample -% neval: number of function evaluations -% -% SPECIAL REQUIREMENTS -% none - -% Copyright (C) 2015-2017 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 sampler_options.rotated %&& ~isempty(sampler_options.V1), - [theta, fxsim, neval] = rotated_slice_sampler(objective_function,theta,thetaprior,sampler_options,varargin{:}); - if isempty(sampler_options.mode) % jumping - return - else - nevalR=sum(neval); - end -end - -theta=theta(:); -npar = length(theta); -W1 = sampler_options.W1; -neval = zeros(npar,1); - -for it=1:npar - neval(it) = 0; - W = W1(it); - xold = theta(it); - % XLB = thetaprior(3); - % XUB = thetaprior(4); - XLB = thetaprior(it,1); - XUB = thetaprior(it,2); - - - % ------------------------------------------------------- - % 1. DRAW Z = ln[f(X0)] - EXP(1) where EXP(1)=-ln(U(0,1)) - % THIS DEFINES THE SLICE S={x: z < ln(f(x))} - % ------------------------------------------------------- - fxold = -feval(objective_function,theta,varargin{:}); - neval(it) = neval(it) + 1; - Z = fxold + log(rand(1,1)); - % ------------------------------------------------------------- - % 2. FIND I=(L,R) AROUND X0 THAT CONTAINS S AS MUCH AS POSSIBLE - % STEPPING-OUT PROCEDURE - % ------------------------------------------------------------- - u = rand(1,1); - L = max(XLB,xold-W*u); - R = min(XUB,L+W); - while(L > XLB) - xsim = L; - theta(it) = xsim; - fxl = -feval(objective_function,theta,varargin{:}); - neval(it) = neval(it) + 1; - if (fxl <= Z) - break - end - L = max(XLB,L-W); - end - while(R < XUB) - xsim = R; - theta(it) = xsim; - fxr = -feval(objective_function,theta,varargin{:}); - neval(it) = neval(it) + 1; - if (fxr <= Z) - break - end - R = min(XUB,R+W); - end - % ------------------------------------------------------ - % 3. SAMPLING FROM THE SET A = (I INTERSECT S) = (LA,RA) - % ------------------------------------------------------ - fxsim = Z-1; - while (fxsim < Z) - u = rand(1,1); - xsim = L + u*(R - L); - theta(it) = xsim; - fxsim = -feval(objective_function,theta,varargin{:}); - neval(it) = neval(it) + 1; - if (xsim > xold) - R = xsim; - else - L = xsim; - end - end - -end - -if sampler_options.rotated && ~isempty(sampler_options.mode) % jumping - neval=sum(neval)+nevalR; -end +function [theta, fxsim, neval] = slice_sampler(objective_function,theta,thetaprior,sampler_options,varargin) +% function [theta, fxsim, neval] = slice_sampler(objective_function,theta,thetaprior,sampler_options,varargin) +% ---------------------------------------------------------- +% UNIVARIATE SLICE SAMPLER - stepping out (Neal, 2003) +% W: optimal value in the range (3,10)*std(x) +% - see C.Planas and A.Rossi (2014) +% objective_function(theta,varargin): -log of any unnormalized pdf +% with varargin (optional) a vector of auxiliaty parameters +% to be passed to f( ). +% ---------------------------------------------------------- +% +% INPUTS +% objective_function: objective function (expressed as minus the log of a density) +% theta: last value of theta +% thetaprior: bounds of the theta space +% sampler_options: posterior sampler options +% varargin: optional input arguments to objective function +% +% OUTPUTS +% theta: new theta sample +% fxsim: value of the objective function for the new sample +% neval: number of function evaluations +% +% SPECIAL REQUIREMENTS +% none + +% Copyright (C) 2015-2017 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 sampler_options.rotated %&& ~isempty(sampler_options.V1), + [theta, fxsim, neval] = rotated_slice_sampler(objective_function,theta,thetaprior,sampler_options,varargin{:}); + if isempty(sampler_options.mode) % jumping + return + else + nevalR=sum(neval); + end +end + +theta=theta(:); +npar = length(theta); +W1 = sampler_options.W1; +neval = zeros(npar,1); + +for it=1:npar + neval(it) = 0; + W = W1(it); + xold = theta(it); + % XLB = thetaprior(3); + % XUB = thetaprior(4); + XLB = thetaprior(it,1); + XUB = thetaprior(it,2); + + + % ------------------------------------------------------- + % 1. DRAW Z = ln[f(X0)] - EXP(1) where EXP(1)=-ln(U(0,1)) + % THIS DEFINES THE SLICE S={x: z < ln(f(x))} + % ------------------------------------------------------- + fxold = -feval(objective_function,theta,varargin{:}); + neval(it) = neval(it) + 1; + Z = fxold + log(rand(1,1)); + % ------------------------------------------------------------- + % 2. FIND I=(L,R) AROUND X0 THAT CONTAINS S AS MUCH AS POSSIBLE + % STEPPING-OUT PROCEDURE + % ------------------------------------------------------------- + u = rand(1,1); + L = max(XLB,xold-W*u); + R = min(XUB,L+W); + while(L > XLB) + xsim = L; + theta(it) = xsim; + fxl = -feval(objective_function,theta,varargin{:}); + neval(it) = neval(it) + 1; + if (fxl <= Z) + break + end + L = max(XLB,L-W); + end + while(R < XUB) + xsim = R; + theta(it) = xsim; + fxr = -feval(objective_function,theta,varargin{:}); + neval(it) = neval(it) + 1; + if (fxr <= Z) + break + end + R = min(XUB,R+W); + end + % ------------------------------------------------------ + % 3. SAMPLING FROM THE SET A = (I INTERSECT S) = (LA,RA) + % ------------------------------------------------------ + fxsim = Z-1; + while (fxsim < Z) + u = rand(1,1); + xsim = L + u*(R - L); + theta(it) = xsim; + fxsim = -feval(objective_function,theta,varargin{:}); + neval(it) = neval(it) + 1; + if (xsim > xold) + R = xsim; + else + L = xsim; + end + end + +end + +if sampler_options.rotated && ~isempty(sampler_options.mode) % jumping + neval=sum(neval)+nevalR; +end diff --git a/matlab/smm_objective.m b/matlab/smm_objective.m index 4b20fbdf04..fc6358205c 100644 --- a/matlab/smm_objective.m +++ b/matlab/smm_objective.m @@ -2,13 +2,13 @@ function [r,flag] = smm_objective(xparams,sample_moments,weighting_matrix,option % Evaluates the objective of the Simulated Moments Method. % % INPUTS: -% xparams [double] p*1 vector of estimated parameters. +% xparams [double] p*1 vector of estimated parameters. % sample_moments [double] n*1 vector of sample moments (n>=p). % weighting_matrix [double] n*n symetric, positive definite matrix. % options [ ] Structure defining options for SMM. % parallel [ ] Structure defining the parallel mode settings (optional). % -% OUTPUTS: +% OUTPUTS: % r [double] scalar, the value of the objective function. % junk [ ] empty matrix. % @@ -30,7 +30,7 @@ function [r,flag] = smm_objective(xparams,sample_moments,weighting_matrix,option % 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/>. +% along with Dynare. If not, see <http://www.gnu.org/licenses/>. global M_ options_ oo_ persistent mainStream mainState @@ -67,7 +67,7 @@ end if penalty>0 flag = 0; - r = priorObjectiveValue + penalty; + r = priorObjectiveValue + penalty; return end @@ -114,7 +114,7 @@ else% parallel mode. end end for j=1:parallel(i).number_of_jobs - if (strcmpi(hostname,machine) && j>1) || ~strcmpi(hostname,machine) + if (strcmpi(hostname,machine) && j>1) || ~strcmpi(hostname,machine) job_number = job_number + 1; unix(['ssh -A ' parallel(i).login '@' machine ' ./call_matlab_session.sh job' int2str(job_number) '.m &']); end @@ -125,7 +125,7 @@ else% parallel mode. eval('job1;') tElapsedMasterJob = etime(clock, tStartMasterJob); TimeLimit = tElapsedMasterJob*1.2; - % Master waits for the slaves' output... + % Master waits for the slaves' output... tStart = clock; tElapsed = 0; while tElapsed<TimeLimit @@ -140,7 +140,7 @@ else% parallel mode. simulated_moments = load(['./intermediary_results_from_master_and_slaves/simulated_moments_slave_' int2str(i) '.dat'],'-ascii'); tmp = tmp + simulated_moments; end - simulated_moments = tmp / job_number; + simulated_moments = tmp / job_number; catch r = priorObjectiveValue*1.1; flag = 0; diff --git a/matlab/smoother2histval.m b/matlab/smoother2histval.m index faec83a495..5d6a67f1df 100644 --- a/matlab/smoother2histval.m +++ b/matlab/smoother2histval.m @@ -1,10 +1,10 @@ function smoother2histval(opts) % This function takes values from oo_.SmoothedVariables (and possibly % oo_.SmoothedShocks) and copies them into M_.histval. -% +% % Optional fields in 'opts' structure: % infile: An optional *_results MAT file created by Dynare. -% If present, oo_.Smoothed{Variables,Shocks} are read from +% If present, oo_.Smoothed{Variables,Shocks} are read from % there. Otherwise, they are read from the global workspace. % invars: An optional char or cell array listing variables to read in % oo_.SmoothedVariables. If absent, all the endogenous @@ -68,7 +68,7 @@ if isstruct(getfield(smoothedvars, tmp{1})) % point and metropolis results are simultaneously present post_metropolis = 2; end - + elseif isstruct(getfield(smoothedvars, tmp{end})) % point and metropolis results are simultaneously present post_metropolis = 2; diff --git a/matlab/solve1.m b/matlab/solve1.m index 3c140c52d7..5ea2651bfd 100644 --- a/matlab/solve1.m +++ b/matlab/solve1.m @@ -15,7 +15,7 @@ function [x,check] = solve1(func,x,j1,j2,jacobian_flag,gstep,tolf,tolx,maxit,deb % maxit maximum number of iterations % debug debug flag % varargin: list of extra arguments to the function -% +% % OUTPUTS % x: results % check=1: the model can not be solved @@ -80,7 +80,7 @@ for its = 1:maxit fjac = fjac(j1,j2); else dh = max(abs(x(j2)),gstep(1)*ones(nn,1))*eps^(1/3); - + for j = 1:nn xdh = x ; xdh(j2(j)) = xdh(j2(j))+dh(j) ; @@ -114,7 +114,7 @@ for its = 1:maxit 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 @@ -147,13 +147,3 @@ disp('SOLVE: maxit has been reached') % 04/13/01 MJ added test f < tolf !! % 05/11/01 MJ changed tests for 'check' so as to remove 'continue' which is % an instruction which appears only in version 6 - - - - - - - - - - diff --git a/matlab/solve_one_boundary.m b/matlab/solve_one_boundary.m index 4753d436b3..a579ea67e2 100644 --- a/matlab/solve_one_boundary.m +++ b/matlab/solve_one_boundary.m @@ -1,7 +1,7 @@ function [y, info] = solve_one_boundary(fname, y, x, params, steady_state, ... y_index_eq, nze, periods, is_linear, Block_Num, y_kmin, maxit_, solve_tolf, lambda, cutoff, stack_solve_algo, forward_backward, is_dynamic, verbose, M, options, oo) % Computes the deterministic simulation of a block of equation containing -% lead or lag variables +% lead or lag variables % % INPUTS % fname [string] name of the file containing the block @@ -26,7 +26,7 @@ function [y, info] = solve_one_boundary(fname, y, x, params, steady_state, ... % 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 : +% Newton algorithm : % - 1 sparse LU % - 2 GMRES % - 3 BicGStab @@ -43,17 +43,17 @@ function [y, info] = solve_one_boundary(fname, y, x, params, steady_state, ... % indirect_call [integer] (0) direct call to the fname % (1) indirect call via the % local_fname wrapper -% OUTPUTS -% y [matrix] All endogenous variables of the model +% OUTPUTS +% y [matrix] All endogenous variables of the model % info [integer] >=0 no error % <0 error -% +% % ALGORITHM % Newton with LU or GMRES or BicGstab for dynamic block -% +% % SPECIAL REQUIREMENTS % none. -% +% % Copyright (C) 1996-2017 Dynare Team % diff --git a/matlab/solve_perfect_foresight_model.m b/matlab/solve_perfect_foresight_model.m index fd06d47d0c..cedf3e0604 100644 --- a/matlab/solve_perfect_foresight_model.m +++ b/matlab/solve_perfect_foresight_model.m @@ -17,107 +17,107 @@ function [flag,endo_simul,err] = solve_perfect_foresight_model(endo_simul,exo_si % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - flag = 0; - err = 0; - stop = 0; - nan_flag = 0; +flag = 0; +err = 0; +stop = 0; +nan_flag = 0; - model_dynamic = pfm.dynamic_model; +model_dynamic = pfm.dynamic_model; - Y = endo_simul(:); +Y = endo_simul(:); - if pfm.verbose - disp (['-----------------------------------------------------']) ; - disp (['MODEL SIMULATION :']) ; - fprintf('\n') ; - end +if pfm.verbose + disp (['-----------------------------------------------------']) ; + disp (['MODEL SIMULATION :']) ; + fprintf('\n') ; +end - if pfm.use_bytecode - [flag, endo_simul]=bytecode(Y, exo_simul, pfm.params); - return - end +if pfm.use_bytecode + [flag, endo_simul]=bytecode(Y, exo_simul, pfm.params); + return +end - z = Y(find(pfm.lead_lag_incidence')); - [d1,jacobian] = model_dynamic(z,exo_simul,pfm.params,pfm.steady_state,2); +z = Y(find(pfm.lead_lag_incidence')); +[d1,jacobian] = model_dynamic(z,exo_simul,pfm.params,pfm.steady_state,2); - % Initialization of the jacobian of the stacked model. - A = sparse([],[],[],pfm.periods*pfm.ny,pfm.periods*pfm.ny,pfm.periods*nnz(jacobian)); +% Initialization of the jacobian of the stacked model. +A = sparse([],[],[],pfm.periods*pfm.ny,pfm.periods*pfm.ny,pfm.periods*nnz(jacobian)); - % Initialization of the Newton residuals. - res = zeros(pfm.periods*pfm.ny,1); +% Initialization of the Newton residuals. +res = zeros(pfm.periods*pfm.ny,1); - h1 = clock; - - % Newton loop. - for iter = 1:pfm.maxit_ - h2 = clock; - i_rows = 1:pfm.ny; - i_cols = find(pfm.lead_lag_incidence'); - i_cols_A = i_cols; - % Fill the jacobian of the stacked model. - for it = 2:(pfm.periods+1) - [d1,jacobian] = model_dynamic(Y(i_cols),exo_simul,pfm.params,pfm.steady_state,it); - if it == 2 - A(i_rows,pfm.i_cols_A1) = jacobian(:,pfm.i_cols_1); - elseif it == pfm.periods+1 - A(i_rows,i_cols_A(pfm.i_cols_T)) = jacobian(:,pfm.i_cols_T); - else - A(i_rows,i_cols_A) = jacobian(:,pfm.i_cols_j); - end - res(i_rows) = d1; - i_rows = i_rows + pfm.ny; - i_cols = i_cols + pfm.ny; - if it > 2 - i_cols_A = i_cols_A + pfm.ny; - end - end - % Stop if Newton residuals are zero. - err = max(abs(res)); - if err < pfm.tolerance - stop = 1 ; - if pfm.verbose - fprintf('\n') ; - disp([' Total time of simulation :' num2str(etime(clock,h1))]) ; - fprintf('\n') ; - disp([' Convergency obtained.']) ; - fprintf('\n') ; - end - flag = 0;% Convergency obtained. - endo_simul = reshape(Y,pfm.ny,pfm.periods+2); - break +h1 = clock; + +% Newton loop. +for iter = 1:pfm.maxit_ + h2 = clock; + i_rows = 1:pfm.ny; + i_cols = find(pfm.lead_lag_incidence'); + i_cols_A = i_cols; + % Fill the jacobian of the stacked model. + for it = 2:(pfm.periods+1) + [d1,jacobian] = model_dynamic(Y(i_cols),exo_simul,pfm.params,pfm.steady_state,it); + if it == 2 + A(i_rows,pfm.i_cols_A1) = jacobian(:,pfm.i_cols_1); + elseif it == pfm.periods+1 + A(i_rows,i_cols_A(pfm.i_cols_T)) = jacobian(:,pfm.i_cols_T); + else + A(i_rows,i_cols_A) = jacobian(:,pfm.i_cols_j); end - % Compute the Newton step. - dy = -A\res; - if any(isnan(dy)) - nan_flag = 1; - break + res(i_rows) = d1; + i_rows = i_rows + pfm.ny; + i_cols = i_cols + pfm.ny; + if it > 2 + i_cols_A = i_cols_A + pfm.ny; end - % Update the endogenous variables paths. - Y(pfm.i_upd) = Y(pfm.i_upd) + dy; end - - if ~stop + % Stop if Newton residuals are zero. + err = max(abs(res)); + if err < pfm.tolerance + stop = 1 ; if pfm.verbose fprintf('\n') ; - disp([' Total time of simulation :' num2str(etime(clock,h1))]) ; + disp([' Total time of simulation :' num2str(etime(clock,h1))]) ; fprintf('\n') ; - disp(['WARNING : maximum number of iterations is reached (modify options_.simul.maxit).']) ; + disp([' Convergency obtained.']) ; fprintf('\n') ; end - flag = 1;% more iterations are needed. - endo_simul = 1; + flag = 0;% Convergency obtained. + endo_simul = reshape(Y,pfm.ny,pfm.periods+2); + break end - if nan_flag - if pfm.verbose - fprintf('\n') ; - disp([' Total time of simulation :' num2str(etime(clock,h1))]) ; - fprintf('\n') ; - disp(['WARNING : NaNs!']) ; - fprintf('\n') ; - end - flag = 1; - endo_simul = 1; + % Compute the Newton step. + dy = -A\res; + if any(isnan(dy)) + nan_flag = 1; + break end + % Update the endogenous variables paths. + Y(pfm.i_upd) = Y(pfm.i_upd) + dy; +end + +if ~stop if pfm.verbose - disp (['-----------------------------------------------------']) ; - end \ No newline at end of file + fprintf('\n') ; + disp([' Total time of simulation :' num2str(etime(clock,h1))]) ; + fprintf('\n') ; + disp(['WARNING : maximum number of iterations is reached (modify options_.simul.maxit).']) ; + fprintf('\n') ; + end + flag = 1;% more iterations are needed. + endo_simul = 1; +end +if nan_flag + if pfm.verbose + fprintf('\n') ; + disp([' Total time of simulation :' num2str(etime(clock,h1))]) ; + fprintf('\n') ; + disp(['WARNING : NaNs!']) ; + fprintf('\n') ; + end + flag = 1; + endo_simul = 1; +end +if pfm.verbose + disp (['-----------------------------------------------------']) ; +end \ No newline at end of file diff --git a/matlab/solve_two_boundaries.m b/matlab/solve_two_boundaries.m index c455bdff5c..4b59049465 100644 --- a/matlab/solve_two_boundaries.m +++ b/matlab/solve_two_boundaries.m @@ -1,6 +1,6 @@ function [y, oo]= solve_two_boundaries(fname, y, x, params, steady_state, y_index, nze, periods, y_kmin_l, y_kmax_l, is_linear, Block_Num, y_kmin, maxit_, solve_tolf, lambda, cutoff, stack_solve_algo,options,M, oo) % Computes the deterministic simulation of a block of equation containing -% both lead and lag variables using relaxation methods +% both lead and lag variables using relaxation methods % % INPUTS % fname [string] name of the file containing the block @@ -27,7 +27,7 @@ function [y, oo]= solve_two_boundaries(fname, y, x, params, steady_state, y_inde % 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 : +% Newton algorithm : % - 1 sprse LU % - 2 GMRES % - 3 BicGStab @@ -36,15 +36,15 @@ function [y, oo]= solve_two_boundaries(fname, y, x, params, steady_state, y_inde % oo [structure] Results % % OUTPUTS -% y [matrix] All endogenous variables of the model +% y [matrix] All endogenous variables of the model % oo [structure] Results % % ALGORITHM % Newton with LU or GMRES or BicGstab -% +% % SPECIAL REQUIREMENTS % none. -% +% % Copyright (C) 1996-2017 Dynare Team % diff --git a/matlab/steady.m b/matlab/steady.m index 9a00069603..3e0ec0095a 100644 --- a/matlab/steady.m +++ b/matlab/steady.m @@ -1,10 +1,10 @@ function steady() % function steady() % computes and prints the steady state calculations -% +% % INPUTS % none -% +% % OUTPUTS % none % @@ -28,7 +28,7 @@ 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_ test_for_deep_parameters_calibration(M_); @@ -70,14 +70,14 @@ if info(1) disp(sprintf('%12s %12.6f',M_.exo_det_names(hv(ixd(i),2),:), ... oo_.exo_det_steady_state(hv(ixd(i),2)))) end - + if options_.homotopy_force_continue disp('Option homotopy_continue is set, so I continue ...') else error('Homotopy step failed') end end - + [steady_state,M_.params,info] = steady_(M_,options_,oo_); oo_.steady_state = steady_state; @@ -99,7 +99,7 @@ else fprintf('\nThe steady state computation failed. It terminated with the following values:\n') for i=1:M_.orig_endo_nbr fprintf('%s \t\t %g\n',M_.endo_names(i,:),steady_state(i)); - end + end end print_info(info,options_.noprint, options_); end diff --git a/matlab/steady_.m b/matlab/steady_.m index 02c7c69ed8..01b935a68e 100644 --- a/matlab/steady_.m +++ b/matlab/steady_.m @@ -1,12 +1,12 @@ function [steady_state,params,info] = steady_(M_,options_,oo_) % function [steady_state,params,info] = steady_(M_,options_,oo_) -% Computes the steady state -% +% Computes the steady state +% % INPUTS % M struct model structure % options struct options % oo struct output results -% +% % OUTPUTS % steady_state vector steady state % params vector parameters (may have been diff --git a/matlab/step_length_correction.m b/matlab/step_length_correction.m index 8950bc7649..5af7dcaee8 100644 --- a/matlab/step_length_correction.m +++ b/matlab/step_length_correction.m @@ -17,8 +17,8 @@ function c = step_length_correction(x,scale,i) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - if isempty(scale) - c = 10^round(log10(abs(x))); - else - c = scale(i); - end +if isempty(scale) + c = 10^round(log10(abs(x))); +else + c = scale(i); +end diff --git a/matlab/stoch_simul.m b/matlab/stoch_simul.m index b77cacc3a3..81f8b886ae 100644 --- a/matlab/stoch_simul.m +++ b/matlab/stoch_simul.m @@ -84,7 +84,7 @@ else [oo_.dr,info,M_,options_,oo_] = resol(0,M_,options_,oo_); end -if options_.loglinear && isfield(oo_.dr,'ys') && options_.logged_steady_state==0 %log steady state for correct display of decision rule +if options_.loglinear && isfield(oo_.dr,'ys') && options_.logged_steady_state==0 %log steady state for correct display of decision rule oo_.dr.ys=log_variable(1:M_.endo_nbr,oo_.dr.ys,M_); oo_.steady_state=log_variable(1:M_.endo_nbr,oo_.steady_state,M_); options_old.logged_steady_state = 1; %make sure option is preserved outside of stoch_simul @@ -160,7 +160,7 @@ if options_.periods > 0 && ~PI_PCL_solver [ys, oo_] = simult(y0,oo_.dr,M_,options_,oo_); oo_.endo_simul = ys; if ~options_.minimal_workspace - dyn2vec; + dyn2vec; end end @@ -201,7 +201,7 @@ if options_.irf else if options_.order>1 && options_.relative_irf % normalize shock to 0.01 before IRF generation for GIRFs; multiply with 100 later y=irf(oo_.dr,cs(M_.exo_names_orig_ord,i)./cs(i,i)/100, options_.irf, options_.drop, ... - options_.replic, options_.order); + options_.replic, options_.order); else %for linear model, rescaling is done later y=irf(oo_.dr,cs(M_.exo_names_orig_ord,i), options_.irf, options_.drop, ... options_.replic, options_.order); diff --git a/matlab/stochastic_solvers.m b/matlab/stochastic_solvers.m index e97a94add8..a51648a439 100644 --- a/matlab/stochastic_solvers.m +++ b/matlab/stochastic_solvers.m @@ -1,33 +1,33 @@ function [dr,info] = stochastic_solvers(dr,task,M_,options_,oo_) % function [dr,info,M_,options_,oo_] = stochastic_solvers(dr,task,M_,options_,oo_) -% computes the reduced form solution of a rational expectations model (first, second or third -% order approximation of the stochastic model around the deterministic steady state). +% computes the reduced form solution of a rational expectations model (first, second or third +% order approximation of the stochastic model around the deterministic steady state). % % INPUTS % dr [matlab structure] Decision rules for stochastic simulations. % task [integer] if task = 0 then dr1 computes decision rules. % if task = 1 then dr1 computes eigenvalues. -% M_ [matlab structure] Definition of the model. +% M_ [matlab structure] Definition of the model. % options_ [matlab structure] Global options. -% oo_ [matlab structure] Results -% +% oo_ [matlab structure] Results +% % OUTPUTS % dr [matlab structure] Decision rules for stochastic simulations. % info [integer] info=1: the model doesn't define current variables uniquely -% info=2: problem in mjdgges.dll info(2) contains error code. +% info=2: problem in mjdgges.dll info(2) contains error code. % info=3: BK order condition not satisfied info(2) contains "distance" % absence of stable trajectory. % info=4: BK order condition not satisfied info(2) contains "distance" % indeterminacy. % info=5: BK rank condition not satisfied. -% info=6: The jacobian matrix evaluated at the steady state is complex. -% info=9: k_order_pert was unable to compute the solution +% info=6: The jacobian matrix evaluated at the steady state is complex. +% info=9: k_order_pert was unable to compute the solution % ALGORITHM % ... -% +% % SPECIAL REQUIREMENTS % none. -% +% % Copyright (C) 1996-2017 Dynare Team % @@ -59,16 +59,16 @@ if M_.hessian_eq_zero && local_order~=1 end if (options_.aim_solver == 1) && (local_order > 1) - error('Option "aim_solver" is incompatible with order >= 2') + error('Option "aim_solver" is incompatible with order >= 2') end -if M_.maximum_endo_lag == 0 +if M_.maximum_endo_lag == 0 if local_order >= 2 - fprintf('\nSTOCHASTIC_SOLVER: Dynare does not solve purely forward models at higher order.\n') - fprintf('STOCHASTIC_SOLVER: To circumvent this restriction, you can add a backward-looking dummy equation of the form:\n') - fprintf('STOCHASTIC_SOLVER: junk=0.9*junk(-1);\n') - error(['2nd and 3rd order approximation not implemented for purely ' ... - 'forward models']) + fprintf('\nSTOCHASTIC_SOLVER: Dynare does not solve purely forward models at higher order.\n') + fprintf('STOCHASTIC_SOLVER: To circumvent this restriction, you can add a backward-looking dummy equation of the form:\n') + fprintf('STOCHASTIC_SOLVER: junk=0.9*junk(-1);\n') + error(['2nd and 3rd order approximation not implemented for purely ' ... + 'forward models']) end if M_.exo_det_nbr~=0 fprintf('\nSTOCHASTIC_SOLVER: Dynare does not solve purely forward models with var_exo_det.\n') @@ -88,7 +88,7 @@ end if options_.k_order_solver if options_.risky_steadystate [dr,info] = dyn_risky_steadystate_solver(oo_.steady_state,M_,dr, ... - options_,oo_); + options_,oo_); else orig_order = options_.order; options_.order = local_order; @@ -119,12 +119,12 @@ if local_order == 1 jacobia_ = [loc_dr.g1 loc_dr.g1_x loc_dr.g1_xd]; else [junk,jacobia_] = feval([M_.fname '_dynamic'],z(iyr0),exo_simul, ... - M_.params, dr.ys, it_); + M_.params, dr.ys, it_); end elseif local_order == 2 if (options_.bytecode) [chck, junk, loc_dr] = bytecode('dynamic','evaluate', z,exo_simul, ... - M_.params, dr.ys, 1); + M_.params, dr.ys, 1); jacobia_ = [loc_dr.g1 loc_dr.g1_x]; else [junk,jacobia_,hessian1] = feval([M_.fname '_dynamic'],z(iyr0),... @@ -138,10 +138,10 @@ elseif local_order == 2 end [infrow,infcol]=find(isinf(hessian1)); if options_.debug - if ~isempty(infrow) - fprintf('\nSTOCHASTIC_SOLVER: The Hessian of the dynamic model contains Inf.\n') - fprintf('STOCHASTIC_SOLVER: Try running model_diagnostics to find the source of the problem.\n') - save([M_.fname '_debug.mat'],'hessian1') + if ~isempty(infrow) + fprintf('\nSTOCHASTIC_SOLVER: The Hessian of the dynamic model contains Inf.\n') + fprintf('STOCHASTIC_SOLVER: Try running model_diagnostics to find the source of the problem.\n') + save([M_.fname '_debug.mat'],'hessian1') end end if ~isempty(infrow) @@ -150,7 +150,7 @@ elseif local_order == 2 end [nanrow,nancol]=find(isnan(hessian1)); if options_.debug - if ~isempty(nanrow) + if ~isempty(nanrow) fprintf('\nSTOCHASTIC_SOLVER: The Hessian of the dynamic model contains NaN.\n') fprintf('STOCHASTIC_SOLVER: Try running model_diagnostics to find the source of the problem.\n') save([M_.fname '_debug.mat'],'hessian1') @@ -159,16 +159,16 @@ elseif local_order == 2 if ~isempty(nanrow) info(1)=12; return - end + end end [infrow,infcol]=find(isinf(jacobia_)); - + if options_.debug - if ~isempty(infrow) - fprintf('\nSTOCHASTIC_SOLVER: The Jacobian of the dynamic model contains Inf. The problem is associated with:\n\n') - display_problematic_vars_Jacobian(infrow,infcol,M_,dr.ys,'dynamic','STOCHASTIC_SOLVER: ') - save([M_.fname '_debug.mat'],'jacobia_') + if ~isempty(infrow) + fprintf('\nSTOCHASTIC_SOLVER: The Jacobian of the dynamic model contains Inf. The problem is associated with:\n\n') + display_problematic_vars_Jacobian(infrow,infcol,M_,dr.ys,'dynamic','STOCHASTIC_SOLVER: ') + save([M_.fname '_debug.mat'],'jacobia_') end end @@ -194,18 +194,18 @@ end [nanrow,nancol]=find(isnan(jacobia_)); if options_.debug - if ~isempty(nanrow) - fprintf('\nSTOCHASTIC_SOLVER: The Jacobian of the dynamic model contains NaN. The problem is associated with:\n\n') - display_problematic_vars_Jacobian(nanrow,nancol,M_,dr.ys,'dynamic','STOCHASTIC_SOLVER: ') - save([M_.fname '_debug.mat'],'jacobia_') + if ~isempty(nanrow) + fprintf('\nSTOCHASTIC_SOLVER: The Jacobian of the dynamic model contains NaN. The problem is associated with:\n\n') + display_problematic_vars_Jacobian(nanrow,nancol,M_,dr.ys,'dynamic','STOCHASTIC_SOLVER: ') + save([M_.fname '_debug.mat'],'jacobia_') end end if ~isempty(nanrow) - info(1) = 8; - NaN_params=find(isnan(M_.params)); - info(2:length(NaN_params)+1) = NaN_params; - return + info(1) = 8; + NaN_params=find(isnan(M_.params)); + info(2:length(NaN_params)+1) = NaN_params; + return end kstate = dr.kstate; @@ -229,9 +229,9 @@ if M_.maximum_endo_lead == 0 % backward models: simplified code exist only at order == 1 if local_order == 1 [k1,junk,k2] = find(kstate(:,4)); - dr.ghx(:,k1) = -b\jacobia_(:,k2); + dr.ghx(:,k1) = -b\jacobia_(:,k2); if M_.exo_nbr - dr.ghu = -b\jacobia_(:,nz+1:end); + dr.ghu = -b\jacobia_(:,nz+1:end); end dr.eigval = eig(kalman_transition_matrix(dr,nstatic+(1:nspred),1:nspred,M_.exo_nbr)); dr.full_rank = 1; @@ -272,7 +272,7 @@ else dr = dyn_second_order_solver(jacobia_,hessian1,dr,M_,... options_.threads.kronecker.A_times_B_kronecker_C,... options_.threads.kronecker.sparse_hessian_times_B_kronecker_C); - + % reordering second order derivatives, used for deterministic % variables below k1 = nonzeros(M_.lead_lag_incidence(:,order_var)'); @@ -306,7 +306,7 @@ if M_.exo_det_nbr > 0 hu = dr.ghu(nstatic+[1:nspred],:); hud = dr.ghud{1}(nstatic+1:nstatic+nspred,:); zx = [eye(nspred);dr.ghx(k0,:);gx*dr.Gy;zeros(M_.exo_nbr+M_.exo_det_nbr, ... - nspred)]; + nspred)]; zu = [zeros(nspred,M_.exo_nbr); dr.ghu(k0,:); gx*hu; zeros(M_.exo_nbr+M_.exo_det_nbr, ... M_.exo_nbr)]; zud=[zeros(nspred,M_.exo_det_nbr);dr.ghud{1};gx(:,1:nspred)*hud;zeros(M_.exo_nbr,M_.exo_det_nbr);eye(M_.exo_det_nbr)]; @@ -377,8 +377,7 @@ if options_.loglinear length(il),1); end if local_order > 1 - error('Loglinear options currently only works at order 1') + error('Loglinear options currently only works at order 1') end end end - diff --git a/matlab/store_smoother_results.m b/matlab/store_smoother_results.m index fa0584ffa0..5ef6e15099 100644 --- a/matlab/store_smoother_results.m +++ b/matlab/store_smoother_results.m @@ -1,7 +1,7 @@ function [oo_, yf]=store_smoother_results(M_,oo_,options_,bayestopt_,dataset_,dataset_info,atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,P,PK,decomp,Trend,state_uncertainty) % oo_=store_smoother_results(M_,oo_,options_,bayestopt_,dataset_,atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,P,PK,decomp,Trend) % Writes the smoother results into respective fields in oo_ -% +% % Inputs: % M_ [structure] storing the model information % oo_ [structure] storing the results @@ -42,15 +42,15 @@ function [oo_, yf]=store_smoother_results(M_,oo_,options_,bayestopt_,dataset_,da % oo_.SmoothedMeasurementErrors: structure storing the smoothed measurement errors % oo_.Smoother.State_uncertainty: smoothed state uncertainty (declaration order) -% yf [double] (nvarobs*T) matrix storing the smoothed observed variables (order of options_.varobs) -% -% Notes: +% yf [double] (nvarobs*T) matrix storing the smoothed observed variables (order of options_.varobs) +% +% Notes: % m: number of endogenous variables (M_.endo_nbr) % T: number of Time periods (options_.nobs) % r: number of strucural shocks (M_.exo_nbr) % n: number of observables (length(options_.varobs)) % K: maximum forecast horizon (max(options_.nk)) -% +% % First all smoothed variables are saved without trend and constant. % Then trend and constant are added for the observed variables. % @@ -113,7 +113,7 @@ trend_constant_observables=constant_part+Trend; yf = atT(bayestopt_.mf,:)+trend_constant_observables; if options_.nk > 0 - %filtered variable E_t(y_t+k) requires to shift trend by k periods + %filtered variable E_t(y_t+k) requires to shift trend by k periods filter_steps_required=union(1,options_.filter_step_ahead); % 1 is required for standard filtered variables for filter_iter=1:length(filter_steps_required) filter_step=filter_steps_required(filter_iter); @@ -167,13 +167,13 @@ for i_endo_in_bayestopt_smoother_varlist=bayestopt_.smoother_saved_var_list' end oo_.UpdatedVariables.(deblank(M_.endo_names(i_endo_declaration_order,:)))=updated_variables(i_endo_in_dr,:)'+constant_current_variable; end - + %% Add trend and constant for observed variables for pos_iter=1:length(bayestopt_.mf) oo_.Smoother.Constant.(deblank(M_.endo_names(bayestopt_.mfys(pos_iter),:)))=constant_part(pos_iter,:)'; if ismember(bayestopt_.mf(pos_iter),bayestopt_.smoother_var_list(bayestopt_.smoother_saved_var_list)) - oo_.SmoothedVariables.(deblank(M_.endo_names(bayestopt_.mfys(pos_iter),:)))=yf(pos_iter,:)'; - if ~isempty(options_.nk) && options_.nk > 0 + oo_.SmoothedVariables.(deblank(M_.endo_names(bayestopt_.mfys(pos_iter),:)))=yf(pos_iter,:)'; + if ~isempty(options_.nk) && options_.nk > 0 %filtered variable E_t(y_t+1) requires to shift trend by 1 period oo_.FilteredVariables.(deblank(M_.endo_names(bayestopt_.mfys(pos_iter),:)))=... squeeze(aK(1,bayestopt_.mf(pos_iter),2:end-(options_.nk-1)))... @@ -182,7 +182,7 @@ for pos_iter=1:length(bayestopt_.mf) filter_step=options_.filter_step_ahead(filter_iter); oo_.FilteredVariablesKStepAhead(filter_iter,find(i_endo_in_dr_matrices==bayestopt_.mf(pos_iter)),1+filter_step:end-(max(options_.filter_step_ahead)-filter_step)) = ... squeeze(aK(filter_step,bayestopt_.mf(pos_iter),1+filter_step:end-(max(options_.filter_step_ahead)-filter_step)))... - +trend_constant_observables_filtered.(['filter_ahead_' num2str(filter_step)])(pos_iter,:)'; + +trend_constant_observables_filtered.(['filter_ahead_' num2str(filter_step)])(pos_iter,:)'; end end %updated variables are E_t(y_t) so no trend shift is required @@ -229,8 +229,8 @@ end %% Smoothed measurement errors if ~isequal(M_.H,0) -% measurement_error_indices=find(diag(M_.H)~=0); + % measurement_error_indices=find(diag(M_.H)~=0); for meas_error_iter=1:length(options_.varobs) - oo_.SmoothedMeasurementErrors.(options_.varobs{meas_error_iter})= measurement_error(meas_error_iter,:)'; + oo_.SmoothedMeasurementErrors.(options_.varobs{meas_error_iter})= measurement_error(meas_error_iter,:)'; end end diff --git a/matlab/subset.m b/matlab/subset.m index e174af2963..5cae1ee35e 100644 --- a/matlab/subset.m +++ b/matlab/subset.m @@ -54,8 +54,8 @@ else 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') ) + 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']) @@ -63,10 +63,10 @@ else error end tt = [tt;tmp]; - elseif isempty(tmp) && nvn + elseif isempty(tmp) && nvn tmp = strmatch(ExcludedParamNames{i},options_.varobs); if ~isempty(tmp) && ( strcmpi(info,'All') || strcmpi(info,'MeasurementErrors') || ... - strcmpi(info,'MeasurementErrorsWithoutCorrelations') ) + 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 diff --git a/matlab/symmetric_matrix_index.m b/matlab/symmetric_matrix_index.m index 73cf4a50b0..b084fc8925 100644 --- a/matlab/symmetric_matrix_index.m +++ b/matlab/symmetric_matrix_index.m @@ -1,9 +1,9 @@ function k = symmetric_matrix_index(i,j,n) % function k = symmetric_matrix_index(i,j,n) -% Returns index number of variable combination (i,j) in vech(A) where A is +% Returns index number of variable combination (i,j) in vech(A) where A is % an symmetric n by n matrix and vech creates row vector by stacking rows % of A on and above the diagonal -% +% % Inputs: % i [scalar] index of first variable % j [scalar] index of second variable diff --git a/matlab/test_for_deep_parameters_calibration.m b/matlab/test_for_deep_parameters_calibration.m index 98d9dcc8b2..518191032a 100644 --- a/matlab/test_for_deep_parameters_calibration.m +++ b/matlab/test_for_deep_parameters_calibration.m @@ -3,13 +3,13 @@ function info=test_for_deep_parameters_calibration(M_) % % INPUTS % M_ [structure] Description of the (simulated or estimated) model. -% +% % OUTPUTS -% info [scalar] 0 if no problems detected, 1 otherwise -% +% info [scalar] 0 if no problems detected, 1 otherwise +% % ALGORITHM % none -% +% % SPECIAL REQUIREMENTS % none @@ -28,7 +28,7 @@ function info=test_for_deep_parameters_calibration(M_) % 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/>. +% along with Dynare. If not, see <http://www.gnu.org/licenses/>. plist = list_of_parameters_calibrated_as_NaN(M_); if ~isempty(plist) info=1; diff --git a/matlab/th_autocovariances.m b/matlab/th_autocovariances.m index 07d2443a5d..78e6fff4bb 100644 --- a/matlab/th_autocovariances.m +++ b/matlab/th_autocovariances.m @@ -1,28 +1,28 @@ function [Gamma_y,stationary_vars] = th_autocovariances(dr,ivar,M_,options_,nodecomposition) -% Computes the theoretical auto-covariances, Gamma_y, for an AR(p) process +% 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. % Theoretical HP-filtering and band-pass filtering 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. -% +% 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, +% 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+1} [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. +% 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 (as a subset of 1:length(ivar)) % % SPECIAL REQUIREMENTS -% +% % Algorithms % The means at order=2 are based on the pruned state space as % in Kim, Kim, Schaumburg, Sims (2008): Calculating and using second-order accurate @@ -34,14 +34,14 @@ function [Gamma_y,stationary_vars] = th_autocovariances(dr,ivar,M_,options_,node % Taking expectations on both sides requires to compute E(x^2)=Var(x), which % can be obtained up to second order from the first order solution % \[ -% \hat x_t = g_x \hat x_{t - 1} + g_u u_t +% \hat x_t = g_x \hat x_{t - 1} + g_u u_t % \] -% by solving the corresponding Lyapunov equation. +% by solving the corresponding Lyapunov equation. % Given Var(x), the above equation can be solved for E(x_t) as % \[ % E(x_t) = (I - {g_x}\right)^{- 1} 0.5\left( g_{\sigma\sigma} \sigma^2 + g_{xx} Var(\hat x_t) + g_{uu} Var(u_t) \right) % \] -% +% % Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. @@ -144,7 +144,7 @@ if options_.order == 2 || options_.hp_filter == 0 aa = ghx(iky,:); bb = ghu(iky,:); if options_.order == 2 % mean correction for 2nd order - if ~isempty(ikx) + if ~isempty(ikx) 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} = NaN*ones(nvar, 1); @@ -164,7 +164,7 @@ if options_.hp_filter == 0 && ~options_.bandpass.indicator Gamma_y{1} = v; % autocorrelations if nar > 0 - vxy = (A*vx*aa'+ghu1*M_.Sigma_e*bb'); + vxy = (A*vx*aa'+ghu1*M_.Sigma_e*bb'); sy = sqrt(diag(Gamma_y{1})); sy = sy(stationary_vars); sy = sy *sy'; @@ -209,7 +209,7 @@ if options_.hp_filter == 0 && ~options_.bandpass.indicator end else% ==> Theoretical filters. % By construction, all variables are stationary when HP filtered - iky = inv_order_var(ivar); + iky = inv_order_var(ivar); stationary_vars = (1:length(ivar))'; aa = ghx(iky,:); %R in Uhlig (2001) bb = ghu(iky,:); %S in Uhlig (2001) @@ -227,7 +227,7 @@ else% ==> Theoretical filters. filter_gain(freqs>=2*pi/lowest_periodicity & freqs<=2*pi/highest_periodicity)=1; filter_gain(freqs<=-2*pi/lowest_periodicity+2*pi & freqs>=-2*pi/highest_periodicity+2*pi)=1; else - filter_gain = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2); %HP transfer function + filter_gain = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2); %HP transfer function end mathp_col = NaN(ngrid,length(ivar)^2); IA = eye(size(A,1)); @@ -237,8 +237,8 @@ else% ==> Theoretical filters. f_hp = zeros(length(ivar),length(ivar)); else f_omega =(1/(2*pi))*([(IA-A*tneg(ig))\ghu1;IE]... - *M_.Sigma_e*[ghu1'/(IA-A'*tpos(ig)) IE]); % spectral density of state variables; top formula Uhlig (2001), p. 20 with N=0 - g_omega = [aa*tneg(ig) bb]*f_omega*[aa'*tpos(ig); bb']; % spectral density of selected variables; middle formula Uhlig (2001), p. 20; only middle block, i.e. y_t' + *M_.Sigma_e*[ghu1'/(IA-A'*tpos(ig)) IE]); % spectral density of state variables; top formula Uhlig (2001), p. 20 with N=0 + g_omega = [aa*tneg(ig) bb]*f_omega*[aa'*tpos(ig); bb']; % spectral density of selected variables; middle formula Uhlig (2001), p. 20; only middle block, i.e. y_t' f_hp = filter_gain(ig)^2*g_omega; % spectral density of selected filtered series; top formula Uhlig (2001), p. 21; end mathp_col(ig,:) = (f_hp(:))'; % store as matrix row for ifft @@ -274,7 +274,7 @@ else% ==> Theoretical filters. else f_omega =(1/(2*pi))*( [(IA-A*tneg(ig))\b1;IE]... *SS*[b1'/(IA-A'*tpos(ig)) IE]); % spectral density of state variables; top formula Uhlig (2001), p. 20 with N=0 - g_omega = [aa*tneg(ig) b2]*f_omega*[aa'*tpos(ig); b2']; % spectral density of selected variables; middle formula Uhlig (2001), p. 20; only middle block, i.e. y_t' + g_omega = [aa*tneg(ig) b2]*f_omega*[aa'*tpos(ig); b2']; % spectral density of selected variables; middle formula Uhlig (2001), p. 20; only middle block, i.e. y_t' f_hp = filter_gain(ig)^2*g_omega; % spectral density of selected filtered series; top formula Uhlig (2001), p. 21; end mathp_col(ig,:) = (f_hp(:))'; % store as matrix row for ifft @@ -290,7 +290,7 @@ else% ==> Theoretical filters. else f_omega =(1/(2*pi))*( [(IA-A*tneg(ig))\b1;IE]... *SSi*[b1'/(IA-A'*tpos(ig)) IE]); % spectral density of state variables; top formula Uhlig (2001), p. 20 with N=0 - g_omega = [aa*tneg(ig) b2]*f_omega*[aa'*tpos(ig); b2']; % spectral density of selected variables; middle formula Uhlig (2001), p. 20; only middle block, i.e. y_t' + g_omega = [aa*tneg(ig) b2]*f_omega*[aa'*tpos(ig); b2']; % spectral density of selected variables; middle formula Uhlig (2001), p. 20; only middle block, i.e. y_t' f_hp = filter_gain(ig)^2*g_omega; % spectral density of selected filtered series; top formula Uhlig (2001), p. 21; end mathp_col(ig,:) = (f_hp(:))'; % store as matrix row for ifft diff --git a/matlab/thet2tau.m b/matlab/thet2tau.m index 65cc63ce1b..965934e3d9 100644 --- a/matlab/thet2tau.m +++ b/matlab/thet2tau.m @@ -51,7 +51,7 @@ elseif flagmoments==-1 [I,J]=find(M_.lead_lag_incidence'); yy0=oo_.dr.ys(I); [residual, g1] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', ... - M_.params, oo_.dr.ys, 1); + M_.params, oo_.dr.ys, 1); tau=[oo_.dr.ys(oo_.dr.order_var); g1(:)]; else diff --git a/matlab/trace_plot.m b/matlab/trace_plot.m index c07e4707b5..9fbf383581 100644 --- a/matlab/trace_plot.m +++ b/matlab/trace_plot.m @@ -135,7 +135,7 @@ dyn_saveas(hh,[M_.fname, filesep, 'graphs', filesep, 'TracePlot_' plot_name],opt if options_.TeX fid=fopen([M_.fname,'/graphs/',M_.fname,'_TracePlot_' plot_name,'.tex'],'w+'); - + if strcmpi(type,'DeepParameter') tex_names=M_.param_names_tex; base_names=M_.param_names; @@ -146,7 +146,7 @@ if options_.TeX tex_names=M_.endo_names_tex; base_names=M_.endo_names; end - + if strcmpi(type,'PosteriorDensity') FigureName = ['Trace plot for ' TYPE name1]; else @@ -159,7 +159,7 @@ if options_.TeX if options_.mh_nblck>1 FigureName = [ FigureName , ' (block number ' int2str(blck) ').']; end - + fprintf(fid,'%-s\n','\begin{figure}[H]'); fprintf(fid,'%-s\n','\centering'); fprintf(fid,'%-s\n',[' \includegraphics[width=0.8\textwidth]{',[M_.fname, '/graphs/TracePlot_' plot_name],'}\\']); @@ -167,4 +167,3 @@ if options_.TeX fprintf(fid,'%-s\n','\end{figure}'); fclose(fid); end - diff --git a/matlab/trust_region.m b/matlab/trust_region.m index 5e21d0fbb5..beb0360a3d 100644 --- a/matlab/trust_region.m +++ b/matlab/trust_region.m @@ -229,4 +229,3 @@ if (xn > delta) x = alpha * x + ((1-alpha) * min (snm, delta)) * s; end end - diff --git a/matlab/uniform_specification.m b/matlab/uniform_specification.m index 5af782162f..cc35fb3308 100644 --- a/matlab/uniform_specification.m +++ b/matlab/uniform_specification.m @@ -3,16 +3,16 @@ function [m,s,p6,p7] = uniform_specification(m,s,p3,p4) % % INPUTS % m: mean -% s: standard deviation -% p3: lower bound -% p4: upper bound +% s: standard deviation +% p3: lower bound +% p4: upper bound % OUTPUTS % m: mean -% s: standard deviation -% p1: lower bound -% p2: upper bound -% +% s: standard deviation +% p1: lower bound +% p2: upper bound +% % SPECIAL REQUIREMENTS % none diff --git a/matlab/update_last_mh_history_file.m b/matlab/update_last_mh_history_file.m index d0c4e9ca54..643b900ce0 100644 --- a/matlab/update_last_mh_history_file.m +++ b/matlab/update_last_mh_history_file.m @@ -5,7 +5,7 @@ function update_last_mh_history_file(MetropolisFolder, ModelName, record) % MetropolisFolder [char] Name of the metropolis subfolder % ModelName [char] Name of the mod-file % record [structure] structure storing the MH history -% Outputs: none +% Outputs: none % Copyright (C) 2013-2015 Dynare Team % diff --git a/matlab/user_has_matlab_license.m b/matlab/user_has_matlab_license.m index 2857ae247d..c8c681283c 100644 --- a/matlab/user_has_matlab_license.m +++ b/matlab/user_has_matlab_license.m @@ -38,14 +38,14 @@ if ~hasLicense end switch toolbox %use function unique to toolbox - case 'statistics_toolbox' - n = 'gppdf'; - case 'optimization_toolbox' - n='fsolve'; - case 'GADS_Toolbox' - n='simulannealbnd'; - case 'control_toolbox' - n='dlyap'; + case 'statistics_toolbox' + n = 'gppdf'; + case 'optimization_toolbox' + n='fsolve'; + case 'GADS_Toolbox' + n='simulannealbnd'; + case 'control_toolbox' + n='dlyap'; end hasInstallation=check_toolbox_installation(n); if ~hasInstallation @@ -64,7 +64,7 @@ else a=ver(ver_string); if isempty(a) hasInstallation=0; - else + else hasInstallation=1; end end diff --git a/matlab/utilities/dataset/descriptive_statistics.m b/matlab/utilities/dataset/descriptive_statistics.m index d2b52292d2..0c5b4bf9ad 100644 --- a/matlab/utilities/dataset/descriptive_statistics.m +++ b/matlab/utilities/dataset/descriptive_statistics.m @@ -3,7 +3,7 @@ function dataset_ = descriptive_statistics(dataset_,statistic,varagin) %@info: %! @deftypefn {Function File} {@var{dataset_} =} descriptive_statistics(@var{dataset_},@var{statistic}) -%! @deftypefn {Function File} {@var{dataset_} =} descriptive_statistics(@var{dataset_},@var{statistic},nlags) +%! @deftypefn {Function File} {@var{dataset_} =} descriptive_statistics(@var{dataset_},@var{statistic},nlags) %! @anchor{compute_corr} %! This function computes various descriptive statistics on the sample (possibly with missing observations). %! @@ -14,15 +14,15 @@ function dataset_ = descriptive_statistics(dataset_,statistic,varagin) %! @item statistic %! String. The name of the statistic to be computed. Admissible values are: %! @table @var -%! @item 'stdv' +%! @item 'stdv' %! Computes the standard deviation of each observed variable. -%! @item 'cova' -%! Computes the covariance matrix of the sample. +%! @item 'cova' +%! Computes the covariance matrix of the sample. %! @item 'corr' %! Computes the correlation matrix of the sample. %! @item 'acov' %! Computes the (multivariate) auto-covariance function of the sample. In this case a third argument (@code{nlags}) defining the -%! maximum number of lags is mandatory. +%! maximum number of lags is mandatory. %! @end table %! @item nlags %! Integer scalar. The maximum number of lags when computing the autocovariance function. @@ -33,20 +33,20 @@ function dataset_ = descriptive_statistics(dataset_,statistic,varagin) %! @item dataset_ %! Dynare structure describing the dataset, built by @ref{initialize_dataset} %! @end table -%! -%! @strong{This function is called by:} +%! +%! @strong{This function is called by:} %! none. -%! +%! %! @strong{This function calls:} %! @ref{compute_stdv}, @ref{compute_cova}, @ref{compute_corr}, @ref{compute_acov}. -%! +%! %! @strong{Remark 1.} On exit, a new field containing the computed statistics is appended to the structure. -%! +%! %! @end deftypefn %@eod: % Copyright (C) 2011-2012 Dynare Team -% +% % This file is part of Dynare. % % Dynare is free software: you can redistribute it and/or modify diff --git a/matlab/utilities/dataset/initialize_dataset.m b/matlab/utilities/dataset/initialize_dataset.m index 550d3dc950..781e1b2949 100644 --- a/matlab/utilities/dataset/initialize_dataset.m +++ b/matlab/utilities/dataset/initialize_dataset.m @@ -55,7 +55,7 @@ if dataset_.info.nvobs-size(rawdata,2) end if size(rawdata,1)~=dataset_.info.ntobs - fprintf('Restricting the sample to observations %d to %d. Using in total %d observations. \n',first,first+dataset_.info.ntobs-1,dataset_.info.ntobs) + fprintf('Restricting the sample to observations %d to %d. Using in total %d observations. \n',first,first+dataset_.info.ntobs-1,dataset_.info.ntobs) end rawdata = rawdata(first:(first+dataset_.info.ntobs-1),:); diff --git a/matlab/utilities/dataset/lagged.m b/matlab/utilities/dataset/lagged.m index fa84577e20..4f17d7eeb3 100644 --- a/matlab/utilities/dataset/lagged.m +++ b/matlab/utilities/dataset/lagged.m @@ -1,34 +1,34 @@ -function xlag = lagged(x, n) -% xlag = lagged(x, n); -% applies n-lags backward shift operator to x -% -% INPUTS -% x = time series -% n = number of backward shifts [DEFAULT=1] -% -% OUTPUT -% xlag = backward shifted series - -% Copyright (C) 2017 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==1 - n=1; -end - -x=x(:); +function xlag = lagged(x, n) +% xlag = lagged(x, n); +% applies n-lags backward shift operator to x +% +% INPUTS +% x = time series +% n = number of backward shifts [DEFAULT=1] +% +% OUTPUT +% xlag = backward shifted series + +% Copyright (C) 2017 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==1 + n=1; +end + +x=x(:); xlag=[NaN(n,1); x(1:end-n)]; \ No newline at end of file diff --git a/matlab/utilities/dataset/makedataset.m b/matlab/utilities/dataset/makedataset.m index 6ac4035c83..e949b5e5bf 100644 --- a/matlab/utilities/dataset/makedataset.m +++ b/matlab/utilities/dataset/makedataset.m @@ -37,7 +37,7 @@ if isempty(DynareOptions.datafile) && isempty(DynareOptions.dataset.file) && ise if gsa_flag DynareDataset = dseries(); DatasetInfo = struct('missing', struct('state', 0, 'aindex', [], 'vindex', [], 'number_of_observations', NaN, 'no_more_missing_observations', NaN), ... - 'descriptive', struct('mean', [], 'covariance', [], 'correlation', [], 'autocovariance', [])); + 'descriptive', struct('mean', [], 'covariance', [], 'correlation', [], 'autocovariance', [])); newdatainterface=0; return else @@ -107,7 +107,7 @@ if ~isempty(datafile) DynareDataset = load_m_file_data_legacy(datafile, DynareOptions.varobs); elseif strcmp(datafile(end-3:end),'.mat') % Load a mat file with the old interface. - DynareDataset = load_mat_file_data_legacy(datafile, DynareOptions.varobs); + DynareDataset = load_mat_file_data_legacy(datafile, DynareOptions.varobs); end end else diff --git a/matlab/utilities/dataset/nanvariance.m b/matlab/utilities/dataset/nanvariance.m index d4894e8e92..85311dab07 100644 --- a/matlab/utilities/dataset/nanvariance.m +++ b/matlab/utilities/dataset/nanvariance.m @@ -1,4 +1,4 @@ -function variances = nanvariance(data) +function variances = nanvariance(data) % Compute the standard deviation for each observed variable (possibly with missing observations). %@info: @@ -17,21 +17,21 @@ function variances = nanvariance(data) %! @item variances %! A N*1 vector of real numbers %! @end table -%! -%! @strong{This function is called by:} +%! +%! @strong{This function is called by:} %! @ref{descriptive_statistics}. -%! +%! %! @strong{This function calls:} %! @ref{ndim}, @ref{demean}, @ref{nandemean}. -%! -%! @strong{Remark 1.} On exit, a new field is appended to the structure: @code{dataset_.descriptive.stdv} is a +%! +%! @strong{Remark 1.} On exit, a new field is appended to the structure: @code{dataset_.descriptive.stdv} is a %! @tex{n\times 1} vector (where @tex{n} is the number of observed variables as defined by @code{dataset_.info.nvobs}). -%! +%! %! @end deftypefn %@eod: % Copyright (C) 2011-2014 Dynare Team -% +% % This file is part of Dynare. % % Dynare is free software: you can redistribute it and/or modify diff --git a/matlab/utilities/dataset/quarterly2annual.m b/matlab/utilities/dataset/quarterly2annual.m index c74111bf91..6342c4605e 100644 --- a/matlab/utilities/dataset/quarterly2annual.m +++ b/matlab/utilities/dataset/quarterly2annual.m @@ -1,136 +1,135 @@ -function [ya, yass, gya, gyass] = quarterly2annual(y,yss,GYTREND0,type,islog,aux) -% function [ya, yass, gya, gyass] = quarterly2annual(y,yss,GYTREND0,type,islog,aux) -% transforms quarterly (log-)level time series to annual level and growth rate -% it accounts for stock/flow/deflator series. -% -% INPUTS -% y quarterly time series -% yss steady state of y -% GYTREND0 growth rate of y -% type 1 sum (default) -% 2 average -% 3 last period (Q4) -% 4 geometric average -% 5 annual price as quantity weighted average -% 6 annual quantity from average price -% 7 annual nominal from Q real and deflator -% islog 0 level (default) -% 1 log-level -% 2 growth rate Q frequency -% aux optional input used when type>4 -% -% -% OUTPUTS -% ya annual (log-)level -% yass annual steadystate (log-)level -% gya annual growth rate -% gyass annual growth rate steadystate - -% Copyright (C) 2017 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('[ya, yass, gya, gyass] = quarterly2annual(y,yss,GYTREND0,type,islog);') - return -end - -if nargin<4 || isempty(type) - type=1; -end -if nargin<5 || isempty(islog) - islog=0; -end -if isstruct(aux) - yaux=aux.y; - yauxss=aux.yss; - islogaux=aux.islog; - GYTREND0aux=aux.GYTREND0; - typeaux=aux.type; - if islogaux - yaux=exp(yaux+yauxss); - yauxss=exp(yauxss); - yaux=yaux-yauxss; - end -elseif type > 4 - error('TYPE>4 requires auxiliary variable!') -end -if islog == 2 - % construct loglevel out of growth rate - y = cumsum(y); - yss=0; - islog=1; -end -if islog == 1 - y=exp(y+yss); - yss=exp(yss); - y=y-yss; -end -switch type - case 1 - yass = yss*(exp(-GYTREND0*3)+exp(-GYTREND0*2)+exp(-GYTREND0)+1); - tmp = lagged(y,3)*exp(-GYTREND0*3)+lagged(y,2)*exp(-GYTREND0*2)+lagged(y,1)*exp(-GYTREND0)+y; % annualized level - ya = tmp(4:4:end); - case 2 - yass = yss*(exp(-GYTREND0*3)+exp(-GYTREND0*2)+exp(-GYTREND0)+1)/4; - tmp = (lagged(y,3)*exp(-GYTREND0*3)+lagged(y,2)*exp(-GYTREND0*2)+lagged(y,1)*exp(-GYTREND0)+y)/4; % annualized level - ya = tmp(4:4:end); - case 3 - yass=yss; - tmp = y; - ya = tmp(4:4:end); - case 4 - yass = yss*(exp(-GYTREND0*3/2)); - tmp = (lagged(y+yss,3)*exp(-GYTREND0*3).*lagged(y+yss,2)*exp(-GYTREND0*2).*lagged(y+yss,1)*exp(-GYTREND0).*(y+yss)).^(1/4); % annualized level - tmp = tmp - yass; - ya = tmp(4:4:end); - case 5 - % nominal series - yn = (y+yss).*(yaux+yauxss) - yss.*yauxss; - [yna, ynass] = quarterly2annual(yn,yss.*yauxss,GYTREND0+GYTREND0aux,typeaux,0,0); - % real series - [yra, yrass] = quarterly2annual(yaux,yauxss,GYTREND0aux,typeaux,0,0); - % deflator - yass = ynass/yrass; - ya = (yna+ynass)./(yr+yrass)-yass; - case 6 - % nominal series - yn = (y+yss).*(yaux+yauxss) - yss.*yauxss; - [yna, ynass] = quarterly2annual(yn,yss.*yauxss,GYTREND0+GYTREND0aux,typeaux,0,0); - % deflator - [pa, pass] = quarterly2annual(yaux,yauxss,GYTREND0aux,2,0,0); - % real series - yass = ynass/pass; - ya = (yna+ynass)./(pa+pass)-yass; - case 7 - % nominal series - yn = (y+yss).*(yaux+yauxss) - yss.*yauxss; - [ya, yass] = quarterly2annual(yn,yss.*yauxss,GYTREND0+GYTREND0aux,typeaux,0,0); - GYTREND0=GYTREND0+GYTREND0aux; - otherwise - error('Wrong type input') -end - -% annual growth rate -gyass = GYTREND0*4; -gya = (ya+yass)./(lagged(ya,1)+yass).*exp(4*GYTREND0)-1-gyass; - -if islog - ya=log(ya+yass); - yass=log(yass); - ya=ya-yass; -end - +function [ya, yass, gya, gyass] = quarterly2annual(y,yss,GYTREND0,type,islog,aux) +% function [ya, yass, gya, gyass] = quarterly2annual(y,yss,GYTREND0,type,islog,aux) +% transforms quarterly (log-)level time series to annual level and growth rate +% it accounts for stock/flow/deflator series. +% +% INPUTS +% y quarterly time series +% yss steady state of y +% GYTREND0 growth rate of y +% type 1 sum (default) +% 2 average +% 3 last period (Q4) +% 4 geometric average +% 5 annual price as quantity weighted average +% 6 annual quantity from average price +% 7 annual nominal from Q real and deflator +% islog 0 level (default) +% 1 log-level +% 2 growth rate Q frequency +% aux optional input used when type>4 +% +% +% OUTPUTS +% ya annual (log-)level +% yass annual steadystate (log-)level +% gya annual growth rate +% gyass annual growth rate steadystate + +% Copyright (C) 2017 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('[ya, yass, gya, gyass] = quarterly2annual(y,yss,GYTREND0,type,islog);') + return +end + +if nargin<4 || isempty(type) + type=1; +end +if nargin<5 || isempty(islog) + islog=0; +end +if isstruct(aux) + yaux=aux.y; + yauxss=aux.yss; + islogaux=aux.islog; + GYTREND0aux=aux.GYTREND0; + typeaux=aux.type; + if islogaux + yaux=exp(yaux+yauxss); + yauxss=exp(yauxss); + yaux=yaux-yauxss; + end +elseif type > 4 + error('TYPE>4 requires auxiliary variable!') +end +if islog == 2 + % construct loglevel out of growth rate + y = cumsum(y); + yss=0; + islog=1; +end +if islog == 1 + y=exp(y+yss); + yss=exp(yss); + y=y-yss; +end +switch type + case 1 + yass = yss*(exp(-GYTREND0*3)+exp(-GYTREND0*2)+exp(-GYTREND0)+1); + tmp = lagged(y,3)*exp(-GYTREND0*3)+lagged(y,2)*exp(-GYTREND0*2)+lagged(y,1)*exp(-GYTREND0)+y; % annualized level + ya = tmp(4:4:end); + case 2 + yass = yss*(exp(-GYTREND0*3)+exp(-GYTREND0*2)+exp(-GYTREND0)+1)/4; + tmp = (lagged(y,3)*exp(-GYTREND0*3)+lagged(y,2)*exp(-GYTREND0*2)+lagged(y,1)*exp(-GYTREND0)+y)/4; % annualized level + ya = tmp(4:4:end); + case 3 + yass=yss; + tmp = y; + ya = tmp(4:4:end); + case 4 + yass = yss*(exp(-GYTREND0*3/2)); + tmp = (lagged(y+yss,3)*exp(-GYTREND0*3).*lagged(y+yss,2)*exp(-GYTREND0*2).*lagged(y+yss,1)*exp(-GYTREND0).*(y+yss)).^(1/4); % annualized level + tmp = tmp - yass; + ya = tmp(4:4:end); + case 5 + % nominal series + yn = (y+yss).*(yaux+yauxss) - yss.*yauxss; + [yna, ynass] = quarterly2annual(yn,yss.*yauxss,GYTREND0+GYTREND0aux,typeaux,0,0); + % real series + [yra, yrass] = quarterly2annual(yaux,yauxss,GYTREND0aux,typeaux,0,0); + % deflator + yass = ynass/yrass; + ya = (yna+ynass)./(yr+yrass)-yass; + case 6 + % nominal series + yn = (y+yss).*(yaux+yauxss) - yss.*yauxss; + [yna, ynass] = quarterly2annual(yn,yss.*yauxss,GYTREND0+GYTREND0aux,typeaux,0,0); + % deflator + [pa, pass] = quarterly2annual(yaux,yauxss,GYTREND0aux,2,0,0); + % real series + yass = ynass/pass; + ya = (yna+ynass)./(pa+pass)-yass; + case 7 + % nominal series + yn = (y+yss).*(yaux+yauxss) - yss.*yauxss; + [ya, yass] = quarterly2annual(yn,yss.*yauxss,GYTREND0+GYTREND0aux,typeaux,0,0); + GYTREND0=GYTREND0+GYTREND0aux; + otherwise + error('Wrong type input') +end + +% annual growth rate +gyass = GYTREND0*4; +gya = (ya+yass)./(lagged(ya,1)+yass).*exp(4*GYTREND0)-1-gyass; + +if islog + ya=log(ya+yass); + yass=log(yass); + ya=ya-yass; +end diff --git a/matlab/utilities/doc/get_internal_doc_block.m b/matlab/utilities/doc/get_internal_doc_block.m index 718b2a28d9..f0d8ce696f 100644 --- a/matlab/utilities/doc/get_internal_doc_block.m +++ b/matlab/utilities/doc/get_internal_doc_block.m @@ -1,8 +1,8 @@ function block = get_internal_doc_block(fname,fpath) % Extract doc sections from matlab's routine. - + % Copyright (C) 2011-2012 Dynare Team -% +% % This file is part of Dynare. % % Dynare is free software: you can redistribute it and/or modify @@ -22,7 +22,7 @@ function block = get_internal_doc_block(fname,fpath) % Default output block = []; - + % Open the matlab file. mid = fopen([fpath '/' fname '.m'],'r'); @@ -43,14 +43,14 @@ if ( isempty(b1) && isempty(b2) && isempty(b) ) return else if ( (~isempty(b1) && isempty(b2) && isempty(b)) || ... - (isempty(b1) && ~isempty(b2) && isempty(b)) || ... - (isempty(b1) && isempty(b2) && ~isempty(b)) || ... - (isempty(b1) && ~isempty(b2) && ~isempty(b)) || ... - (~isempty(b1) && isempty(b2) && ~isempty(b)) || ... - (~isempty(b1) && ~isempty(b2) && isempty(b)) ) + (isempty(b1) && ~isempty(b2) && isempty(b)) || ... + (isempty(b1) && isempty(b2) && ~isempty(b)) || ... + (isempty(b1) && ~isempty(b2) && ~isempty(b)) || ... + (~isempty(b1) && isempty(b2) && ~isempty(b)) || ... + (~isempty(b1) && ~isempty(b2) && isempty(b)) ) error('get_internal_doc_block:: There is a problem with the internal block definition!') end - if ( b2~=b(end) || b1~=b(1) || any(b-transpose(b1:1:b2)) ) + if ( b2~=b(end) || b1~=b(1) || any(b-transpose(b1:1:b2)) ) error('get_internal_doc_block:: There is a problem with the internal block definition!') end end diff --git a/matlab/utilities/general/compare_vectors.m b/matlab/utilities/general/compare_vectors.m index aec07a2a54..3264d88414 100644 --- a/matlab/utilities/general/compare_vectors.m +++ b/matlab/utilities/general/compare_vectors.m @@ -1,5 +1,5 @@ function C = compare_vectors(f, A, B) % --*-- Unitary tests --*-- - + % Performs lexicographical comparison of vectors. % % INPUTS @@ -7,12 +7,12 @@ function C = compare_vectors(f, A, B) % --*-- Unitary tests --*-- % o A vector of real numbers. % o B vector of real numbers. % -% OUTPUTS +% OUTPUTS % o C integer scalar, 1 or 0. % -% REMARKS +% REMARKS % o It is assumed that vectors A and B have the same number of elements. - + % Copyright (C) 2013-2014 Dynare Team % % This file is part of Dynare. diff --git a/matlab/utilities/general/delete_stale_file.m b/matlab/utilities/general/delete_stale_file.m index 8ac8b79963..cce629fe38 100644 --- a/matlab/utilities/general/delete_stale_file.m +++ b/matlab/utilities/general/delete_stale_file.m @@ -23,4 +23,3 @@ Files_info = dir(fname); if length(Files_info)>0 delete(fname) end - diff --git a/matlab/utilities/general/demean.m b/matlab/utilities/general/demean.m index 4bf53aaa62..fc7096e976 100644 --- a/matlab/utilities/general/demean.m +++ b/matlab/utilities/general/demean.m @@ -1,6 +1,6 @@ function c = demean(x) % Removes the mean of each column of a matrix. - + %@info: %! @deftypefn {Function File} {@var{c} =} demean (@var{x}) %! @anchor{demean} @@ -17,18 +17,18 @@ function c = demean(x) %! @item c %! Matlab matrix (T-by-N). The demeaned x matrix. %! @end table -%! -%! @strong{This function is called by:} +%! +%! @strong{This function is called by:} %! @ref{compute_cova}, @ref{compute_acov}, @ref{compute_std}. -%! -%! @strong{This function calls:} +%! +%! @strong{This function calls:} %! @ref{ndim}, -%! +%! %! @end deftypefn %@eod: % Copyright (C) 2011-2012 Dynare Team -% +% % This file is part of Dynare. % % Dynare is free software: you can redistribute it and/or modify @@ -45,7 +45,7 @@ function c = demean(x) % along with Dynare. If not, see <http://www.gnu.org/licenses/>. % Original author: stephane DOT adjemian AT univ DASH lemans DOT fr - + if ndim(x)==1 c = x-mean(x); elseif ndim(x)==2 diff --git a/matlab/utilities/general/disp_verbose.m b/matlab/utilities/general/disp_verbose.m index 09c09e4d7e..504c4403cb 100644 --- a/matlab/utilities/general/disp_verbose.m +++ b/matlab/utilities/general/disp_verbose.m @@ -1,7 +1,7 @@ function disp_verbose(input_string,Verbose) % function disp_verbose(input_string,Verbose) % Prints input_string unless Verbose=0 is requested -% +% % Copyright (C) 2015 Dynare Team % % This file is part of Dynare. diff --git a/matlab/utilities/general/dyn_mex.m b/matlab/utilities/general/dyn_mex.m index 7892ee9bed..9220bfdd55 100644 --- a/matlab/utilities/general/dyn_mex.m +++ b/matlab/utilities/general/dyn_mex.m @@ -1,20 +1,20 @@ function dyn_mex(win_compiler,basename,force) % Compile Dynare model dlls when model option use_dll is used -% if C file is fresher than mex file +% if C file is fresher than mex file % % INPUTS -% o win_compiler str compiler used under Windows (unused under Linux or OSX): +% o win_compiler str compiler used under Windows (unused under Linux or OSX): % 'msvc' (MS Visual C) % 'cygwin' % o basename str filenames base -% o force bool recompile if 1 -% -% OUTPUTS +% o force bool recompile if 1 +% +% OUTPUTS % none % - + % Copyright (C) 2015-2016 Dynare Team % % This file is part of Dynare. @@ -47,26 +47,26 @@ end if ~exist('OCTAVE_VERSION') % Some mex commands are enclosed in an eval(), because otherwise it will make Octave fail if ispc - if strcmp(win_compiler,'msvc') - % MATLAB/Windows + Microsoft Visual C++ - % Add /TP flag as fix for #1227 - eval(['mex -O LINKFLAGS="$LINKFLAGS /export:Dynamic" COMPFLAGS="/TP" ' basename '_dynamic.c ' basename '_dynamic_mex.c']) - eval(['mex -O LINKFLAGS="$LINKFLAGS /export:Static" COMPFLAGS="/TP" ' basename '_static.c ' basename '_static_mex.c']) - elseif strcmp(win_compiler,'mingw') - eval(['mex -O LINKFLAGS="$LINKFLAGS /export:Dynamic" ' basename '_dynamic.c ' basename '_dynamic_mex.c']) - eval(['mex -O LINKFLAGS="$LINKFLAGS /export:Static" ' basename '_static.c ' basename '_static_mex.c']) - elseif strcmp(win_compiler,'cygwin') %legacy support for Cygwin with mexopts.bat - % MATLAB/Windows + Cygwin g++ - eval(['mex -O PRELINK_CMDS1="echo EXPORTS > mex.def & echo ' ... - 'mexFunction >> mex.def & echo Dynamic >> mex.def" ' ... - basename '_dynamic.c ' basename '_dynamic_mex.c']) - eval(['mex -O PRELINK_CMDS1="echo EXPORTS > mex.def & echo ' ... - 'mexFunction >> mex.def & echo Dynamic >> mex.def" ' ... - basename '_static.c ' basename '_static_mex.c']) - else - error(['When using the USE_DLL option, you must give either ' ... - '''cygwin'', ''mingw'' or ''msvc'' option to the ''dynare'' command']) - end + if strcmp(win_compiler,'msvc') + % MATLAB/Windows + Microsoft Visual C++ + % Add /TP flag as fix for #1227 + eval(['mex -O LINKFLAGS="$LINKFLAGS /export:Dynamic" COMPFLAGS="/TP" ' basename '_dynamic.c ' basename '_dynamic_mex.c']) + eval(['mex -O LINKFLAGS="$LINKFLAGS /export:Static" COMPFLAGS="/TP" ' basename '_static.c ' basename '_static_mex.c']) + elseif strcmp(win_compiler,'mingw') + eval(['mex -O LINKFLAGS="$LINKFLAGS /export:Dynamic" ' basename '_dynamic.c ' basename '_dynamic_mex.c']) + eval(['mex -O LINKFLAGS="$LINKFLAGS /export:Static" ' basename '_static.c ' basename '_static_mex.c']) + elseif strcmp(win_compiler,'cygwin') %legacy support for Cygwin with mexopts.bat + % MATLAB/Windows + Cygwin g++ + eval(['mex -O PRELINK_CMDS1="echo EXPORTS > mex.def & echo ' ... + 'mexFunction >> mex.def & echo Dynamic >> mex.def" ' ... + basename '_dynamic.c ' basename '_dynamic_mex.c']) + eval(['mex -O PRELINK_CMDS1="echo EXPORTS > mex.def & echo ' ... + 'mexFunction >> mex.def & echo Dynamic >> mex.def" ' ... + basename '_static.c ' basename '_static_mex.c']) + else + error(['When using the USE_DLL option, you must give either ' ... + '''cygwin'', ''mingw'' or ''msvc'' option to the ''dynare'' command']) + end elseif isunix && ~ismac % MATLAB/Linux if matlab_ver_less_than('8.3') diff --git a/matlab/utilities/general/get_all_variables_but_lagged_leaded_exogenous.m b/matlab/utilities/general/get_all_variables_but_lagged_leaded_exogenous.m index 37697e723e..8a6fb56574 100644 --- a/matlab/utilities/general/get_all_variables_but_lagged_leaded_exogenous.m +++ b/matlab/utilities/general/get_all_variables_but_lagged_leaded_exogenous.m @@ -10,7 +10,7 @@ function k = get_all_variables_but_lagged_leaded_exogenous(M) % % Copyright (C) 2011-2016 Dynare Team -% +% % This file is part of Dynare. % % Dynare is free software: you can redistribute it and/or modify @@ -31,5 +31,5 @@ if isempty(M.aux_vars) else type = [M.aux_vars.type]; k = [1:M.orig_endo_nbr, M.orig_endo_nbr ... - + find((type ~= 2) & (type ~= 3))]; + + find((type ~= 2) & (type ~= 3))]; end \ No newline at end of file diff --git a/matlab/utilities/general/indices_lagged_leaded_exogenous_variables.m b/matlab/utilities/general/indices_lagged_leaded_exogenous_variables.m index 6b3f0b4161..5d2d6b4376 100644 --- a/matlab/utilities/general/indices_lagged_leaded_exogenous_variables.m +++ b/matlab/utilities/general/indices_lagged_leaded_exogenous_variables.m @@ -13,7 +13,7 @@ function [il,l1,ik,k1] = indices_lagged_leaded_exogenous_variables(k,M) % k1: value of non lagged or leaded variable in vector k % Copyright (C) 2011-2016 Dynare Team -% +% % This file is part of Dynare. % % Dynare is free software: you can redistribute it and/or modify diff --git a/matlab/utilities/general/isconst.m b/matlab/utilities/general/isconst.m index e869f7b5c2..aabff20ad8 100644 --- a/matlab/utilities/general/isconst.m +++ b/matlab/utilities/general/isconst.m @@ -1,6 +1,6 @@ function aa = isconst(y) % Returns 1 if vector y is constant, 0 otherwise. -% +% % INPUTS: % yy [double] n*1 vector. % diff --git a/matlab/utilities/general/isdiagonal.m b/matlab/utilities/general/isdiagonal.m index f76e437972..aa32c4c015 100644 --- a/matlab/utilities/general/isdiagonal.m +++ b/matlab/utilities/general/isdiagonal.m @@ -60,5 +60,3 @@ end %$ t = isdiagonal(A); %$ T = all(t); %@eof:5 - - diff --git a/matlab/utilities/general/isinestimationobjective.m b/matlab/utilities/general/isinestimationobjective.m index b6bbb5faf4..023e4cb14e 100644 --- a/matlab/utilities/general/isinestimationobjective.m +++ b/matlab/utilities/general/isinestimationobjective.m @@ -25,8 +25,8 @@ tmp = struct2cell(dbstack); list_of_previously_called_routines = transpose(tmp(2,:)); if ~isempty(strmatch('dsge_likelihood', list_of_previously_called_routines, 'exact')) || ... - ~isempty(strmatch('dsge_var_likelihood', list_of_previously_called_routines, 'exact')) || ... - ~isempty(strmatch('non_linear_dsge_likelihood', list_of_previously_called_routines, 'exact')) || ... - ~isempty(strmatch('simulated_moments_estimation', list_of_previously_called_routines, 'exact')) + ~isempty(strmatch('dsge_var_likelihood', list_of_previously_called_routines, 'exact')) || ... + ~isempty(strmatch('non_linear_dsge_likelihood', list_of_previously_called_routines, 'exact')) || ... + ~isempty(strmatch('simulated_moments_estimation', list_of_previously_called_routines, 'exact')) b = true; end diff --git a/matlab/utilities/general/isint.m b/matlab/utilities/general/isint.m index 5201a4649e..5a0a94e0a7 100644 --- a/matlab/utilities/general/isint.m +++ b/matlab/utilities/general/isint.m @@ -1,18 +1,18 @@ function [b,c,d] = isint(a) % This function tests if the input argument is an integer. % -% INPUT +% INPUT % a [double] m*n matrix. % -% OUTPUT -% b [integer] m*n matrix of 0 and 1. b(i,j)=1 if a(i,j) is an integer. +% OUTPUT +% b [integer] m*n matrix of 0 and 1. b(i,j)=1 if a(i,j) is an integer. % c [integer] p*1 vector of indices pointing to the integer elements of a. % d [integer] q*1 vector of indices pointing to the non integer elements of a. -% +% % SPECIAL REQUIREMENTS % None. -% -% NOTES +% +% NOTES % p+q is equal to the product of m by n. % Copyright (C) 2009-2014 Dynare Team diff --git a/matlab/utilities/general/ispd.m b/matlab/utilities/general/ispd.m index e319a47a1f..7fed2d44c1 100644 --- a/matlab/utilities/general/ispd.m +++ b/matlab/utilities/general/ispd.m @@ -44,7 +44,7 @@ function [test, penalty] = ispd(A) if ~isquare(A) error(['ispd:: Input argument ' inputname(1) ' has to be a square matrix!']) end - + [cholA, info] = chol(A); test = ~info; diff --git a/matlab/utilities/general/log_variable.m b/matlab/utilities/general/log_variable.m index 74a6aa126d..1c6de682ae 100644 --- a/matlab/utilities/general/log_variable.m +++ b/matlab/utilities/general/log_variable.m @@ -13,7 +13,7 @@ function y = log_variable(ivar,x,M) % % Copyright (C) 2011-2016 Dynare Team -% +% % This file is part of Dynare. % % Dynare is free software: you can redistribute it and/or modify diff --git a/matlab/utilities/general/ndim.m b/matlab/utilities/general/ndim.m index 1c4d003bb8..8d55e48e8f 100644 --- a/matlab/utilities/general/ndim.m +++ b/matlab/utilities/general/ndim.m @@ -3,7 +3,7 @@ function n = ndim(x) %@info: %! @deftypefn {Function File} {@var{n} =} ndim (@var{x}) -%! @anchor{ndim} +%! @anchor{ndim} %! This function reports the number of non singleton dimensions of a matlab array. %! %! @strong{Inputs} @@ -17,18 +17,18 @@ function n = ndim(x) %! @item n %! Integer scalar. The number of non singleton dimensions of a matlab array. %! @end table -%! -%! @strong{This function is called by:} +%! +%! @strong{This function is called by:} %! @ref{demean}, @ref{nandemean}. -%! +%! %! @strong{This function calls:} %! none. -%! +%! %! @end deftypefn %@eod: % Copyright (C) 2011-2012 Dynare Team -% +% % This file is part of Dynare. % % Dynare is free software: you can redistribute it and/or modify diff --git a/matlab/utilities/general/remove_fractional_xticks.m b/matlab/utilities/general/remove_fractional_xticks.m index 19eab7a044..d2c70633ff 100644 --- a/matlab/utilities/general/remove_fractional_xticks.m +++ b/matlab/utilities/general/remove_fractional_xticks.m @@ -17,7 +17,7 @@ function remove_fractional_xticks % 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/>. +% along with Dynare. If not, see <http://www.gnu.org/licenses/>. xticks=get(gca,'xtick'); fractional_periods=find(rem(xticks,1)~=0); diff --git a/matlab/utilities/graphics/colorspace.m b/matlab/utilities/graphics/colorspace.m index a260914723..b70e2486dc 100644 --- a/matlab/utilities/graphics/colorspace.m +++ b/matlab/utilities/graphics/colorspace.m @@ -1,18 +1,18 @@ function varargout = colorspace(Conversion,varargin) %COLORSPACE Transform a color image between color representations. % B = COLORSPACE(S,A) transforms the color representation of image A -% where S is a string specifying the conversion. The input array A -% should be a real full double array of size Mx3 or MxNx3. The output B +% where S is a string specifying the conversion. The input array A +% should be a real full double array of size Mx3 or MxNx3. The output B % is the same size as A. % -% S tells the source and destination color spaces, S = 'dest<-src', or +% S tells the source and destination color spaces, S = 'dest<-src', or % alternatively, S = 'src->dest'. Supported color spaces are % % 'RGB' sRGB IEC 61966-2-1 % 'YCbCr' Luma + Chroma ("digitized" version of Y'PbPr) % 'JPEG-YCbCr' Luma + Chroma space used in JFIF JPEG % 'YDbDr' SECAM Y'DbDr Luma + Chroma -% 'YPbPr' Luma (ITU-R BT.601) + Chroma +% 'YPbPr' Luma (ITU-R BT.601) + Chroma % 'YUV' NTSC PAL Y'UV Luma + Chroma % 'YIQ' NTSC Y'IQ Luma + Chroma % 'HSV' or 'HSB' Hue Saturation Value/Brightness @@ -26,22 +26,22 @@ function varargout = colorspace(Conversion,varargin) % % All conversions assume 2 degree observer and D65 illuminant. % -% Color space names are case insensitive and spaces are ignored. When -% sRGB is the source or destination, it can be omitted. For example +% Color space names are case insensitive and spaces are ignored. When +% sRGB is the source or destination, it can be omitted. For example % 'yuv<-' is short for 'yuv<-rgb'. % -% For sRGB, the values should be scaled between 0 and 1. Beware that -% transformations generally do not constrain colors to be "in gamut." -% Particularly, transforming from another space to sRGB may obtain -% R'G'B' values outside of the [0,1] range. So the result should be +% For sRGB, the values should be scaled between 0 and 1. Beware that +% transformations generally do not constrain colors to be "in gamut." +% Particularly, transforming from another space to sRGB may obtain +% R'G'B' values outside of the [0,1] range. So the result should be % clamped to [0,1] before displaying: % image(min(max(B,0),1)); % Clamp B to [0,1] and display % % sRGB (Red Green Blue) is the (ITU-R BT.709 gamma-corrected) standard -% red-green-blue representation of colors used in digital imaging. The -% components should be scaled between 0 and 1. The space can be +% red-green-blue representation of colors used in digital imaging. The +% components should be scaled between 0 and 1. The space can be % visualized geometrically as a cube. -% +% % Y'PbPr, Y'CbCr, Y'DbDr, Y'UV, and Y'IQ are related to sRGB by linear % transformations. These spaces separate a color into a grayscale % luminance component Y and two chroma components. The valid ranges of @@ -66,7 +66,7 @@ function varargout = colorspace(Conversion,varargin) % S = 1 - min(R',G',B')/I (0 <= S <= 1), % I = (R'+G'+B')/3 (0 <= I <= 1). % Unlike HSV and HSL, the hue angle H is computed on a circle rather than -% a hexagon. +% a hexagon. % % CIE XYZ is related to sRGB by inverse gamma correction followed by a % linear transform. Other CIE color spaces are defined relative to XYZ. @@ -75,8 +75,8 @@ function varargout = colorspace(Conversion,varargin) % component is designed to match closely with human perception of % lightness. The other two components describe the chroma. % -% CIE CAT02 LMS is the linear transformation of XYZ using the MCAT02 -% chromatic adaptation matrix. The space is designed to model the +% CIE CAT02 LMS is the linear transformation of XYZ using the MCAT02 +% chromatic adaptation matrix. The space is designed to model the % response of the three types of cones in the human eye, where L, M, S, % correspond respectively to red ("long"), green ("medium"), and blue % ("short"). @@ -88,11 +88,11 @@ function varargout = colorspace(Conversion,varargin) % modification, are permitted provided that the following conditions are % met: % - % * Redistributions of source code must retain the above copyright - % notice, this list of conditions and the following disclaimer. - % * Redistributions in binary form must reproduce the above copyright - % notice, this list of conditions and the following disclaimer in - % the documentation and/or other materials provided with the distribution +% * Redistributions of source code must retain the above copyright +% notice, this list of conditions and the following disclaimer. +% * Redistributions in binary form must reproduce the above copyright +% notice, this list of conditions and the following disclaimer in +% the documentation and/or other materials provided with the distribution % % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" % AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE @@ -111,11 +111,11 @@ if nargin < 2, error('Not enough input arguments.'); end [SrcSpace,DestSpace] = parse(Conversion); if nargin == 2 - Image = varargin{1}; + Image = varargin{1}; elseif nargin >= 3 - Image = cat(3,varargin{:}); + Image = cat(3,varargin{:}); else - error('Invalid number of input arguments.'); + error('Invalid number of input arguments.'); end FlipDims = (size(Image,3) == 1); @@ -128,31 +128,31 @@ SrcT = gettransform(SrcSpace); DestT = gettransform(DestSpace); if ~ischar(SrcT) && ~ischar(DestT) - % Both source and destination transforms are affine, so they - % can be composed into one affine operation - T = [DestT(:,1:3)*SrcT(:,1:3),DestT(:,1:3)*SrcT(:,4)+DestT(:,4)]; - Temp = zeros(size(Image)); - Temp(:,:,1) = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10); - Temp(:,:,2) = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11); - Temp(:,:,3) = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12); - Image = Temp; + % Both source and destination transforms are affine, so they + % can be composed into one affine operation + T = [DestT(:,1:3)*SrcT(:,1:3),DestT(:,1:3)*SrcT(:,4)+DestT(:,4)]; + Temp = zeros(size(Image)); + Temp(:,:,1) = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10); + Temp(:,:,2) = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11); + Temp(:,:,3) = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12); + Image = Temp; elseif ~ischar(DestT) - Image = rgb(Image,SrcSpace); - Temp = zeros(size(Image)); - Temp(:,:,1) = DestT(1)*Image(:,:,1) + DestT(4)*Image(:,:,2) + DestT(7)*Image(:,:,3) + DestT(10); - Temp(:,:,2) = DestT(2)*Image(:,:,1) + DestT(5)*Image(:,:,2) + DestT(8)*Image(:,:,3) + DestT(11); - Temp(:,:,3) = DestT(3)*Image(:,:,1) + DestT(6)*Image(:,:,2) + DestT(9)*Image(:,:,3) + DestT(12); - Image = Temp; + Image = rgb(Image,SrcSpace); + Temp = zeros(size(Image)); + Temp(:,:,1) = DestT(1)*Image(:,:,1) + DestT(4)*Image(:,:,2) + DestT(7)*Image(:,:,3) + DestT(10); + Temp(:,:,2) = DestT(2)*Image(:,:,1) + DestT(5)*Image(:,:,2) + DestT(8)*Image(:,:,3) + DestT(11); + Temp(:,:,3) = DestT(3)*Image(:,:,1) + DestT(6)*Image(:,:,2) + DestT(9)*Image(:,:,3) + DestT(12); + Image = Temp; else - Image = feval(DestT,Image,SrcSpace); + Image = feval(DestT,Image,SrcSpace); end %%% Output format %%% if nargout > 1 - varargout = {Image(:,:,1),Image(:,:,2),Image(:,:,3)}; + varargout = {Image(:,:,1),Image(:,:,2),Image(:,:,3)}; else - if FlipDims, Image = permute(Image,[1,3,2]); end - varargout = {Image}; + if FlipDims, Image = permute(Image,[1,3,2]); end + varargout = {Image}; end return @@ -162,29 +162,29 @@ function [SrcSpace,DestSpace] = parse(Str) % Parse conversion argument if ischar(Str) - Str = lower(strrep(strrep(Str,'-',''),'=','')); - k = find(Str == '>'); - - if length(k) == 1 % Interpret the form 'src->dest' - SrcSpace = Str(1:k-1); - DestSpace = Str(k+1:end); - else - k = find(Str == '<'); - - if length(k) == 1 % Interpret the form 'dest<-src' - DestSpace = Str(1:k-1); - SrcSpace = Str(k+1:end); - else - error(['Invalid conversion, ''',Str,'''.']); - end - end - - SrcSpace = alias(SrcSpace); - DestSpace = alias(DestSpace); + Str = lower(strrep(strrep(Str,'-',''),'=','')); + k = find(Str == '>'); + + if length(k) == 1 % Interpret the form 'src->dest' + SrcSpace = Str(1:k-1); + DestSpace = Str(k+1:end); + else + k = find(Str == '<'); + + if length(k) == 1 % Interpret the form 'dest<-src' + DestSpace = Str(1:k-1); + SrcSpace = Str(k+1:end); + else + error(['Invalid conversion, ''',Str,'''.']); + end + end + + SrcSpace = alias(SrcSpace); + DestSpace = alias(DestSpace); else - SrcSpace = 1; % No source pre-transform - DestSpace = Conversion; - if any(size(Conversion) ~= 3), error('Transformation matrix must be 3x3.'); end + SrcSpace = 1; % No source pre-transform + DestSpace = Conversion; + if any(size(Conversion) ~= 3), error('Transformation matrix must be 3x3.'); end end return @@ -193,18 +193,18 @@ function Space = alias(Space) Space = strrep(strrep(Space,'cie',''),' ',''); if isempty(Space) - Space = 'rgb'; + Space = 'rgb'; end switch Space -case {'ycbcr','ycc'} - Space = 'ycbcr'; -case {'hsv','hsb'} - Space = 'hsv'; -case {'hsl','hsi','hls'} - Space = 'hsl'; -case {'rgb','yuv','yiq','ydbdr','ycbcr','jpegycbcr','xyz','lab','luv','lch'} - return + case {'ycbcr','ycc'} + Space = 'ycbcr'; + case {'hsv','hsb'} + Space = 'hsv'; + case {'hsl','hsi','hls'} + Space = 'hsl'; + case {'rgb','yuv','yiq','ydbdr','ycbcr','jpegycbcr','xyz','lab','luv','lch'} + return end return @@ -213,32 +213,32 @@ function T = gettransform(Space) % Get a colorspace transform: either a matrix describing an affine transform, % or a string referring to a conversion subroutine switch Space -case 'ypbpr' - T = [0.299,0.587,0.114,0;-0.1687367,-0.331264,0.5,0;0.5,-0.418688,-0.081312,0]; -case 'yuv' - % sRGB to NTSC/PAL YUV - % Wikipedia: http://en.wikipedia.org/wiki/YUV - T = [0.299,0.587,0.114,0;-0.147,-0.289,0.436,0;0.615,-0.515,-0.100,0]; -case 'ydbdr' - % sRGB to SECAM YDbDr - % Wikipedia: http://en.wikipedia.org/wiki/YDbDr - T = [0.299,0.587,0.114,0;-0.450,-0.883,1.333,0;-1.333,1.116,0.217,0]; -case 'yiq' - % sRGB in [0,1] to NTSC YIQ in [0,1];[-0.595716,0.595716];[-0.522591,0.522591]; - % Wikipedia: http://en.wikipedia.org/wiki/YIQ - T = [0.299,0.587,0.114,0;0.595716,-0.274453,-0.321263,0;0.211456,-0.522591,0.311135,0]; -case 'ycbcr' - % sRGB (range [0,1]) to ITU-R BRT.601 (CCIR 601) Y'CbCr - % Wikipedia: http://en.wikipedia.org/wiki/YCbCr - % Poynton, Equation 3, scaling of R'G'B to Y'PbPr conversion - T = [65.481,128.553,24.966,16;-37.797,-74.203,112.0,128;112.0,-93.786,-18.214,128]; -case 'jpegycbcr' - % Wikipedia: http://en.wikipedia.org/wiki/YCbCr - T = [0.299,0.587,0.114,0;-0.168736,-0.331264,0.5,0.5;0.5,-0.418688,-0.081312,0.5]*255; -case {'rgb','xyz','hsv','hsl','lab','luv','lch','cat02lms'} - T = Space; -otherwise - error(['Unknown color space, ''',Space,'''.']); + case 'ypbpr' + T = [0.299,0.587,0.114,0;-0.1687367,-0.331264,0.5,0;0.5,-0.418688,-0.081312,0]; + case 'yuv' + % sRGB to NTSC/PAL YUV + % Wikipedia: http://en.wikipedia.org/wiki/YUV + T = [0.299,0.587,0.114,0;-0.147,-0.289,0.436,0;0.615,-0.515,-0.100,0]; + case 'ydbdr' + % sRGB to SECAM YDbDr + % Wikipedia: http://en.wikipedia.org/wiki/YDbDr + T = [0.299,0.587,0.114,0;-0.450,-0.883,1.333,0;-1.333,1.116,0.217,0]; + case 'yiq' + % sRGB in [0,1] to NTSC YIQ in [0,1];[-0.595716,0.595716];[-0.522591,0.522591]; + % Wikipedia: http://en.wikipedia.org/wiki/YIQ + T = [0.299,0.587,0.114,0;0.595716,-0.274453,-0.321263,0;0.211456,-0.522591,0.311135,0]; + case 'ycbcr' + % sRGB (range [0,1]) to ITU-R BRT.601 (CCIR 601) Y'CbCr + % Wikipedia: http://en.wikipedia.org/wiki/YCbCr + % Poynton, Equation 3, scaling of R'G'B to Y'PbPr conversion + T = [65.481,128.553,24.966,16;-37.797,-74.203,112.0,128;112.0,-93.786,-18.214,128]; + case 'jpegycbcr' + % Wikipedia: http://en.wikipedia.org/wiki/YCbCr + T = [0.299,0.587,0.114,0;-0.168736,-0.331264,0.5,0.5;0.5,-0.418688,-0.081312,0.5]*255; + case {'rgb','xyz','hsv','hsl','lab','luv','lch','cat02lms'} + T = Space; + otherwise + error(['Unknown color space, ''',Space,'''.']); end return @@ -246,43 +246,43 @@ return function Image = rgb(Image,SrcSpace) % Convert to sRGB from 'SrcSpace' switch SrcSpace -case 'rgb' - return -case 'hsv' - % Convert HSV to sRGB - Image = huetorgb((1 - Image(:,:,2)).*Image(:,:,3),Image(:,:,3),Image(:,:,1)); -case 'hsl' - % Convert HSL to sRGB - L = Image(:,:,3); - Delta = Image(:,:,2).*min(L,1-L); - Image = huetorgb(L-Delta,L+Delta,Image(:,:,1)); -case {'xyz','lab','luv','lch','cat02lms'} - % Convert to CIE XYZ - Image = xyz(Image,SrcSpace); - % Convert XYZ to RGB - T = [3.2406, -1.5372, -0.4986; -0.9689, 1.8758, 0.0415; 0.0557, -0.2040, 1.057]; - R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3); % R - G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3); % G - B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3); % B - % Desaturate and rescale to constrain resulting RGB values to [0,1] - AddWhite = -min(min(min(R,G),B),0); - R = R + AddWhite; - G = G + AddWhite; - B = B + AddWhite; - % Apply gamma correction to convert linear RGB to sRGB - Image(:,:,1) = gammacorrection(R); % R' - Image(:,:,2) = gammacorrection(G); % G' - Image(:,:,3) = gammacorrection(B); % B' -otherwise % Conversion is through an affine transform - T = gettransform(SrcSpace); - temp = inv(T(:,1:3)); - T = [temp,-temp*T(:,4)]; - R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10); - G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11); - B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12); - Image(:,:,1) = R; - Image(:,:,2) = G; - Image(:,:,3) = B; + case 'rgb' + return + case 'hsv' + % Convert HSV to sRGB + Image = huetorgb((1 - Image(:,:,2)).*Image(:,:,3),Image(:,:,3),Image(:,:,1)); + case 'hsl' + % Convert HSL to sRGB + L = Image(:,:,3); + Delta = Image(:,:,2).*min(L,1-L); + Image = huetorgb(L-Delta,L+Delta,Image(:,:,1)); + case {'xyz','lab','luv','lch','cat02lms'} + % Convert to CIE XYZ + Image = xyz(Image,SrcSpace); + % Convert XYZ to RGB + T = [3.2406, -1.5372, -0.4986; -0.9689, 1.8758, 0.0415; 0.0557, -0.2040, 1.057]; + R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3); % R + G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3); % G + B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3); % B + % Desaturate and rescale to constrain resulting RGB values to [0,1] + AddWhite = -min(min(min(R,G),B),0); + R = R + AddWhite; + G = G + AddWhite; + B = B + AddWhite; + % Apply gamma correction to convert linear RGB to sRGB + Image(:,:,1) = gammacorrection(R); % R' + Image(:,:,2) = gammacorrection(G); % G' + Image(:,:,3) = gammacorrection(B); % B' + otherwise % Conversion is through an affine transform + T = gettransform(SrcSpace); + temp = inv(T(:,1:3)); + T = [temp,-temp*T(:,4)]; + R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10); + G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11); + B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12); + Image(:,:,1) = R; + Image(:,:,2) = G; + Image(:,:,3) = B; end % Clip to [0,1] @@ -292,53 +292,53 @@ return function Image = xyz(Image,SrcSpace) % Convert to CIE XYZ from 'SrcSpace' -WhitePoint = [0.950456,1,1.088754]; +WhitePoint = [0.950456,1,1.088754]; switch SrcSpace -case 'xyz' - return -case 'luv' - % Convert CIE L*uv to XYZ - WhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3)); - WhitePointV = (9*WhitePoint(2))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3)); - L = Image(:,:,1); - Y = (L + 16)/116; - Y = invf(Y)*WhitePoint(2); - U = Image(:,:,2)./(13*L + 1e-6*(L==0)) + WhitePointU; - V = Image(:,:,3)./(13*L + 1e-6*(L==0)) + WhitePointV; - Image(:,:,1) = -(9*Y.*U)./((U-4).*V - U.*V); % X - Image(:,:,2) = Y; % Y - Image(:,:,3) = (9*Y - (15*V.*Y) - (V.*Image(:,:,1)))./(3*V); % Z -case {'lab','lch'} - Image = lab(Image,SrcSpace); - % Convert CIE L*ab to XYZ - fY = (Image(:,:,1) + 16)/116; - fX = fY + Image(:,:,2)/500; - fZ = fY - Image(:,:,3)/200; - Image(:,:,1) = WhitePoint(1)*invf(fX); % X - Image(:,:,2) = WhitePoint(2)*invf(fY); % Y - Image(:,:,3) = WhitePoint(3)*invf(fZ); % Z -case 'cat02lms' + case 'xyz' + return + case 'luv' + % Convert CIE L*uv to XYZ + WhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3)); + WhitePointV = (9*WhitePoint(2))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3)); + L = Image(:,:,1); + Y = (L + 16)/116; + Y = invf(Y)*WhitePoint(2); + U = Image(:,:,2)./(13*L + 1e-6*(L==0)) + WhitePointU; + V = Image(:,:,3)./(13*L + 1e-6*(L==0)) + WhitePointV; + Image(:,:,1) = -(9*Y.*U)./((U-4).*V - U.*V); % X + Image(:,:,2) = Y; % Y + Image(:,:,3) = (9*Y - (15*V.*Y) - (V.*Image(:,:,1)))./(3*V); % Z + case {'lab','lch'} + Image = lab(Image,SrcSpace); + % Convert CIE L*ab to XYZ + fY = (Image(:,:,1) + 16)/116; + fX = fY + Image(:,:,2)/500; + fZ = fY - Image(:,:,3)/200; + Image(:,:,1) = WhitePoint(1)*invf(fX); % X + Image(:,:,2) = WhitePoint(2)*invf(fY); % Y + Image(:,:,3) = WhitePoint(3)*invf(fZ); % Z + case 'cat02lms' % Convert CAT02 LMS to XYZ - T = inv([0.7328, 0.4296, -0.1624;-0.7036, 1.6975, 0.0061; 0.0030, 0.0136, 0.9834]); - L = Image(:,:,1); - M = Image(:,:,2); - S = Image(:,:,3); - Image(:,:,1) = T(1)*L + T(4)*M + T(7)*S; % X - Image(:,:,2) = T(2)*L + T(5)*M + T(8)*S; % Y - Image(:,:,3) = T(3)*L + T(6)*M + T(9)*S; % Z -otherwise % Convert from some gamma-corrected space - % Convert to sRGB - Image = rgb(Image,SrcSpace); - % Undo gamma correction - R = invgammacorrection(Image(:,:,1)); - G = invgammacorrection(Image(:,:,2)); - B = invgammacorrection(Image(:,:,3)); - % Convert RGB to XYZ - T = inv([3.2406, -1.5372, -0.4986; -0.9689, 1.8758, 0.0415; 0.0557, -0.2040, 1.057]); - Image(:,:,1) = T(1)*R + T(4)*G + T(7)*B; % X - Image(:,:,2) = T(2)*R + T(5)*G + T(8)*B; % Y - Image(:,:,3) = T(3)*R + T(6)*G + T(9)*B; % Z + T = inv([0.7328, 0.4296, -0.1624;-0.7036, 1.6975, 0.0061; 0.0030, 0.0136, 0.9834]); + L = Image(:,:,1); + M = Image(:,:,2); + S = Image(:,:,3); + Image(:,:,1) = T(1)*L + T(4)*M + T(7)*S; % X + Image(:,:,2) = T(2)*L + T(5)*M + T(8)*S; % Y + Image(:,:,3) = T(3)*L + T(6)*M + T(9)*S; % Z + otherwise % Convert from some gamma-corrected space + % Convert to sRGB + Image = rgb(Image,SrcSpace); + % Undo gamma correction + R = invgammacorrection(Image(:,:,1)); + G = invgammacorrection(Image(:,:,2)); + B = invgammacorrection(Image(:,:,3)); + % Convert RGB to XYZ + T = inv([3.2406, -1.5372, -0.4986; -0.9689, 1.8758, 0.0415; 0.0557, -0.2040, 1.057]); + Image(:,:,1) = T(1)*R + T(4)*G + T(7)*B; % X + Image(:,:,2) = T(2)*R + T(5)*G + T(8)*B; % Y + Image(:,:,3) = T(3)*R + T(6)*G + T(9)*B; % Z end return @@ -355,27 +355,27 @@ return function Image = hsl(Image,SrcSpace) -% Convert to HSL +% Convert to HSL switch SrcSpace -case 'hsv' - % Convert HSV to HSL - MaxVal = Image(:,:,3); - MinVal = (1 - Image(:,:,2)).*MaxVal; - L = 0.5*(MaxVal + MinVal); - temp = min(L,1-L); - Image(:,:,2) = 0.5*(MaxVal - MinVal)./(temp + (temp == 0)); - Image(:,:,3) = L; -otherwise - Image = rgb(Image,SrcSpace); % Convert to sRGB - % Convert sRGB to HSL - MinVal = min(Image,[],3); - MaxVal = max(Image,[],3); - L = 0.5*(MaxVal + MinVal); - temp = min(L,1-L); - S = 0.5*(MaxVal - MinVal)./(temp + (temp == 0)); - Image(:,:,1) = rgbtohue(Image); - Image(:,:,2) = S; - Image(:,:,3) = L; + case 'hsv' + % Convert HSV to HSL + MaxVal = Image(:,:,3); + MinVal = (1 - Image(:,:,2)).*MaxVal; + L = 0.5*(MaxVal + MinVal); + temp = min(L,1-L); + Image(:,:,2) = 0.5*(MaxVal - MinVal)./(temp + (temp == 0)); + Image(:,:,3) = L; + otherwise + Image = rgb(Image,SrcSpace); % Convert to sRGB + % Convert sRGB to HSL + MinVal = min(Image,[],3); + MaxVal = max(Image,[],3); + L = 0.5*(MaxVal + MinVal); + temp = min(L,1-L); + S = 0.5*(MaxVal - MinVal)./(temp + (temp == 0)); + Image(:,:,1) = rgbtohue(Image); + Image(:,:,2) = S; + Image(:,:,3) = L; end return @@ -385,25 +385,25 @@ function Image = lab(Image,SrcSpace) WhitePoint = [0.950456,1,1.088754]; switch SrcSpace -case 'lab' - return -case 'lch' - % Convert CIE L*CH to CIE L*ab - C = Image(:,:,2); - Image(:,:,2) = cos(Image(:,:,3)*pi/180).*C; % a* - Image(:,:,3) = sin(Image(:,:,3)*pi/180).*C; % b* -otherwise - Image = xyz(Image,SrcSpace); % Convert to XYZ - % Convert XYZ to CIE L*a*b* - X = Image(:,:,1)/WhitePoint(1); - Y = Image(:,:,2)/WhitePoint(2); - Z = Image(:,:,3)/WhitePoint(3); - fX = f(X); - fY = f(Y); - fZ = f(Z); - Image(:,:,1) = 116*fY - 16; % L* - Image(:,:,2) = 500*(fX - fY); % a* - Image(:,:,3) = 200*(fY - fZ); % b* + case 'lab' + return + case 'lch' + % Convert CIE L*CH to CIE L*ab + C = Image(:,:,2); + Image(:,:,2) = cos(Image(:,:,3)*pi/180).*C; % a* + Image(:,:,3) = sin(Image(:,:,3)*pi/180).*C; % b* + otherwise + Image = xyz(Image,SrcSpace); % Convert to XYZ + % Convert XYZ to CIE L*a*b* + X = Image(:,:,1)/WhitePoint(1); + Y = Image(:,:,2)/WhitePoint(2); + Z = Image(:,:,3)/WhitePoint(3); + fX = f(X); + fY = f(Y); + fZ = f(Z); + Image(:,:,1) = 116*fY - 16; % L* + Image(:,:,2) = 500*(fX - fY); % a* + Image(:,:,3) = 200*(fY - fZ); % b* end return diff --git a/matlab/utilities/graphics/distinguishable_colors.m b/matlab/utilities/graphics/distinguishable_colors.m index cf45e582d6..6b927be2e6 100644 --- a/matlab/utilities/graphics/distinguishable_colors.m +++ b/matlab/utilities/graphics/distinguishable_colors.m @@ -61,11 +61,11 @@ function colors = distinguishable_colors(n_colors,bg,func) % modification, are permitted provided that the following conditions are % met: % - % * Redistributions of source code must retain the above copyright - % notice, this list of conditions and the following disclaimer. - % * Redistributions in binary form must reproduce the above copyright - % notice, this list of conditions and the following disclaimer in - % the documentation and/or other materials provided with the distribution +% * Redistributions of source code must retain the above copyright +% notice, this list of conditions and the following disclaimer. +% * Redistributions in binary form must reproduce the above copyright +% notice, this list of conditions and the following disclaimer in +% the documentation and/or other materials provided with the distribution % % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" % AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE diff --git a/matlab/variance_decomposition_mc_analysis.m b/matlab/variance_decomposition_mc_analysis.m index 6b101d0da3..2c11fdb02d 100644 --- a/matlab/variance_decomposition_mc_analysis.m +++ b/matlab/variance_decomposition_mc_analysis.m @@ -94,7 +94,7 @@ if options_.estimation.moments_posterior_density.indicator posterior_moments(tmp,1,mh_conf_sig); else [p_mean, p_median, p_var, hpd_interval, p_deciles] = ... - posterior_moments(tmp,0,mh_conf_sig); + posterior_moments(tmp,0,mh_conf_sig); end oo_.([TYPE, 'TheoreticalMoments']).dsge.VarianceDecomposition.Mean.(var).(exo) = p_mean; diff --git a/matlab/varlist_indices.m b/matlab/varlist_indices.m index 24714f572a..4347f9af42 100644 --- a/matlab/varlist_indices.m +++ b/matlab/varlist_indices.m @@ -4,7 +4,7 @@ function [i_var,nvar,index_uniques] = varlist_indices(sublist,list) % % INPUT % sublist: sublist of variables -% list: list of variables +% list: list of variables % % OUTPUT % i_var: variable indices in M_.endo_names diff --git a/matlab/vnorm.m b/matlab/vnorm.m index b6bb123d94..56be98bb4d 100644 --- a/matlab/vnorm.m +++ b/matlab/vnorm.m @@ -71,7 +71,7 @@ if isempty(dim) idx = find(size(A)~=1); dim = idx(1); end - + if isempty(ntype) y = sqrt(sum( abs(A).^2 , dim) ); elseif ntype==1 @@ -88,4 +88,3 @@ elseif ntype~=floor(ntype) || ntype<1 else y = (sum( abs(A).^ntype , dim) ).^(1/ntype); end - diff --git a/matlab/warning_config.m b/matlab/warning_config.m index 3b9f45d63e..79098a6104 100644 --- a/matlab/warning_config.m +++ b/matlab/warning_config.m @@ -3,10 +3,10 @@ function warning_config() % % INPUTS % none -% +% % OUTPUTS % none -% +% % SPECIAL REQUIREMENTS % none diff --git a/matlab/write_latex_definitions.m b/matlab/write_latex_definitions.m index 2bf3acf366..144f6242be 100644 --- a/matlab/write_latex_definitions.m +++ b/matlab/write_latex_definitions.m @@ -65,9 +65,9 @@ for i=1:length(tables) long = eval([M_var_root{i} '_names_long']); for j=1:size(names,1) fprintf(fid, '\\texttt{%s} & $%s$ & %s\\\\\n', ... - regexprep(strtrim(names(j,:)), '_', '\\_'), ... - strtrim(tex(j,:)), ... - regexprep(strtrim(long(j,:)), '_', '\\_')); + regexprep(strtrim(names(j,:)), '_', '\\_'), ... + strtrim(tex(j,:)), ... + regexprep(strtrim(long(j,:)), '_', '\\_')); end fprintf(fid, '\\hline%%\n'); fprintf(fid, '\\end{longtable}\n'); diff --git a/matlab/write_latex_parameter_table.m b/matlab/write_latex_parameter_table.m index ea76074505..92374d77c9 100644 --- a/matlab/write_latex_parameter_table.m +++ b/matlab/write_latex_parameter_table.m @@ -75,20 +75,20 @@ fprintf(fid, '\\endhead\n'); tex = M_.param_names_tex; long = M_.param_names_long; for j=1:size(tex,1) -if Long_names_present==1 - % replace underscores - long_names_temp=regexprep(strtrim(long(j,:)), '_', '\\_'); - % replace percent - long_names_temp=regexprep(long_names_temp, '%', '\\%'); - fprintf(fid, '$%s$ \t & \t %4.3f \t & \t %s\\\\\n', ... - strtrim(tex(j,:)), ... - M_.params(j,:),... - long_names_temp); -else - fprintf(fid, '$%s$ \t & \t %4.3f \\\\\n', ... - strtrim(tex(j,:)), ... - M_.params(j,:)); -end + if Long_names_present==1 + % replace underscores + long_names_temp=regexprep(strtrim(long(j,:)), '_', '\\_'); + % replace percent + long_names_temp=regexprep(long_names_temp, '%', '\\%'); + fprintf(fid, '$%s$ \t & \t %4.3f \t & \t %s\\\\\n', ... + strtrim(tex(j,:)), ... + M_.params(j,:),... + long_names_temp); + else + fprintf(fid, '$%s$ \t & \t %4.3f \\\\\n', ... + strtrim(tex(j,:)), ... + M_.params(j,:)); + end end fprintf(fid, '\\bottomrule%%\n'); fprintf(fid, '\\end{longtable}\n'); diff --git a/matlab/write_latex_prior_table.m b/matlab/write_latex_prior_table.m index 46a5e3bf52..db9c8bfbce 100644 --- a/matlab/write_latex_prior_table.m +++ b/matlab/write_latex_prior_table.m @@ -37,11 +37,11 @@ end if (size(estim_params_.var_endo,1) || size(estim_params_.corrn,1)) % Prior over measurement errors are defined... - if ((isfield(options_,'varobs') && isempty(options_.varobs)) || ~isfield(options_,'varobs')) - % ... But the list of observed variabled is not yet defined. - fprintf(['\nwrite_latex_prior_table:: varobs should be declared before. Skipping table creation.\n']) - return - end + if ((isfield(options_,'varobs') && isempty(options_.varobs)) || ~isfield(options_,'varobs')) + % ... But the list of observed variabled is not yet defined. + fprintf(['\nwrite_latex_prior_table:: varobs should be declared before. Skipping table creation.\n']) + return + end end % Fill or update bayestopt_ structure @@ -115,56 +115,56 @@ for i=1:size(BayesOptions.name,1) PriorMode = BayesOptions.p5(i); PriorStandardDeviation = BayesOptions.p2(i); switch BayesOptions.pshape(i) - case { 1 , 5 } + case { 1 , 5 } + LowerBound = BayesOptions.p3(i); + UpperBound = BayesOptions.p4(i); + if ~isinf(lb(i)) + LowerBound=max(LowerBound,lb(i)); + end + if ~isinf(ub(i)) + UpperBound=min(UpperBound,ub(i)); + end + case { 2 , 4 , 6, 8 } + LowerBound = BayesOptions.p3(i); + if ~isinf(lb(i)) + LowerBound=max(LowerBound,lb(i)); + end + if ~isinf(ub(i)) + UpperBound=ub(i); + else + UpperBound = '$\infty$'; + end + case 3 + if isinf(BayesOptions.p3(i)) && isinf(lb(i)) + LowerBound = '$-\infty$'; + else LowerBound = BayesOptions.p3(i); - UpperBound = BayesOptions.p4(i); if ~isinf(lb(i)) LowerBound=max(LowerBound,lb(i)); end + end + if isinf(BayesOptions.p4(i)) && isinf(ub(i)) + UpperBound = '$\infty$'; + else + UpperBound = BayesOptions.p4(i); if ~isinf(ub(i)) UpperBound=min(UpperBound,ub(i)); end - case { 2 , 4 , 6, 8 } - LowerBound = BayesOptions.p3(i); - if ~isinf(lb(i)) - LowerBound=max(LowerBound,lb(i)); - end - if ~isinf(ub(i)) - UpperBound=ub(i); - else - UpperBound = '$\infty$'; - end - case 3 - if isinf(BayesOptions.p3(i)) && isinf(lb(i)) - LowerBound = '$-\infty$'; - else - LowerBound = BayesOptions.p3(i); - if ~isinf(lb(i)) - LowerBound=max(LowerBound,lb(i)); - end - end - if isinf(BayesOptions.p4(i)) && isinf(ub(i)) - UpperBound = '$\infty$'; - else - UpperBound = BayesOptions.p4(i); - if ~isinf(ub(i)) - UpperBound=min(UpperBound,ub(i)); - end - end - otherwise - error('write_latex_prior_table:: Dynare bug!') + end + otherwise + error('write_latex_prior_table:: Dynare bug!') end format_string = build_format_string(PriorMode, PriorStandardDeviation,LowerBound,UpperBound); fprintf(fidTeX,format_string, ... - TexName, ... - PriorShape, ... - PriorMean, ... - PriorMode, ... - PriorStandardDeviation, ... - LowerBound, ... - UpperBound, ... - PriorIntervals.lb(i), ... - PriorIntervals.ub(i) ); + TexName, ... + PriorShape, ... + PriorMean, ... + PriorMode, ... + PriorStandardDeviation, ... + LowerBound, ... + UpperBound, ... + PriorIntervals.lb(i), ... + PriorIntervals.ub(i) ); end fprintf(fidTeX,'\\end{longtable}\n '); fprintf(fidTeX,'\\end{center}\n'); diff --git a/matlab/write_mh_history_file.m b/matlab/write_mh_history_file.m index 00984c26cf..2cc7ef2d85 100644 --- a/matlab/write_mh_history_file.m +++ b/matlab/write_mh_history_file.m @@ -5,7 +5,7 @@ function i = write_mh_history_file(MetropolisFolder, ModelName, record) % MetropolisFolder [char] Name of the metropolis subfolder % ModelName [char] Name of the mod-file % record [structure] structure storing the MH history -% Outputs: +% Outputs: % i [scalar] number of the mh_history file % Copyright (C) 2013-2015 Dynare Team diff --git a/matlab/writecellofchar.m b/matlab/writecellofchar.m index be636e6f17..5251a31e61 100644 --- a/matlab/writecellofchar.m +++ b/matlab/writecellofchar.m @@ -2,13 +2,13 @@ function str = writecellofchar(c) % Writes a two dimensional cell of char in a string. % -% INPUTS +% INPUTS % - c [cell] cell of char. % -% OUTPUTS +% OUTPUTS % - str [char] % -% EXAMPLES +% EXAMPLES % >> writecellofchar({'a', {'b'; 'c'}}) % % ans = @@ -19,7 +19,7 @@ function str = writecellofchar(c) % % ans = % -%{'a', '['b'; 'c']', 'd'} +%{'a', '['b'; 'c']', 'd'} % Copyright (C) 2015 Dynare Team % @@ -37,27 +37,27 @@ function str = writecellofchar(c) % % You should have received a copy of the GNU General Public License % along with Dynare. If not, see <http://www.gnu.org/licenses/>. - + str = '{'; for i=1:size(c, 1) - for j=1:size(c, 2) - if iscell(c{i,j}) - str = sprintf('%s%s', str, writecellofchar(c{i, j})); - elseif ischar(c{i, j}) - if size(c{i, j}, 1)>1 - str = sprintf('%s''%s''', str, writematrixofchar(c{i, j})); - else - str = sprintf('%s''%s''', str, c{i, j}); - end - else - error('Type not implemenented!') - end - if j<size(c, 2) - str = sprintf('%s, ', str); - end - end - if i<size(c, 1) - str = sprintf('%s; ', str); - end +for j=1:size(c, 2) +if iscell(c{i,j}) +str = sprintf('%s%s', str, writecellofchar(c{i, j})); +elseif ischar(c{i, j}) +if size(c{i, j}, 1)>1 +str = sprintf('%s''%s''', str, writematrixofchar(c{i, j})); +else +str = sprintf('%s''%s''', str, c{i, j}); +end +else +error('Type not implemenented!') +end +if j<size(c, 2) +str = sprintf('%s, ', str); +end +end +if i<size(c, 1) +str = sprintf('%s; ', str); +end end str = sprintf('%s}', str); \ No newline at end of file diff --git a/matlab/writedata.m b/matlab/writedata.m index 112d7f1306..1512d0827b 100644 --- a/matlab/writedata.m +++ b/matlab/writedata.m @@ -1,6 +1,6 @@ function writedata(fname) % function writedata(fname) -% store endogenous and exogenous variables in a XLS spreadsheet file +% store endogenous and exogenous variables in a XLS spreadsheet file % INPUT % fname: name of the XLS file % OUTPUT diff --git a/matlab/writedata_text.m b/matlab/writedata_text.m index ac56ad10d4..0fa0f7ac2a 100644 --- a/matlab/writedata_text.m +++ b/matlab/writedata_text.m @@ -1,6 +1,6 @@ function writedata_text(fname) % function writedata(fname) -% store endogenous and exogenous variables in a text file +% store endogenous and exogenous variables in a text file % INPUT % fname: name of the text file % OUTPUT diff --git a/matlab/writematrixofchar.m b/matlab/writematrixofchar.m index 6f230e554f..59e8fdb634 100644 --- a/matlab/writematrixofchar.m +++ b/matlab/writematrixofchar.m @@ -2,13 +2,13 @@ function str = writematrixofchar(m) % Writes a matrix of char in a string. % -% INPUTS +% INPUTS % - m [char] matrix of char. % -% OUTPUTS +% OUTPUTS % - str [char] % -% EXAMPLE +% EXAMPLE % >> writematrixofchar(['a'; 'b']) % % ans = @@ -16,7 +16,7 @@ function str = writematrixofchar(m) % ['a'; 'b'] % % where the returned argument is a string which can be evaluated or printed. - + % Copyright (C) 2015 Dynare Team % % This file is part of Dynare. -- GitLab