diff --git a/.gitignore b/.gitignore index e6d44a024..9fc713587 100644 --- a/.gitignore +++ b/.gitignore @@ -60,6 +60,7 @@ checksum /doc/dynare.info /doc/dynare.info-1 /doc/dynare.info-2 +/doc/dynare.info-3 /doc/dynare.cp /doc/dynare.fn /doc/dynare.fns @@ -212,3 +213,6 @@ tests/julia/rbc/rbc*.jl # Octave variables saved when Octave crashes octave-workspace + +# VERSION generated file +VERSION \ No newline at end of file diff --git a/NEWS b/NEWS index 500f3e325..71e9b45d4 100644 --- a/NEWS +++ b/NEWS @@ -1,3 +1,800 @@ +Announcement for Dynare 4.5.0 (on 2013-12-16) +============================================= + +We are pleased to announce the release of Dynare 4.5.0. + +This major release adds new features and fixes various bugs. + +The Windows packages are already available for download at: + + http://www.dynare.org/download/dynare-stable + +The Mac and Debian/Ubuntu packages should follow soon. + +All users are strongly encouraged to upgrade. + +This release is compatible with MATLAB versions ranging from 7.3 (R2006b) to +9.2 (R2017a) and with GNU Octave version 4.2. + +Here is the list of major user-visible changes: + + + +Dynare 4.5 +========== + + + - Ramsey policy + + + Added command `ramsey_model` that builds the expanded model with + FOC conditions for the planner's problem but doesn't perform any + computation. Usefull to compute Ramsey policy in a perfect + foresight model, + + + `ramsey_policy` accepts multipliers in its variable list and + displays results for them. + + + - Perfect foresight models + + + New commands `perfect_foresight_setup` (for preparing the + simulation) and `perfect_foresight_solver` (for computing it). The + old `simul` command still exist and is now an alias for + `perfect_foresight_setup` + `perfect_foresight_solver`. It is no + longer possible to manipulate by hand the contents of + `oo_.exo_simul` when using `simul`. People who want to do + it must first call `perfect_foresight_setup`, then do the + manipulations, then call `perfect_foresight_solver`, + + + By default, the perfect foresight solver will try a homotopy + method if it fails to converge at the first try. The old behavior + can be restored with the `no_homotopy` option, + + + New option `stack_solve_algo=7` that allows specifying a + `solve_algo` solver for solving the model, + + + New option `solve_algo` that allows specifying a solver for + solving the model when using `stack_solve_algo=7`, + + + New option `lmmcp` that solves the model via a Levenberg-Marquardt + mixed complementarity problem (LMMCP) solver, + + + New option `robust_lin_solve` that triggers the use of a robust + linear solver for the default `solve_algo=4`, + + + New options `tolf` and `tolx` to control termination criteria of + solvers, + + + New option `endogenous_terminal_period` to `simul`, + + + Added the possibility to set the initial condition of the + (stochastic) extended path simulations with the histval block. + + + - Optimal simple rules + + + Saves the optimal value of parameters to `oo_.osr.optim_params`, + + + New block `osr_params_bounds` allows specifying bounds for the + estimated parameters, + + + New option `opt_algo` allows selecting different optimizers while + the new option `optim` allows specifying the optimizer options, + + + The `osr` command now saves the names, bounds, and indices for the + estimated parameters as well as the indices and weights of the + variables entering the objective function into `M_.osr`. + + + - Forecasts and Smoothing + + + The smoother and forecasts take uncertainty about trends and means + into account, + + + Forecasts accounting for measurement error are now saved in fields + of the form `HPDinf_ME` and `HPDsup_ME`, + + + New fields `oo_.Smoother.Trend` and `oo_.Smoother.Constant` that + save the trend and constant parts of the smoothed variables, + + + new field `oo_.Smoother.TrendCoeffs` that stores the trend + coefficients. + + + Rolling window forecasts allowed in `estimation` command by + passing a vector to `first_obs`, + + + The `calib_smoother` command now accepts the `loglinear`, + `prefilter`, `first_obs` and `filter_decomposition` options. + + + - Estimation + + + New options: `logdata`, `consider_all_endogenous`, + `consider_only_observed`, `posterior_max_subsample_draws`, + `mh_conf_sig`, `diffuse_kalman_tol`, `dirname`, `nodecomposition` + + + `load_mh_file` and `mh_recover` now try to load chain's proposal density, + + + New option `load_results_after_load_mh` that allows loading some + posterior results from a previous run if no new MCMC draws are + added, + + + New option `posterior_nograph` that suppresses the generation of + graphs associated with Bayesian IRFs, posterior smoothed objects, + and posterior forecasts, + + + Saves the posterior density at the mode in + `oo_.posterior.optimization.log_density`, + + + The `filter_covariance` option now also works with posterior + sampling like Metropolis-Hastings, + + + New option `no_posterior_kernel_density` to suppress computation + of kernel density of posterior objects, + + + Recursive estimation and forecasting now provides the individual + `oo_` structures for each sample in `oo_recursive_`, + + + The `trace_plot` command can now plot the posterior density, + + + New command `generate_trace_plots` allows generating all trace + plots for one chain, + + + New commands `prior_function` and `posterior_function` that + execute a user-defined function on parameter draws from the + prior/posterior distribution, + + + New option `huge_number` for replacement of infinite bounds with + large number during `mode_compute`, + + + New option `posterior_sampling_method` allows selecting the new + posterior sampling options: + `tailored_random_block_metropolis_hastings` (Tailored randomized + block (TaRB) Metropolis-Hastings), `slice` (Slice sampler), + `independent_metropolis_hastings` (Independent + Metropolis-Hastings), + + + New option `posterior_sampler_options` that allow controlling the + options of the `posterior_sampling_method`, its `scale_file`-option + pair allows loading the `_mh_scale.mat`-file storing the tuned + scale factor from a previous run of `mode_compute=6`, + + + New option `raftery_lewis_diagnostics` that computes Raftery/Lewis + (1992) convergence diagnostics, + + + New option `fast_kalman_filter` that provides fast Kalman filter + using Chandrasekhar recursions as described in Ed Herbst (2015), + + + The `dsge_var` option now saves results at the posterior mode into + `oo_.dsge_var`, + + + New option `smoothed_state_uncertainty` to provide the uncertainty + estimate for the smoothed state estimate from the Kalman smoother, + + + New prior density: generalized Weibull distribution, + + + Option `mh_recover` now allows continuing a crashed chain at the + last save mh-file, + + + New option `nonlinear_filter_initialization` for the + `estimation` command. Controls the initial covariance matrix + of the state variables in nonlinear filters. + + + The `conditional_variance_decomposition` option now displays + output and stores it as a LaTeX-table when the `TeX` option is + invoked, + + + The `use_calibration` to `estimated_params_init` now also works + with ML, + + + Improved initial estimation checks. + + + - Steady state + + + The default solver for finding the steady state is now a + trust-region solver (can be triggered explicitly with option + `solve_algo=4`), + + + New options `tolf` and `tolx` to control termination criteria of + solver, + + + The debugging mode now provides the termination values in steady + state finding. + + + - Stochastic simulations + + + New options `nodecomposition`, + + + New option `bandpass_filter` to compute bandpass-filtered + theoretical and simulated moments, + + + New option `one_sided_hp_filter` to compute one-sided HP-filtered + simulated moments, + + + `stoch_simul` displays a simulated variance decomposition when + simulated moments are requested, + + + `stoch_simul` saves skewness and kurtosis into respective fields + of `oo_` when simulated moments have been requested, + + + `stoch_simul` saves the unconditional variance decomposition in + `oo_.variance_decomposition`, + + + New option `dr_display_tol` that governs omission of small terms + in display of decision rules, + + + The `stoch_simul` command now prints the displayed tables as LaTeX + code when the new `TeX` option is enabled, + + + The `loglinear` option now works with lagged and leaded exogenous + variables like news shocks, + + + New option `spectral_density` that allows displaying the spectral + density of (filtered) endogenous variables, + + + New option `contemporaneous_correlation` that allows saving + contemporaneous correlations in addition to the covariances. + + + - Identification + + + New options `diffuse_filter` and `prior_trunc`, + + + The `identification` command now supports correlations via + simulated moments, + + + - Sensitivity analysis + + + New blocks `irf_calibration` and `moment_calibration`, + + + Outputs LaTeX tables if the new `TeX` option is used, + + + New option `relative_irf` to `irf_calibration` block. + + + - Conditional forecast + + + Command `conditional_forecast` now takes into account `histval` + block if present. + + + - Shock decomposition + + + New option `colormap` to `shocks_decomposition` for controlling + the color map used in the shocks decomposition graphs, + + + `shocks_decomposition` now accepts the `nograph` option, + + + New command `realtime_shock_decomposition` that for each period `T= [presample,...,nobs]` + allows computing the: + + * realtime historical shock decomposition `Y(t|T)`, i.e. without observing data in `[T+1,...,nobs]` + + * forecast shock decomposition `Y(T+k|T)` + + * realtime conditional shock decomposition `Y(T+k|T+k)-Y(T+k|T)` + + + New block `shock_groups` that allows grouping shocks for the + `shock_decomposition` and `realtime_shock_decomposition` commands, + + + New command `plot_shock_decomposition` that allows plotting the + results from `shock_decomposition` and + `realtime_shock_decomposition` for different vintages and shock + groupings. + + + - Macroprocessor + + + Can now pass a macro-variable to the `@#include` macro directive, + + + New preprocessor flag `-I`, macro directive `@#includepath`, and + dynare config file block `[paths]` to pass a search path to the + macroprocessor to be used for file inclusion via `@#include`. + + + - Command line + + + New option `onlyclearglobals` (do not clear JIT compiled functions + with recent versions of Matlab), + + + New option `minimal_workspace` to use fewer variables in the + current workspace, + + + New option `params_derivs_order` allows limiting the order of the + derivatives with respect to the parameters that are calculated by + the preprocessor, + + + New command line option `mingw` to support the MinGW-w64 C/C++ + Compiler from TDM-GCC for `use_dll`. + + + - dates/dseries/reporting classes + + + New methods `abs`, `cumprod` and `chain`, + + + New option `tableRowIndent` to `addTable`, + + + Reporting system revamped and made more efficient, dependency on + matlab2tikz has been dropped. + + + - Optimization algorithms + + + `mode_compute=2` Uses the simulated annealing as described by + Corana et al. (1987), + + + `mode_compute=101` Uses SOLVEOPT as described by Kuntsevich and + Kappel (1997), + + + `mode_compute=102` Uses `simulannealbnd` from Matlab's Global + Optimization Toolbox (if available), + + + New option `silent_optimizer` to shut off output from mode + computing/optimization, + + + New options `verbosity` and `SaveFiles` to control output and + saving of files during mode computing/optimization. + + + - LaTeX output + + + New command `write_latex_original_model`, + + + New option `write_equation_tags` to `write_latex_dynamic_model` + that allows printing the specified equation tags to the generate + LaTeX code, + + + New command `write_latex_parameter_table` that writes the names and + values of model parameters to a LaTeX table, + + + New command `write_latex_prior_table` that writes the descriptive + statistics about the prior distribution to a LaTeX table, + + + New command `collect_latex_files` that creates one compilable LaTeX + file containing all TeX-output. + + + - Misc. + + + Provides 64bit preprocessor, + + + Introduces new path management to avoid conflicts with other + toolboxes, + + + Full compatibility with Matlab 2014b's new graphic interface, + + + When using `model(linear)`, Dynare automatically checks + whether the model is truly linear, + + + `usedll`, the `msvc` option now supports `normcdf`, `acosh`, + `asinh`, and `atanh`, + + + New parallel option `NumberOfThreadsPerJob` for Windows nodes that + sets the number of threads assigned to each remote MATLAB/Octave + run, + + + Improved numerical performance of + `schur_statespace_transformation` for very large models, + + + The `all_values_required` option now also works with `histval`, + + + Add missing `horizon` option to `ms_forecast`, + + + BVAR now saves the marginal data density in + `oo_.bvar.log_marginal_data_density` and stores prior and + posterior information in `oo_.bvar.prior` and + `oo_.bvar.posterior`. + + + +* Bugs and problems identified in version 4.4.3 and that have been fixed in version 4.5.0: + + + - BVAR models + + + `bvar_irf` could display IRFs in an unreadable way when they moved from + negative to positive values, + + + In contrast to what is stated in the documentation, the confidence interval + size `conf_sig` was 0.6 by default instead of 0.9. + + + - Conditional forecasts + + + The `conditional_forecast` command produced wrong results in calibrated + models when used at initial values outside of the steady state (given with + `initval`), + + + The `plot_conditional_forecast` option could produce unreadable figures if + the areas overlap, + + + The `conditional_forecast` command after MLE crashed, + + + In contrast to what is stated in the manual, the confidence interval size + `conf_sig` was 0.6 by default instead of 0.8. + + + Conditional forecasts were wrong when the declaration of endogenous + variables was not preceeding the declaration of the exogenous + variables and parameters. + + + - Discretionary policy + + + Dynare allowed running models where the number of instruments did not match + the number of omitted equations, + + + Dynare could crash in some cases when trying to display the solution, + + + Parameter dependence embedded via a `steady_state` was not taken into + account, typically resulting in crashes. + + - dseries class + + + When subtracting a dseries object from a number, the number was instead + subtracted from the dseries object. + + + - DSGE-VAR models + + + Dynare crashed when estimation encountered non-finite values in the Jacobian + at the steady state, + + + The presence of a constant was not considered for degrees of freedom + computation of the Gamma function used during the posterior computation; due + to only affecting the constant term, results should be be unaffected, except + for model_comparison when comparing models with and without. + + + - Estimation command + + + In contrast to what was stated in the manual, the confidence interval size + `conf_sig` for `forecast` without MCMC was 0.6 by default instead of 0.9, + + + Calling estimation after identification could lead to crashes, + + + When using recursive estimation/forecasting and setting some elements of + `nobs` to be larger than the number of observations T in the data, + `oo_recursive_` contained additional cell entries that simply repeated the + results obtained for `oo_recursive_T`, + + + Computation of Bayesian smoother could crash for larger models when + requesting `forecast` or `filtered_variables`, + + + Geweke convergence diagnostics were not computed on the full MCMC chain when + the `load_mh_file` option was used, + + + The Geweke convergence diagnostics always used the default `taper_steps` and + `geweke_interval`, + + + Bayesian IRFs (`bayesian_irfs` option) could be displayed in an unreadable + way when they move from negative to positive values, + + + If `bayesian_irfs` was requested when `mh_replic` was too low to compute + HPDIs, plotting was crashing, + + + The x-axis value in `oo_.prior_density` for the standard deviation and + correlation of measurement errors was written into a field + `mearsurement_errors_*` instead of `measurement_errors_*`, + + + Using a user-defined `mode_compute` crashed estimation, + + + Option `mode_compute=10` did not work with infinite prior bounds, + + + The posterior variances and covariances computed by `moments_varendo` were + wrong for very large models due to a matrix erroneously being filled up with + zeros, + + + Using the `forecast` option with `loglinear` erroneously added the unlogged + steady state, + + + When using the `loglinear` option the check for the presence of a constant + was erroneously based on the unlogged steady state, + + + Estimation of `observation_trends` was broken as the trends specified as a + function of deep parameters were not correctly updated during estimation, + + + When using `analytic_derivation`, the parameter values were not set before + testing whether the steady state file changes parameter values, leading to + subsequent crashes, + + + If the steady state of an initial parameterization did not solve, the + observation equation could erroneously feature no constant when the + `use_calibration` option was used, + + + When computing posterior moments, Dynare falsely displayed that moment + computations are skipped, although the computation was performed correctly, + + + If `conditional_variance_decomposition` was requested, although all + variables contain unit roots, Dynare crashed instead of providing an error + message, + + + Computation of the posterior parameter distribution was erroneously based + on more draws than specified (there was one additional draw for every Markov + chain), + + + The estimation option `lyapunov=fixed_point` was broken, + + + Computation of `filtered_vars` with only one requested step crashed Dynare, + + + Option `kalman_algo=3` was broken with non-diagonal measurement error, + + + When using the diffuse Kalman filter with missing observations, an additive + factor log(2*pi) was missing in the last iteration step, + + + Passing of the `MaxFunEvals` and `InitialSimplexSize` options to + `mode_compute=8` was broken, + + + Bayesian forecasts contained initial conditions and had the wrong length in + both plots and stored variables, + + + Filtered variables obtained with `mh_replic=0`, ML, or + `calibrated_smoother` were padded with zeros at the beginning and end and + had the wrong length in stored variables, + + + Computation of smoothed measurement errors in Bayesian estimation was broken, + + + The `selected_variables_only` option (`mh_replic=0`, ML, or + `calibrated_smoother`) returned wrong results for smoothed, updated, and + filtered variables, + + + Combining the `selected_variables_only` option with forecasts obtained + using `mh_replic=0`, ML, or `calibrated_smoother` leaded to crashes, + + + `oo_.UpdatedVariables` was only filled when the `filtered_vars` option was specified, + + + When using Bayesian estimation with `filtered_vars`, but without + `smoother`, then `oo_.FilteredVariables` erroneously also contained filtered + variables at the posterior mean as with `mh_replic=0`, + + + Running an MCMC a second time in the same folder with a different number of + iterations could result in crashes due to the loading of stale files, + + + Results displayed after Bayesian estimation when not specifying + the `smoother` option were based on the parameters at the mode + from mode finding instead of the mean parameters from the + posterior draws. This affected the smoother results displayed, but + also calls to subsequent command relying on the parameters stored + in `M_.params` like `stoch_simul`, + + + The content of `oo_.posterior_std` after Bayesian estimation was based on + the standard deviation at the posterior mode, not the one from the MCMC, this + was not consistent with the reference manual, + + + When the initialization of an MCMC run failed, the metropolis.log file was + locked, requiring a restart of Matlab to restart estimation, + + + If the posterior mode was right at the corner of the prior bounds, the + initialization of the MCMC erroneously crashed, + + + If the number of dropped draws via `mh_drop` coincided with the number of + draws in a `_mh'-file`, `oo_.posterior.metropolis.mean` and + `oo_.posterior.metropolis.Variance` were NaN. + + + - Estimation and calibrated smoother + + + When using `observation_trends` with the `prefilter` option, the mean shift + due to the trend was not accounted for, + + + When using `first_obs`>1, the higher trend starting point of + `observation_trends` was not taken into account, leading, among other things, + to problems in recursive forecasting, + + + The diffuse Kalman smoother was crashing if the forecast error variance + matrix becomes singular, + + + The multivariate Kalman smoother provided incorrect state estimates when + all data for one observation are missing, + + + The multivariate diffuse Kalman smoother provided incorrect state estimates + when the `Finf` matrix becomes singular, + + + The univariate diffuse Kalman filter was crashing if the initial covariance + matrix of the nonstationary state vector is singular, + + + - Forecats + + + In contrast to what is stated in the manual, the confidence interval size + `conf_sig` was 0.6 by default instead of 0.9. + + + Forecasting with exogenous deterministic variables provided wrong decision + rules, yielding wrong forecasts. + + + Forecasting with exogenous deterministic variables crashed when the + `periods` option was not explicitly specified, + + + Option `forecast` when used with `initval` was using the initial values in + the `initval` block and not the steady state computed from these initial + values as the starting point of forecasts. + + + - Global Sensitivity Analysis + + + Sensitivity with ML estimation could result in crashes, + + + Option `mc` must be forced if `neighborhood_width` is used, + + + Fixed dimension of `stock_logpo` and `stock_ys`, + + + Incomplete variable initialization could lead to crashes with `prior_range=1`. + + + - Indentification + + + Identification did not correctly pass the `lik_init` option, + requiring the manual setting of `options_.diffuse_filter=1` in + case of unit roots, + + + Testing identification of standard deviations as the only + parameters to be estimated with ML leaded to crashes, + + + Automatic increase of the lag number for autocovariances when the + number of parameters is bigger than the number of non-zero moments + was broken, + + + When using ML, the asymptotic Hessian was not computed, + + + Checking for singular values when the eigenvectors contained only + one column did not work correctly, + + + - Model comparison + + + Selection of the `modifiedharmonicmean` estimator was broken, + + + - Optimal Simple Rules + + + When covariances were specified, variables that only entered with + their variance and no covariance term obtained a wrong weight, + resulting in wrong results, + + + Results reported for stochastic simulations after `osr` were based + on the last parameter vector encountered during optimization, + which does not necessarily coincide with the optimal parameter + vector, + + + Using only one (co)variance in the objective function resulted in crashes, + + + For models with non-stationary variables the objective function was computed wrongly. + + + - Ramsey policy + + + If a Lagrange multiplier appeared in the model with a lead or a lag + of more than one period, the steady state could be wrong. + + + When using an external steady state file, incorrect steady states + could be accepted, + + + When using an external steady state file with more than one + instrument, Dynare crashed, + + + When using an external steady state file and running `stoch_simul` + after `ramsey_planner`, an incorrect steady state was used, + + + When the number of instruments was not equal to the number of + omitted equations, Dynare crashed with a cryptic message, + + + The `planner_objective` accepted `varexo`, but ignored them for computations, + + + - Shock decomposition + + + Did not work with the `parameter_set=calibration` option if an + `estimated_params` block is present, + + + Crashed after MLE. + + + - Perfect foresight models + + + The perfect foresight solver could accept a complex solution + instead of continuing to look for a real-valued one, + + + The `initval_file` command only accepted column and not row vectors, + + + The `initval_file` command did not work with Excel files, + + + Deterministic simulations with one boundary condition crashed in + `solve_one_boundary` due to a missing underscore when passing + `options_.simul.maxit`, + + + Deterministic simulation with exogenous variables lagged by more + than one period crashed, + + + Termination criterion `maxit` was hard-coded for `solve_algo=0` + and could no be changed, + + + When using `block`/`bytecode`, relational operators could not be enforced, + + + When using `block` some exceptions were not properly handled, + leading to code crashes, + + + Using `periods=1` crashed the solver (bug only partially fixed). + + + - Smoothing + + + The univariate Kalman smoother returned wrong results when used + with correlated measurement error, + + + The diffuse smoother sometimes returned linear combinations of the + smoothed stochastic trend estimates instead of the original trend + estimates. + + - Perturbation reduced form + + + In contrast to what is stated in the manual, the results of the + unconditional variance decomposition were only stored in + `oo_.gamma_y(nar+2)`, not in `oo_.variance_decomposition`, + + + Dynare could crash when the steady state could not be computed + when using the `loglinear` option, + + + Using `bytcode` when declared exogenous variables were not + used in the model leaded to crashes in stochastic simulations, + + + Displaying decision rules involving lags of auxiliary variables of + type 0 (leads>1) crashed. + + + The `relative_irf` option resulted in wrong output at `order>1` as + it implicitly relies on linearity. + + + - Displaying of the MH-history with the `internals` command crashed + if parameter names did not have same length. + + - Dynare crashed when the user-defined steady state file returned an + error code, but not an conformable-sized steady state vector. + + - Due to a bug in `mjdgges.mex` unstable parameter draws with + eigenvalues up to 1+1e-6 could be accepted as stable for the + purpose of the Blanchard-Kahn conditions, even if `qz_criterium<1`. + + - The `use_dll` option on Octave for Windows required to pass a + compiler flag at the command line, despite the manual stating this + was not necessary. + + - Dynare crashed for models with `block` option if the Blanchard-Kahn + conditions were not satisfied instead of generating an error + message. + + - The `verbose` option did not work with `model(block)`. + + - When falsely specifying the `model(linear)` for nonlinear models, + incorrect steady states were accepted instead of aborting. + + - The `STEADY_STATE` operator called on model local variables + (so-called pound variables) did not work as expected. + + - The substring operator in macro-processor was broken. The + characters of the substring could be mixed with random characters + from the memory space. + + - Block decomposition could sometimes cause the preprocessor to crash. + + - A bug when external functions were used in model local variables + that were contained in equations that required auxiliary + variable/equations led to crashes of Matlab. + + - Sampling from the prior distribution for an inverse gamma II + distribution when `prior_trunc>0` could result in incorrect + sampling. + + - Sampling from the prior distribution for a uniform distribution + when `prior_trunc>0` was ignoring the prior truncation. + + - Conditional forecasts were wrong when the declaration of endogenous + variables was not preceeding the declaration of the exogenous + variables and parameters. + + + Announcement for Dynare 4.4.3 (on 2014-07-31) ============================================= @@ -988,7 +1785,7 @@ Here is a list of the main bugfixes since version 4.2.0: * Option `conditional_variance_decomposition' of `stoch_simul' and `estimation' has been fixed - + * Automatic detrending now works in conjunction with the `EXPECTATION' operator @@ -1029,7 +1826,7 @@ This release is compatible with MATLAB versions ranging from 6.5 (R13) to 7.11 Here is the list of major user-visible changes: -* New solution algorithms: +* New solution algorithms: - Pruning for second order simulations has been added, as described in Kim, Kim, Schaumburg and Sims (2008) [1,2] @@ -1066,7 +1863,7 @@ Here is the list of major user-visible changes: - Syntax of deterministic shocks has changed: after the values keyword, arbitrary expressions must be enclosed within parentheses (but numeric - constants are still accepted as is) + constants are still accepted as is) * Various improvements: @@ -1095,7 +1892,7 @@ Here is the list of major user-visible changes: from the console, it will replace graphical waitbars by text waitbars for long computations - - Steady option "solve_algo=0" (uses fsolve()) now works under Octave + - Steady option "solve_algo=0" (uses fsolve()) now works under Octave * For Emacs users: diff --git a/README.md b/README.md index 202ed7d5b..9b4d3aed0 100644 --- a/README.md +++ b/README.md @@ -303,7 +303,7 @@ After this, prepare the source and configure the build tree as described for Lin - **NB**: If not compiling Dynare mex files for Octave, add ```--without-octave``` to the installation command - **NB**: To compile the latest stable version of dynare, follow the same instructions as above, omitting the ```--HEAD``` argument - **NB**: To update a ```--HEAD``` install of dynare you need to uninstall it then install it again: ```brew uninstall dynare; brew install dynare --HEAD```. -- **NB**: If you want to maintain a separate git directory of dynare, you can do a ```--HEAD``` install of dynare, then uninstall it. This will have the effect of bringing in all the dependencies you will need to then compile dynare from your git directory. Then, change to the git directory and type: +- **NB**: If you want to maintain a separate git directory of dynare, you can do a ```--HEAD``` install of dynare, then uninstall it. This will have the effect of bringing in all the dependencies you will need to then compile dynare from your git directory. (For `flex` and `bison` it may be necessary to symlink them via `brew link bison --force` and `brew link flex --force` as they are keg-only). Then, change to the git directory and type: - ```autoreconf -si; ./configure --with-matlab=/Applications/MATLAB_R2015a.app MATLAB_VERSION=R2015a```, adjusting the Matlab path and version to accord with your version - Once compilation is done, open Matlab and type the last line shown when you type ```brew info dynare``` in the Terminal window. With the typical Homebrew setup, this is: - ```addpath /usr/local/opt/dynare/lib/dynare/matlab``` diff --git a/VERSION.in b/VERSION.in new file mode 100644 index 000000000..7b4f3f3a0 --- /dev/null +++ b/VERSION.in @@ -0,0 +1 @@ +@PACKAGE_VERSION@ \ No newline at end of file diff --git a/configure.ac b/configure.ac index a29888519..4ddf92682 100755 --- a/configure.ac +++ b/configure.ac @@ -18,7 +18,7 @@ dnl You should have received a copy of the GNU General Public License dnl along with Dynare. If not, see . AC_PREREQ([2.62]) -AC_INIT([dynare], [4.5-unstable]) +AC_INIT([dynare], [4.6-unstable]) AC_CONFIG_SRCDIR([preprocessor/DynareMain.cc]) AM_INIT_AUTOMAKE([1.11 -Wall -Wno-portability foreign no-dist-gzip dist-xz tar-pax]) @@ -172,6 +172,7 @@ esac AX_PTHREAD AC_CONFIG_FILES([Makefile + VERSION preprocessor/macro/Makefile preprocessor/Makefile doc/Makefile diff --git a/doc/bvar-a-la-sims.tex b/doc/bvar-a-la-sims.tex index 6caf4d8b2..b58b83b75 100644 --- a/doc/bvar-a-la-sims.tex +++ b/doc/bvar-a-la-sims.tex @@ -12,7 +12,7 @@ \begin{document} \title{BVAR models ``\`a la Sims'' in Dynare\thanks{Copyright \copyright~2007--2015 S\'ebastien - Villemot; \copyright~2016 S\'ebastien + Villemot; \copyright~2016--2017 S\'ebastien Villemot and Johannes Pfeifer. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free @@ -27,7 +27,7 @@ \author{S\'ebastien Villemot\thanks{Paris School of Economics and CEPREMAP.} \and Johannes Pfeifer\thanks{University of Cologne. E-mail: \href{mailto:jpfeifer@uni-koeln.de}{\texttt{jpfeifer@uni-koeln.de}}.}} -\date{First version: September 2007 \hspace{1cm} This version: October 2016} +\date{First version: September 2007 \hspace{1cm} This version: May 2017} \maketitle @@ -545,7 +545,7 @@ Most results are stored for future use: The syntax for computing impulse response functions is: \medskip -\texttt{bvar\_irf(}\textit{number\_of\_periods},\textit{identification\_scheme}\texttt{);} +\texttt{bvar\_irf(}\textit{number\_of\_lags},\textit{identification\_scheme}\texttt{);} \medskip The \textit{identification\_scheme} option has two potential values @@ -556,7 +556,25 @@ The \textit{identification\_scheme} option has two potential values Keep in mind that the first factorization of the covariance matrix is sensible to the ordering of the variables (as declared in the mod file with \verb+var+). This is not the case of the second factorization, but its structural interpretation is, at best, unclear (the Matrix square root of a covariance matrix, $\Sigma$, is the unique symmetric matrix $A$ such that $\Sigma = AA$).\newline -The mean, median, variance and confidence intervals for IRFs are saved in \texttt{oo\_.bvar.irf} +If you want to change the length of the IRFs plotted by the command, you can put\\ + +\medskip +\texttt{options\_.irf=40;}\\ +\medskip + +before the \texttt{bvar\_irf}-command. Similarly, to change the coverage of the highest posterior density intervals to e.g. 60\% you can put the command\\ + +\medskip +\texttt{options\_.bvar.conf\_sig=0.6;}\\ +\medskip + +there.\newline + + +The mean, median, variance, and confidence intervals for IRFs are saved in \texttt{oo\_.bvar.irf} + + + \section{Examples} diff --git a/doc/dynare.texi b/doc/dynare.texi index dd1fc71e7..9e83da8e2 100644 --- a/doc/dynare.texi +++ b/doc/dynare.texi @@ -6114,7 +6114,7 @@ singularity is encountered, Dynare by default automatically switches to the univ recursions as described by @cite{Herbst, 2015}. This setting is only used with @code{kalman_algo=1} or @code{kalman_algo=3}. In case of using the diffuse Kalman filter (@code{kalman_algo=3/lik_init=3}), the observables must be stationary. This option -is not yet compatible with @code{analytical_derivation}. +is not yet compatible with @ref{analytic_derivation}. @item kalman_tol = @var{DOUBLE} @anchor{kalman_tol} Numerical tolerance for determining the singularity of the covariance matrix of the prediction errors during the Kalman filter (minimum allowed reciprocal of the matrix condition number). Default value is @code{1e-10} @@ -6260,9 +6260,10 @@ where the model is ill-behaved. By default the original objective function is used. @item analytic_derivation +@anchor{analytic_derivation} Triggers estimation with analytic gradient. The final hessian is also computed analytically. Only works for stationary models without -missing observations. +missing observations, i.e. for @code{kalman_algo<3}. @item ar = @var{INTEGER} @xref{ar}. Only useful in conjunction with option @code{moments_varendo}. diff --git a/dynare++/kord/journal.cweb b/dynare++/kord/journal.cweb index b43b27bcc..3fb666bb7 100644 --- a/dynare++/kord/journal.cweb +++ b/dynare++/kord/journal.cweb @@ -101,7 +101,11 @@ void SystemResources::getRUS(double& load_avg, long int& pg_avail, majflt = -1; #endif -#if !defined(__MINGW32__) && !defined(__CYGWIN32__) && !defined(__CYGWIN__) && !defined(__MINGW64__) && !defined(__CYGWIN64__) + +#define MINGCYGTMP (!defined(__MINGW32__) && !defined(__CYGWIN32__) && !defined(__CYGWIN__)) +#define MINGCYG (MINGCYGTMP && !defined(__MINGW64__) && !defined(__CYGWIN64__)) + +#if MINGCYG getloadavg(&load_avg, 1); #else load_avg = -1.0; diff --git a/license.txt b/license.txt index b284e9f24..486f3242e 100644 --- a/license.txt +++ b/license.txt @@ -1,16 +1,15 @@ Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Name: Dynare -Upstream-Contact: Dynare Team, whose members in 2016 are: +Upstream-Contact: Dynare Team, whose members in 2017 are: Stéphane Adjemian Houtan Bastani Michel Juillard Frédéric Karamé Junior Maih Ferhat Mihoubi - George Perendia Johannes Pfeifer - Marco Ratto - Sébastien Villemot + Marco Ratto + Sébastien Villemot Source: http://www.dynare.org Files: * @@ -205,7 +204,7 @@ License: permissive Unlimited permission is granted to everyone to use, copy, modify or distribute this software. -Files: matlab/utilities\graphics\distinguishable_colors.m +Files: matlab/utilities/graphics/distinguishable_colors.m Copyright 2010-2011 by Timothy E. Holy All rights reserved. Redistribution and use in source and binary forms, with or without @@ -228,7 +227,7 @@ 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. -Files: matlab/utilities\graphics\colorspace.m +Files: matlab/utilities/graphics/colorspace.m Pascal Getreuer 2005-2010 All rights reserved. Redistribution and use in source and binary forms, with or without diff --git a/matlab/@dynTimeIndex/display.m b/matlab/@dynTimeIndex/display.m deleted file mode 100644 index 87162fd40..000000000 --- a/matlab/@dynTimeIndex/display.m +++ /dev/null @@ -1,20 +0,0 @@ -function display(t) - -% Copyright (C) 2013 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 . - -fprintf('%s = \n', inputname(1), int2str(t.index)); diff --git a/matlab/@dynTimeIndex/dynTimeIndex.m b/matlab/@dynTimeIndex/dynTimeIndex.m deleted file mode 100644 index 323122c4b..000000000 --- a/matlab/@dynTimeIndex/dynTimeIndex.m +++ /dev/null @@ -1,61 +0,0 @@ -function t = dynTimeIndex() % --*-- Unitary tests --*-- - -% t = dynTimeIndex() -% -% Constructor for the dynTimeIndex class. -% -% INPUTS: -% None. -% -% OUTPUTS: -% * t, dynTimeIndex object. -% -% DESCRIPTION: -% The dynTimeIndex object is used to shift backward or forward dseries objects. For instance, if ts -% is a dseries object and t is a dynTimeIndex object then the following expressions are equivalent: -% -% us = ts.lag() -% us = ts.lag(1) -% us = lag(ts,1) -% us = ts(t-1) -% -% This class has only one member: t = int8(0) when instantiated. - -% Copyright (C) 2013 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 . - -t = struct(); - -t.index = int8(0); - -t = class(t,'dynTimeIndex'); - -%@test:1 -%$ % Instantiate a dynTimeIndex object -%$ try -%$ u = dynTimeIndex(); -%$ t(1) = 1; -%$ catch -%$ t(1) = 0; -%$ end -%$ -%$ if t(1) -%$ t(2) = isa(u,'dynTimeIndex'); -%$ end -%$ -%$ T = all(t); -%@eof:1 \ No newline at end of file diff --git a/matlab/@dynTimeIndex/minus.m b/matlab/@dynTimeIndex/minus.m deleted file mode 100644 index dff65f42d..000000000 --- a/matlab/@dynTimeIndex/minus.m +++ /dev/null @@ -1,62 +0,0 @@ -function C = minus(A,B) % --*-- Unitary tests --*-- - -% C = minus(A,B) -% -% Overloads binary minus operator. -% -% INPUTS: -% * A, dynTimeIndex object. -% * B, integer scalar. -% -% OUTPUTS: -% * C, dynTimeIndex object. -% -% EXAMPLE: -% -% >> t = dynTimeIndex(); -% >> t.index -% -% ans = -% -% 0 -% -% >> s = t-1; -% >> s.index -% -% ans = -% -% -1 -% - -% Copyright (C) 2013 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 . - -if ~(isa(A,'dynTimeIndex') || isint(B)) - error(['dynTimeIndex::plus: Input arguments ''' inputname(1) ''' and ''' inputname(2) ''' must be a dynTimeIndex object and an integer!']) -end - -C = struct(); -C.index = A.index-B; -C = class(C,'dynTimeIndex'); - -%@test:1 -%$ a = dynTimeIndex(); -%$ b = a-1; -%$ t(1) = isa(b,'dynTimeIndex'); -%$ t(2) = isequal(b.index,-int8(1)); -%$ T = all(t); -%@eof:1 \ No newline at end of file diff --git a/matlab/@dynTimeIndex/mpower.m b/matlab/@dynTimeIndex/mpower.m deleted file mode 100644 index c4077caaa..000000000 --- a/matlab/@dynTimeIndex/mpower.m +++ /dev/null @@ -1,74 +0,0 @@ -function C = mpower(A,B) % --*-- Unitary tests --*-- - -% C = mpower(A,B) -% -% Overloads binary mpower operator (^). -% -% INPUTS : -% * A, dynTimeIndex object. -% * B, integer scalar. -% -% OUTPUTS : -% * C, dynTimeIndex object. -% -% EXAMPLE 1 : -% -% >> B = dynTimeIndex()-1; -% >> B -% B = -% >> B^4 -% ans = -% >> -% -% EXAMPLE 2 : -% This method can be used to apply the lead and lag methods an arbitrary number of times to a dseries object. For instance, if -% ts is a dseries object, and if we define -% -% >> B = dynTimeIndex()-1; -% >> F = dynTimeIndex()+1; -% -% B and F can be used as lag and lead operators and the following syntax: -% -% >> us = ts(F^2); -% -% is equivalent to -% -% >> us = ts.lead(2) -% -% or -% -% >> us = ts.lead.lead -% - -% Copyright (C) 2013 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 . - -if ~(isa(A,'dynTimeIndex') || isint(B)) - error(['dynTimeIndex::mpower: Input arguments ''' inputname(1) ''' and ''' inputname(2) ''' must be a dynTimeIndex object and an integer!']) -end - -C = struct(); -C.index = A.index*B; -C = class(C,'dynTimeIndex'); - -%@test:1 -%$ a = dynTimeIndex()+1; -%$ b = a^2; -%$ t(1) = isa(b,'dynTimeIndex'); -%$ t(2) = isequal(b.index,int8(2)); -%$ T = all(t); -%@eof:1 \ No newline at end of file diff --git a/matlab/@dynTimeIndex/plus.m b/matlab/@dynTimeIndex/plus.m deleted file mode 100644 index 7b4752db9..000000000 --- a/matlab/@dynTimeIndex/plus.m +++ /dev/null @@ -1,62 +0,0 @@ -function C = plus(A,B) % --*-- Unitary tests --*-- - -% C = plus(A,B) -% -% Overloads binary plus operator. -% -% INPUTS: -% * A, dynTimeIndex object. -% * B, integer scalar. -% -% OUTPUTS: -% * C, dynTimeIndex object. -% -% EXAMPLE: -% -% >> t = dynTimeIndex(); -% >> t.index -% -% ans = -% -% 0 -% -% >> s = t+1; -% >> s.index -% -% ans = -% -% 1 -% - -% Copyright (C) 2013 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 . - -if ~(isa(A,'dynTimeIndex') || isint(B)) - error(['dynTimeIndex::plus: Input arguments ''' inputname(1) ''' and ''' inputname(2) ''' must be a dynTimeIndex object and an integer!']) -end - -C = struct(); -C.index = A.index+B; -C = class(C,'dynTimeIndex'); - -%@test:1 -%$ a = dynTimeIndex(); -%$ b = a+1; -%$ t(1) = isa(b,'dynTimeIndex'); -%$ t(2) = isequal(b.index,int8(1)); -%$ T = all(t); -%@eof:1 \ No newline at end of file diff --git a/matlab/@dynTimeIndex/subsasgn.m b/matlab/@dynTimeIndex/subsasgn.m deleted file mode 100644 index 101468062..000000000 --- a/matlab/@dynTimeIndex/subsasgn.m +++ /dev/null @@ -1,20 +0,0 @@ -function val = subsasgn(val, idx, rhs) - -% Copyright (C) 2013 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 . - -error('dynTimeIndex::subsasgn: Members of dynTimeIndex class are private!') \ No newline at end of file diff --git a/matlab/@dynTimeIndex/subsref.m b/matlab/@dynTimeIndex/subsref.m deleted file mode 100644 index bae6edc56..000000000 --- a/matlab/@dynTimeIndex/subsref.m +++ /dev/null @@ -1,54 +0,0 @@ -function B = subsref(A,S) % --*-- Unitary tests --*-- - -% B = subsref(A,S) -% -% Overloads the subsref method for dynTimeIndex class. This method only allows to get -% the value of the field `index`. - -% Copyright (C) 2013 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 . - -if length(S)>1 - error('dynTimeIndex::subsref: Something is wrong in your syntax!') -end - -if isequal(S.type,'.') - if isequal(S.subs,'index') - B = builtin('subsref', A, S(1)); - else - error(['dynTimeIndex::subsref: ' S.subs ' is not a known member!']) - end -else - error('dynTimeIndex::subsref: Something is wrong in your syntax!') -end - -%@test:1 -%$ % Instantiate a dynTimeIndex object -%$ u = dynTimeIndex(); -%$ try -%$ v = u.index; -%$ t(1) = 1; -%$ catch -%$ t(1) = 0; -%$ end -%$ -%$ if t(1) -%$ t(2) = isequal(v,int8(0)); -%$ end -%$ -%$ T = all(t); -%@eof:1 \ No newline at end of file diff --git a/matlab/AHessian.m b/matlab/AHessian.m index be59603fd..890dc92d7 100644 --- a/matlab/AHessian.m +++ b/matlab/AHessian.m @@ -8,7 +8,7 @@ function [AHess, DLIK, LIK] = AHessian(T,R,Q,H,P,Y,DT,DYss,DOm,DH,DP,start,mf,ka % NOTE: the derivative matrices (DT,DR ...) are 3-dim. arrays with last % dimension equal to the number of structural parameters -% Copyright (C) 2011-2016 Dynare Team +% Copyright (C) 2011-2017 Dynare Team % % This file is part of Dynare. % @@ -39,7 +39,7 @@ 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, +if nargout > 1 DLIK = zeros(k,1); % Initialization of the score. end AHess = zeros(k,k); % Initialization of the Hessian @@ -47,7 +47,7 @@ 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=start AHess = AHess + Dv'*iF*Dv + .5*(vecDPmf' * kron(iF,iF) * vecDPmf); end - a = T*(a+K*v); + a = T*(a+K*v); P = T*(P-K*P(mf,:))*transpose(T)+Om; DP = DP1; end @@ -107,8 +105,8 @@ if t < smpl end end if t>=start - AHess = AHess + Dv'*iF*Dv; - end + AHess = AHess + Dv'*iF*Dv; + end a = T*(a+K*v); lik(t) = transpose(v)*iF*v; end @@ -124,17 +122,17 @@ if t < smpl % H(ii,jj) = trace(iPmf*(.5*DP(mf,mf,ii)*iPmf*DP(mf,mf,jj) + Dv(:,ii)*Dv(:,jj)')); % end % end -end +end -AHess = -AHess; -if nargout > 1, +AHess = -AHess; +if nargout > 1 DLIK = DLIK/2; end % adding log-likelihhod constants 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) @@ -142,13 +140,11 @@ 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); DP1(:,:,ii) = DT(:,:,ii)*tmp*T' + T*Dtmp*T' + T*tmp*DT(:,:,ii)' + DOm(:,:,ii); end -% end of computeDKalman - - +% end of computeDKalman \ No newline at end of file diff --git a/matlab/AIM/SPAimerr.m b/matlab/AIM/SPAimerr.m index fb2070527..646747928 100644 --- a/matlab/AIM/SPAimerr.m +++ b/matlab/AIM/SPAimerr.m @@ -1,4 +1,4 @@ -function e = SPAimerr(c); +function e = SPAimerr(c) % e = aimerr(c); % % Interpret the return codes generated by the aim routines. diff --git a/matlab/AIM/SPAmalg.m b/matlab/AIM/SPAmalg.m index 19cc958fe..c371a91b0 100644 --- a/matlab/AIM/SPAmalg.m +++ b/matlab/AIM/SPAmalg.m @@ -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. @@ -66,26 +66,26 @@ bcols=neq*nlag;q=zeros(qrows,qcols);rts=zeros(qcols,1); [h,q,iq,nexact]=SPExact_shift(h,q,iq,qrows,qcols,neq); if (iq>qrows) aimcode = 61; - return; + return end [h,q,iq,nnumeric]=SPNumeric_shift(h,q,iq,qrows,qcols,neq,condn); if (iq>qrows) aimcode = 62; - return; + return 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'); + if flag_trouble==1 + 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 b4d61ad92..5701d3bf1 100644 --- a/matlab/AIM/SPBuild_a.m +++ b/matlab/AIM/SPBuild_a.m @@ -51,7 +51,7 @@ 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; diff --git a/matlab/AIM/SPCopy_w.m b/matlab/AIM/SPCopy_w.m index d7da8c647..82dafe40a 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: diff --git a/matlab/AIM/SPEigensystem.m b/matlab/AIM/SPEigensystem.m index 2ef1676ce..61dd46069 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); @@ -56,7 +56,7 @@ 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 876d9ca4f..5ba49aa11 100644 --- a/matlab/AIM/SPExact_shift.m +++ b/matlab/AIM/SPExact_shift.m @@ -44,4 +44,3 @@ while( any(zerorows) && iq <= qrows ) zerorows = find( sum(abs( hs(:,right)' ))==0 ); end h=full(hs); - diff --git a/matlab/AIM/SPObstruct.m b/matlab/AIM/SPObstruct.m index ea8252856..9d9206501 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,7 +51,7 @@ qs=sparse(q); qs(1:rc,1:cc) = sparse(cofb); qcols = neq*(nlag+nlead); -if( nlead > 1 ) +if( nlead > 1 ) for i = 1:nlead-1 rows = i*neq + (1:neq); qs(rows,:) = SPShiftright( qs((rows-neq),:), neq ); diff --git a/matlab/AIM/SPReduced_form.m b/matlab/AIM/SPReduced_form.m index 8d529fc4e..e7d60a180 100644 --- a/matlab/AIM/SPReduced_form.m +++ b/matlab/AIM/SPReduced_form.m @@ -1,4 +1,4 @@ -function [nonsing,b] = SPReduced_form(q,qrows,qcols,bcols,neq,condn); +function [nonsing,b] = SPReduced_form(q,qrows,qcols,bcols,neq,condn) % [nonsing,b] = SPReduced_form(q,qrows,qcols,bcols,neq,b,condn); % % Compute reduced-form coefficient matrix, b. @@ -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 8299ce516..704908484 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 2e23e0222..52a2ae6f9 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,22 +31,22 @@ 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 +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -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 51993d119..893deefb0 100644 --- a/matlab/AIM_first_order_solver.m +++ b/matlab/AIM_first_order_solver.m @@ -51,7 +51,7 @@ function [dr,info]=AIM_first_order_solver(jacobia,M,dr,qz_criterium) %! @end deftypefn %@eod: -% Copyright (C) 2001-2016 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -91,11 +91,10 @@ if nba ~= nsfwrd if nba > nsfwrd temp = temp(nd-nba+1:nd-nsfwrd)-1-qz_criterium; info(1) = 3; - elseif nba < nsfwrd; + 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 c83005513..002c9bd17 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 @@ -12,7 +12,7 @@ function [DirectoryName, info] = CheckPath(type,dname) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2005-2013 Dynare Team +% Copyright (C) 2005-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/CutSample.m b/matlab/CutSample.m index 5ec0881a8..1582ec883 100644 --- a/matlab/CutSample.m +++ b/matlab/CutSample.m @@ -16,7 +16,7 @@ function CutSample(M_, options_, estim_params_) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2005-2015 Dynare Team +% Copyright (C) 2005-2017 Dynare Team % % This file is part of Dynare. % @@ -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 d3894bc08..997904afc 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,36 +29,36 @@ 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 -% Copyright (C) 2006-2016 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -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)) % @@ -256,7 +256,7 @@ if kalman_algo == 2 || kalman_algo == 4 else Pstar = blkdiag(Pstar,H); if ~isempty(Pinf) - Pinf = blkdiag(Pinf,zeros(vobs)); + Pinf = blkdiag(Pinf,zeros(vobs)); end end %now reset H to 0 @@ -265,7 +265,7 @@ if kalman_algo == 2 || kalman_algo == 4 %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 88e80f918..0408da509 100644 --- a/matlab/GetAllPosteriorDraws.m +++ b/matlab/GetAllPosteriorDraws.m @@ -5,18 +5,18 @@ 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 -% Copyright (C) 2005-2011 Dynare Team +% Copyright (C) 2005-2017 Dynare Team % % This file is part of Dynare. % @@ -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 82d4c088f..f8e2a0d63 100644 --- a/matlab/GetOneDraw.m +++ b/matlab/GetOneDraw.m @@ -5,15 +5,15 @@ 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 -% Copyright (C) 2005-2015 Dynare Team +% Copyright (C) 2005-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/GetPosteriorMeanVariance.m b/matlab/GetPosteriorMeanVariance.m index 285b94480..22d9e6004 100644 --- a/matlab/GetPosteriorMeanVariance.m +++ b/matlab/GetPosteriorMeanVariance.m @@ -1,6 +1,6 @@ function [mean,variance] = GetPosteriorMeanVariance(M,drop) -% Copyright (C) 2012-2016 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/GetPosteriorParametersStatistics.m b/matlab/GetPosteriorParametersStatistics.m index a7c910621..6bea8d66a 100644 --- a/matlab/GetPosteriorParametersStatistics.m +++ b/matlab/GetPosteriorParametersStatistics.m @@ -1,22 +1,22 @@ 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. -% Copyright (C) 2006-2016 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -34,7 +34,7 @@ function oo_ = GetPosteriorParametersStatistics(estim_params_, M_, options_, bay % along with Dynare. If not, see . %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,:)); @@ -163,7 +163,7 @@ if nvx end disp(sprintf(pformat,header_width,name,bayestopt_.p1(ip),post_mean,hpd_interval,... pnames(bayestopt_.pshape(ip)+1,:),bayestopt_.p2(ip))); - if TeX, + if TeX name = deblank(M_.exo_names_tex(k,:)); TeXCore(fid,name,deblank(pnames(bayestopt_.pshape(ip)+1,:)),bayestopt_.p1(ip),... bayestopt_.p2(ip),post_mean,sqrt(post_var),hpd_interval); @@ -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 @@ -311,15 +311,15 @@ if ncn end disp(sprintf(pformat, header_width,name,bayestopt_.p1(ip),post_mean,hpd_interval, ... pnames(bayestopt_.pshape(ip)+1,:),bayestopt_.p2(ip))); - if TeX, + 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 89f35dac6..6c3de53ab 100644 --- a/matlab/MakeAllFigures.m +++ b/matlab/MakeAllFigures.m @@ -1,6 +1,6 @@ function MakeAllFigures(NumberOfPlots,Caption,FigureProperties,Info) -% Copyright (C) 2005-2009 Dynare Team +% Copyright (C) 2005-2017 Dynare Team % % This file is part of Dynare. % @@ -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 d2e89ea00..84ff775ea 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); @@ -151,13 +151,13 @@ for i=1:npar title(nam,'Interpreter','none'); hold off; drawnow - if subplotnum == MaxNumberOfPlotPerFigure || i == npar; + if subplotnum == MaxNumberOfPlotPerFigure || i == npar dyn_saveas(hfig,[OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber)],options_.nodisplay,options_.graph_format); if TeX && any(strcmp('eps',cellstr(options_.graph_format))) 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 1d51f5967..157a5e3a1 100644 --- a/matlab/PosteriorIRF.m +++ b/matlab/PosteriorIRF.m @@ -16,7 +16,7 @@ function PosteriorIRF(type) % functions associated with it(the _core1 and _core2). % See also the comments posterior_sampler.m funtion. -% Copyright (C) 2006-2016 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -178,7 +178,7 @@ if strcmpi(type,'posterior') end end -if ~strcmpi(type,'prior'), +if ~strcmpi(type,'prior') localVars.x=x; end @@ -202,16 +202,16 @@ localVars.ifil2=ifil2; localVars.MhDirectoryName=MhDirectoryName; % Like sequential execution! -if isnumeric(options_.parallel), +if isnumeric(options_.parallel) [fout] = PosteriorIRF_core1(localVars,1,B,0); nosaddle = fout.nosaddle; else % Parallel execution! [nCPU, totCPU, nBlockPerCPU] = distributeJobs(options_.parallel, 1, B); - for j=1:totCPU-1, + for j=1:totCPU-1 nfiles = ceil(nBlockPerCPU(j)/MAX_nirfs_dsge); NumberOfIRFfiles_dsge(j+1) =NumberOfIRFfiles_dsge(j)+nfiles; - if MAX_nirfs_dsgevar, + if MAX_nirfs_dsgevar nfiles = ceil(nBlockPerCPU(j)/MAX_nirfs_dsgevar); else nfiles=0; @@ -236,8 +236,8 @@ else NamFileInput(1,:) = {'',[M_.fname '_static.m']}; NamFileInput(2,:) = {'',[M_.fname '_dynamic.m']}; NamFileInput(3,:) = {'',[M_.fname '_set_auxiliary_variables.m']}; - if options_.steadystate_flag, - if options_.steadystate_flag == 1, + if options_.steadystate_flag + if options_.steadystate_flag == 1 NamFileInput(length(NamFileInput)+1,:)={'',[M_.fname '_steadystate.m']}; else NamFileInput(length(NamFileInput)+1,:)={'',[M_.fname '_steadystate2.m']}; @@ -245,7 +245,7 @@ else end [fout] = masterParallel(options_.parallel, 1, B,NamFileInput,'PosteriorIRF_core1', localVars, globalVars, options_.parallel_info); nosaddle=0; - for j=1:length(fout), + for j=1:length(fout) nosaddle = nosaddle + fout(j).nosaddle; end @@ -408,9 +408,9 @@ if ~options_.nograph && ~options_.no_graph.posterior 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'); + + if subplotnum == 1 + fprintf(fidTeX,'\\begin{figure}[H]\n'); end name = deblank(varlist(jj,:)); texname = deblank(varlist_TeX(jj,:)); @@ -418,7 +418,7 @@ if ~options_.nograph && ~options_.no_graph.posterior 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 @@ -429,9 +429,9 @@ if ~options_.nograph && ~options_.no_graph.posterior 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 end fprintf(fidTeX,'%% End of TeX file.\n'); @@ -443,11 +443,11 @@ if ~options_.nograph && ~options_.no_graph.posterior % Comment for testing! if ~isoctave - if isnumeric(options_.parallel) || (M_.exo_nbr*ceil(size(varlist,1)/MaxNumberOfPlotPerFigure))<8, + 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), + for indPC=1:length(options_.parallel) isRemoteOctave = isRemoteOctave + (findstr(options_.parallel(indPC).MatlabOctavePath, 'octave')); end if isRemoteOctave diff --git a/matlab/PosteriorIRF_core1.m b/matlab/PosteriorIRF_core1.m index 37f98209b..561104f67 100644 --- a/matlab/PosteriorIRF_core1.m +++ b/matlab/PosteriorIRF_core1.m @@ -23,7 +23,7 @@ function myoutput=PosteriorIRF_core1(myinputs,fpar,B,whoiam, ThisMatlab) % SPECIAL REQUIREMENTS. % None. % -% Copyright (C) 2006-2016 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -43,7 +43,7 @@ function myoutput=PosteriorIRF_core1(myinputs,fpar,B,whoiam, ThisMatlab) global options_ estim_params_ oo_ M_ bayestopt_ dataset_ dataset_info -if nargin<4, +if nargin<4 whoiam=0; end @@ -55,7 +55,7 @@ irun =myinputs.irun; irun2=myinputs.irun2; npar=myinputs.npar; type=myinputs.type; -if ~strcmpi(type,'prior'), +if ~strcmpi(type,'prior') x=myinputs.x; end @@ -102,7 +102,7 @@ end RemoteFlag = 0; if whoiam - if Parallel(ThisMatlab).Local==0, + if Parallel(ThisMatlab).Local==0 RemoteFlag =1; end prct0={0,whoiam,Parallel(ThisMatlab)}; @@ -165,7 +165,7 @@ while fpar 0) figunumber = figunumber+1; dyn_saveas(hh,[DirectoryName '/' M_.fname '_Bayesian_IRF_' deblank(tit(i,:)) '_' int2str(figunumber)],options_.nodisplay,options_.graph_format); - if RemoteFlag==1, + if RemoteFlag==1 OutputFileName = [OutputFileName; {[DirectoryName,filesep], [M_.fname '_Bayesian_IRF_' deblank(tit(i,:)) '_' int2str(figunumber) '.*']}]; end subplotnum = 0; end end% loop over selected endo_var - if whoiam, + 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)); diff --git a/matlab/ReshapeMatFiles.m b/matlab/ReshapeMatFiles.m index 1ad90fce1..1d127a67b 100644 --- a/matlab/ReshapeMatFiles.m +++ b/matlab/ReshapeMatFiles.m @@ -18,14 +18,14 @@ function ReshapeMatFiles(type, type2) % posterior % gsa % prior -% +% % OUTPUTS: -% none +% none % % SPECIAL REQUIREMENTS % none -% Copyright (C) 2003-2011 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -44,15 +44,15 @@ function ReshapeMatFiles(type, type2) global M_ options_ -if nargin==1, +if nargin==1 MhDirectoryName = [ CheckPath('metropolis',M_.dname) filesep ]; else if strcmpi(type2,'posterior') MhDirectoryName = [CheckPath('metropolis',M_.dname) filesep ]; elseif strcmpi(type2,'gsa') - if options_.opt_gsa.morris==1, + if options_.opt_gsa.morris==1 MhDirectoryName = [CheckPath('gsa/screen',M_.dname) filesep ]; - elseif options_.opt_gsa.morris==2, + elseif options_.opt_gsa.morris==2 MhDirectoryName = [CheckPath('gsa/identif',M_.dname) filesep ]; elseif options_.opt_gsa.pprior MhDirectoryName = [CheckPath(['gsa' filesep 'prior'],M_.dname) filesep ]; @@ -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 4d29add34..948266a23 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,8 +20,9 @@ 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 +% + +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -40,4 +41,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 7d0e947c9..d3ba8c0be 100644 --- a/matlab/Tracing.m +++ b/matlab/Tracing.m @@ -2,19 +2,19 @@ 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 -% Copyright (C) 2010 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/UnivariateSpectralDensity.m b/matlab/UnivariateSpectralDensity.m index 0039cae30..41b67c403 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 @@ -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); @@ -134,12 +134,12 @@ for ig = 1:ngrid g_omega = [aa*tneg(ig) bb]*f_omega*[aa'*tpos(ig); bb']; % selected variables f_hp = filter_gain(ig)^2*g_omega; % spectral density of selected filtered series mathp_col(ig,:) = (f_hp(:))'; % store as matrix row -end; +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 e71b2772d..5417e5250 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 @@ -42,14 +42,14 @@ end % number of components equals number of shocks + 1 (initial conditions) comp_nbr = size(z,2)-1; -if nargin==8 , +if nargin==8 if isfield(opts_decomp,'steady_state') SteadyState = opts_decomp.steady_state; 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 @@ -61,14 +61,14 @@ if nargin==8 , 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_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); @@ -84,7 +84,7 @@ end nvar = length(i_var); labels = char(char(shock_names),'Initial values'); -if ~(screen_shocks && comp_nbr>18), +if ~(screen_shocks && comp_nbr>18) screen_shocks=0; end comp_nbr0=comp_nbr; @@ -92,14 +92,14 @@ comp_nbr0=comp_nbr; for j=1:nvar d0={}; z1 = squeeze(z(i_var(j),:,:)); - if screen_shocks, + if screen_shocks [junk, isort] = sort(mean(abs(z1(1:end-2,:)')), 'descend'); labels = char(char(shock_names(isort(1:16),:)),'Others', 'Initial values'); zres = sum(z1(isort(17:end),:),1); 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); @@ -107,12 +107,12 @@ for j=1:nvar d0(LastRow+2,1)={'Legend.'}; d0(LastRow+2,2)={'Shocks include:'}; d0(LastRow+3:LastRow+3+comp_nbr-1,1)=cellstr(labels(1:comp_nbr,:)); - for ic=1:comp_nbr, + for ic=1:comp_nbr group_members = shock_groups.(shock_ind{ic}).shocks; 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 a11dbe552..4b0a63ede 100644 --- a/matlab/add_filter_subtitle.m +++ b/matlab/add_filter_subtitle.m @@ -1,5 +1,22 @@ function title=add_filter_subtitle(title,options_) +% 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 . + if ~options_.hp_filter && ~options_.one_sided_hp_filter && ~options_.bandpass.indicator %do not filter %nothing to add here elseif ~options_.hp_filter && ~options_.one_sided_hp_filter && options_.bandpass.indicator @@ -10,6 +27,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/annualized_shock_decomposition.m b/matlab/annualized_shock_decomposition.m index fe0b9cc4e..4972edb30 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,7 +57,7 @@ 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_; @@ -75,7 +75,7 @@ if isfield(q2a,'name') if isfield(q2a,'tex_name') mytex = q2a.tex_name; end - if mytype==2, + if mytype==2 gtxt = ['PHI' mytxt]; % inflation rate gtex = ['{\pi(' mytex ')}']; elseif mytype @@ -101,7 +101,7 @@ if isstruct(aux) end yaux=aux.y; end -if mytype==2, +if mytype==2 gtxt = 'PHI'; % inflation rate gtex = '\pi'; elseif mytype @@ -115,7 +115,7 @@ nterms = size(z,2); nfrcst = opts.forecast/4; for j=1:nvar - if j>1, + if j>1 endo_names = char(endo_names,[deblank(M_.endo_names(i_var(j),:)) '_A']); endo_names_tex = char(endo_names_tex,['{' deblank(M_.endo_names_tex(i_var(j),:)) '}^A']); gendo_names = char(gendo_names,[gtxt endo_names(j,:)]); @@ -133,15 +133,15 @@ for j=1:nvar gendo_names_tex = [gtex '(' deblank(endo_names_tex(j,:)) ')']; end end - for k =1:nterms, - if isstruct(aux), + for k =1:nterms + 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(squeeze(z(j,k,min((t0-3):-4:1):end)),steady_state(j),GYTREND0,var_type,islog,aux); end ztmp=squeeze(za(j,:,:)); - if cumfix==0, + 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 @@ -149,7 +149,7 @@ for j=1:nvar ztmp(end-1,:) = ztmp(end-1,:) + zres; end gztmp=squeeze(gza(j,:,:)); - if cumfix==0, + 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 @@ -160,7 +160,7 @@ for j=1:nvar gza(j,:,:) = gztmp; end -if q2a.plot ==1, +if q2a.plot ==1 z=gza; endo_names = gendo_names; endo_names_tex = gendo_names_tex; @@ -176,9 +176,9 @@ end % end % realtime -if realtime_ && isstruct(oo_) && isfield(oo_, 'realtime_shock_decomposition'), +if realtime_ && isstruct(oo_) && isfield(oo_, 'realtime_shock_decomposition') init=1; - for i=t0:4:t1, + for i=t0:4:t1 yr=floor(i/4); za=[]; gza=[]; @@ -197,18 +197,18 @@ if realtime_ && isstruct(oo_) && isfield(oo_, 'realtime_shock_decomposition'), 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, + for k =nterms:-1:1 % if knfrcst @@ -272,7 +272,7 @@ if realtime_ && isstruct(oo_) && isfield(oo_, 'realtime_shock_decomposition'), 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, + 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); @@ -293,24 +293,24 @@ if realtime_ && isstruct(oo_) && isfield(oo_, 'realtime_shock_decomposition'), switch realtime_ - + case 0 z = oo_.annualized_shock_decomposition; - + 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 if vintage_ z = oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(floor(vintage_/4))]); else error(); end - + case 3 % forecast if vintage_ z = oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(floor(vintage_/4))]); @@ -320,15 +320,14 @@ if realtime_ && isstruct(oo_) && isfield(oo_, 'realtime_shock_decomposition'), end end -if q2a.plot ==0, +if q2a.plot ==0 i_var=1:2*nvar; steady_state = [steady_state_a;steady_state_ga]; else i_var=1:nvar; - if q2a.plot ==1, + if q2a.plot ==1 steady_state = steady_state_ga; else steady_state = steady_state_a; end end - diff --git a/matlab/autoregressive_process_specification.m b/matlab/autoregressive_process_specification.m index 7cc34db27..6f73b7e05 100644 --- a/matlab/autoregressive_process_specification.m +++ b/matlab/autoregressive_process_specification.m @@ -2,48 +2,48 @@ 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) -% Copyright (C) 2009 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/backward/backward_model_inversion.m b/matlab/backward/backward_model_inversion.m index 34acdca80..6acbcc606 100644 --- a/matlab/backward/backward_model_inversion.m +++ b/matlab/backward/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/backward/simul_backward_linear_model.m b/matlab/backward/simul_backward_linear_model.m index c4ed4fe26..44555449f 100644 --- a/matlab/backward/simul_backward_linear_model.m +++ b/matlab/backward/simul_backward_linear_model.m @@ -34,7 +34,7 @@ function DynareOutput = simul_backward_linear_model(initial_conditions, sample_s %! @end deftypefn %@eod: -% Copyright (C) 2012-2016 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -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/backward/simul_backward_model.m b/matlab/backward/simul_backward_model.m index 5327e6435..e581faa25 100644 --- a/matlab/backward/simul_backward_model.m +++ b/matlab/backward/simul_backward_model.m @@ -34,7 +34,7 @@ function DynareOutput = simul_backward_model(initial_conditions, sample_size, Dy %! @end deftypefn %@eod: -% Copyright (C) 2012-2016 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/backward/simul_backward_nonlinear_model.m b/matlab/backward/simul_backward_nonlinear_model.m index 6ac2cfbbd..fadf6ee3f 100644 --- a/matlab/backward/simul_backward_nonlinear_model.m +++ b/matlab/backward/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/basic_plan.m b/matlab/basic_plan.m index 233e795eb..ae7d6bcbf 100644 --- a/matlab/basic_plan.m +++ b/matlab/basic_plan.m @@ -14,7 +14,7 @@ function plan = basic_plan(plan, exogenous, expectation_type, date, value) % plan [structure] Returns a structure containing the updated forecast scenario. % % -% Copyright (C) 2013-2014 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % @@ -38,7 +38,7 @@ 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; +end sdate = length(date); if sdate > 1 if date(1) < plan.date(1) || date(end) > plan.date(end) diff --git a/matlab/bksup0.m b/matlab/bksup0.m index c304b42a4..b801e40e2 100644 --- a/matlab/bksup0.m +++ b/matlab/bksup0.m @@ -4,14 +4,14 @@ 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 % % SPECIAL REQUIREMENTS % none -% Copyright (C) 2003-2009 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/bksup1.m b/matlab/bksup1.m index a6bcb3b9f..4e6fb733c 100644 --- a/matlab/bksup1.m +++ b/matlab/bksup1.m @@ -5,14 +5,14 @@ function d = bksup1(c,ny,jcf,iyf,periods) % INPUTS % ny: number of endogenous variables % jcf: variables index forward -% +% % OUTPUTS % d: vector of backsubstitution results % % SPECIAL REQUIREMENTS % none -% Copyright (C) 2003-2010 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -40,4 +40,3 @@ for i = 2:periods end d = c(:,jcf) ; - diff --git a/matlab/bksupk.m b/matlab/bksupk.m index 33f9c18b0..64de63b8b 100644 --- a/matlab/bksupk.m +++ b/matlab/bksupk.m @@ -15,7 +15,7 @@ function d1 = bksupk(ny,fid,jcf,icc1) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2003-2011 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -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 2ab688e0b..c8b2de0fc 100644 --- a/matlab/bseastr.m +++ b/matlab/bseastr.m @@ -1,6 +1,6 @@ function x = bseastr(s1,s2) -% Copyright (C) 2001-2009 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -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 b147834ed..5c75f18f8 100644 --- a/matlab/bvar_density.m +++ b/matlab/bvar_density.m @@ -12,7 +12,7 @@ function bvar_density(maxnlags) % none % Copyright (C) 2003-2007 Christopher Sims -% Copyright (C) 2007-2016 Dynare Team +% Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. % @@ -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 5319ab8be..55fdf9ce9 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 @@ -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 17228b5c4..5f017aa7d 100644 --- a/matlab/bvar_irf.m +++ b/matlab/bvar_irf.m @@ -11,7 +11,7 @@ function bvar_irf(nlags,identification) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2007-2012 Dynare Team +% Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. % @@ -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 05086a875..4393e21ac 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 @@ -42,7 +42,7 @@ function [ny, nx, posterior, prior, forecast_data] = bvar_toolbox(nlags) % - bvar_prior_{tau,decay,lambda,mu,omega,flat,train} % Copyright (C) 2003-2007 Christopher Sims -% Copyright (C) 2007-2012 Dynare Team +% Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. % @@ -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: @@ -216,3 +216,108 @@ dimy = size(ydum); ydum = reshape(permute(ydum,[1 3 2]),dimy(1)*dimy(3),nv); xdum = reshape(permute(xdum,[1 3 2]),dimy(1)*dimy(3),nx); breaks = breaks(1:(end-1)); + + +function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu) +%function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu) +% This algorithm goes for accuracy without worrying about memory requirements. +% ydata: dependent variable data matrix +% xdata: exogenous variable data matrix +% lags: number of lags +% breaks: rows in ydata and xdata after which there is a break. This allows for +% 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 +% first lags observations at the top and after each "break" in ydata and xdata as +% 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, +% constant term is not included in the dummy observation, so that stationary models +% with means equal to initial ybar do not fit the prior mean. With lambda>0, the prior +% implies that large constants are unlikely if unit roots are present. +% mu: weight on "own persistence" prior dummy observation. Expresses belief +% that when y_i has been stable at its initial level, it will tend to persist +% at that level, regardless of the values of other variables. There is +% 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 +% xdata(1:lags,:) are reasonable subsititutes. These values are used in forming the +% persistence priors. + +% Original file downloaded from: +% http://sims.princeton.edu/yftp/VARtools/matlab/rfvar3.m + +[T,nvar] = size(ydata); +nox = isempty(xdata); +if ~nox + [T2,nx] = size(xdata); +else + T2 = T; + nx = 0; + xdata = zeros(T2,0); +end +% note that x must be same length as y, even though first part of x will not be used. +% This is so that the lags parameter can be changed without reshaping the xdata matrix. +if T2 ~= T, error('Mismatch of x and y data lengths'),end +if nargin < 4 + nbreaks = 0; + breaks = []; +else + nbreaks = length(breaks); +end +breaks = [0;breaks;T]; +smpl = []; +for nb = 1:nbreaks+1 + smpl = [smpl;[breaks(nb)+lags+1:breaks(nb+1)]']; +end +Tsmpl = size(smpl,1); +X = zeros(Tsmpl,nvar,lags); +for is = 1:length(smpl) + X(is,:,:) = ydata(smpl(is)-(1:lags),:)'; +end +X = [X(:,:) xdata(smpl,:)]; +y = ydata(smpl,:); +% Everything now set up with input data for y=Xb+e + +% Add persistence dummies +if lambda ~= 0 || mu > 0 + ybar = mean(ydata(1:lags,:),1); + if ~nox + xbar = mean(xdata(1:lags,:),1); + else + xbar = []; + end + if lambda ~= 0 + if lambda>0 + xdum = lambda*[repmat(ybar,1,lags) xbar]; + else + lambda = -lambda; + xdum = lambda*[repmat(ybar,1,lags) zeros(size(xbar))]; + end + ydum = zeros(1,nvar); + ydum(1,:) = lambda*ybar; + y = [y;ydum]; + X = [X;xdum]; + end + if mu>0 + xdum = [repmat(diag(ybar),1,lags) zeros(nvar,nx)]*mu; + ydum = mu*diag(ybar); + X = [X;xdum]; + y = [y;ydum]; + end +end + +% Compute OLS regression and residuals +[vl,d,vr] = svd(X,0); +di = 1./diag(d); +B = (vr.*repmat(di',nvar*lags+nx,1))*vl'*y; +u = y-X*B; +xxi = vr.*repmat(di',nvar*lags+nx,1); +xxi = xxi*xxi'; + +var.B = B; +var.u = u; +var.xxi = xxi; diff --git a/matlab/cartesian_product_of_sets.m b/matlab/cartesian_product_of_sets.m index 8901886ff..9fbe37c07 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} @@ -31,7 +31,7 @@ function cprod = cartesian_product_of_sets(varargin) %! @end deftypefn %@eod: -% Copyright (C) 2011-2012 Dynare Team +% Copyright (C) 2011-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/cellofchar2mfile.m b/matlab/cellofchar2mfile.m index 6cfce7c5f..6160f5a47 100644 --- a/matlab/cellofchar2mfile.m +++ b/matlab/cellofchar2mfile.m @@ -2,14 +2,14 @@ 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 +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/check.m b/matlab/check.m index a0e7aa1bb..f97a758f4 100644 --- a/matlab/check.m +++ b/matlab/check.m @@ -40,7 +40,7 @@ function [eigenvalues_,result,info] = check(M, options, oo) %! @end deftypefn %@eod: -% Copyright (C) 2001-2013 Dynare Team +% Copyright (C) 2001-2014 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/check_dsge_var_model.m b/matlab/check_dsge_var_model.m index 8b16ec09d..fb06d42ee 100644 --- a/matlab/check_dsge_var_model.m +++ b/matlab/check_dsge_var_model.m @@ -2,7 +2,7 @@ function check_dsge_var_model(Model, EstimatedParameters, BayesInfo) % Check if the dsge model can be estimated with the DSGE-VAR approach. -% Copyright (C) 2013 Dynare Team +% Copyright (C) 2013-2014 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/check_for_calibrated_covariances.m b/matlab/check_for_calibrated_covariances.m index b6d960c2b..7bf00e6a4 100644 --- a/matlab/check_for_calibrated_covariances.m +++ b/matlab/check_for_calibrated_covariances.m @@ -12,7 +12,7 @@ function estim_params=check_for_calibrated_covariances(xparam1,estim_params,M) % Notes: M is local to this function and not updated when calling % set_all_parameters -% Copyright (C) 2013 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % @@ -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 e9fb3be3b..7bf05e478 100644 --- a/matlab/check_list_of_variables.m +++ b/matlab/check_list_of_variables.m @@ -1,20 +1,20 @@ 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-2014 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -33,8 +33,8 @@ function varlist = check_list_of_variables(options_, M_, varlist) %get uniques -[junk1,junk2,index_uniqes] = varlist_indices(varlist,M_.endo_names); -varlist=varlist(index_uniqes,:); +[junk1,junk2,index_uniques] = varlist_indices(varlist,M_.endo_names); +varlist=varlist(index_uniques,:); msg = 0; if options_.dsge_var && options_.bayesian_irf @@ -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 a5156df91..8f0d187c3 100644 --- a/matlab/check_matlab_path.m +++ b/matlab/check_matlab_path.m @@ -1,6 +1,6 @@ function check_matlab_path(change_path_flag) -% Copyright (C) 2015-2016 Dynare Team +% Copyright (C) 2015-2017 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,14 +107,14 @@ else end function q = path2cell(p) -% Converts the output of path() to a cell +% 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)}; + q(i) = {p(s(i-1)+1:s(i)-1)}; end function flist = getallroutinenames(p, excludedsubfolders) diff --git a/matlab/check_model.m b/matlab/check_model.m index 60cf7cba1..1abc89db1 100644 --- a/matlab/check_model.m +++ b/matlab/check_model.m @@ -1,6 +1,6 @@ function check_model(DynareModel) -% Copyright (C) 2005-2012 Dynare Team +% Copyright (C) 2005-2013 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/check_posterior_analysis_data.m b/matlab/check_posterior_analysis_data.m index b1d25b3d1..75aa78a7f 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. @@ -17,7 +17,7 @@ function [info,description] = check_posterior_analysis_data(type,M_) % info = 6; % Ok (nothing to do ;-) % description [string] Message corresponding to info -% Copyright (C) 2008-2015 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -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 d20f85a16..4683639f3 100644 --- a/matlab/check_posterior_sampler_options.m +++ b/matlab/check_posterior_sampler_options.m @@ -13,7 +13,7 @@ function [posterior_sampler_options, options_] = check_posterior_sampler_options % SPECIAL REQUIREMENTS % none -% Copyright (C) 2015 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -32,32 +32,32 @@ function [posterior_sampler_options, options_] = check_posterior_sampler_options init=0; -if isempty(posterior_sampler_options), +if isempty(posterior_sampler_options) init=1; end -if init, +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')) @@ -66,15 +66,15 @@ if init, 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 @@ -101,23 +101,23 @@ if init, end 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')) @@ -126,18 +126,18 @@ if init, 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}; @@ -162,31 +162,31 @@ if init, 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 - + 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')) @@ -195,22 +195,22 @@ if init, 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}; @@ -219,17 +219,17 @@ if init, end 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); @@ -242,7 +242,7 @@ if init, % or % 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 @@ -253,19 +253,19 @@ if init, % This will automatically trigger % default = [] tmp_mode = options_list{i,2}; - for j=1:size(tmp_mode,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 option. + % set the option. % This will automatically trigger % 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. @@ -275,7 +275,7 @@ if init, % 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], @@ -298,18 +298,18 @@ if init, 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 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 @@ -327,52 +327,52 @@ if init, options_.mh_posterior_mode_estimation=0; end end - - if any(isinf(bounds.lb)) || any(isinf(bounds.ub)), + + 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, + if options_.load_mh_file posterior_sampler_options.slice_initialize_with_mode = 0; else - if ~posterior_sampler_options.slice_initialize_with_mode, + if ~posterior_sampler_options.slice_initialize_with_mode posterior_sampler_options.invhess=[]; end end - - if ~isempty(posterior_sampler_options.mode_files), % multimodal case + + 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, + 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), + 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=[]; end - + otherwise error('check_posterior_sampler_options:: Unknown posterior_sampling_method option %s ',posterior_sampler_options.posterior_sampling_method); end - + return end @@ -386,7 +386,7 @@ if ~strcmp(posterior_sampler_options.posterior_sampling_method,'slice') end end -if options_.load_mh_file && posterior_sampler_options.use_mh_covariance_matrix, +if options_.load_mh_file && posterior_sampler_options.use_mh_covariance_matrix [junk, invhess] = compute_mh_covariance_matrix; posterior_sampler_options.invhess = invhess; end @@ -396,10 +396,8 @@ end % check specific options for slice sampler if strcmp(posterior_sampler_options.posterior_sampling_method,'slice') invhess = posterior_sampler_options.invhess; - - if posterior_sampler_options.rotated, - if isempty(posterior_sampler_options.mode_files) && isempty(posterior_sampler_options.mode), % rotated unimodal - + if posterior_sampler_options.rotated + if isempty(posterior_sampler_options.mode_files) && isempty(posterior_sampler_options.mode) % rotated unimodal if ~options_.cova_compute && ~(options_.load_mh_file && posterior_sampler_options.use_mh_covariance_matrix) skipline() disp('check_posterior_sampler_options:: I cannot start rotated slice sampler because') @@ -419,19 +417,13 @@ if strcmp(posterior_sampler_options.posterior_sampling_method,'slice') posterior_sampler_options.WR=sqrt(diag(D))*3; end else - if ~options_.load_mh_file && ~posterior_sampler_options.slice_initialize_with_mode, + if ~options_.load_mh_file && ~posterior_sampler_options.slice_initialize_with_mode posterior_sampler_options.invhess=[]; end end - % needs to be re-set to zero otherwise posterior analysis is filtered % out in dynare_estimation_1.m options_.mh_posterior_mode_estimation = 0; - - -else - - end return @@ -442,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 8d74ba943..e0570cc68 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. @@ -18,7 +18,7 @@ function [info,description] = check_prior_analysis_data(type,M_) % description [string] Message corresponding to info -% Copyright (C) 2009-2011 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -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 pdfdate1 diff --git a/matlab/check_prior_bounds.m b/matlab/check_prior_bounds.m index 5214ce010..9c982ff4d 100644 --- a/matlab/check_prior_bounds.m +++ b/matlab/check_prior_bounds.m @@ -5,12 +5,12 @@ 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 -% Copyright (C) 2013 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/chol_SE.m b/matlab/chol_SE.m index 0e516c496..48b70edf4 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,39 +21,40 @@ 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 -% A [n*n] Matrix to be factorized -% pivoting [scalar] dummy whether pivoting is used -% -% 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 -% P [n*1] record of how the rows and columns of the matrix were permuted while -% performing the decomposition +% INPUTS +% - A [n*n] Matrix to be factorized +% - pivoting [scalar] dummy whether pivoting is used +% +% 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 +% - P [n*1] record of how the rows and columns of the matrix were permuted while +% 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 +% Copyright (C) 2015-2017 Dynare Team +% % This file is part of Dynare. % % Dynare is free software: you can redistribute it and/or modify @@ -148,7 +149,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 +184,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 +230,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 +260,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 +273,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); @@ -293,17 +294,16 @@ function g=gersh_nested(A,j,n) g=zeros(n,1); for ii = j:n - if ii == 1; + if ii == 1 sum_up_to_i = 0; else sum_up_to_i = sum(abs(A(ii,j:(ii-1)))); - end; - if ii == n; + end + if ii == n sum_after_i = 0; else sum_after_i = sum(abs(A((ii+1):n,ii))); - end; + end 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 e2fe5666f..c3250fb4d 100644 --- a/matlab/clear_persistent_variables.m +++ b/matlab/clear_persistent_variables.m @@ -2,7 +2,7 @@ function clear_persistent_variables(folder, writelistofroutinestobecleared) % Clear all the functions with persistent variables in directory folder (and subdirectories). -% Copyright (C) 2015 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -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 6395a7e44..b090aba76 100644 --- a/matlab/cli/prior.m +++ b/matlab/cli/prior.m @@ -11,7 +11,7 @@ function varargout = prior(varargin) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2015-2016 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -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; diff --git a/matlab/collect_latex_files.m b/matlab/collect_latex_files.m index 9220d2564..45902f1ba 100644 --- a/matlab/collect_latex_files.m +++ b/matlab/collect_latex_files.m @@ -1,14 +1,14 @@ 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 -% Copyright (C) 2015-16 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -49,7 +49,7 @@ for ii=1:length(TeX_Files) ~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,'}']); + 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 03db4b972..d847ffacc 100644 --- a/matlab/compute_Pinf_Pstar.m +++ b/matlab/compute_Pinf_Pstar.m @@ -1,36 +1,36 @@ 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 % None -% Copyright (C) 2006-2011 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -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 8b62a2afe..d7885c7f9 100644 --- a/matlab/compute_mh_covariance_matrix.m +++ b/matlab/compute_mh_covariance_matrix.m @@ -1,21 +1,21 @@ 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 _mh_mode.mat. -% -% INPUTS +% a file _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 % None. -% Copyright (C) 2006-2011 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -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 1c89a5e07..50c1d0072 100644 --- a/matlab/compute_model_moments.m +++ b/matlab/compute_model_moments.m @@ -4,14 +4,14 @@ 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 -% Copyright (C) 2008-2009 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/compute_moments_varendo.m b/matlab/compute_moments_varendo.m index a74b55fe3..c072f9c10 100644 --- a/matlab/compute_moments_varendo.m +++ b/matlab/compute_moments_varendo.m @@ -2,21 +2,21 @@ 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). % % SPECIAL REQUIREMENTS % none -% Copyright (C) 2008-2010 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . +% along with Dynare. If not, see . fprintf('Estimation::compute_moments_varendo: I''m computing endogenous moments (this may take a while)... '); diff --git a/matlab/compute_overall_acceptance_ratio.m b/matlab/compute_overall_acceptance_ratio.m index 937579e91..90db1d374 100644 --- a/matlab/compute_overall_acceptance_ratio.m +++ b/matlab/compute_overall_acceptance_ratio.m @@ -1,6 +1,6 @@ function overallacceptanceratio = compute_overall_acceptance_ratio(MetropolisFolder, ModelName) -% Copyright (C) 2013 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % @@ -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/compute_trend_coefficients.m b/matlab/compute_trend_coefficients.m index 9686867e2..d9bd3441a 100644 --- a/matlab/compute_trend_coefficients.m +++ b/matlab/compute_trend_coefficients.m @@ -18,7 +18,7 @@ function [trend_addition, trend_coeff]=compute_trend_coefficients(M_,DynareOptio % SPECIAL REQUIREMENTS % none -% Copyright (C) 2014 Dynare Team +% Copyright (C) 2014-2016 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/conditional_variance_decomposition.m b/matlab/conditional_variance_decomposition.m index 3ecf74410..177684ce6 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 @@ -16,7 +16,7 @@ function ConditionalVarianceDecomposition = conditional_variance_decomposition(S % % [1] In this version, absence of measurement errors is assumed... -% Copyright (C) 2010-2011 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -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 67b42d0b0..c320554eb 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 @@ -23,7 +23,7 @@ function oo_ = ... % OUTPUTS % oo_ [structure] Dynare structure where the results are saved. -% Copyright (C) 2009-2015 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -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 ff6c1089d..a3fa70fd9 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]); @@ -101,7 +101,7 @@ end my_title='MCMC Inefficiency factors per block'; IFAC_header='Parameter'; IFAC_header_tex='Parameter'; -for j=1:nblck, +for j=1:nblck IFAC_header = char(IFAC_header,['Block ' int2str(j)]); IFAC_header_tex = char(IFAC_header_tex,['Block~' int2str(j)]); 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]; @@ -190,22 +190,22 @@ if nblck == 1 % Brooks and Gelman tests need more than one block 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) 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; + + 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); @@ -262,7 +262,7 @@ localVars.M_ = M_; % Like sequential execution! -if isnumeric(options_.parallel), +if isnumeric(options_.parallel) fout = McMCDiagnostics_core(localVars,1,npar,0); UDIAG = fout.UDIAG; clear fout @@ -273,19 +273,19 @@ 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, + for j=2:totCPU UDIAG = cat(3,UDIAG ,fout(j).UDIAG); end 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'); @@ -346,7 +346,7 @@ if reste if reste == 1 nr = 3; nc = 1; - elseif reste == 2; + elseif reste == 2 nr = 2; nc = 3; end @@ -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)']; @@ -391,9 +391,9 @@ if reste dyn_saveas(h,[ OutputFolder '/' ModelName '_udiag' int2str(pages+1)],options_.nodisplay,options_.graph_format); if TeX && any(strcmp('eps',cellstr(options_.graph_format))) fprintf(fidTeX,'\\begin{figure}[H]\n'); - for jj = 1:size(NAMES,1); + 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 af41566c9..283e6ada1 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,15 +25,15 @@ 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. -% Copyright (C) 2006-2016 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -50,7 +50,7 @@ function myoutput = McMCDiagnostics_core(myinputs,fpar,npar,whoiam, ThisMatlab) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see . -if nargin<4, +if nargin<4 whoiam=0; end @@ -71,7 +71,7 @@ M_=myinputs.M_; if whoiam Parallel=myinputs.Parallel; end -if ~exist('MetropolisFolder'), +if ~exist('MetropolisFolder') MetropolisFolder = CheckPath('metropolis',M_.dname); end @@ -81,16 +81,16 @@ UDIAG = zeros(NumberOfLines,6,npar-fpar+1); if whoiam waitbarString = ['Please wait... McMCDiagnostics (' int2str(fpar) 'of' int2str(npar) ')...']; - if Parallel(ThisMatlab).Local, + if Parallel(ThisMatlab).Local waitbarTitle=['Local ']; else waitbarTitle=[Parallel(ThisMatlab).ComputerName]; end fMessageStatus(0,whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab)); end -for j=fpar:npar, +for j=fpar:npar if isoctave - if (whoiam==0), + if (whoiam==0) printf(' Parameter %d... ',j); end else @@ -131,13 +131,13 @@ for j=fpar:npar, end end if isoctave - if (whoiam==0), + if (whoiam==0) printf('Done! \n'); end else fprintf('Done! \n'); end - if whoiam, + if whoiam waitbarString = [ 'Parameter ' int2str(j) '/' int2str(npar) ' done.']; fMessageStatus((j-fpar+1)/(npar-fpar+1),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab)) end diff --git a/matlab/convergence_diagnostics/geweke_chi2_test.m b/matlab/convergence_diagnostics/geweke_chi2_test.m index 5009b5f26..6c543a8ca 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 @@ -26,7 +26,7 @@ function results_struct = geweke_chi2_test(results1,results2,results_struct,opti % SPECIAL REQUIREMENTS % None. -% Copyright (C) 2013 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % @@ -49,26 +49,24 @@ 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; +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); - - test_stat=diff_Means.^2./sum(NSE.^2,2); + 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; - +end diff --git a/matlab/convergence_diagnostics/geweke_moments.m b/matlab/convergence_diagnostics/geweke_moments.m index eceaa7ee1..61c22979f 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 @@ -22,7 +22,7 @@ function [results_vec, results_struct] = geweke_moments(draws,Dynareoptions) % SPECIAL REQUIREMENTS % None. -% Copyright (C) 2013 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % @@ -44,14 +44,14 @@ 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); @@ -64,10 +64,10 @@ n_draws_used = ns*n_groups; %effective number of draws used after rounding down window_means= zeros(n_groups,1); window_uncentered_variances= zeros(n_groups,1); -for ig=1:n_groups; +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; -end; %for ig + 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; @@ -88,9 +88,9 @@ results_struct.rne_iid = results_vec(1,4); %get autocovariance of grouped means centered_window_means=window_means-total_mean; autocov_grouped_means=zeros(n_groups,1); -for lag=0:n_groups-1; +for lag=0:n_groups-1 autocov_grouped_means(lag+1)=centered_window_means(lag+1:n_groups,1)'*centered_window_means(1:n_groups-lag,1)/100; -end; +end % numerical standard error with tapered autocovariance functions for taper_index=1:length(taper_steps) @@ -105,5 +105,4 @@ 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 - +end % end of for mm loop diff --git a/matlab/convergence_diagnostics/mcmc_ifac.m b/matlab/convergence_diagnostics/mcmc_ifac.m index 7f231842b..32b72bcee 100644 --- a/matlab/convergence_diagnostics/mcmc_ifac.m +++ b/matlab/convergence_diagnostics/mcmc_ifac.m @@ -14,12 +14,12 @@ function Ifac = mcmc_ifac(X, Nc) % ALGORITHM: % Inefficiency factors are computed as % \[ -% Ifac = 1 + 2\sum\limits_{i=1}^{Nc} {\hat \rho(i)} +% 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): +% +% 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 @@ -36,7 +36,7 @@ function Ifac = mcmc_ifac(X, Nc) % consistent covariance matrix estimation", Econometrica, 59(3), p. 817-858 -% Copyright (C) 2015-16 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -54,7 +54,7 @@ function Ifac = mcmc_ifac(X, Nc) % along with Dynare. If not, see . Nc = floor(min(Nc, length(X)/2)); -if mod(Nc,2), +if mod(Nc,2) Nc=Nc-1; end AcorrXSIM = dyn_autocorr(X(:), Nc); diff --git a/matlab/convergence_diagnostics/raftery_lewis.m b/matlab/convergence_diagnostics/raftery_lewis.m index d6e403c5b..ab0e51cb7 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,23 +30,23 @@ 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. % % ---------------------------------------------------- % Copyright (C) 2016 Benjamin Born and Johannes Pfeifer -% Copyright (C) 2016 Dynare Team +% Copyright (C) 2016-2017 Dynare Team % % This file is part of Dynare. % @@ -80,42 +80,42 @@ 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'); - end; - - k_thin_current_var = 1; - bic = 1; + error('Quantile must be between 0 and 1'); + end + + 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; - + 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; - end; + end alpha = transition_matrix(1,2)/(transition_matrix(1,1)+transition_matrix(1,2)); %prob of going from 1 to 2 beta = transition_matrix(2,1)/(transition_matrix(2,1)+transition_matrix(2,2)); %prob of going from 2 to 1 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; - + 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 @@ -124,18 +124,18 @@ for nv = 1:n_vars % big loop over variables raftery_lewis.k_ind(nv) = max(fix(raftery_lewis.I_stat(nv)+1),kmind); raftery_lewis.k_thin(nv) = k_thin_current_var; raftery_lewis.N_total(nv)= raftery_lewis.M_burn(nv)+raftery_lewis.N_prec(nv); -end; +end 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; -end; +end % 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 @@ -146,9 +146,9 @@ for ind_1 = 1: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 + 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; @@ -161,19 +161,19 @@ n_obs=size(d,1); 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; +end +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; + end + end +end +g2 = g2*2; bic = g2 - log(dcm1); end diff --git a/matlab/convertAimCodeToInfo.m b/matlab/convertAimCodeToInfo.m index 2aaf05be7..2320c7f65 100644 --- a/matlab/convertAimCodeToInfo.m +++ b/matlab/convertAimCodeToInfo.m @@ -19,7 +19,7 @@ function [info] = convertAimCodeToInfo(aimCode) % OUTPUTS % info [integer] Code to be used to print error in print_info.m -% Copyright (C) 2011-2012 Dynare Team +% Copyright (C) 2011-2017 Dynare Team % % This file is part of Dynare. % @@ -55,7 +55,7 @@ switch aimCode info = 161; case 62 info = 162; - case 63; + case 63 info = 163; case 64 info = 164; diff --git a/matlab/convert_dyn_45_to_44.m b/matlab/convert_dyn_45_to_44.m index 12306cccc..3f0561b58 100644 --- a/matlab/convert_dyn_45_to_44.m +++ b/matlab/convert_dyn_45_to_44.m @@ -13,7 +13,7 @@ function oo_ = convert_dyn_45_to_44(M_, options_, oo_,bayestopt_) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2015-2016 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -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)); diff --git a/matlab/convert_oo_.m b/matlab/convert_oo_.m index 948fc708d..914cc0adb 100644 --- a/matlab/convert_oo_.m +++ b/matlab/convert_oo_.m @@ -15,7 +15,7 @@ function oo_ = convert_oo_(M_, options_, oo_, from_ver, to_ver) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2015 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -63,7 +63,7 @@ else end if strcmp(from_ver, to_ver) - return; + return end if ver_greater_than(to_ver, from_ver) diff --git a/matlab/correlation_mc_analysis.m b/matlab/correlation_mc_analysis.m index 6eba19485..7b3d63848 100644 --- a/matlab/correlation_mc_analysis.m +++ b/matlab/correlation_mc_analysis.m @@ -2,7 +2,7 @@ function oo_ = correlation_mc_analysis(SampleSize,type,dname,fname,vartan,nvar,v % This function analyses the (posterior or prior) distribution of the % endogenous variables correlation function. -% Copyright (C) 2008-2013 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -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 8fcf7fb79..b64245e7b 100644 --- a/matlab/cosn.m +++ b/matlab/cosn.m @@ -1,4 +1,4 @@ -function [co, b, yhat] = cosn(H); +function [co, b, yhat] = cosn(H) % function co = cosn(H); % computes the cosine of the angle between the H(:,1) and its @@ -7,7 +7,7 @@ function [co, b, yhat] = cosn(H); % Not the same as multiple correlation coefficient since the means are not % zero % -% Copyright (C) 2008-2012 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -28,15 +28,12 @@ y = H(:,1); X = H(:,2:end); b=(X\y); -if any(isnan(b)) || any(isinf(b)), +if any(isnan(b)) || any(isinf(b)) b=0; end yhat = X*b; -if rank(yhat), +if rank(yhat) co = abs(y'*yhat/sqrt((y'*y)*(yhat'*yhat))); else co=0; end - - - diff --git a/matlab/covariance_mc_analysis.m b/matlab/covariance_mc_analysis.m index 1d0139d43..ebf3602a2 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,12 +14,12 @@ 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. -% Copyright (C) 2008-2015 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -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,7 +104,7 @@ 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 diff --git a/matlab/csolve.m b/matlab/csolve.m index 3af47243e..e45a4b2ff 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 @@ -22,7 +22,7 @@ function [x,rc] = csolve(FUN,x,gradfun,crit,itmax,varargin) % http://sims.princeton.edu/yftp/optimize/mfiles/csolve.m % Copyright (C) 1993-2007 Christopher Sims -% Copyright (C) 2007-2011 Dynare Team +% Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. % @@ -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; @@ -122,7 +122,7 @@ while ~done factor=factor^.6; shrink=1; end - if abs(lambda*(1-factor))*dxSize > .1*delta; + if abs(lambda*(1-factor))*dxSize > .1*delta lambda = factor*lambda; elseif (lambda > 0) && (factor==.6) %i.e., we've only been shrinking lambda=-.3; @@ -162,7 +162,7 @@ while ~done if itct >= itmax done=1; rc=4; - elseif af0) dx -%! -%! +%! +%! %! @end deftypefn %@eod: -% Copyright (C) 2012-2013 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -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); @@ -130,7 +130,7 @@ m(:,4) = -m(:,1); %@test:1 %$ % Set problem %$ d = 4; -%$ +%$ %$ t = zeros(5,1); %$ %$ % Call the tested routine @@ -289,7 +289,7 @@ m(:,4) = -m(:,1); %@test:5 %$ % Set problem %$ d = 5; -%$ +%$ %$ t = zeros(6,1); %$ %$ % Call the tested routine @@ -333,7 +333,7 @@ m(:,4) = -m(:,1); %@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 59cdc5717..be8fdb3e8 100644 --- a/matlab/cycle_reduction.m +++ b/matlab/cycle_reduction.m @@ -43,7 +43,7 @@ function [X, info] = cycle_reduction(A0, A1, A2, cvg_tol, ch) % --*-- Unitary te %! @end deftypefn %@eod: -% Copyright (C) 2013 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % @@ -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 c2ea03ef6..76928c77f 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') ; @@ -78,4 +78,3 @@ end % Close the data file. fclose(fid) ; - diff --git a/matlab/dcompare.m b/matlab/dcompare.m index 6efc5ae27..d50541f12 100644 --- a/matlab/dcompare.m +++ b/matlab/dcompare.m @@ -1,6 +1,6 @@ function dcompare(s1) -% Copyright (C) 2001-2011 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -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 635bb9c94..084f3e783 100644 --- a/matlab/delete_mh_history_files.m +++ b/matlab/delete_mh_history_files.m @@ -1,6 +1,6 @@ function info = delete_mh_history_files(MetropolisFolder, ModelName) -% Copyright (C) 2013 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/discretionary_policy.m b/matlab/discretionary_policy.m index d12af30bd..e021e3375 100644 --- a/matlab/discretionary_policy.m +++ b/matlab/discretionary_policy.m @@ -1,6 +1,6 @@ function info = discretionary_policy(var_list) -% Copyright (C) 2007-2011 Dynare Team +% Copyright (C) 2007-2015 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/discretionary_policy_1.m b/matlab/discretionary_policy_1.m index 09584e864..0837067b2 100644 --- a/matlab/discretionary_policy_1.m +++ b/matlab/discretionary_policy_1.m @@ -1,6 +1,6 @@ function [dr,ys,info]=discretionary_policy_1(oo_,Instruments) -% Copyright (C) 2007-2016 Dynare Team +% Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. % @@ -96,11 +96,11 @@ 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 diff --git a/matlab/discretionary_policy_engine.m b/matlab/discretionary_policy_engine.m index 7189dabef..05c781ae4 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,14 +41,14 @@ 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, 31–55. -% Copyright (C) 2007-2015 Dynare Team +% Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. % @@ -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); @@ -239,11 +239,11 @@ function v= SylvesterDoubling (d,g,h,tol,maxit) % to solve the Sylvester equation v = d + g v h v = d; -for i =1:maxit, +for i =1:maxit vadd = g*v*h; v = v+vadd; if norm (vadd,1) <= (tol*norm(v,1)) - break; + break end g = g*g; h = h*h; @@ -295,8 +295,8 @@ temp = []; %First handle the i = 1 case outside the loop -if i< n, - if abs(h(i+1,i)) < tol, +if i< n + if abs(h(i+1,i)) < tol v(:,i)= (w - g*h(i,i))\d(:,i); i = i+1; else @@ -312,10 +312,10 @@ end %Handle the rest of the matrix with the possible exception of i=n -while i - if abs(h(i+1,i)) < tol, + if abs(h(i+1,i)) < tol v(:,i) = (w - g*h(i,i))\(d(:,i) + temp*h(1:b,i)); i = i+1; else @@ -332,7 +332,7 @@ end %Handle the i = n case if i=n was not in a 2-2 block -if i==n, +if i==n b = i-1; temp = [temp g*v(:,size(temp,2)+1:b)]; v(:,i) = (w-g*h(i,i))\(d(:,i) + temp*h(1:b,i)); diff --git a/matlab/disp_dr.m b/matlab/disp_dr.m index 673838a6e..f8f4e4b4c 100644 --- a/matlab/disp_dr.m +++ b/matlab/disp_dr.m @@ -7,8 +7,8 @@ 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-2015 Dynare Team +% +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -36,7 +36,7 @@ else k = find(dr.kstate(:,2) <= M_.maximum_lag+1); klag = dr.kstate(k,[1 2]); k1 = dr.order_var; -end; +end if size(var_list,1) == 0 var_list = M_.endo_names(1:M_.orig_endo_nbr, :); @@ -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, :)); diff --git a/matlab/disp_identification.m b/matlab/disp_identification.m index 6f89e429d..b8a3421d5 100644 --- a/matlab/disp_identification.m +++ b/matlab/disp_identification.m @@ -1,6 +1,6 @@ function disp_identification(pdraws, idemodel, idemoments, name, advanced) -% Copyright (C) 2008-2012 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -19,7 +19,7 @@ function disp_identification(pdraws, idemodel, idemoments, name, advanced) global options_ -if nargin < 5 || isempty(advanced), +if nargin < 5 || isempty(advanced) advanced=0; end @@ -84,16 +84,16 @@ end disp([' ']), -if any(idemodel.ino), +if any(idemodel.ino) disp('WARNING !!!') - if SampleSize>1, + if SampleSize>1 disp(['The rank of H (model) is deficient for ', num2str(length(find(idemodel.ino))),' out of ',int2str(SampleSize),' MC runs!' ]), else disp(['The rank of H (model) is deficient!' ]), end skipline() - for j=1:npar, - if any(idemodel.ind0(:,j)==0), + for j=1:npar + if any(idemodel.ind0(:,j)==0) pno = 100*length(find(idemodel.ind0(:,j)==0))/SampleSize; if SampleSize>1 disp([' ',name{j},' is not identified in the model for ',num2str(pno),'% of MC runs!' ]) @@ -107,9 +107,9 @@ if any(idemodel.ino), jmap_pair=dyn_unvech(1:npairs); jstore=[]; skipline() - for j=1:npairs, + for j=1:npairs iweak = length(find(idemodel.jweak_pair(:,j))); - if iweak, + if iweak [jx,jy]=find(jmap_pair==j); jstore=[jstore jx(1) jy(1)]; if SampleSize > 1 @@ -118,12 +118,12 @@ 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, + for j=1:npar iweak = length(find(idemodel.jweak(:,j))); - if iweak && ~ismember(j,jstore), + if iweak && ~ismember(j,jstore) % disp('WARNING !!!') % disp(['Model derivatives of parameter ',name{j},' are multi-collinear (with tol = 1.e-10) for ',num2str(iweak/SampleSize*100),'% of MC runs!' ]) if SampleSize>1 @@ -157,10 +157,10 @@ if ~any(idemodel.ino) && ~any(any(idemodel.ind0==0)) skipline() end -if any(idemoments.ino), +if any(idemoments.ino) skipline() disp('WARNING !!!') - if SampleSize > 1, + if SampleSize > 1 disp(['The rank of J (moments) is deficient for ', num2str(length(find(idemoments.ino))),' out of ',int2str(SampleSize),' MC runs!' ]), else disp(['The rank of J (moments) is deficient!' ]), @@ -173,8 +173,8 @@ if any(idemoments.ino), % ifreq=find(freqno); % disp('MOMENT RANK FAILURE DUE TO COLLINEARITY OF PARAMETERS:'); skipline() - for j=1:npar, - if any(idemoments.ind0(:,j)==0), + for j=1:npar + if any(idemoments.ind0(:,j)==0) pno = 100*length(find(idemoments.ind0(:,j)==0))/SampleSize; if SampleSize > 1 disp([' ',name{j},' is not identified by J moments for ',num2str(pno),'% of MC runs!' ]) @@ -188,9 +188,9 @@ if any(idemoments.ino), npairs=size(idemoments.jweak_pair,2); jmap_pair=dyn_unvech(1:npairs); jstore=[]; - for j=1:npairs, + for j=1:npairs iweak = length(find(idemoments.jweak_pair(:,j))); - if iweak, + if iweak [jx,jy]=find(jmap_pair==j); jstore=[jstore' jx(1) jy(1)]'; if SampleSize > 1 @@ -199,15 +199,15 @@ 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, + for j=1:npar iweak = length(find(idemoments.jweak(:,j))); - if iweak && ~ismember(j,jstore), + if iweak && ~ismember(j,jstore) % disp('WARNING !!!') % disp(['Moment derivatives of parameter ',name{j},' are multi-collinear (with tol = 1.e-10) for ',num2str(iweak/SampleSize*100),'% of MC runs!' ]) - if SampleSize > 1, + if SampleSize > 1 disp([name{j},' is collinear w.r.t. all other params ',num2str(iweak/SampleSize*100),'% of MC runs!' ]) else disp([name{j},' is collinear w.r.t. all other params!' ]) @@ -255,30 +255,30 @@ 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(' ') % identificaton patterns -if SampleSize==1 && advanced, +if SampleSize==1 && advanced skipline() disp('Press ENTER to print advanced diagnostics'), pause(5), - for j=1:size(idemoments.cosnJ,2), + for j=1:size(idemoments.cosnJ,2) pax=NaN(npar,npar); 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:npar, + for i=1:npar namx=''; - for in=1:j, + for in=1:j dumpindx = idemoments.pars{i,j}(in); - if isnan(dumpindx), + if isnan(dumpindx) namx=[namx ' ' sprintf('%-15s','--')]; else namx=[namx ' ' sprintf('%-15s',name{dumpindx})]; diff --git a/matlab/disp_model_summary.m b/matlab/disp_model_summary.m index 394bc00d9..b04d025b4 100644 --- a/matlab/disp_model_summary.m +++ b/matlab/disp_model_summary.m @@ -4,11 +4,11 @@ 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 % -% Copyright (C) 2001-2016 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -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 8bbf1f567..6e55bb571 100644 --- a/matlab/disp_moments.m +++ b/matlab/disp_moments.m @@ -7,11 +7,11 @@ 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, -% Copyright (C) 2001-2016 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -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); @@ -197,7 +197,7 @@ 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 diff --git a/matlab/disp_steady_state.m b/matlab/disp_steady_state.m index 354b0f6a4..0543affc7 100644 --- a/matlab/disp_steady_state.m +++ b/matlab/disp_steady_state.m @@ -1,18 +1,18 @@ 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 % % SPECIAL REQUIREMENTS % none -% Copyright (C) 2001-2011 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/disp_th_moments.m b/matlab/disp_th_moments.m index 77e38c5e7..014102f5c 100644 --- a/matlab/disp_th_moments.m +++ b/matlab/disp_th_moments.m @@ -1,7 +1,7 @@ function oo_=disp_th_moments(dr,var_list,M_,options_,oo_) % Display theoretical moments of variables -% Copyright (C) 2001-2015 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -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 @@ -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,7 +107,7 @@ 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_); @@ -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, + if ~options_.noprint skipline() if options_.order == 2 - title='APPROXIMATED MATRIX OF CORRELATIONS'; + title='APPROXIMATED MATRIX OF CORRELATIONS'; else title='MATRIX OF CORRELATIONS'; end @@ -153,23 +153,23 @@ if options_.ar > 0 && size(stationary_vars, 1) > 0 oo_.autocorr{i} = oo_.gamma_y{i+1}; z(:,i) = diag(oo_.gamma_y{i+1}(i1,i1)); end - if ~options_.noprint, - skipline() + if ~options_.noprint + 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 2a82c7e2f..f0c115ad4 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,10 +10,10 @@ function display_conditional_variance_decomposition(conditional_decomposition_ar % Model description % options_ [structure] Dynare structure containing the % options -% OUTPUTS +% OUTPUTS % none % -% Copyright (C) 2010-2014 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -61,5 +61,5 @@ for i=1:length(Steps) 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 end \ No newline at end of file diff --git a/matlab/display_estimation_results_table.m b/matlab/display_estimation_results_table.m index 52ffacfda..6faf6a834 100644 --- a/matlab/display_estimation_results_table.m +++ b/matlab/display_estimation_results_table.m @@ -1,26 +1,26 @@ 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 % None. -% Copyright (C) 2014-2016 Dynare Team +% Copyright (C) 2014-2017 Dynare Team % % This file is part of Dynare. % @@ -106,14 +106,14 @@ if nvn 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)); 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);']); @@ -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)); 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)); 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,7 +302,7 @@ 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); @@ -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); @@ -379,7 +379,7 @@ 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) +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)]); @@ -400,7 +400,7 @@ fprintf(fid,'\\bottomrule \\multicolumn{4}{r}{(Continued on next page)} \\endfo 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 26cfef452..310b37fa5 100644 --- a/matlab/display_problematic_vars_Jacobian.m +++ b/matlab/display_problematic_vars_Jacobian.m @@ -1,22 +1,22 @@ 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 +% Copyright (C) 2014-2017 Dynare Team % % This file is part of Dynare. % @@ -50,7 +50,7 @@ if strcmp(type,'dynamic') type_string=''; elseif var_row==1 type_string='lag of'; - elseif var_row==3; + elseif var_row==3 type_string='lead of'; end if problemcol(ii)<=max(max(M_.lead_lag_incidence)) && var_index<=M_.orig_endo_nbr @@ -62,23 +62,23 @@ 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 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))) + 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))) + 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)) + 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)) + 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 @@ -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,23 +108,23 @@ 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))) + 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))) + 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 @@ -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 33a38085d..df804812c 100644 --- a/matlab/distributions/beta_specification.m +++ b/matlab/distributions/beta_specification.m @@ -2,17 +2,17 @@ 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. -% Copyright (C) 2015 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -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 3286c08ea..86c20dae8 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,18 +12,18 @@ 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. -% Copyright (C) 2009-2016 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/distributions/gamma_specification.m b/matlab/distributions/gamma_specification.m index 0f7301193..c78713407 100644 --- a/matlab/distributions/gamma_specification.m +++ b/matlab/distributions/gamma_specification.m @@ -2,17 +2,17 @@ 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). -% Copyright (C) 2015-2016 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/distributions/inverse_gamma_specification.m b/matlab/distributions/inverse_gamma_specification.m index c7f02a194..410d4e52b 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,16 +10,16 @@ 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. -% Copyright (C) 2003-2015 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -85,10 +85,10 @@ nu = []; sigma = sqrt(sigma2); mu2 = mu*mu; -if type == 2; % Inverse Gamma 2 +if type == 2 % Inverse Gamma 2 nu = 2*(2+mu2/sigma2); s = 2*mu*(1+mu2/sigma2); -elseif type == 1; % Inverse Gamma 1 +elseif type == 1 % Inverse Gamma 1 if sigma2 < Inf nu = sqrt(2*(2+mu2/sigma2)); if use_fzero_flag diff --git a/matlab/distributions/lpdfgweibull.m b/matlab/distributions/lpdfgweibull.m index e8ca18c2e..708a5b4d4 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) @@ -16,7 +16,7 @@ function [ldens,Dldens,D2ldens] = lpdfgweibull(x,a,b,c) % --*-- Unitary tests - % SPECIAL REQUIREMENTS % none -% Copyright (C) 2015-2016 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -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 @@ -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 a69f0cdbe..8611955b0 100644 --- a/matlab/distributions/mode_and_variance_to_mean.m +++ b/matlab/distributions/mode_and_variance_to_mean.m @@ -1,23 +1,23 @@ 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 +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . -% 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 29feabaf6..55bae7283 100644 --- a/matlab/distributions/multivariate_normal_pdf.m +++ b/matlab/distributions/multivariate_normal_pdf.m @@ -1,21 +1,21 @@ -function density = multivariate_normal_pdf(X,Mean,Sigma_upper_chol,n); +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-2009 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . -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 3f498c673..1465d4402 100644 --- a/matlab/distributions/multivariate_student_pdf.m +++ b/matlab/distributions/multivariate_student_pdf.m @@ -1,20 +1,20 @@ -function density = multivariate_student_pdf(X,Mean,Sigma_upper_chol,df); +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-2009 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/distributions/rand_inverse_wishart.m b/matlab/distributions/rand_inverse_wishart.m index c561fb7f4..4f3675e3c 100644 --- a/matlab/distributions/rand_inverse_wishart.m +++ b/matlab/distributions/rand_inverse_wishart.m @@ -17,14 +17,14 @@ 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 +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . -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 ff595cca8..0de2faf08 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,14 +13,14 @@ 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 -% Copyright (C) 2003-2009 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/distributions/rand_multivariate_normal.m b/matlab/distributions/rand_multivariate_normal.m index 174c3706c..d74d74b7b 100644 --- a/matlab/distributions/rand_multivariate_normal.m +++ b/matlab/distributions/rand_multivariate_normal.m @@ -2,19 +2,19 @@ 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 +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/distributions/rand_multivariate_student.m b/matlab/distributions/rand_multivariate_student.m index eca1d0585..69b26e85e 100644 --- a/matlab/distributions/rand_multivariate_student.m +++ b/matlab/distributions/rand_multivariate_student.m @@ -3,27 +3,27 @@ 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. -% Copyright (C) 2003-2009 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/distributions/weibull_specification.m b/matlab/distributions/weibull_specification.m index 8036dcb8d..b9d498a53 100644 --- a/matlab/distributions/weibull_specification.m +++ b/matlab/distributions/weibull_specification.m @@ -2,14 +2,14 @@ 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 +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -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 1f18c3f56..145984cec 100644 --- a/matlab/do_parameter_initialization.m +++ b/matlab/do_parameter_initialization.m @@ -6,24 +6,24 @@ 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 -% Copyright (C) 2013 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % @@ -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 d2e35a105..784911f7e 100644 --- a/matlab/dr_block.m +++ b/matlab/dr_block.m @@ -1,40 +1,40 @@ 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-2016 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -69,13 +69,13 @@ if (isfield(M_,'block_structure')) else data = M_; Size = 1; -end; +end if (options_.bytecode) [chck, zz, data]= bytecode('dynamic','evaluate', z, zx, M_.params, dr.ys, 1, data); else [r, data] = feval([M_.fname '_dynamic'], options_, M_, oo_, z', zx, M_.params, dr.ys, M_.maximum_lag+1, data); chck = 0; -end; +end mexErrCheck('bytecode', chck); dr.full_rank = 1; dr.eigval = []; @@ -90,7 +90,7 @@ n_sv = size(dr.state_var, 2); dr.ghx = zeros(M_.endo_nbr, length(dr.state_var)); dr.exo_var = 1:M_.exo_nbr; dr.ghu = zeros(M_.endo_nbr, M_.exo_nbr); -for i = 1:Size; +for i = 1:Size ghx = []; indexi_0 = 0; if (verbose) @@ -98,7 +98,7 @@ for i = 1:Size; disp(['Block ' int2str(i)]); disp('-----------'); data(i) - end; + end n_pred = data(i).n_backward; n_fwrd = data(i).n_forward; n_both = data(i).n_mixed; @@ -118,20 +118,20 @@ for i = 1:Size; disp(jacob); disp('lead_lag_incidence'); disp(lead_lag_incidence); - end; + end 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 + end + end + if maximum_lag > 0 && (n_pred > 0 || n_both > 0) && block_type ~= 1 indexi_0 = min(lead_lag_incidence(2,:)); - end; + end switch block_type case 1 %% ------------------------------------------------------------------ @@ -153,7 +153,7 @@ for i = 1:Size; if (maximum_lag > 0 && n_pred > 0) [indx_r, tmp1, indx_r_v] = find(M_.block_structure.block(i).lead_lag_incidence(1,:)); ghx = - B \ jacob(:,indx_r_v); - end; + end if other_endo_nbr fx = data(i).g1_o; % retrieves the derivatives with respect to endogenous @@ -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; - + end + if exo_nbr fu = data(i).g1_x; exo = dr.exo_var; @@ -194,7 +194,7 @@ for i = 1:Size; fu_complet = zeros(n, M_.exo_nbr); fu_complet(:,data(i).exogenous) = fu; ghu = - B \ fu_complet; - end; + end else exo = dr.exo_var; if other_endo_nbr > 0 @@ -229,7 +229,7 @@ for i = 1:Size; indx_r = find(M_.block_structure.block(i).lead_lag_incidence(3,:)); indx_c = M_.block_structure.block(i).lead_lag_incidence(3,indx_r); ghx = - inv(jacob(indx_r, indx_c)); - end; + end ghu = - inv(jacob(indx_r, indx_c)) * data(i).g1_x; end case 3 @@ -241,7 +241,7 @@ for i = 1:Size; else data(i).eigval = []; data(i).rank = 0; - end; + end dr.eigval = [dr.eigval ; data(i).eigval]; %First order approximation if task ~= 1 @@ -249,7 +249,7 @@ for i = 1:Size; ghx = - jacob(1 , 1 : n_pred) / jacob(1 , n_pred + n_static + 1 : n_pred + n_static + n_pred + n_both); else ghx = 0; - end; + end if other_endo_nbr fx = data(i).g1_o; % retrieves the derivatives with respect to endogenous @@ -269,12 +269,12 @@ 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; - end; + end if exo_nbr fu = data(i).g1_x; if other_endo_nbr > 0 @@ -287,7 +287,7 @@ for i = 1:Size; exo = dr.exo_var; else ghu = - fu / jacob(1 , n_pred + 1 : n_pred + n_static + n_pred + n_both); - end; + end else if other_endo_nbr > 0 l_u_sv = dr.ghu(dr.state_var,:); @@ -311,7 +311,7 @@ for i = 1:Size; data(i).eigval = []; data(i).rank = 0; full_rank = 1; - end; + end dr.full_rank = dr.full_rank && full_rank; dr.eigval = [dr.eigval ; data(i).eigval]; case 6 @@ -322,7 +322,7 @@ for i = 1:Size; + n_pred + n_both) \ jacob(: , 1 : n_pred); else ghx = 0; - end; + end if maximum_lag > 0 && n_pred > 0 data(i).eigval = -eig(ghx(n_static+1:end,:)); data(i).rank = 0; @@ -331,7 +331,7 @@ for i = 1:Size; data(i).eigval = []; data(i).rank = 0; full_rank = 1; - end; + end dr.eigval = [dr.eigval ; data(i).eigval]; dr.full_rank = dr.full_rank && full_rank; if task ~= 1 @@ -354,11 +354,11 @@ 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; - end; + end if exo_nbr fu = data(i).g1_x; if other_endo_nbr > 0 @@ -371,7 +371,7 @@ for i = 1:Size; exo = dr.exo_var; else ghu = - fu / jacob(: , n_pred + 1 : n_pred + n_static + n_pred + n_both); - end; + end else if other_endo_nbr > 0 l_u_sv = dr.ghu(dr.state_var,:); @@ -397,14 +397,14 @@ for i = 1:Size; data(i).eigval = []; data(i).rank = 0; full_rank = 1; - end; + end 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 @@ -413,7 +413,7 @@ for i = 1:Size; aa = Q'*jacob; else aa = jacob; - end; + end index_0m = (n_static+1:n_static+n_pred) + indexi_0 - 1; index_0p = (n_static+n_pred+1:n) + indexi_0 - 1; index_m = 1:(n_pred+n_both); @@ -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) ] ]; @@ -445,7 +445,7 @@ for i = 1:Size; if (verbose) disp('eigval'); disp(data(i).eigval); - end; + end if info1 if info1 == -30 % one eigenvalue is close to 0/0 @@ -468,7 +468,7 @@ for i = 1:Size; disp(['sum eigval > 1 = ' int2str(sum(abs(data(i).eigval) > 1.)) ' nyf=' int2str(nyf) ' and dr.rank=' int2str(data(i).rank)]); disp(['data(' int2str(i) ').eigval']); disp(data(i).eigval); - end; + end %First order approximation if task ~= 1 @@ -487,7 +487,7 @@ for i = 1:Size; if nba > nyf temp = sorted_roots(nd-nba+1:nd-nyf)-1-options_.qz_criterium; info(1) = 3; - elseif nba < nyf; + elseif nba < nyf temp = sorted_roots(nd-nyf+1:nd-nba)-1-options_.qz_criterium; info(1) = 4; end @@ -507,7 +507,7 @@ for i = 1:Size; % condest() fails on a scalar under Octave info(1) = 5; info(2) = condest(Z21); - return; + return else %gx = -inv(Z22) * Z21; gx = - Z22 \ Z21; @@ -520,20 +520,20 @@ for i = 1:Size; k2 = 1:(n_fwrd+n_both); ghx = [hx(k1,:); gx(k2(n_both+1:end),:)]; - end; - end; - - if task~= 1 + end + end + + 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 B_static = []; - end; + end %static variables, backward variable, mixed variables and forward variables B_pred = B(:,n_static+1:n_static+n_pred+n_both); B_fyd = B(:,n_static+n_pred+n_both+1:end); @@ -549,16 +549,16 @@ for i = 1:Size; temp = b10\(temp-b11*ghx); ghx = [temp; ghx]; temp = []; - end; - + 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; else fx = data(i).g1_o; - end; + end % retrieves the derivatives with respect to endogenous % variable belonging to previous blocks fx_tm1 = zeros(n,other_endo_nbr); @@ -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,23 +590,23 @@ 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; + end if options_.aim_solver ~= 1 && options_.use_qzdiv % Necessary when using Sims' routines for QZ ghx_other = real(ghx_other); end - + dr.ghx(endo, :) = dr.ghx(endo, :) + ghx_other; - end; + end if exo_nbr if n_static > 0 fu = Q' * data(i).g1_x; else fu = data(i).g1_x; - end; + end if other_endo_nbr > 0 l_u_sv = dr.ghu(dr.state_var,:); @@ -616,12 +616,12 @@ 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 ghu = - A_ \ fu; - end; + end else if other_endo_nbr > 0 l_u_sv = dr.ghu(dr.state_var,:); @@ -633,17 +633,17 @@ for i = 1:Size; exo = dr.exo_var; else ghu = []; - end; + end 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; @@ -671,7 +671,7 @@ for i = 1:Size; % end end end - end; + end if task ~=1 if (maximum_lag > 0 && (n_pred > 0 || n_both > 0)) sorted_col_dr_ghx = M_.block_structure.block(i).sorted_col_dr_ghx; @@ -680,27 +680,26 @@ for i = 1:Size; data(i).pol.i_ghx = sorted_col_dr_ghx; else data(i).pol.i_ghx = []; - end; + end data(i).ghu = ghu; dr.ghu(endo, exo) = ghu; data(i).pol.i_ghu = exo; - end; - + end if (verbose) disp('dr.ghx'); dr.ghx disp('dr.ghu'); dr.ghu - end; - -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; +end if (task == 1) - return; -end; + return +end diff --git a/matlab/draw_prior_density.m b/matlab/draw_prior_density.m index 23479b404..94f32ac88 100644 --- a/matlab/draw_prior_density.m +++ b/matlab/draw_prior_density.m @@ -1,20 +1,20 @@ -function [x,f,abscissa,dens,binf,bsup] = draw_prior_density(indx,bayestopt_); +function [x,f,abscissa,dens,binf,bsup] = draw_prior_density(indx,bayestopt_) % Computes values of prior densities at many points (before plotting) % % 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 -% Copyright (C) 2004-2011 Dynare Team +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % @@ -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 2e7251ac1..945c0fd86 100644 --- a/matlab/dsample.m +++ b/matlab/dsample.m @@ -1,21 +1,21 @@ 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 -% Copyright (C) 2001-2009 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/dsge_likelihood.m b/matlab/dsge_likelihood.m index b8ee614b9..0b62e5167 100644 --- a/matlab/dsge_likelihood.m +++ b/matlab/dsge_likelihood.m @@ -115,7 +115,7 @@ function [fval,info,exit_flag,DLIK,Hess,SteadyState,trend_coeff,Model,DynareOpti %! @end deftypefn %@eod: -% Copyright (C) 2004-2016 Dynare Team +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % @@ -167,11 +167,11 @@ if analytic_derivation && DynareOptions.loglinear error('The analytic_derivation and loglinear options are not compatible') end -if nargout==1, +if nargout==1 analytic_derivation=0; end -if analytic_derivation, +if analytic_derivation kron_flag=DynareOptions.analytic_derivation_mode; end @@ -186,7 +186,7 @@ if isestimation(DynareOptions) && ~isequal(DynareOptions.mode_compute,1) && any( exit_flag = 0; info(1) = 41; info(4)= sum((BoundsInfo.lb(k)-xparam1(k)).^2); - if analytic_derivation, + if analytic_derivation DLIK=ones(length(xparam1),1); end return @@ -199,7 +199,7 @@ if isestimation(DynareOptions) && ~isequal(DynareOptions.mode_compute,1) && any( exit_flag = 0; info(1) = 42; info(4)= sum((xparam1(k)-BoundsInfo.ub(k)).^2); - if analytic_derivation, + if analytic_derivation DLIK=ones(length(xparam1),1); end return @@ -274,35 +274,32 @@ if info(1) fval = Inf; info(4) = info(2); exit_flag = 0; - if analytic_derivation, + if analytic_derivation DLIK=ones(length(xparam1),1); end - return else fval = Inf; info(4) = 0.1; exit_flag = 0; - if analytic_derivation, + if analytic_derivation DLIK=ones(length(xparam1),1); end - return end end % check endogenous prior restrictions info=endogenous_prior_restrictions(T,R,Model,DynareOptions,DynareResults); -if info(1), +if info(1) fval = Inf; info(4)=info(2); exit_flag = 0; - if analytic_derivation, + if analytic_derivation DLIK=ones(length(xparam1),1); end return end -% % Define a vector of indices for the observed variables. Is this really usefull?... BayesInfo.mf = BayesInfo.mf1; @@ -433,7 +430,7 @@ switch DynareOptions.lik_init Pinf = blkdiag(Pinf,zeros(pp)); H1 = zeros(pp,1); mmm = mm+pp; - + end end @@ -446,14 +443,14 @@ switch DynareOptions.lik_init T,R,Q,H1,Z,mmm,pp,rr); diffuse_periods = size(dlik,1); end - if isnan(dLIK), + if isnan(dLIK) fval = Inf; info(1) = 45; info(4) = 0.1; exit_flag = 0; return end - + case 4% Start from the solution of the Riccati equation. if kalman_algo ~= 2 kalman_algo = 1; @@ -495,20 +492,19 @@ switch DynareOptions.lik_init error('dsge_likelihood:: Unknown initialization approach for the Kalman filter!') end -if analytic_derivation, +if analytic_derivation offset = EstimatedParameters.nvx; offset = offset+EstimatedParameters.nvn; offset = offset+EstimatedParameters.ncx; offset = offset+EstimatedParameters.ncn; - no_DLIK = 0; full_Hess = analytic_derivation==2; asy_Hess = analytic_derivation==-2; outer_product_gradient = analytic_derivation==-1; - if asy_Hess, + if asy_Hess analytic_derivation=1; end - if outer_product_gradient, + if outer_product_gradient analytic_derivation=1; end DLIK = []; @@ -526,8 +522,7 @@ if analytic_derivation, else indparam=[]; end - - if full_Hess, + if full_Hess [dum, DT, DOm, DYss, dum2, D2T, D2Om, D2Yss] = getH(A, B, EstimatedParameters, Model,DynareResults,DynareOptions,kron_flag,indparam,indexo,iv); clear dum dum2; else @@ -537,15 +532,15 @@ if analytic_derivation, DT = derivatives_info.DT(iv,iv,:); DOm = derivatives_info.DOm(iv,iv,:); DYss = derivatives_info.DYss(iv,:); - if isfield(derivatives_info,'full_Hess'), + if isfield(derivatives_info,'full_Hess') full_Hess = derivatives_info.full_Hess; end - if full_Hess, + if full_Hess D2T = derivatives_info.D2T; D2Om = derivatives_info.D2Om; D2Yss = derivatives_info.D2Yss; end - if isfield(derivatives_info,'no_DLIK'), + if isfield(derivatives_info,'no_DLIK') no_DLIK = derivatives_info.no_DLIK; end clear('derivatives_info'); @@ -554,8 +549,8 @@ if analytic_derivation, DH=zeros([length(H),length(H),length(xparam1)]); DQ=zeros([size(Q),length(xparam1)]); DP=zeros([size(T),length(xparam1)]); - if full_Hess, - for j=1:size(D2Yss,1), + if full_Hess + for j=1:size(D2Yss,1) tmp(j,:,:) = blkdiag(zeros(offset,offset), squeeze(D2Yss(j,:,:))); end D2Yss = tmp; @@ -563,7 +558,7 @@ if analytic_derivation, D2P=sparse(size(D2Om,1),size(D2Om,2)); %zeros([size(T),length(xparam1),length(xparam1)]); jcount=0; end - if DynareOptions.lik_init==1, + 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)); @@ -572,7 +567,7 @@ if analytic_derivation, % dum(kk) = 0; DP(:,:,i)=dum; if full_Hess - for j=1:i, + 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); @@ -592,7 +587,7 @@ if analytic_derivation, end end offset = offset + EstimatedParameters.nvn; - if DynareOptions.lik_init==1, + 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); @@ -601,7 +596,7 @@ if analytic_derivation, if full_Hess DTj = DT(:,:,j+offset); DPj = dum; - for i=1:j+offset, + for i=1:j+offset jcount=jcount+1; DTi = DT(:,:,i); DPi = DP(:,:,i); @@ -616,11 +611,11 @@ if analytic_derivation, end end end - if analytic_derivation==1, + if analytic_derivation==1 analytic_deriv_info={analytic_derivation,DT,DYss,DOm,DH,DP,asy_Hess}; else analytic_deriv_info={analytic_derivation,DT,DYss,DOm,DH,DP,D2T,D2Yss,D2Om,D2H,D2P}; - clear DT DYss DOm DP D2T D2Yss D2Om D2H D2P, + clear DT DYss DOm DP D2T D2Yss D2Om D2H D2P end else analytic_deriv_info={0}; @@ -645,10 +640,9 @@ 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), ... a,Pstar, ... kalman_tol, riccati_tol, ... @@ -677,7 +671,7 @@ if ((kalman_algo==1) || (kalman_algo==3))% Multivariate Kalman Filter T,Q,R,H,Z,mm,pp,rr,Zflag,diffuse_periods); end end - if analytic_derivation, + if analytic_derivation LIK1=LIK; LIK=LIK1{1}; lik1=lik; @@ -701,8 +695,8 @@ if ((kalman_algo==1) || (kalman_algo==3))% Multivariate Kalman Filter else if DynareOptions.lik_init==3 LIK = LIK + dLIK; - if analytic_derivation==0 && nargout>3, - if ~singular_diffuse_filter, + if analytic_derivation==0 && nargout>3 + if ~singular_diffuse_filter lik = [dlik; lik]; else lik = [sum(dlik,2); lik]; @@ -718,7 +712,7 @@ if (kalman_algo==2) || (kalman_algo==4) if isequal(H,0) H1 = zeros(pp,1); mmm = mm; - if analytic_derivation, + if analytic_derivation DH = zeros(pp,length(xparam1)); end else @@ -726,8 +720,8 @@ if (kalman_algo==2) || (kalman_algo==4) H1 = diag(H); mmm = mm; clear('tmp') - if analytic_derivation, - for j=1:pp, + if analytic_derivation + for j=1:pp tmp(j,:)=DH(j,j,:); end DH=tmp; @@ -752,21 +746,20 @@ 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 - if analytic_derivation, + if analytic_derivation analytic_deriv_info{5}=DH; end - [LIK, lik] = univariate_kalman_filter(DatasetInfo.missing.aindex,DatasetInfo.missing.number_of_observations,DatasetInfo.missing.no_more_missing_observations,Y,diffuse_periods+1,size(Y,2), ... a,Pstar, ... DynareOptions.kalman_tol, ... DynareOptions.riccati_tol, ... DynareOptions.presample, ... T,Q,R,H1,Z,mmm,pp,rr,Zflag,diffuse_periods,analytic_deriv_info{:}); - if analytic_derivation, + if analytic_derivation LIK1=LIK; LIK=LIK1{1}; lik1=lik; @@ -774,7 +767,7 @@ if (kalman_algo==2) || (kalman_algo==4) end if DynareOptions.lik_init==3 LIK = LIK+dLIK; - if analytic_derivation==0 && nargout>3, + if analytic_derivation==0 && nargout>3 lik = [dlik; lik]; end end @@ -785,12 +778,12 @@ if analytic_derivation DLIK = LIK1{2}; % [DLIK] = score(T,R,Q,H,Pstar,Y,DT,DYss,DOm,DH,DP,start,Z,kalman_tol,riccati_tol); end - if full_Hess , + if full_Hess Hess = -LIK1{3}; % [Hess, DLL] = get_Hessian(T,R,Q,H,Pstar,Y,DT,DYss,DOm,DH,DP,D2T,D2Yss,D2Om,D2H,D2P,start,Z,kalman_tol,riccati_tol); % Hess0 = getHessian(Y,T,DT,D2T, R*Q*transpose(R),DOm,D2Om,Z,DYss,D2Yss); end - if asy_Hess, + if asy_Hess % if ~((kalman_algo==2) || (kalman_algo==4)), % [Hess] = AHessian(T,R,Q,H,Pstar,Y,DT,DYss,DOm,DH,DP,start,Z,kalman_tol,riccati_tol); % else @@ -829,7 +822,7 @@ likelihood = LIK; % 5. Adds prior if necessary % ------------------------------------------------------------------------------ if analytic_derivation - if full_Hess, + if full_Hess [lnprior, dlnprior, d2lnprior] = priordens(xparam1,BayesInfo.pshape,BayesInfo.p6,BayesInfo.p7,BayesInfo.p3,BayesInfo.p4); Hess = Hess - d2lnprior; else @@ -838,7 +831,7 @@ if analytic_derivation if no_DLIK==0 DLIK = DLIK - dlnprior'; end - if outer_product_gradient, + if outer_product_gradient dlik = lik1{2}; dlik=[- dlnprior; dlik(start:end,:)]; Hess = dlik'*dlik; @@ -884,7 +877,7 @@ if ~DynareOptions.kalman.keep_kalman_algo_if_singularity_is_detected DynareOptions.kalman_algo = kalman_algo; end -if analytic_derivation==0 && nargout>3, +if analytic_derivation==0 && nargout>3 lik=lik(start:end,:); DLIK=[-lnprior; lik(:)]; end diff --git a/matlab/dsge_simulated_theoretical_correlation.m b/matlab/dsge_simulated_theoretical_correlation.m index 23485a8d5..ae141905b 100644 --- a/matlab/dsge_simulated_theoretical_correlation.m +++ b/matlab/dsge_simulated_theoretical_correlation.m @@ -17,7 +17,7 @@ function [nvar,vartan,CorrFileNumber] = dsge_simulated_theoretical_correlation(S % vartan [char] array of characters (with nvar rows). % CorrFileNumber [integer] scalar, number of prior or posterior data files (for correlation). -% Copyright (C) 2007-2015 Dynare Team +% Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. % @@ -126,7 +126,7 @@ for file = 1:NumberOfDrawsFiles Correlation_array = zeros(NumberOfLinesInTheLastCorrFile,nvar,nvar,nar); NumberOfCorrLines = NumberOfLinesInTheLastCorrFile; CorrFileNumber = CorrFileNumber - 1; - elseif test<0; + elseif test<0 Correlation_array = zeros(MaXNumberOfCorrLines,nvar,nvar,nar); else clear('Correlation_array'); diff --git a/matlab/dsge_simulated_theoretical_covariance.m b/matlab/dsge_simulated_theoretical_covariance.m index 8296b90da..304028ba5 100644 --- a/matlab/dsge_simulated_theoretical_covariance.m +++ b/matlab/dsge_simulated_theoretical_covariance.m @@ -16,7 +16,7 @@ function [nvar,vartan,CovarFileNumber] = dsge_simulated_theoretical_covariance(S % vartan [char] array of characters (with nvar rows). % CovarFileNumber [integer] scalar, number of prior or posterior data files (for covariance). -% Copyright (C) 2007-2015 Dynare Team +% 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 1cb8f0d31..9eb985174 100644 --- a/matlab/dsge_simulated_theoretical_variance_decomposition.m +++ b/matlab/dsge_simulated_theoretical_variance_decomposition.m @@ -18,7 +18,7 @@ function [nvar,vartan,NumberOfDecompFiles] = ... % vartan [char] array of characters (with nvar rows). % CovarFileNumber [integer] scalar, number of prior or posterior data files (for covariance). -% Copyright (C) 2007-2015 Dynare Team +% Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. % @@ -121,7 +121,7 @@ for file = 1:NumberOfDrawsFiles 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; + only_non_stationary_vars=1; end end if only_non_stationary_vars @@ -129,7 +129,7 @@ for file = 1:NumberOfDrawsFiles 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 @@ -150,7 +150,7 @@ for file = 1:NumberOfDrawsFiles if ~test% Prepare the last round... Decomposition_array = zeros(NumberOfLinesInTheLastDecompFile,nvar*nexo); NumberOfDecompLines = NumberOfLinesInTheLastDecompFile; - elseif test<0; + elseif test<0 Decomposition_array = zeros(MaXNumberOfDecompLines,nvar*nexo); else clear('Decomposition_array'); diff --git a/matlab/dsge_var_likelihood.m b/matlab/dsge_var_likelihood.m index c37fca058..9878d19c9 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. @@ -108,7 +108,7 @@ if isestimation(DynareOptions) && DynareOptions.mode_compute ~= 1 && any(xparam1 exit_flag = 0; info(1) = 41; info(4)= sum((BoundsInfo.lb(k)-xparam1(k)).^2); - return; + return end % Return, with endogenous penalty, if some dsge-parameters are greater than the upper bound of the prior domain. @@ -118,7 +118,7 @@ if isestimation(DynareOptions) && DynareOptions.mode_compute ~= 1 && any(xparam1 exit_flag = 0; info(1) = 42; info(4) = sum((xparam1(k)-BoundsInfo.ub(k)).^2); - return; + return end % Get the variance of each structural innovation. @@ -137,7 +137,7 @@ Model.Sigma_e = Q; dsge_prior_weight = Model.params(dsge_prior_weight_idx); % Is the dsge prior proper? -if dsge_prior_weight<(NumberOfParameters+NumberOfObservedVariables)/NumberOfObservations; +if dsge_prior_weight<(NumberOfParameters+NumberOfObservedVariables)/NumberOfObservations fval = Inf; exit_flag = 0; info(1) = 51; @@ -239,14 +239,14 @@ if ~SIGMA_u_star_is_positive_definite info(1) = 53; info(4) = penalty; exit_flag = 0; - return; + return end if ~isinf(dsge_prior_weight)% Evaluation of the likelihood of the dsge-var model when the dsge prior weight is finite. tmp0 = dsge_prior_weight*NumberOfObservations*TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1) + mYY ; %first term of square bracket in formula (29), DS (2004) tmp1 = dsge_prior_weight*NumberOfObservations*GYX + mYX; %first element of second term of square bracket in formula (29), DS (2004) tmp2 = inv(dsge_prior_weight*NumberOfObservations*GXX+mXX); %middle element of second term of square bracket in formula (29), DS (2004) - SIGMA_u_tilde = tmp0 - tmp1*tmp2*tmp1'; %square bracket term in formula (29), DS (2004) + 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 @@ -254,7 +254,7 @@ if ~isinf(dsge_prior_weight)% Evaluation of the likelihood of the dsge-var model info(1) = 52; info(4) = penalty; exit_flag = 0; - return; + return end SIGMA_u_tilde = SIGMA_u_tilde / (NumberOfObservations*(1+dsge_prior_weight)); %prefactor of formula (29), DS (2004) PHI_tilde = tmp2*tmp1'; %formula (28), DS (2004) @@ -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 7ce72e836..9d9bb31f4 100644 --- a/matlab/dy_date.m +++ b/matlab/dy_date.m @@ -1,6 +1,6 @@ function y=dy_date(year,period) -% Copyright (C) 2005-2009 Dynare Team +% Copyright (C) 2005-2017 Dynare Team % % This file is part of Dynare. % @@ -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 a944dc188..50e62b4f1 100644 --- a/matlab/dyn2vec.m +++ b/matlab/dyn2vec.m @@ -12,9 +12,9 @@ function [z,zss]=dyn2vec(s1,s2) % % SPECIAL REQUIREMENTS % none -% +% -% Copyright (C) 2001-2009 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -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_autocorr.m b/matlab/dyn_autocorr.m index 43534d7be..e4565cf45 100644 --- a/matlab/dyn_autocorr.m +++ b/matlab/dyn_autocorr.m @@ -35,6 +35,6 @@ acf = NaN(ar+1,1); acf(1)=1; m = mean(y); sd = std(y,1); -for i=1:ar, +for i=1:ar acf(i+1) = (y(i+1:end)-m)'*(y(1:end-i)-m)./((size(y,1))*sd^2); end diff --git a/matlab/dyn_diag_vech.m b/matlab/dyn_diag_vech.m index 5d5d94664..e8b9cf338 100644 --- a/matlab/dyn_diag_vech.m +++ b/matlab/dyn_diag_vech.m @@ -1,14 +1,14 @@ 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 +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/dyn_first_order_solver.m b/matlab/dyn_first_order_solver.m index 0adf0e2c0..a09aa1645 100644 --- a/matlab/dyn_first_order_solver.m +++ b/matlab/dyn_first_order_solver.m @@ -47,7 +47,7 @@ function [dr,info] = dyn_first_order_solver(jacobia,DynareModel,dr,DynareOptions %! @end deftypefn %@eod: -% Copyright (C) 2001-2012 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -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)'); ... @@ -184,7 +184,7 @@ if task ~= 1 && (DynareOptions.dr_cycle_reduction || DynareOptions.dr_logarithmi 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 @@ -244,14 +244,13 @@ else if nba > nsfwrd temp = temp(nd-nba+1:nd-nsfwrd)-1-DynareOptions.qz_criterium; info(1) = 3; - elseif nba < nsfwrd; + elseif nba < nsfwrd temp = temp(nd-nsfwrd+1:nd-nba)-1-DynareOptions.qz_criterium; info(1) = 4; end info(2) = temp'*temp; return end - %First order approximation indx_stable_root = 1: (nd - nsfwrd); %=> index of stable roots indx_explosive_root = npred + nboth + 1:nd; %=> index of explosive roots @@ -267,7 +266,7 @@ else % Z22 is near singular info(1) = 5; info(2) = -log(rc); - return; + return end gx = -minus_gx; % predetermined variables @@ -285,7 +284,7 @@ if nstatic > 0 B_static = B(:,1:nstatic); % submatrix containing the derivatives w.r. to static variables else B_static = []; -end; +end %static variables, backward variable, mixed variables and forward variables B_pred = B(:,nstatic+1:nstatic+npred+nboth); B_fyd = B(:,nstatic+npred+nboth+1:end); @@ -309,12 +308,12 @@ if exo_nbr fu = Q' * jacobia(:,innovations_idx); else fu = jacobia(:,innovations_idx); - end; + end ghu = - A_ \ fu; else ghu = []; -end; +end dr.ghx = ghx; dr.ghu = ghu; diff --git a/matlab/dyn_forecast.m b/matlab/dyn_forecast.m index e5faf86af..a58b126a1 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) @@ -21,7 +21,7 @@ function [forecast,info] = dyn_forecast(var_list,M,options,oo,task,dataset_info) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2003-2016 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -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,10 +146,10 @@ 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,... @@ -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 ca14e351f..8cfdc6e53 100644 --- a/matlab/dyn_latex_table.m +++ b/matlab/dyn_latex_table.m @@ -1,7 +1,7 @@ function dyn_latex_table(M_,options_,title,LaTeXtitle,headers,labels,values,label_width,val_width,val_precis,optional_header) %function dyn_latex_table(M_,options_,title,LaTeXtitle,headers,labels,values,label_width,val_width,val_precis,optional_header) -% Copyright (C) 2015-2016 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/dyn_ramsey_static.m b/matlab/dyn_ramsey_static.m index d20582c3b..25b5301e6 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 @@ -18,7 +18,7 @@ function [steady_state,params,check] = dyn_ramsey_static(ys_init,M,options_,oo) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2003-2016 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -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 @@ -125,7 +125,7 @@ if options_.steadystate_flag 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 steady_state=NaN(endo_nbr,1); - return; + return end end @@ -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); @@ -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 1292523a4..b677c7840 100644 --- a/matlab/dyn_risky_steadystate_solver.m +++ b/matlab/dyn_risky_steadystate_solver.m @@ -62,7 +62,7 @@ function [dr,info] = dyn_risky_steadystate_solver(ys0,M, ... %! @end deftypefn %@eod: -% Copyright (C) 2001-2012 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -106,7 +106,7 @@ 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, ... @@ -118,7 +118,7 @@ if isfield(options,'portfolio') && options.portfolio == 1 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); + [resids,dr1] = risky_residuals_ds(x,pm,M,dr,options,oo); ys1 = dr1.ys; else pm = model_structure(M,options); @@ -201,7 +201,7 @@ v_p = pm.v_p; v_np = pm.v_np; % computing steady state of non-portfolio variables consistent with -% assumed portfolio +% assumed portfolio dr.ys(v_p) = x; ys0 = dr.ys(v_np); f_h =str2func([M.fname '_static']); @@ -300,19 +300,19 @@ z = z(iyr0) ; 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); @@ -333,13 +333,13 @@ if nargout > 1 [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); @@ -389,9 +389,9 @@ if nargout > 1 print_info(info, 0, options); return end - + disp_dr(dr,dr.order_var,[]); - + end end @@ -421,7 +421,7 @@ for i=1:n 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 @@ -435,7 +435,7 @@ 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)'); +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; @@ -506,7 +506,7 @@ 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)'); +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; diff --git a/matlab/dyn_saveas.m b/matlab/dyn_saveas.m index fb70bab75..009a49d5e 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,7 +53,7 @@ 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 + % 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)]) diff --git a/matlab/dyn_second_order_solver.m b/matlab/dyn_second_order_solver.m index 37e13f841..df6ba7693 100644 --- a/matlab/dyn_second_order_solver.m +++ b/matlab/dyn_second_order_solver.m @@ -32,7 +32,7 @@ function dr = dyn_second_order_solver(jacobia,hessian_mat,dr,M_,threads_ABC,thre %! @end deftypefn %@eod: -% Copyright (C) 2001-2012 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -154,8 +154,8 @@ 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; +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); diff --git a/matlab/dyn_unvech.m b/matlab/dyn_unvech.m index f70670a98..0c6c853cc 100644 --- a/matlab/dyn_unvech.m +++ b/matlab/dyn_unvech.m @@ -1,13 +1,13 @@ 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 +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/dyn_vech.m b/matlab/dyn_vech.m index 6e54c4050..dc18f974b 100644 --- a/matlab/dyn_vech.m +++ b/matlab/dyn_vech.m @@ -1,13 +1,13 @@ 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 +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/dyn_waitbar.m b/matlab/dyn_waitbar.m index 5b315a5d1..43567dcd3 100644 --- a/matlab/dyn_waitbar.m +++ b/matlab/dyn_waitbar.m @@ -4,7 +4,7 @@ function h = dyn_waitbar(prctdone, varargin) % octave and when console_mode=1 % -% Copyright (C) 2011 Dynare Team +% Copyright (C) 2011-2017 Dynare Team % % This file is part of Dynare. % @@ -30,7 +30,7 @@ if iscell(prctdone) prctdone=prctdone{1}; end -if prctdone==0, +if prctdone==0 init=1; if isempty(whoiam) whoiam=0; @@ -38,23 +38,20 @@ if prctdone==0, else init=0; end -if nargout, +if nargout h=[]; end if ~whoiam - if isoctave || options_.console_mode - - if init, + if init diary off; running_text = varargin{1}; newString=''; - return; - elseif nargin>2, + return + elseif nargin>2 running_text = varargin{2}; end - if isoctave printf([running_text,' %3.f%% done\r'], prctdone*100); else @@ -62,26 +59,23 @@ if ~whoiam newString=sprintf([running_text,' %3.f%% done'], prctdone*100); fprintf([s0,'%s'],newString); end - else - if nargout, + if nargout h = waitbar(prctdone,varargin{:}); else waitbar(prctdone,varargin{:}); end end - else - if init, + if init running_text = varargin{1}; elseif nargin>2 running_text = varargin{2}; end - if Parallel.Local, + if Parallel.Local waitbarTitle=['Local ']; else waitbarTitle=[Parallel.ComputerName]; end fMessageStatus(prctdone,whoiam,running_text, waitbarTitle, Parallel); end - diff --git a/matlab/dyn_waitbar_close.m b/matlab/dyn_waitbar_close.m index 894e4c6fa..c2864a9b6 100644 --- a/matlab/dyn_waitbar_close.m +++ b/matlab/dyn_waitbar_close.m @@ -1,10 +1,10 @@ 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 % -% Copyright (C) 2011 Dynare Team +% Copyright (C) 2011-2017 Dynare Team % % This file is part of Dynare. % @@ -22,14 +22,12 @@ function dyn_waitbar_close(h) % along with Dynare. If not, see . global options_ -if isoctave || options_.console_mode, +if isoctave || options_.console_mode clear dyn_waitbar; - diary on, + diary on fprintf('\n'); else - close(h), + close(h) end clear dyn_waitbar; - - diff --git a/matlab/dynare.m b/matlab/dynare.m index 38dbe1b4c..472888be9 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,14 +9,14 @@ function dynare(fname, varargin) % INPUTS % fname: file name % varargin: list of arguments following fname -% +% % OUTPUTS % none -% +% % SPECIAL REQUIREMENTS % none -% Copyright (C) 2001-2015 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -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 @@ -114,9 +114,9 @@ else || ~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; + end fnamelength = length(fname) - 4; -end; +end if fnamelength + length('_set_auxiliary_variables') > namelengthmax() error('The name of your MOD file is too long, please shorten it') @@ -192,7 +192,7 @@ end disp(result) if ismember('onlymacro', varargin) disp('Preprocesser stopped after macroprocessing step because of ''onlymacro'' option.'); - return; + return end % post-dynare-prerocessor-hook diff --git a/matlab/dynare_config.m b/matlab/dynare_config.m index 342a03c4b..ae65aab15 100644 --- a/matlab/dynare_config.m +++ b/matlab/dynare_config.m @@ -15,7 +15,7 @@ function dynareroot = dynare_config(path_to_dynare,verbose) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2001-2016 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/dynare_estimation.m b/matlab/dynare_estimation.m index a476a8072..98ad16c32 100644 --- a/matlab/dynare_estimation.m +++ b/matlab/dynare_estimation.m @@ -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); @@ -82,8 +82,8 @@ if nnobs>1 || nfirstobs > 1 if nnobs>1 options_.nobs = nobs(i); M_.dname = [dname '_' int2str(nobs(i))]; - elseif nfirstobs>1; - options_.first_obs=first_obs(i); + elseif nfirstobs>1 + options_.first_obs=first_obs(i); M_.dname = [dname '_' int2str(first_obs(i))]; end dynare_estimation_1(var_list,M_.dname); @@ -97,7 +97,7 @@ if nnobs>1 || nfirstobs > 1 end if nnobs>1 oo_recursive_{nobs(i)} = oo_; - elseif nfirstobs>1; + elseif nfirstobs>1 oo_recursive_{first_obs(i)} = oo_; end end @@ -105,7 +105,7 @@ else dynare_estimation_1(var_list,dname); end -if isnumeric(options_.mode_compute) && options_.mode_compute && options_.analytic_derivation, +if isnumeric(options_.mode_compute) && options_.mode_compute && options_.analytic_derivation options_.analytic_derivation=analytic_derivation0; end @@ -138,7 +138,7 @@ 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, ... @@ -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 83361af11..a4b416614 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 @@ -202,7 +202,7 @@ if ~isequal(options_.mode_compute,0) && ~options_.mh_posterior_mode_estimation end end end - if options_.analytic_derivation, + if options_.analytic_derivation options_analytic_derivation_old = options_.analytic_derivation; options_.analytic_derivation = -1; if ~isempty(newratflag) && newratflag~=0 %numerical hessian explicitly specified @@ -210,32 +210,32 @@ 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'), + 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_); options_.analytic_derivation = ana_deriv_old; - elseif ~isnumeric(options_.mode_compute) || ~(isequal(options_.mode_compute,5) && newratflag~=1), + 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 if options_.hessian.use_penalized_objective penalized_objective_function = str2func('penalty_objective_function'); @@ -258,15 +258,15 @@ if ~isequal(options_.mode_compute,0) && ~options_.mh_posterior_mode_estimation % densitities for outer product gradient kalman_algo0 = options_.kalman_algo; compute_hessian = 1; - if ~((options_.kalman_algo == 2) || (options_.kalman_algo == 4)), + if ~((options_.kalman_algo == 2) || (options_.kalman_algo == 4)) options_.kalman_algo=2; - if options_.lik_init == 3, + if options_.lik_init == 3 options_.kalman_algo=4; end - elseif newratflag==0, % hh already contains outer product gradient with univariate filter - compute_hessian = 0; + elseif newratflag==0 % hh already contains outer product gradient with univariate filter + compute_hessian = 0; end - if compute_hessian, + if compute_hessian crit = options_.newrat.tolerance.f; newratflag = newratflag>0; hh = reshape(mr_hessian(xparam1,objective_function,fval,newratflag,crit,new_rat_hess_info,dataset_, dataset_info, options_,M_,estim_params_,bayestopt_,bounds,oo_), nx, nx); @@ -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,7 +481,7 @@ 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 @@ -490,11 +490,11 @@ if (any(bayestopt_.pshape >0 ) && options_.mh_replic) || ... 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; @@ -530,14 +530,13 @@ if options_.particle.status return end -if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.pshape ... - > 0) && options_.load_mh_file)) ... +if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.pshape> 0) && options_.load_mh_file)) ... || ~options_.smoother ) && options_.partial_information == 0 % to be fixed %% ML estimation, or posterior mode without Metropolis-Hastings or Metropolis without Bayesian smoothes variables [atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,T,R,P,PK,decomp,Trend,state_uncertainty,M_,oo_,options_,bayestopt_] = DsgeSmoother(xparam1,dataset_.nobs,transpose(dataset_.data),dataset_info.missing.aindex,dataset_info.missing.state,M_,oo_,options_,bayestopt_,estim_params_); [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); - if ~options_.nograph, + if ~options_.nograph [nbplt,nr,nc,lr,lc,nstar] = pltorg(M_.exo_nbr); if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) fidTeX = fopen([M_.fname '_SmoothedShocks.tex'],'w'); @@ -545,7 +544,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha fprintf(fidTeX,['%% ' datestr(now,0) '\n']); fprintf(fidTeX,' \n'); end - for plt = 1:nbplt, + for plt = 1:nbplt fh = dyn_figure(options_.nodisplay,'Name','Smoothed shocks'); NAMES = []; if options_.TeX, TeXNAMES = []; end @@ -557,7 +556,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha marker_string{1,1}='-r'; marker_string{2,1}='-k'; end - for i=1:nstar0, + for i=1:nstar0 k = (plt-1)*nstar+i; subplot(nr,nc,i); plot([1 gend],[0 0],marker_string{1,1},'linewidth',.5) @@ -699,7 +698,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha fprintf(fidTeX,['%% ' datestr(now,0) '\n']); fprintf(fidTeX,' \n'); end - for plt = 1:nbplt, + for plt = 1:nbplt fh = dyn_figure(options_.nodisplay,'Name','Historical and smoothed variables'); NAMES = []; if options_.TeX, TeXNAMES = []; end @@ -711,7 +710,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha marker_string{1,1}='-r'; marker_string{2,1}='--k'; end - for i=1:nstar0, + for i=1:nstar0 k = (plt-1)*nstar+i; subplot(nr,nc,i); plot(1:gend,yf(k,:),marker_string{1,1},'linewidth',1) @@ -745,7 +744,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha 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, + 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'); diff --git a/matlab/dynare_estimation_init.m b/matlab/dynare_estimation_init.m index 6e52a2d53..5ee9a9fa7 100644 --- a/matlab/dynare_estimation_init.m +++ b/matlab/dynare_estimation_init.m @@ -28,11 +28,11 @@ 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 -% Copyright (C) 2003-2016 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -104,7 +104,7 @@ 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']) @@ -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') @@ -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')]; @@ -474,18 +474,18 @@ else [junk,ic] = intersect(bayestopt_.smoother_var_list,nstatic+(1:npred)'); bayestopt_.smoother_restrict_columns = ic; [junk,bayestopt_.smoother_mf] = ismember(var_obs_index_dr, bayestopt_.smoother_var_list); -end; +end -if options_.analytic_derivation, - if options_.lik_init == 3, +if options_.analytic_derivation + if options_.lik_init == 3 error('analytic derivation is incompatible with diffuse filter') end options_.analytic_derivation = 1; - if ~(exist('sylvester3','file')==2), + if ~(exist('sylvester3','file')==2) dynareroot = strrep(which('dynare'),'dynare.m',''); addpath([dynareroot 'gensylv']) end - if estim_params_.np, + if estim_params_.np % check if steady state changes param values M=M_; M.params(estim_params_.param_vals(:,1)) = xparam1(estim_params_.nvx+estim_params_.ncx+estim_params_.nvn+estim_params_.ncn+1:end); %set parameters @@ -497,8 +497,8 @@ if options_.analytic_derivation, end [tmp1, params] = evaluate_steady_state(oo_.steady_state,M,options_,oo_,steadystate_check_flag); change_flag=any(find(params-M.params)); - if change_flag, - skipline(); + if change_flag + skipline() if any(isnan(params)) disp('After computing the steadystate, the following parameters are still NaN: '), disp(M.param_names(isnan(params),:)) @@ -609,7 +609,7 @@ if options_.load_results_after_load_mh end end -if options_.mh_replic || options_.load_mh_file, +if options_.mh_replic || options_.load_mh_file [current_options, options_] = check_posterior_sampler_options([], options_, bounds); options_.posterior_sampler_options.current_options = current_options; end diff --git a/matlab/dynare_gradient.m b/matlab/dynare_gradient.m index 91b4140c1..2f4dfc9d4 100644 --- a/matlab/dynare_gradient.m +++ b/matlab/dynare_gradient.m @@ -4,15 +4,15 @@ 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 +% +% Copyright (C) 2010-2017 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 9af832f7f..3717efa45 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 @@ -12,7 +12,7 @@ function dyn_graph=dynare_graph(dyn_graph,y,tit,x) % SPECIAL REQUIREMENT % none -% Copyright (C) 2006-2013 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -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; @@ -42,11 +42,11 @@ subplot(dyn_graph.nr,dyn_graph.nc,nplot); line_types = dyn_graph.line_types; line_type = line_types{1}; -for i=1:size(y,2); +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 ed4371034..72622314d 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 @@ -11,7 +11,7 @@ function dynare_graph_close() % SPECIAL REQUIREMENT % none -% Copyright (C) 2006-2009 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . - diff --git a/matlab/dynare_graph_init.m b/matlab/dynare_graph_init.m index 0783a4029..b97c2b5f8 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 a7d005b38..7b5c1e556 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,13 +13,13 @@ 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-2016 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -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 @@ -78,48 +78,48 @@ end options_ident = set_default_option(options_ident,'lik_init',1); options_ident = set_default_option(options_ident,'analytic_derivation',1); -if isfield(options_ident,'nograph'), +if isfield(options_ident,'nograph') options_.nograph=options_ident.nograph; end -if isfield(options_ident,'nodisplay'), +if isfield(options_ident,'nodisplay') options_.nodisplay=options_ident.nodisplay; end -if isfield(options_ident,'graph_format'), +if isfield(options_ident,'graph_format') options_.graph_format=options_ident.graph_format; end -if isfield(options_ident,'prior_trunc'), +if isfield(options_ident,'prior_trunc') options_.prior_trunc=options_ident.prior_trunc; end -if options_ident.gsa_sample_file, +if options_ident.gsa_sample_file GSAFolder = checkpath('gsa',M_.dname); - if options_ident.gsa_sample_file==1, + if options_ident.gsa_sample_file==1 load([GSAFolder,filesep,fname_,'_prior'],'lpmat','lpmat0','istable'); - elseif options_ident.gsa_sample_file==2, + elseif options_ident.gsa_sample_file==2 load([GSAFolder,filesep,fname_,'_mc'],'lpmat','lpmat0','istable'); else load([GSAFolder,filesep,options_ident.gsa_sample_file],'lpmat','lpmat0','istable'); end - if isempty(istable), + if isempty(istable) istable=1:size(lpmat,1); end - if ~isempty(lpmat0), + if ~isempty(lpmat0) lpmatx=lpmat0(istable,:); else lpmatx=[]; end pdraws0 = [lpmatx lpmat(istable,:)]; clear lpmat lpmat0 istable; -elseif nargin==1, +elseif nargin==1 pdraws0=[]; end external_sample=0; -if nargin==2 || ~isempty(pdraws0), +if nargin==2 || ~isempty(pdraws0) options_ident.prior_mc=size(pdraws0,1); options_ident.load_ident_files = 0; external_sample=1; end -if isempty(estim_params_), +if isempty(estim_params_) options_ident.prior_mc=1; options_ident.prior_range=0; prior_exist=0; @@ -164,28 +164,24 @@ end SampleSize = options_ident.prior_mc; -if ~(exist('sylvester3','file')==2), - +if ~(exist('sylvester3','file')==2) dynareroot = strrep(which('dynare'),'dynare.m',''); addpath([dynareroot 'gensylv']) end IdentifDirectoryName = CheckPath('identification',M_.dname); -if prior_exist, - +if prior_exist indx = []; - if ~isempty(estim_params_.param_vals), + if ~isempty(estim_params_.param_vals) indx = estim_params_.param_vals(:,1); end indexo=[]; if ~isempty(estim_params_.var_exo) indexo = estim_params_.var_exo(:,1); end - nparam = length(bayestopt_.name); np = estim_params_.np; - - if estim_params_.nvn || estim_params_.ncn, + if estim_params_.nvn || estim_params_.ncn error('Identification does not support measurement errors. Instead, define them explicitly in measurement equations in model definition.') else offset = estim_params_.nvx; @@ -199,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,'$',''); @@ -229,9 +225,9 @@ else end skipline() -disp(['==== Identification analysis ====' ]), +disp(['==== Identification analysis ====' ]) skipline() -if nparam<2, +if nparam<2 options_ident.advanced=0; advanced = options_ident.advanced; disp('There is only one parameter to study for identitification.') @@ -246,10 +242,9 @@ options_ident.max_dim_cova_group = min([options_ident.max_dim_cova_group,nparam- MaxNumberOfBytes=options_.MaxNumberOfBytes; store_options_ident = options_ident; -if iload <=0, - +if iload <=0 [I,J]=find(M_.lead_lag_incidence'); - if prior_exist, + if prior_exist % if exist([fname_,'_mean.mat'],'file'), % % disp('Testing posterior mean') % load([fname_,'_mean'],'xparam1') @@ -272,7 +267,7 @@ if iload <=0, case 'calibration' parameters_TeX = 'Calibration'; disp('Testing calibration') - params(1,:) = get_all_parameters(estim_params_,M_);; + params(1,:) = get_all_parameters(estim_params_,M_); case 'posterior_mode' parameters_TeX = 'Posterior mode'; disp('Testing posterior mode') @@ -290,7 +285,7 @@ if iload <=0, disp('Testing prior mode') params(1,:) = bayestopt_.p5(:); case 'prior_mean' - parameters_TeX = 'Prior mean'; + parameters_TeX = 'Prior mean'; disp('Testing prior mean') params(1,:) = bayestopt_.p1; otherwise @@ -311,37 +306,37 @@ if iload <=0, end [idehess_point, idemoments_point, idemodel_point, idelre_point, derivatives_info_point, info, options_ident] = ... identification_analysis(params,indx,indexo,options_ident,dataset_, dataset_info, prior_exist, name_tex,1,parameters,bounds); - if info(1)~=0, + if info(1)~=0 skipline() disp('----------- ') disp('Parameter error:') disp(['The model does not solve for ', parameters, ' with error code info = ', int2str(info(1))]), skipline() - if info(1)==1, + if info(1)==1 disp('info==1 %! The model doesn''t determine the current variables uniquely.') - elseif info(1)==2, + elseif info(1)==2 disp('info==2 %! MJDGGES returned an error code.') - elseif info(1)==3, + elseif info(1)==3 disp('info==3 %! Blanchard & Kahn conditions are not satisfied: no stable equilibrium. ') - elseif info(1)==4, + elseif info(1)==4 disp('info==4 %! Blanchard & Kahn conditions are not satisfied: indeterminacy. ') - elseif info(1)==5, + elseif info(1)==5 disp('info==5 %! Blanchard & Kahn conditions are not satisfied: indeterminacy due to rank failure. ') - elseif info(1)==6, + elseif info(1)==6 disp('info==6 %! The jacobian evaluated at the deterministic steady state is complex.') - elseif info(1)==19, + elseif info(1)==19 disp('info==19 %! The steadystate routine thrown an exception (inconsistent deep parameters). ') - elseif info(1)==20, + elseif info(1)==20 disp('info==20 %! Cannot find the steady state, info(2) contains the sum of square residuals (of the static equations). ') - elseif info(1)==21, + 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.') - elseif info(1)==22, + elseif info(1)==22 disp('info==22 %! The steady has NaNs. ') - elseif info(1)==23, + elseif info(1)==23 disp('info==23 %! M_.params has been updated in the steadystate routine and has complex valued scalars. ') - elseif info(1)==24, + elseif info(1)==24 disp('info==24 %! M_.params has been updated in the steadystate routine and has some NaNs. ') - elseif info(1)==30, + elseif info(1)==30 disp('info==30 %! Ergodic variance can''t be computed. ') end disp('----------- ') @@ -349,7 +344,7 @@ if iload <=0, if any(bayestopt_.pshape) disp('Try sampling up to 50 parameter sets from the prior.') kk=0; - while kk<50 && info(1), + while kk<50 && info(1) kk=kk+1; params = prior_draw(); [idehess_point, idemoments_point, idemodel_point, idelre_point, derivatives_info_point, info, options_ident] = ... @@ -381,11 +376,11 @@ if iload <=0, 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); - if ~options_.nograph, + if ~options_.nograph plot_identification(params,idemoments_point,idehess_point,idemodel_point,idelre_point,advanced,parameters,name,IdentifDirectoryName,parameters_TeX,name_tex); end - if SampleSize > 1, + if SampleSize > 1 skipline() disp('Monte Carlo Testing') h = dyn_waitbar(0,'Monte Carlo identification checks ...'); @@ -399,16 +394,16 @@ if iload <=0, iteration = 1; pdraws = []; end - while iteration < SampleSize, + while iteration < SampleSize loop_indx = loop_indx+1; - if external_sample, + if external_sample params = pdraws0(iteration+1,:); else params = prior_draw(); end [dum1, ideJ, ideH, ideGP, dum2 , info, options_MC] = ... identification_analysis(params,indx,indexo,options_MC,dataset_, dataset_info, prior_exist, name_tex,0,[],bounds); - if iteration==0 && info(1)==0, + if iteration==0 && info(1)==0 MAX_tau = min(SampleSize,ceil(MaxNumberOfBytes/(size(ideH.siH,1)*nparam)/8)); stoH = zeros([size(ideH.siH,1),nparam,MAX_tau]); stoJJ = zeros([size(ideJ.siJ,1),nparam,MAX_tau]); @@ -439,7 +434,7 @@ if iload <=0, idemoments.V = zeros(SampleSize,nparam,min(8,nparam)); delete([IdentifDirectoryName '/' M_.fname '_identif_*.mat']) end - if info(1)==0, + if info(1)==0 iteration = iteration + 1; run_index = run_index + 1; TAU(:,iteration)=ideH.TAU; @@ -469,9 +464,9 @@ if iload <=0, stoH(:,:,run_index) = ideH.siH; stoJJ(:,:,run_index) = ideJ.siJ; pdraws(iteration,:) = params; - if run_index==MAX_tau || iteration==SampleSize, + if run_index==MAX_tau || iteration==SampleSize file_index = file_index + 1; - if run_index 1, + + if SampleSize > 1 % if isoctave || options_.console_mode, % console_waitbar(0,iteration/SampleSize); % else @@ -492,31 +487,31 @@ if iload <=0, % end end end - + end - - - if SampleSize > 1, - if isoctave || options_.console_mode, + + + if SampleSize > 1 + if isoctave || options_.console_mode fprintf('\n'); diary on; else - close(h), + close(h) end normTAU=std(TAU')'; normLRE=std(LRE')'; normGAM=std(GAM')'; normaliz1=std(pdraws); iter=0; - for ifile_index = 1:file_index, + for ifile_index = 1:file_index load([IdentifDirectoryName '/' M_.fname '_identif_' int2str(ifile_index) '.mat'], 'stoH', 'stoJJ', 'stoLRE') - for irun=1:size(stoH,3), + for irun=1:size(stoH,3) iter=iter+1; siJnorm(iter,:) = vnorm(stoJJ(:,:,irun)./repmat(normGAM,1,nparam)).*normaliz1; 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; @@ -528,7 +523,7 @@ if iload <=0, siHnorm = idemodel_point.siHnorm; siLREnorm = idelre_point.siLREnorm; end - + else load([IdentifDirectoryName '/' M_.fname '_identif']) % identFiles = dir([IdentifDirectoryName '/' M_.fname '_identif_*']); @@ -537,86 +532,86 @@ else options_ident.prior_mc=size(pdraws,1); SampleSize = options_ident.prior_mc; options_.options_ident = options_ident; -end +end -if nargout>3 && iload, +if nargout>3 && iload filnam = dir([IdentifDirectoryName '/' M_.fname '_identif_*.mat']); H=[]; JJ = []; gp = []; - for j=1:length(filnam), + for j=1:length(filnam) load([IdentifDirectoryName '/' M_.fname '_identif_',int2str(j),'.mat']); H = cat(3,H, stoH(:,abs(iload),:)); JJ = cat(3,JJ, stoJJ(:,abs(iload),:)); gp = cat(3,gp, stoLRE(:,abs(iload),:)); - + end end -if iload, +if iload disp(['Testing ',parameters]) disp_identification(idehess_point.params, idemodel_point, idemoments_point, name,advanced); - if ~options_.nograph, + if ~options_.nograph plot_identification(idehess_point.params,idemoments_point,idehess_point,idemodel_point,idelre_point,advanced,parameters,name,IdentifDirectoryName,[],name_tex); end end -if SampleSize > 1, +if SampleSize > 1 fprintf('\n') disp('Testing MC sample') disp_identification(pdraws, idemodel, idemoments, name); - if ~options_.nograph, + if ~options_.nograph plot_identification(pdraws,idemoments,idehess_point,idemodel,idelre,advanced,'MC sample ',name, IdentifDirectoryName,[],name_tex); end - if advanced, + if advanced jcrit=find(idemoments.ino); - if length(jcrit) 1, end if isoctave - warning('on'), + warning('on') else - warning on, + warning on end skipline() -disp(['==== Identification analysis completed ====' ]), +disp(['==== Identification analysis completed ====' ]) skipline(2) options_ = options0_; diff --git a/matlab/dynare_resolve.m b/matlab/dynare_resolve.m index a2fad992a..32a1a885d 100644 --- a/matlab/dynare_resolve.m +++ b/matlab/dynare_resolve.m @@ -49,7 +49,7 @@ function [A,B,ys,info,Model,DynareOptions,DynareResults] = dynare_resolve(Model, %! @end deftypefn %@eod: -% Copyright (C) 2001-2016 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -90,7 +90,7 @@ switch nargin ic = [ nstatic+(1:nspred) endo_nbr+(1:size(DynareResults.dr.ghx,2)-nspred) ]'; else ic = DynareResults.dr.restrict_columns; - end; + end case 4 iv = DynareResults.dr.restrict_var_list; ic = DynareResults.dr.restrict_columns; diff --git a/matlab/dynare_sensitivity.m b/matlab/dynare_sensitivity.m index b661dd32e..acb0f12b5 100644 --- a/matlab/dynare_sensitivity.m +++ b/matlab/dynare_sensitivity.m @@ -4,7 +4,7 @@ function x0=dynare_sensitivity(options_gsa) % Reference: % M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006. -% Copyright (C) 2008-2016 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -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; @@ -32,36 +32,36 @@ lgy_ = M_.endo_names; x0=[]; % check user defined options -if isfield(options_gsa,'neighborhood_width') && options_gsa.neighborhood_width, - if isfield(options_gsa,'pprior') && options_gsa.pprior, +if isfield(options_gsa,'neighborhood_width') && options_gsa.neighborhood_width + if isfield(options_gsa,'pprior') && options_gsa.pprior error('sensitivity:: neighborhood_width is incompatible with prior sampling') end - if isfield(options_gsa,'ppost') && options_gsa.ppost, + if isfield(options_gsa,'ppost') && options_gsa.ppost error('sensitivity:: neighborhood_width is incompatible with posterior sampling') end end -if isfield(options_gsa,'morris') && options_gsa.morris==1, - if isfield(options_gsa,'identification') && options_gsa.identification==0, +if isfield(options_gsa,'morris') && options_gsa.morris==1 + if isfield(options_gsa,'identification') && options_gsa.identification==0 % options_gsa.redform=1; end - if isfield(options_gsa,'ppost') && options_gsa.ppost, + if isfield(options_gsa,'ppost') && options_gsa.ppost error('sensitivity:: Morris is incompatible with posterior sampling') - elseif isfield(options_gsa,'pprior') && options_gsa.pprior==0, - if ~(isfield(options_gsa,'neighborhood_width') && options_gsa.neighborhood_width), + elseif isfield(options_gsa,'pprior') && options_gsa.pprior==0 + if ~(isfield(options_gsa,'neighborhood_width') && options_gsa.neighborhood_width) error('sensitivity:: Morris is incompatible with MC sampling with correlation matrix') end end - if isfield(options_gsa,'rmse') && options_gsa.rmse, + if isfield(options_gsa,'rmse') && options_gsa.rmse error('sensitivity:: Morris is incompatible with rmse analysis') end if (isfield(options_gsa,'alpha2_stab') && options_gsa.alpha2_stab<1) || ... (isfield(options_gsa,'pvalue_ks') && options_gsa.pvalue_ks) || ... (isfield(options_gsa,'pvalue_corr') && options_gsa.pvalue_corr) - error('sensitivity:: Morris is incompatible with Monte Carlo filtering') end end + % end check user defined options options_gsa = set_default_option(options_gsa,'datafile',[]); options_gsa = set_default_option(options_gsa,'rmse',0); @@ -69,51 +69,50 @@ options_gsa = set_default_option(options_gsa,'useautocorr',0); options_gsa = set_default_option(options_gsa,'moment_calibration',options_.endogenous_prior_restrictions.moment); options_gsa = set_default_option(options_gsa,'irf_calibration',options_.endogenous_prior_restrictions.irf); -if isfield(options_gsa,'nograph'), +if isfield(options_gsa,'nograph') options_.nograph=options_gsa.nograph; end -if isfield(options_gsa,'nodisplay'), +if isfield(options_gsa,'nodisplay') options_.nodisplay=options_gsa.nodisplay; end -if isfield(options_gsa,'graph_format'), +if isfield(options_gsa,'graph_format') options_.graph_format=options_gsa.graph_format; end -if isfield(options_gsa,'mode_file'), +if isfield(options_gsa,'mode_file') options_.mode_file=options_gsa.mode_file; -elseif isfield(options_gsa,'neighborhood_width') && options_gsa.neighborhood_width>0, - options_.mode_file=''; +elseif isfield(options_gsa,'neighborhood_width') && options_gsa.neighborhood_width>0 + options_.mode_file=''; end options_.order = 1; -if ~isempty(options_gsa.datafile) || isempty(bayestopt_) || options_gsa.rmse, - if isempty(options_gsa.datafile) && options_gsa.rmse, +if ~isempty(options_gsa.datafile) || isempty(bayestopt_) || options_gsa.rmse + if isempty(options_gsa.datafile) && options_gsa.rmse disp('The data file and all relevant estimation options ') disp('[first_obs, nobs, presample, prefilter, loglinear, lik_init, kalman_algo, ...]') disp('must be specified for RMSE analysis!'); - error('Sensitivity anaysis error!'); + error('Sensitivity anaysis error!') end - options_.datafile = options_gsa.datafile; - if isfield(options_gsa,'first_obs'), + if isfield(options_gsa,'first_obs') options_.first_obs=options_gsa.first_obs; end - if isfield(options_gsa,'nobs'), + if isfield(options_gsa,'nobs') options_.nobs=options_gsa.nobs; end - if isfield(options_gsa,'presample'), + if isfield(options_gsa,'presample') options_.presample=options_gsa.presample; end - if isfield(options_gsa,'prefilter'), + if isfield(options_gsa,'prefilter') options_.prefilter=options_gsa.prefilter; end - if isfield(options_gsa,'loglinear'), + if isfield(options_gsa,'loglinear') options_.loglinear=options_gsa.loglinear; end - if isfield(options_gsa,'lik_init'), + if isfield(options_gsa,'lik_init') options_.lik_init=options_gsa.lik_init; end - if isfield(options_gsa,'kalman_algo'), + if isfield(options_gsa,'kalman_algo') options_.kalman_algo=options_gsa.kalman_algo; end options_.mode_compute = 0; @@ -124,28 +123,28 @@ if ~isempty(options_gsa.datafile) || isempty(bayestopt_) || options_gsa.rmse, else if isempty(options_.qz_criterium) options_.qz_criterium = 1+1e-6; - end + end end [make,my,day,punk,M_,options_,oo_] = dynare_resolve(M_,options_,oo_); options_gsa = set_default_option(options_gsa,'identification',0); -if options_gsa.identification, +if options_gsa.identification options_gsa.redform=0; options_gsa = set_default_option(options_gsa,'morris',1); options_gsa = set_default_option(options_gsa,'trans_ident',0); options_gsa = set_default_option(options_gsa,'load_ident_files',0); options_gsa = set_default_option(options_gsa,'ar',1); options_.ar = options_gsa.ar; - if options_gsa.morris==0, + if options_gsa.morris==0 disp('The option morris = 0 is no longer supported (Type I errors)') disp('This option is reset at morris = 2 (local identification analysis).') options_gsa.morris=2; end - if options_gsa.morris==2, - if isfield(options_,'options_ident'), + if options_gsa.morris==2 + 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=[]; @@ -199,27 +198,27 @@ options_gsa = set_default_option(options_gsa,'istart_rmse',options_.presample+1) options_gsa = set_default_option(options_gsa,'alpha_rmse',0.001); options_gsa = set_default_option(options_gsa,'alpha2_rmse',1.e-5); -if options_gsa.neighborhood_width, +if options_gsa.neighborhood_width options_gsa.pprior=0; options_gsa.ppost=0; end -if options_gsa.redform && options_gsa.neighborhood_width==0 && isempty(options_gsa.threshold_redform), +if options_gsa.redform && options_gsa.neighborhood_width==0 && isempty(options_gsa.threshold_redform) options_gsa.pprior=1; options_gsa.ppost=0; end -if options_gsa.morris>2, +if options_gsa.morris>2 disp('The option morris = 3 is no longer supported') disp('the option is reset at morris = 1 .') options_gsa.morris=1; end -if options_gsa.morris==1, - if ~options_gsa.identification, +if options_gsa.morris==1 + if ~options_gsa.identification options_gsa.redform=1; end - if options_gsa.neighborhood_width, + if options_gsa.neighborhood_width options_gsa.pprior=0; else options_gsa.pprior=1; @@ -244,38 +243,37 @@ end % options_.opt_gsa = options_gsa; -if (options_gsa.load_stab || options_gsa.load_rmse || options_gsa.load_redform) ... - && options_gsa.pprior, +if (options_gsa.load_stab || options_gsa.load_rmse || options_gsa.load_redform) && options_gsa.pprior filetoload=[OutputDirectoryName '/' fname_ '_prior.mat']; - if ~exist(filetoload), + if ~exist(filetoload) disp([filetoload,' not found!']) disp(['You asked to load a non existent analysis']) %options_gsa.load_stab=0; - return, + 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 + if isempty(strmatch('bkpprior',who('-file', filetoload),'exact')) + disp('Warning! Missing prior info for saved sample') % trap for files previous + disp('The saved files are generated with previous version of GSA package') % trap for files previous else - load(filetoload,'bkpprior'), + load(filetoload,'bkpprior') if any(bayestopt_.pshape~=bkpprior.pshape) || ... any(bayestopt_.p1~=bkpprior.p1) || ... any(bayestopt_.p2~=bkpprior.p2) || ... any(bayestopt_.p3(~isnan(bayestopt_.p3))~=bkpprior.p3(~isnan(bkpprior.p3))) || ... - any(bayestopt_.p4(~isnan(bayestopt_.p4))~=bkpprior.p4(~isnan(bkpprior.p4))), + any(bayestopt_.p4(~isnan(bayestopt_.p4))~=bkpprior.p4(~isnan(bkpprior.p4))) disp('WARNING!') disp('The saved sample has different priors w.r.t. to current ones!!') skipline() disp('Press ENTER to continue') - pause; + pause end end end end -if options_gsa.stab && ~options_gsa.ppost, +if options_gsa.stab && ~options_gsa.ppost x0 = stab_map_(OutputDirectoryName,options_gsa); - if isempty(x0), + if isempty(x0) skipline() disp('Sensitivity computations stopped: no parameter set provided a unique solution') return @@ -286,20 +284,19 @@ end % redform_map(namendo, namlagendo, namexo, icomp, pprior, ilog, threshold) options_.opt_gsa = options_gsa; -if ~isempty(options_gsa.moment_calibration) || ~isempty(options_gsa.irf_calibration), +if ~isempty(options_gsa.moment_calibration) || ~isempty(options_gsa.irf_calibration) map_calibration(OutputDirectoryName, M_, options_, oo_, estim_params_,bayestopt_); end -if options_gsa.identification, +if options_gsa.identification map_ident_(OutputDirectoryName,options_gsa); end -if options_gsa.redform && ~isempty(options_gsa.namendo),% ... - % && ~options_gsa.ppost, - if options_gsa.ppost, +if options_gsa.redform && ~isempty(options_gsa.namendo) + if options_gsa.ppost filnam = dir([M_.dname filesep 'metropolis' filesep '*param_irf*.mat']); lpmat=[]; - for j=1:length(filnam), + for j=1:length(filnam) load ([M_.dname filesep 'metropolis' filesep M_.fname '_param_irf' int2str(j) '.mat']) lpmat=[lpmat; stock]; end @@ -308,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)); @@ -317,25 +314,24 @@ 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'), + if strmatch(':',options_gsa.namendo,'exact') options_gsa.namendo=M_.endo_names(1:M_.orig_endo_nbr,:); end - if strmatch(':',options_gsa.namexo,'exact'), + if strmatch(':',options_gsa.namexo,'exact') options_gsa.namexo=M_.exo_names; end - if strmatch(':',options_gsa.namlagendo,'exact'), + if strmatch(':',options_gsa.namlagendo,'exact') options_gsa.namlagendo=M_.endo_names(1:M_.orig_endo_nbr,:); end % options_.opt_gsa = options_gsa; - if options_gsa.morris==1, + if options_gsa.morris==1 redform_screen(OutputDirectoryName,options_gsa); else % check existence of the SS_ANOVA toolbox - if isempty(options_gsa.threshold_redform) && ... - ~(exist('gsa_sdp','file')==6 || exist('gsa_sdp','file')==2), + if isempty(options_gsa.threshold_redform) && ~(exist('gsa_sdp','file')==6 || exist('gsa_sdp','file')==2) fprintf('\nThe "SS-ANOVA-R: MATLAB Toolbox for the estimation of Smoothing Spline ANOVA models with Recursive algorithms" is missing.\n') fprintf('To obtain it, go to:\n\n') fprintf('http://ipsc.jrc.ec.europa.eu/?id=790 \n\n') @@ -350,30 +346,30 @@ end % RMSE mapping % function [rmse_MC, ixx] = filt_mc_(vvarvecm, loadSA, pfilt, alpha, alpha2) options_.opt_gsa = options_gsa; -if options_gsa.rmse, +if options_gsa.rmse if ~options_gsa.ppost if options_gsa.pprior a=whos('-file',[OutputDirectoryName,'/',fname_,'_prior'],'logpo2'); else a=whos('-file',[OutputDirectoryName,'/',fname_,'_mc'],'logpo2'); end - if isoctave + if isoctave() aflag=0; - for ja=1:length(a), + for ja=1:length(a) aflag=aflag+strcmp('logpo2',a(ja).name); end - if aflag==0, + if aflag==0 a=[]; else a=1; end end - if isempty(a), - if options_gsa.lik_only, + if isempty(a) + if options_gsa.lik_only options_.smoother=0; options_.filter_step_ahead=[]; options_.forecast=0; - options_.filtered_vars=0; + options_.filtered_vars=0; end % dynare_MC([],OutputDirectoryName,data,rawdata,data_info); if options_gsa.pprior @@ -381,18 +377,18 @@ if options_gsa.rmse, else TmpDirectoryName = ([M_.dname filesep 'gsa' filesep 'mc']); end - if exist(TmpDirectoryName,'dir'); + 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), + for j=1:length(filparam) if isempty(strmatch([M_.fname '_param_irf'],filparam(j).name)) delete([TmpDirectoryName filesep filparam(j).name]); end end - + end prior_posterior_statistics('gsa',dataset_, dataset_info); if options_.bayesian_irf @@ -412,7 +408,7 @@ if options_gsa.rmse, % dynare_MC([],OutputDirectoryName); % options_gsa.load_rmse=0; % end - + end end clear a; @@ -422,7 +418,7 @@ end options_.opt_gsa = options_gsa; -if options_gsa.glue, +if options_gsa.glue dr_ = oo_.dr; if options_gsa.ppost load([OutputDirectoryName,'/',fname_,'_post']); @@ -434,7 +430,7 @@ if options_gsa.glue, load([OutputDirectoryName,'/',fname_,'_mc']); end end - if ~exist('x'), + if ~exist('x') disp(['No RMSE analysis is available for current options']) disp(['No GLUE file prepared']) return, @@ -452,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 @@ -481,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)); @@ -494,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), + 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)]; @@ -517,8 +513,8 @@ if options_gsa.glue, end end tit(M_.exo_names_orig_ord,:) = M_.exo_names; - for j=1:M_.exo_nbr, - Exo(j).name = deblank(tit(j,:)); + for j=1:M_.exo_nbr + Exo(j).name = deblank(tit(j,:)); end if ~options_gsa.ppost Lik(length(options_.varobs)+1).name = 'logpo'; @@ -529,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; @@ -543,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'; @@ -559,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 8c13f524e..366bfa3a4 100644 --- a/matlab/dynare_solve.m +++ b/matlab/dynare_solve.m @@ -17,7 +17,7 @@ function [x,info,fvec,fjac] = dynare_solve(func,x,options,varargin) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2001-2016 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -187,7 +187,7 @@ if options.solve_algo == 0 [x,fval,exitval,output] = fsolve(func,x,options4fsolve); else exitval = 3; - end; + end end if exitval == 1 @@ -203,7 +203,7 @@ if options.solve_algo == 0 if max(abs(fvec)) >= tolf info = 1; else - info = 0; + info = 0; end else info = 1; @@ -295,4 +295,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 37ba7a8ea..2a1f547b9 100644 --- a/matlab/dynare_solve_block_or_bytecode.m +++ b/matlab/dynare_solve_block_or_bytecode.m @@ -1,5 +1,5 @@ function [x,info] = dynare_solve_block_or_bytecode(y, exo, params, options, M) -% Copyright (C) 2010-2015 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -80,7 +80,7 @@ elseif options.bytecode info = 1; return end - end; + end end else [x, check] = dynare_solve('bytecode_steadystate', y, ... diff --git a/matlab/dynare_squeeze.m b/matlab/dynare_squeeze.m index b01be342f..85e66f332 100644 --- a/matlab/dynare_squeeze.m +++ b/matlab/dynare_squeeze.m @@ -1,7 +1,7 @@ -function B = dynare_squeeze(A); +function B = dynare_squeeze(A) % Same as matlab's squeeze function except that it also affects 2D arrays. -% Copyright (C) 2009 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . -sizA = size(A); +sizA = size(A); dimA = length(sizA); switch dimA case 1 diff --git a/matlab/dynare_version.m.in b/matlab/dynare_version.m.in index 6a1391613..f2c502ea0 100644 --- a/matlab/dynare_version.m.in +++ b/matlab/dynare_version.m.in @@ -1,6 +1,6 @@ -function v = dynare_version -% function v = dynare_version -% This command returns Dynare version number +function v = dynare_version() + +% This command returns Dynare version number. % % INPUTS % none @@ -11,7 +11,7 @@ function v = dynare_version % SPECIAL REQUIREMENTS % none -% Copyright (C) 2008-2009 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -28,4 +28,4 @@ function v = dynare_version % You should have received a copy of the GNU General Public License % along with Dynare. If not, see . - v = '@PACKAGE_VERSION@'; +v = '@PACKAGE_VERSION@'; diff --git a/matlab/dynasave.m b/matlab/dynasave.m index f2cc991ca..ef938dbc2 100644 --- a/matlab/dynasave.m +++ b/matlab/dynasave.m @@ -12,7 +12,7 @@ function dynasave(s,var_list) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2001-2010 Dynare Team +% Copyright (C) 2001-2015 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/dynatype.m b/matlab/dynatype.m index 35276028f..517bcc0b1 100644 --- a/matlab/dynatype.m +++ b/matlab/dynatype.m @@ -1,19 +1,19 @@ 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 % % SPECIAL REQUIREMENTS % none -% Copyright (C) 2001-2009 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/dyntable.m b/matlab/dyntable.m index f67789bc3..5b632cde3 100644 --- a/matlab/dyntable.m +++ b/matlab/dyntable.m @@ -7,11 +7,11 @@ 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-2015 Dynare Team +% +% +% Copyright (C) 2002-2017 Dynare Team % % This file is part of Dynare. % @@ -33,7 +33,7 @@ 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); else %use default length @@ -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 7e879df60..26ea7ce5f 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,8 +23,8 @@ 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) 2013 Dynare Team +% Copyright (C) 2011 Lawrence J. Christiano, Mathias Trabandt and Karl Walentin +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % @@ -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 5d480fd9e..eff00e220 100644 --- a/matlab/endogenous_prior_restrictions.m +++ b/matlab/endogenous_prior_restrictions.m @@ -1,4 +1,5 @@ -function [info, info_irf, info_moment, data_irf, data_moment] = endogenous_prior_restrictions(T,R,Model,DynareOptions,DynareResults); +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 @@ -13,9 +14,9 @@ function [info, info_irf, info_moment, data_irf, data_moment] = endogenous_prior % 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 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % @@ -41,18 +42,18 @@ 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, +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), + 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)endo_prior_restrictions.irf{j,4}(1)) && (RR(iendo,iexo)endo_prior_restrictions.irf{j,4}(1)) && (RR(iendo,iexo)1, +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), + for j=1:size(endo_prior_restrictions.moment,1) tmp=endo_prior_restrictions.moment{j,1}; - if ~ismember(tmp,cellstr(var_list_)), + 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_)), + 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), + 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 @@ -133,21 +132,21 @@ if ~isempty(endo_prior_restrictions.moment), 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']) ; + 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 + 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, + 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'); @@ -157,10 +156,10 @@ if ~isempty(endo_prior_restrictions.moment), 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}(1)) && (RR(iendo1,iendo2) 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); diff --git a/matlab/ep/euler_equation_error.m b/matlab/ep/euler_equation_error.m index 16de7a4b1..7496852fb 100644 --- a/matlab/ep/euler_equation_error.m +++ b/matlab/ep/euler_equation_error.m @@ -1,5 +1,22 @@ function e = euler_equation_error(y0,x,innovations,M,options,oo,pfm,nodes,weights) +% Copyright (C) 2016-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 . + dynamic_model = str2func([M.fname '_dynamic']); ep = options.ep; [y1, info_convergence, endogenousvariablespaths] = extended_path_core(ep.periods, ... @@ -18,7 +35,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 +43,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 03a7e4ed7..13747890b 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] % @@ -19,7 +19,7 @@ function [ts, DynareResults] = extended_path(initialconditions, samplesize, exog % % SPECIAL REQUIREMENTS -% Copyright (C) 2009-2016 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -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 8a5664643..5a99b6f21 100644 --- a/matlab/ep/extended_path_core.m +++ b/matlab/ep/extended_path_core.m @@ -4,7 +4,7 @@ function [y, info_convergence, endogenousvariablespaths] = extended_path_core(pe debug,bytecode_flag,order,M,pfm,algo,solve_algo,stack_solve_algo,... olmmcp,options,oo,initialguess) -% Copyright (C) 2016 Dynare Team +% Copyright (C) 2016-2017 Dynare Team % % This file is part of Dynare. % @@ -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 47259765c..8036ae50f 100644 --- a/matlab/ep/extended_path_homotopy.m +++ b/matlab/ep/extended_path_homotopy.m @@ -1,6 +1,6 @@ function [info_convergence, endo_simul] = extended_path_homotopy(endo_simul, exo_simul, M, options, oo, pfm, ep, order, algo, method, debug) -% Copyright (C) 2016 Dynare Team +% Copyright (C) 2016-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/ep/extended_path_initialization.m b/matlab/ep/extended_path_initialization.m index 34d7cdc68..fb8581bc6 100644 --- a/matlab/ep/extended_path_initialization.m +++ b/matlab/ep/extended_path_initialization.m @@ -2,21 +2,21 @@ 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 % % SPECIAL REQUIREMENTS -% Copyright (C) 2016 Dynare Team +% Copyright (C) 2016-2017 Dynare Team % % This file is part of Dynare. % @@ -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); @@ -134,6 +134,5 @@ if DynareOptions.ep.solve_algo == 10 elseif DynareOptions.ep.solve_algo == 11 DynareOptions.mcppath.lb = repmat(lb,block_nbr,1); DynareOptions.mcppath.ub = repmat(ub,block_nbr,1); -end; +end pfm.block_nbr = block_nbr; - diff --git a/matlab/ep/extended_path_mc.m b/matlab/ep/extended_path_mc.m index f03bca8ae..f31ae2dc9 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] % @@ -19,7 +19,7 @@ function Simulations = extended_path_mc(initialconditions, samplesize, replic, e % % SPECIAL REQUIREMENTS -% Copyright (C) 2016 Dynare Team +% Copyright (C) 2016-2017 Dynare Team % % This file is part of Dynare. % @@ -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/extended_path_shocks.m b/matlab/ep/extended_path_shocks.m index 693990340..b642f225b 100644 --- a/matlab/ep/extended_path_shocks.m +++ b/matlab/ep/extended_path_shocks.m @@ -1,6 +1,6 @@ -function [shocks, spfm_exo_simul, innovations, DynareResults] = extended_path_shocks(innovations, ep, exogenousvariables, sample_size,DynareModel,DynareOptions, DynareResults); +function [shocks, spfm_exo_simul, innovations, DynareResults] = extended_path_shocks(innovations, ep, exogenousvariables, sample_size,DynareModel,DynareOptions, DynareResults) -% Copyright (C) 2016 Dynare Team +% Copyright (C) 2016-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/ep/setup_integration_nodes.m b/matlab/ep/setup_integration_nodes.m index 2577d5932..5a6d206c1 100644 --- a/matlab/ep/setup_integration_nodes.m +++ b/matlab/ep/setup_integration_nodes.m @@ -5,7 +5,7 @@ if EpOptions.stochastic.order 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. + % 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 diff --git a/matlab/ep/setup_stochastic_perfect_foresight_model_solver.m b/matlab/ep/setup_stochastic_perfect_foresight_model_solver.m index 6ec1dbe9e..732714d4a 100644 --- a/matlab/ep/setup_stochastic_perfect_foresight_model_solver.m +++ b/matlab/ep/setup_stochastic_perfect_foresight_model_solver.m @@ -1,6 +1,6 @@ function pfm = setup_stochastic_perfect_foresight_model_solver(DynareModel,DynareOptions,DynareOutput) -% Copyright (C) 2013 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % @@ -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 12373d15d..742895f91 100644 --- a/matlab/ep/solve_stochastic_perfect_foresight_model.m +++ b/matlab/ep/solve_stochastic_perfect_foresight_model.m @@ -1,6 +1,6 @@ function [flag,endo_simul,err] = solve_stochastic_perfect_foresight_model(endo_simul,exo_simul,pfm,nnodes,order) -% Copyright (C) 2012-2015 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/ep/solve_stochastic_perfect_foresight_model_1.m b/matlab/ep/solve_stochastic_perfect_foresight_model_1.m index 638a4fa4b..3e0ced538 100644 --- a/matlab/ep/solve_stochastic_perfect_foresight_model_1.m +++ b/matlab/ep/solve_stochastic_perfect_foresight_model_1.m @@ -1,6 +1,6 @@ function [flag,endo_simul,err,y] = solve_stochastic_perfect_foresight_model_1(endo_simul,exo_simul,Options,pfm,order,varargin) -% Copyright (C) 2012-2013 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -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 deleted file mode 100644 index 57d3f8d62..000000000 --- a/matlab/ep/stroud_judd_7.5.8.m +++ /dev/null @@ -1,9 +0,0 @@ -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 56b554de8..6eea0ef4d 100644 --- a/matlab/ep_residuals.m +++ b/matlab/ep_residuals.m @@ -1,23 +1,23 @@ 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 Dynare Team. +% Copyright (C) 2010-2017 Dynare Team. % % This file is part of Dynare. % diff --git a/matlab/evaluate_likelihood.m b/matlab/evaluate_likelihood.m index 020edd29d..a76534adf 100644 --- a/matlab/evaluate_likelihood.m +++ b/matlab/evaluate_likelihood.m @@ -18,7 +18,7 @@ function [llik,parameters] = evaluate_likelihood(parameters) % [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-2012 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/evaluate_max_dynamic_residual.m b/matlab/evaluate_max_dynamic_residual.m index ac4dbb32a..9ea67a5fe 100644 --- a/matlab/evaluate_max_dynamic_residual.m +++ b/matlab/evaluate_max_dynamic_residual.m @@ -1,6 +1,6 @@ function err = evaluate_max_dynamic_residual(model_dynamic, Y, exogenous_variables, params, steady_state, periods, ny, max_lag, lead_lag_incidence) -% Copyright (C) 2013 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/evaluate_planner_objective.m b/matlab/evaluate_planner_objective.m index 599fab1c0..f8d03f978 100644 --- a/matlab/evaluate_planner_objective.m +++ b/matlab/evaluate_planner_objective.m @@ -1,17 +1,17 @@ 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 -% Copyright (C) 2007-2015 Dynare Team +% Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/evaluate_posterior_kernel.m b/matlab/evaluate_posterior_kernel.m index 96ccac8d5..997962127 100644 --- a/matlab/evaluate_posterior_kernel.m +++ b/matlab/evaluate_posterior_kernel.m @@ -2,22 +2,22 @@ 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 +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/evaluate_prior.m b/matlab/evaluate_prior.m index b8b2f7b0b..01cede921 100644 --- a/matlab/evaluate_prior.m +++ b/matlab/evaluate_prior.m @@ -2,21 +2,21 @@ 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 % % REMARKS % [1] This function cannot evaluate the prior density of a dsge-var model... -% Copyright (C) 2009-2012 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/evaluate_smoother.m b/matlab/evaluate_smoother.m index 09fb958be..9ab94654b 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) diff --git a/matlab/evaluate_static_model.m b/matlab/evaluate_static_model.m index 873dabe2b..ecf7ebb39 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 @@ -20,7 +20,7 @@ function [residuals,check1,jacob] = evaluate_static_model(ys,exo_ss,params,M,opt % SPECIAL REQUIREMENTS % none -% Copyright (C) 2001-2016 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/evaluate_steady_state.m b/matlab/evaluate_steady_state.m index fd101f321..afd8bb4c5 100644 --- a/matlab/evaluate_steady_state.m +++ b/matlab/evaluate_steady_state.m @@ -22,7 +22,7 @@ function [ys,params,info] = evaluate_steady_state(ys_init,M,options,oo,steadysta % SPECIAL REQUIREMENTS % none -% Copyright (C) 2001-2016 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -67,7 +67,7 @@ if options.ramsey_policy 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); + 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') @@ -75,35 +75,35 @@ if options.ramsey_policy for ii=1:length(nan_indices) fprintf('%d, ',nan_indices(ii)); end - skipline(); + skipline() fprintf('evaluate_steady_state: If those initial values are not admissable, change them using an initval-block.\n') - skipline(2); + skipline(2) end info(1) = 84; info(2) = resids'*resids; - return; + 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); + 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); + skipline(2) end info(1) = 86; info(2) = resids'*resids; - return; + 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); + 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') @@ -112,11 +112,11 @@ if options.ramsey_policy fprintf('\t Equation number %d: %f\n',ii-n_multipliers, resids(ii)) end end - skipline(2); + skipline(2) end info(1) = 85; info(2) = resids'*resids; - return; + return end end if options.debug @@ -138,7 +138,7 @@ if options.ramsey_policy %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; + return end %check whether steady state really solves the model resids = evaluate_static_model(ys,exo_ss,params,M,options); @@ -151,7 +151,7 @@ if options.ramsey_policy 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); + 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') @@ -159,17 +159,17 @@ if options.ramsey_policy for ii=1:length(nan_indices) fprintf('%d, ',nan_indices(ii)); end - skipline(); + skipline() end info(1) = 82; - return; + return end 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); + 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') @@ -177,17 +177,17 @@ if options.ramsey_policy for ii=1:length(nan_indices_multiplier) fprintf('%d, ',nan_indices_multiplier(ii)); end - skipline(); + skipline() end info(1) = 83; - return; + 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); + 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') @@ -201,21 +201,20 @@ if options.ramsey_policy fprintf('\t Equation number %d: %f\n',ii-n_multipliers, resids(ii)) end end - skipline(2); + skipline(2) end info(1) = 81; info(2) = resids'*resids; - return; + 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); + [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; + return end elseif (options.bytecode == 0 && options.block == 0) if options.linear == 0 @@ -237,7 +236,7 @@ elseif (options.bytecode == 0 && options.block == 0) 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)); + 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') @@ -268,7 +267,6 @@ elseif (options.bytecode == 0 && options.block == 0) 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; end @@ -285,8 +283,7 @@ elseif (options.bytecode == 0 && options.block == 0) end else % block or bytecode - [ys,check] = dynare_solve_block_or_bytecode(ys_init,exo_ss, params, ... - options, M); + [ys,check] = dynare_solve_block_or_bytecode(ys_init,exo_ss, params, options, M); end if check @@ -320,7 +317,6 @@ if M.static_and_dynamic_models_differ 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; diff --git a/matlab/evaluate_steady_state_file.m b/matlab/evaluate_steady_state_file.m index 2e3afceb9..67a3b0c4d 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 @@ -19,7 +19,7 @@ function [ys,params,info] = evaluate_steady_state_file(ys_init,exo_ss,M,options, % SPECIAL REQUIREMENTS % none -% Copyright (C) 2001-2016 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -48,14 +48,14 @@ 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']); + 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']); + h_steadystate = str2func([fname '_steadystate2']); [ys,params1,check] = h_steadystate(ys_init, exo_ss, params); -end +end if check info(1) = 19; @@ -134,7 +134,7 @@ if steady_state_checkflag if check info(1) = 19; info(2) = check; % to be improved - return; + return end if max(abs(residuals)) > options.dynatol.f info(1) = 19; @@ -156,5 +156,3 @@ elseif ~isempty(options.steadystate_partial) ys(indv),... options, exo_ss,indv); end - - diff --git a/matlab/expand_group.m b/matlab/expand_group.m index 7681ffeea..c20d38c37 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 332e46f28..a8e6e386f 100644 --- a/matlab/fastgensylv.m +++ b/matlab/fastgensylv.m @@ -39,7 +39,7 @@ function X = fastgensylv(A, B, C, D, tol,maxit,X0) %! @end deftypefn %@eod: -% Copyright (C) 2012 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -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 4b6b666ce..1ed766d95 100644 --- a/matlab/ff1_.m +++ b/matlab/ff1_.m @@ -5,14 +5,14 @@ function y=ff1_(x) % % INPUTS % x: argument splitted between endogenous and exogenous -% +% % OUTPUTS % y: 'static' function residuals -% +% % SPECIAL REQUIREMENTS % none -% Copyright (C) 2001-2008 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -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 fc72c9f9f..cb8f0d321 100644 --- a/matlab/ffill.m +++ b/matlab/ffill.m @@ -7,15 +7,15 @@ function [a,b] = ffill(x,ixc,y) % x: matrix % ixc: vector of indices % y: matrix -% +% % OUTPUTS % a: concatenation results % b: vector -% +% % SPECIAL REQUIREMENTS % none -% Copyright (C) 2001-2009 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/fjaco.m b/matlab/fjaco.m index 5217ca93a..5f5de0783 100644 --- a/matlab/fjaco.m +++ b/matlab/fjaco.m @@ -10,7 +10,7 @@ function fjac = fjaco(f,x,varargin) % OUTPUT % fjac : finite differnce Jacobian % -% Copyright (C) 2010 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -34,7 +34,7 @@ h = tol.*max(abs(x),1); xh1=x+h; xh0=x-h; h=xh1-xh0; fjac = NaN(length(ff),length(x)); -for j=1:length(x); +for j=1:length(x) xx = x; xx(j) = xh1(j); f1=feval(f,xx,varargin{:}); xx(j) = xh0(j); f0=feval(f,xx,varargin{:}); diff --git a/matlab/flip_plan.m b/matlab/flip_plan.m index 15fd3aa68..14b470ab4 100644 --- a/matlab/flip_plan.m +++ b/matlab/flip_plan.m @@ -15,7 +15,7 @@ function plan = flip_plan(plan, exogenous, endogenous, expectation_type, date, v % plan [structure] Returns a structure containing the updated forecast scenario. % % -% Copyright (C) 2013-2014 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % @@ -38,12 +38,12 @@ 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; +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; +end sdate = length(date); if sdate > 1 if date(1) < plan.date(1) || date(end) > plan.date(end) @@ -98,4 +98,4 @@ plan.constrained_int_date_{i_ix} = [date(i1) - plan.date(1) + 1; plan.constraine 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 \ No newline at end of file diff --git a/matlab/forcst.m b/matlab/forcst.m index 9c7654ae6..d760ca892 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 @@ -22,7 +22,7 @@ function [yf,int_width,int_width_ME]=forcst(dr,y0,horizon,var_list,M_,oo_,option % SPECIAL REQUIREMENTS % none -% Copyright (C) 2003-2016 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -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 43c2b4c4e..1c0d91b24 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,8 +11,8 @@ 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 +% +% Copyright (C) 2008-2017 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 16fcdc143..bbac43b71 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 @@ -9,7 +9,7 @@ function yf=forcst2a(y0,dr,e) % Outputs: % - yf [horizon+maximum_endo_lag,endo_nbr] matrix of forecasts % -% Copyright (C) 2008-2015 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -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 50e682c3a..5631ff4b4 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 @@ -63,7 +63,7 @@ m = 1; n_fig = 1; hh=dyn_figure(options_.nodisplay,'Name','Forecasts (I)'); for j= 1:nvar - if m > nc*nr; + if m > nc*nr dyn_saveas(hh,[ dname '/graphs/forcst' int2str(n_fig)],options_.nodisplay,options_.graph_format); if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) fprintf(fidTeX,'\\begin{figure}[H]\n'); @@ -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,16 +118,16 @@ 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)'); for j= 1:length(var_names) - if m > nc*nr; + if m > nc*nr 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'); @@ -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/formdata.m b/matlab/formdata.m index 06dba8416..b8040515c 100644 --- a/matlab/formdata.m +++ b/matlab/formdata.m @@ -11,7 +11,7 @@ function formdata(fname,date) % SPECIAL REQUIREMENT % none -% Copyright (C) 2007-2010 Dynare Team +% Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. % @@ -29,6 +29,7 @@ function formdata(fname,date) % along with Dynare. If not, see . global M_ oo_ + fid = fopen([fname '_endo.frm'],'w'); n=size(oo_.endo_simul,1); t=size(oo_.endo_simul,2); @@ -46,11 +47,10 @@ for i=1:n fprintf(fid,'%10.5f %10.5f\n',oo_.endo_simul(i,floor(t/4)*4+1:t)); case 3 fprintf(fid,'%10.5f %10.5f %10.5f\n',oo_.endo_simul(i,floor(t/4)*4+1:t)); - end; - %else - % fprintf(fid,'\n'); - end; -end; + end + end +end + fclose(fid); fid = fopen([fname '_exo.frm'],'w'); @@ -70,10 +70,8 @@ for i=1:n fprintf(fid,'%10.5f %10.5f\n',oo_.exo_simul(floor(t/4)*4+1:t,i)'); case 3 fprintf(fid,'%10.5f %10.5f %10.5f\n',oo_.exo_simul(floor(t/4)*4+1:t,i)'); - end; - %else - % fprintf(fid,'\n'); - end; -end; -fclose(fid); -return; \ No newline at end of file + end + end +end + +fclose(fid); \ No newline at end of file diff --git a/matlab/ftest.m b/matlab/ftest.m index 97bedb6e5..c433bb453 100644 --- a/matlab/ftest.m +++ b/matlab/ftest.m @@ -1,6 +1,6 @@ function ftest (s1,s2) -% Copyright (C) 2001-2010 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -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 a9a75b4e1..646033c06 100644 --- a/matlab/gauss_hermite_weights_and_nodes.m +++ b/matlab/gauss_hermite_weights_and_nodes.m @@ -31,7 +31,7 @@ function [nodes,weights] = gauss_hermite_weights_and_nodes(n) %! @end deftypefn %@eod: -% Copyright (C) 2011-2012 Dynare Team +% Copyright (C) 2011-2017 Dynare Team % % This file is part of Dynare. % @@ -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 a1b6fc290..074f520d7 100644 --- a/matlab/gauss_legendre_weights_and_nodes.m +++ b/matlab/gauss_legendre_weights_and_nodes.m @@ -40,7 +40,7 @@ function [nodes,weights] = gauss_legendre_weights_and_nodes(n,a,b) %! @end deftypefn %@eod: -% Copyright (C) 2012 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -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 d8a1e2ae8..6cb02f6a1 100644 --- a/matlab/gcompare.m +++ b/matlab/gcompare.m @@ -1,12 +1,12 @@ 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 % saved by the instruction DYNASAVE. The simulation in file1 % is refered to as the base simulation. -% Copyright (C) 2001-2010 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -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 26624fea7..2920aca4d 100644 --- a/matlab/gensylv/gensylv.m +++ b/matlab/gensylv/gensylv.m @@ -3,23 +3,23 @@ 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-2011 Dynare Team +% Copyright (C) 1996-2017 Dynare Team % % This file is part of Dynare. % @@ -36,9 +36,9 @@ function [err, E] = gensylv(kron_prod,A,B,C0,D) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see . C = C0; -for i=1:(kron_prod-1); - C = kron(C0,C); -end; +for i=1:(kron_prod-1) + C = kron(C0,C); +end x0 = sylvester3(A,B,C,D); E = sylvester3a(x0,A,B,C,D); diff --git a/matlab/gensylv/sylvester3.m b/matlab/gensylv/sylvester3.m index be4d8c574..4e0ab85ee 100644 --- a/matlab/gensylv/sylvester3.m +++ b/matlab/gensylv/sylvester3.m @@ -1,7 +1,7 @@ function x=sylvester3(a,b,c,d) % solves a*x+b*x*c=d where d is [n x m x p] -% Copyright (C) 2005-2012 Dynare Team +% Copyright (C) 2005-2017 Dynare Team % % This file is part of Dynare. % @@ -23,21 +23,21 @@ m = size(c,1); p = size(d,3); x=zeros(n,m,p); if n == 1 - for j=1:p, + for j=1:p x(:,:,j)=d(:,:,j)./(a*ones(1,m)+b*c); end return end if m == 1 - for j=1:p, + for j=1:p x(:,:,j) = (a+c*b)\d(:,:,j); end - return; + return end [u,t]=schur(c); if isoctave [aa,bb,qq,zz]=qz(full(a),full(b)); - for j=1:p, + for j=1:p if octave_ver_less_than('3.4.0') d(:,:,j)=qq'*d(:,:,j)*u; else @@ -46,7 +46,7 @@ if isoctave end else [aa,bb,qq,zz]=qz(full(a),full(b),'real'); % available in Matlab version 6.0 - for j=1:p, + for j=1:p d(:,:,j)=qq*d(:,:,j)*u; end end @@ -58,7 +58,7 @@ while i < m if i == 1 c = zeros(n,1,p); else - for j=1:p, + for j=1:p c(:,:,j) = bb*(x(:,1:i-1,j)*t(1:i-1,i)); end end @@ -69,7 +69,7 @@ while i < m c = zeros(n,1,p); c1 = zeros(n,1,p); else - for j=1:p, + for j=1:p c(:,:,j) = bb*(x(:,1:i-1,j)*t(1:i-1,i)); c1(:,:,j) = bb*(x(:,1:i-1,j)*t(1:i-1,i+1)); end @@ -82,13 +82,13 @@ while i < m end end if i == m - for j=1:p, + for j=1:p c(:,:,j) = bb*(x(:,1:m-1,j)*t(1:m-1,m)); end aabbt = (aa+bb*t(m,m)); x(:,m,:)=aabbt\squeeze(d(:,m,:)-c); end -for j=1:p, +for j=1:p x(:,:,j)=zz*x(:,:,j)*u'; end diff --git a/matlab/gensylv/sylvester3a.m b/matlab/gensylv/sylvester3a.m index 00724dc38..f286c8bdf 100644 --- a/matlab/gensylv/sylvester3a.m +++ b/matlab/gensylv/sylvester3a.m @@ -1,7 +1,7 @@ function [x0, flag]=sylvester3a(x0,a,b,c,dd) % solves iteratively ax+bxc=d -% Copyright (C) 2005-2012 Dynare Team +% Copyright (C) 2005-2017 Dynare Team % % This file is part of Dynare. % @@ -21,7 +21,7 @@ function [x0, flag]=sylvester3a(x0,a,b,c,dd) a_1 = inv(a); b = a_1*b; flag=0; -for j=1:size(dd,3), +for j=1:size(dd,3) d = a_1*dd(:,:,j); e = 1; iter = 1; diff --git a/matlab/gensylv_fp.m b/matlab/gensylv_fp.m index 35ca3352a..51c96fceb 100644 --- a/matlab/gensylv_fp.m +++ b/matlab/gensylv_fp.m @@ -7,23 +7,23 @@ 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. -% Copyright (C) 1996-2012 Dynare Team +% none. +% Copyright (C) 1996-2017 Dynare Team % % This file is part of Dynare. % @@ -50,11 +50,11 @@ if isempty(hxo) X = zeros(size(B, 2), size(C, 1)); else X = hxo; -end; +end it_fp = 0; maxit_fp = 1000; Z = - (B * X * C + D); -while it_fp < maxit_fp && evol > tol; +while it_fp < maxit_fp && evol > tol %X_old = X; %X = - A1 * ( B * X * C + D); %evol = max(max(abs(X - X_old))); @@ -64,10 +64,10 @@ while it_fp < maxit_fp && evol > tol; evol = max(sum(abs(Z - Z_old))); %norm_1 %evol = max(sum(abs(Z - Z_old)')); %norm_inf it_fp = it_fp + 1; -end; +end %fprintf('sylvester it_fp=%d evol=%g | ',it_fp,evol); if evol < tol eval(['hxo_' int2str(block) ' = X;']); else error(['convergence not achieved in fixed point solution of Sylvester equation after ' int2str(it_fp) ' iterations']); -end; \ No newline at end of file +end \ No newline at end of file diff --git a/matlab/getH.m b/matlab/getH.m index 7a3b8d791..3491e6422 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) @@ -32,7 +32,7 @@ function [H, dA, dOm, Hss, gp, d2A, d2Om, H2ss] = getH(A, B, estim_params_,M_,oo % H2s: Hessian of steady state with respect to estimated % structural parameters only (indx) -% Copyright (C) 2010-2016 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -50,23 +50,23 @@ function [H, dA, dOm, Hss, gp, d2A, d2Om, H2ss] = getH(A, B, estim_params_,M_,oo % along with Dynare. If not, see . 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'); yy0=oo_.dr.ys(I); param_nbr = length(indx); tot_param_nbr = param_nbr + length(indexo); -if nargout>5, +if nargout>5 param_nbr_2 = param_nbr*(param_nbr+1)/2; tot_param_nbr_2 = tot_param_nbr*(tot_param_nbr+1)/2; end @@ -75,18 +75,18 @@ m = size(A,1); m1=length(iv); n = size(B,2); -if kronflag==-1, % perturbation +if kronflag==-1 % perturbation gp=0; fun = 'thet2tau'; params0 = M_.params; H = fjaco(fun,[sqrt(diag(M_.Sigma_e(indexo,indexo))); M_.params(indx)], M_, oo_, indx, indexo,0); - if nargout>1, + if nargout>1 dOm = zeros(m1,m1,tot_param_nbr); dA=zeros(m1,m1,tot_param_nbr); Hss=H(iv,length(indexo)+1:end); da = H(m+1:m+m*m,:); dom = H(m+m*m+1:end,:); - for j=1:tot_param_nbr, + for j=1:tot_param_nbr tmp = dyn_unvech(dom(:,j)); dOm(:,:,j) = tmp(iv,iv); tmp = reshape(da(:,j),m,m); @@ -94,13 +94,13 @@ if kronflag==-1, % perturbation end clear da dom tmp end - if nargout>5, + 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); H2ss = zeros(m1,tot_param_nbr,tot_param_nbr); iax=find(triu(rand(tot_param_nbr,tot_param_nbr))); H2 = H2(:,iax); - for j=1:m1, + for j=1:m1 H2ss(j,:,:)=dyn_unvech(full(H2(j,:))); end H2ss=H2ss(:,length(indexo)+1:end,length(indexo)+1:end); @@ -122,20 +122,20 @@ if kronflag==-1, % perturbation return end -if kronflag==-2, - if nargout>5, +if kronflag==-2 + if nargout>5 [residual, g1, g2 ] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', ... 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]); - for j=1:M_.endo_nbr, + for j=1:M_.endo_nbr H2ss(j,:,:)=dyn_unvech(dyn_vech(H2ss(j,:,:))); end g22=g22(M_.endo_nbr+1:end,:); inx=find(g22); gx22=zeros(length(inx),5); - for j=1:length(inx), + for j=1:length(inx) [i1, i2] = ind2sub(size(g22),inx(j)); [ig1, ig2] = ind2sub(size(g1),i1); [ip1, ip2] = ind2sub([param_nbr param_nbr],i2); @@ -145,25 +145,20 @@ 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 - - % yy0=[]; - % for j=1:size(M_.lead_lag_incidence,1); - % yy0 = [ yy0; oo_.dr.ys(find(M_.lead_lag_incidence(j,:)))]; - % end 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, + 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); @@ -172,27 +167,25 @@ else [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, + if isempty(find(gg2)) + for j=1:M_.param_nbr d2yssdtheta(:,:,j) = -gg1\d2f(:,:,j); end else gam = d2f*0; - for j=1:nr, + 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, + for j=1:M_.param_nbr d2yssdtheta(:,:,j) = -gg1\(d2f(:,:,j)+gam(:,:,j)); - % d2yssdtheta(:,:,j) = -gg1\(d2f(:,:,j)+gam(:,:,j)+ squeeze(gpx(:,:,j))*dyssdtheta); end - clear tmp1 gpx gam, + clear tmp1 gpx gam end end - if any(any(isnan(dyssdtheta))), + if any(any(isnan(dyssdtheta))) [U,T] = schur(gg1); qz_criterium=options_.qz_criterium; e1 = abs(ordeig(T)) < qz_criterium-1; @@ -207,13 +200,10 @@ else end end end - if nargout>5, + 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); - % nelem=size(g1,2); - % g22 = get_all_2nd_derivs(gpp,m,nelem,M_.param_nbr); - % g22 = g22(:,:,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); @@ -227,12 +217,12 @@ else 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, + for j=1:nr [II JJ]=ind2sub([nc nc],find(g2(j,:))); - for i=1:nc, + for i=1:nc is = find(II==i); is = is(find(JJ(is)<=ns)); - if ~isempty(is), + if ~isempty(is) g20=full(g2(j,find(g2(j,:)))); gp2(j,i,:)=g20(is)*dyssdtheta(JJ(is),:); end @@ -242,7 +232,7 @@ else gp = gp+gp2; gp = gp(:,:,indx); - if nargout>5, + if nargout>5 % h22 = get_all_hess_derivs(hp,nr,nc,M_.param_nbr); g22 = gpp; gp22 = sparse(nr*nc,param_nbr*param_nbr); @@ -251,16 +241,16 @@ else % 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, + 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]); + 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, + 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)]; @@ -268,7 +258,7 @@ else 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)), + 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]); @@ -280,10 +270,10 @@ else % g22 = g22+gp22; % g22 = g22(:,:,indx,indx); - clear tmp0 tmp1 tmp2 tmpu tmpx tmpy, + clear tmp0 tmp1 tmp2 tmpu tmpx tmpy inx=find(gp22); gx22=zeros(length(inx),5); - for j=1:length(inx), + for j=1:length(inx) [i1, i2] = ind2sub(size(gp22),inx(j)); [ig1, ig2] = ind2sub(size(g1),i1); [ip1, ip2] = ind2sub([param_nbr param_nbr],i2); @@ -301,15 +291,14 @@ klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1; k11 = M_.lead_lag_incidence(find([1:klen] ~= M_.maximum_endo_lag+1),:); a = g1(:,nonzeros(k11')); da = gp(:,nonzeros(k11'),:); -if nargout > 5, +if nargout > 5 indind = ismember(g22(:,2),nonzeros(k11')); tmp = g22(indind,:); d2a=tmp; - for j=1:size(tmp,1), + for j=1:size(tmp,1) inxinx = find(nonzeros(k11')==tmp(j,2)); d2a(j,2) = inxinx; end - % d2a = g22(:,nonzeros(k11'),:,:); end kstate = oo_.dr.kstate; @@ -319,12 +308,12 @@ Dg1 = zeros(M_.endo_nbr,M_.endo_nbr,param_nbr); k1 = find(kstate(:,2) == M_.maximum_endo_lag+2 & kstate(:,3)); GAM1(:, kstate(k1,1)) = -a(:,kstate(k1,3)); Dg1(:, kstate(k1,1), :) = -da(:,kstate(k1,3),:); -if nargout > 5, +if nargout > 5 indind = ismember(d2a(:,2),kstate(k1,3)); tmp = d2a(indind,:); tmp(:,end)=-tmp(:,end); D2g1 = tmp; - for j=1:size(tmp,1), + for j=1:size(tmp,1) inxinx = (kstate(k1,3)==tmp(j,2)); D2g1(j,2) = kstate(k1(inxinx),1); end @@ -336,11 +325,11 @@ GAM0 = zeros(M_.endo_nbr,M_.endo_nbr); Dg0 = zeros(M_.endo_nbr,M_.endo_nbr,param_nbr); GAM0(:,cols_b) = g1(:,cols_j); Dg0(:,cols_b,:) = gp(:,cols_j,:); -if nargout > 5, +if nargout > 5 indind = ismember(g22(:,2),cols_j); tmp = g22(indind,:); D2g0=tmp; - for j=1:size(tmp,1), + for j=1:size(tmp,1) inxinx = (cols_j==tmp(j,2)); D2g0(j,2) = cols_b(inxinx); end @@ -352,12 +341,12 @@ GAM2 = zeros(M_.endo_nbr,M_.endo_nbr); Dg2 = zeros(M_.endo_nbr,M_.endo_nbr,param_nbr); GAM2(:, kstate(k2,1)) = -a(:,kstate(k2,4)); Dg2(:, kstate(k2,1), :) = -da(:,kstate(k2,4),:); -if nargout > 5, +if nargout > 5 indind = ismember(d2a(:,2),kstate(k2,4)); tmp = d2a(indind,:); tmp(:,end)=-tmp(:,end); D2g2 = tmp; - for j=1:size(tmp,1), + for j=1:size(tmp,1) inxinx = (kstate(k2,4)==tmp(j,2)); D2g2(j,2) = kstate(k2(inxinx),1); end @@ -365,13 +354,13 @@ end GAM3 = -g1(:,length(yy0)+1:end); Dg3 = -gp(:,length(yy0)+1:end,:); -if nargout>5, +if nargout>5 cols_ex = [length(yy0)+1:size(g1,2)]; indind = ismember(g22(:,2),cols_ex); tmp = g22(indind,:); tmp(:,end)=-tmp(:,end); D2g3=tmp; - for j=1:size(tmp,1), + for j=1:size(tmp,1) inxinx = find(cols_ex==tmp(j,2)); D2g3(j,2) = inxinx; end @@ -380,11 +369,11 @@ end clear g1 g2 g3 df d2f gpp hp residual gg1 gg2 gp2 dyssdtheta d2yssdtheta -if kronflag==1, % kronecker products +if kronflag==1 % kronecker products Dg0=reshape(Dg0,m^2,param_nbr); Dg1=reshape(Dg1,m^2,param_nbr); Dg2=reshape(Dg2,m^2,param_nbr); - for j=1:param_nbr, + for j=1:param_nbr Dg3(:,:,j)=Dg3(:,:,j)*M_.Sigma_e; end Dg3=reshape(Dg3,m*n,param_nbr); @@ -427,7 +416,7 @@ if kronflag==1, % kronecker products H(m*m+1:end,:) = tmpH(Index,:); Hx = []; - if ~isempty(indexo), + if ~isempty(indexo) dSig = zeros(M_.exo_nbr,M_.exo_nbr); dOm = cat(3,zeros(size(dOm,1),size(dOm,1),length(indexo)),dOm); for j=1:length(indexo) @@ -435,7 +424,7 @@ if kronflag==1, % kronecker products y = B*dSig*B'; y = y(nauxe+1:end,nauxe+1:end); Hx(:,j) = [zeros((m-nauxe)^2,1); dyn_vech(y)]; - if nargout>1, + if nargout>1 dOm(:,:,j) = y; end dSig(indexo(j),indexo(j)) = 0; @@ -452,24 +441,24 @@ else % generalized sylvester equation c = A; elem = zeros(m,m,param_nbr); d = elem; - for j=1:param_nbr, + for j=1:param_nbr elem(:,:,j) = (Dg0(:,:,j)-Dg1(:,:,j)*A); d(:,:,j) = Dg2(:,:,j)-elem(:,:,j)*A; end xx=sylvester3(a,b,c,d); flag=1; icount=0; - while flag && icount<4, + while flag && icount<4 [xx, flag]=sylvester3a(xx,a,b,c,d); icount=icount+1; end H=zeros(m1*m1+m1*(m1+1)/2,param_nbr+length(indexo)); - if nargout>1, + if nargout>1 dOm = zeros(m1,m1,param_nbr+length(indexo)); dA=zeros(m1,m1,param_nbr+length(indexo)); dB=zeros(m,n,param_nbr); end - if ~isempty(indexo), + if ~isempty(indexo) dSig = zeros(M_.exo_nbr,M_.exo_nbr,length(indexo)); for j=1:length(indexo) dSig(indexo(j),indexo(j),j) = 2*sqrt(M_.Sigma_e(indexo(j),indexo(j))); @@ -477,22 +466,22 @@ else % generalized sylvester equation % 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, + if nargout>1 dOm(:,:,j) = y(iv,iv); end % dSig(indexo(j),indexo(j)) = 0; end end - for j=1:param_nbr, + for j=1:param_nbr x = xx(:,:,j); y = inva * (Dg3(:,:,j)-(elem(:,:,j)-GAM1*x)*B); - if nargout>1, + if nargout>1 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); - if nargout>1, + if nargout>1 dA(:,:,j+length(indexo)) = x(iv,iv); dOm(:,:,j+length(indexo)) = y(iv,iv); end @@ -515,7 +504,7 @@ else % generalized sylvester equation end -if nargout > 5, +if nargout > 5 H2ss = H2ss(iv,:,:); d = zeros(m,m,floor(sqrt(param_nbr_2))); % d2A = zeros(m,m,tot_param_nbr,tot_param_nbr); @@ -533,8 +522,8 @@ if nargout > 5, jinx = []; x2x=sparse(m*m,param_nbr_2); % x2x=[]; - for i=1:param_nbr, - for j=1:i, + 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); elem1 = get_2nd_deriv(D2g2,m,m,j,i)-elem1*A; elemj0 = Dg0(:,:,j)-Dg1(:,:,j)*A; @@ -545,15 +534,15 @@ if nargout > 5, jcount=jcount+1; jinx = [jinx; [j i]]; d(:,:,jcount) = elem1+elem2; - if jcount==floor(sqrt(param_nbr_2)) || (j*i)==param_nbr^2, - if (j*i)==param_nbr^2, + if jcount==floor(sqrt(param_nbr_2)) || (j*i)==param_nbr^2 + if (j*i)==param_nbr^2 d = d(:,:,1:jcount); end % d(find(abs(d)<1.e-12))=0; xx2=sylvester3(a,b,c,d); flag=1; icount=0; - while flag && icount<4, + while flag && icount<4 [xx2, flag]=sylvester3a(xx2,a,b,c,d); icount = icount + 1; end @@ -583,11 +572,11 @@ if nargout > 5, offset = length(indexo); % d2B = zeros(m,n,tot_param_nbr,tot_param_nbr); d2Sig = zeros(M_.exo_nbr,M_.exo_nbr,length(indexo)); - for j=1:tot_param_nbr, - for i=1:j, + for j=1:tot_param_nbr + for i=1:j jcount=jcount+1; - if j<=offset, - if i==j, + if j<=offset + if i==j d2Sig(indexo(j),indexo(j),j) = 2; y = B*d2Sig(:,:,j)*B'; % y(abs(y)<1.e-8)=0; @@ -596,7 +585,7 @@ if nargout > 5, else jind = j-offset; iind = i-offset; - if i<=offset, + if i<=offset y = dB(:,:,jind)*dSig(:,:,i)*B'+B*dSig(:,:,i)*dB(:,:,jind)'; % y(abs(y)<1.e-8)=0; d2Om_tmp(:,jcount) = dyn_vech(y(iv,iv)); @@ -620,7 +609,7 @@ if nargout > 5, d2Om_tmp(:,jcount) = dyn_vech(y(iv,iv)); end end - if jcount==ncol || i*j==tot_param_nbr^2, + if jcount==ncol || i*j==tot_param_nbr^2 d2A(:,cumjcount+1:cumjcount+jcount) = d2A_tmp(:,1:jcount); % d2A(:,:,j+length(indexo),i+length(indexo)) = x; % d2A(:,:,i+length(indexo),j+length(indexo)) = x; @@ -635,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 @@ -643,35 +632,35 @@ end return -function g22 = get_2nd_deriv(gpp,m,n,i,j), +function g22 = get_2nd_deriv(gpp,m,n,i,j) g22=zeros(m,n); is=find(gpp(:,3)==i); is=is(find(gpp(is,4)==j)); -if ~isempty(is), +if ~isempty(is) g22(sub2ind([m,n],gpp(is,1),gpp(is,2)))=gpp(is,5)'; end return -function g22 = get_2nd_deriv_mat(gpp,i,j,n), +function g22 = get_2nd_deriv_mat(gpp,i,j,n) g22=zeros(n,n); is=find(gpp(:,1)==i); is=is(find(gpp(is,2)==j)); -if ~isempty(is), +if ~isempty(is) g22(sub2ind([n,n],gpp(is,3),gpp(is,4)))=gpp(is,5)'; g22(sub2ind([n,n],gpp(is,4),gpp(is,3)))=gpp(is,5)'; end return -function g22 = get_all_2nd_derivs(gpp,m,n,npar,fsparse), +function g22 = get_all_2nd_derivs(gpp,m,n,npar,fsparse) -if nargin==4 || isempty(fsparse), +if nargin==4 || isempty(fsparse) fsparse=0; end -if fsparse, +if fsparse g22=sparse(m*n,npar*npar); else g22=zeros(m,n,npar,npar); @@ -680,11 +669,11 @@ end % c=triu(c); % ic=find(c); -for is=1:length(gpp), +for is=1:length(gpp) % d=zeros(npar,npar); % d(gpp(is,3),gpp(is,4))=1; % indx = find(ic==find(d)); - if fsparse, + 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 @@ -695,14 +684,14 @@ end return -function r22 = get_all_resid_2nd_derivs(rpp,m,npar), +function r22 = get_all_resid_2nd_derivs(rpp,m,npar) r22=zeros(m,npar,npar); % c=ones(npar,npar); % c=triu(c); % ic=find(c); -for is=1:length(rpp), +for is=1:length(rpp) % d=zeros(npar,npar); % d(rpp(is,2),rpp(is,3))=1; % indx = find(ic==find(d)); @@ -712,31 +701,31 @@ end return -function h2 = get_all_hess_derivs(hp,r,m,npar), +function h2 = get_all_hess_derivs(hp,r,m,npar) h2=zeros(r,m,m,npar); -for is=1:length(hp), +for is=1:length(hp) h2(hp(is,1),hp(is,2),hp(is,3),hp(is,4))=hp(is,5); h2(hp(is,1),hp(is,3),hp(is,2),hp(is,4))=hp(is,5); end return -function h2 = get_hess_deriv(hp,i,j,m,npar), +function h2 = get_hess_deriv(hp,i,j,m,npar) h2=zeros(m,npar); is1=find(hp(:,1)==i); is=is1(find(hp(is1,2)==j)); -if ~isempty(is), +if ~isempty(is) h2(sub2ind([m,npar],hp(is,3),hp(is,4)))=hp(is,5)'; end is=is1(find(hp(is1,3)==j)); -if ~isempty(is), +if ~isempty(is) h2(sub2ind([m,npar],hp(is,2),hp(is,4)))=hp(is,5)'; end -return +return \ No newline at end of file diff --git a/matlab/getIrfShocksIndx.m b/matlab/getIrfShocksIndx.m index 737bfcfb1..788d58cd1 100644 --- a/matlab/getIrfShocksIndx.m +++ b/matlab/getIrfShocksIndx.m @@ -8,7 +8,7 @@ function irf_shocks_indx=getIrfShocksIndx() % Outputs: % irf_shocks_indx: [1 by n_irf_shocks] vector storing the indices % -% Copyright (C) 2011-13 Dynare Team +% Copyright (C) 2011-2017 Dynare Team % % This file is part of Dynare. % @@ -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 c3b1f1c1e..7f934b81a 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,25 +19,25 @@ 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) -% Copyright (C) 2010-2016 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -56,21 +56,21 @@ function [JJ, H, gam, gp, dA, dOm, dYss] = getJJ(A, B, estim_params_, M_,oo_,opt if nargin<8 || isempty(indx) % indx = [1:M_.param_nbr]; -end, +end if nargin<9 || isempty(indexo) indexo = []; -end, +end if nargin<11 || isempty(nlags) - nlags=3; + nlags=3; end if nargin<12 || isempty(useautocorr) - useautocorr=0; + useautocorr=0; end % if useautocorr, warning('off','MATLAB:divideByZero') % end -if kronflag == -1, +if kronflag == -1 fun = 'thet2tau'; params0 = M_.params; para0 = get_all_parameters(estim_params_, M_); @@ -87,7 +87,7 @@ if kronflag == -1, dYss = H(1:M_.endo_nbr,offset+1:end); dA = reshape(H(M_.orig_endo_nbr+[1:numel(A)],:),[size(A),size(H,2)]); dOm = dA*0; - for j=1:size(H,2), + for j=1:size(H,2) dOm(:,:,j) = dyn_unvech(H(M_.endo_nbr+numel(A)+1:end,j)); end assignin('base','M_', M_); @@ -109,13 +109,13 @@ 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); % end % XX = lyapunov_symm_mr(A,BB,options_.qz_criterium,options_.lyapunov_complex_threshold,0); - for j=1:length(indexo), + for j=1:length(indexo) dum = lyapunov_symm(A,dOm(:,:,j),options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold,2,options_.debug); % dum = XX(:,:,j); k = find(abs(dum) < 1e-12); @@ -130,7 +130,7 @@ else else dumm = dyn_vech(dum(mf,mf)); end - for i=1:nlags, + for i=1:nlags dum1 = A^i*dum; if useautocorr dum1 = (dum1.*sy-dsy.*(A^i*GAM))./(sy.*sy); @@ -140,7 +140,7 @@ else JJ(:,j) = dumm; end nexo = length(indexo); - for j=1:length(indx), + for j=1:length(indx) dum = lyapunov_symm(A,dA(:,:,j+nexo)*GAM*A'+A*GAM*dA(:,:,j+nexo)'+dOm(:,:,j+nexo),options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold,2,options_.debug); % dum = XX(:,:,j); k = find(abs(dum) < 1e-12); @@ -155,9 +155,9 @@ else else dumm = dyn_vech(dum(mf,mf)); end - for i=1:nlags, + for i=1:nlags dum1 = A^i*dum; - for ii=1:i, + for ii=1:i dum1 = dum1 + A^(ii-1)*dA(:,:,j+nexo)*A^(i-ii)*GAM; end if useautocorr @@ -167,27 +167,27 @@ else end JJ(:,j+nexo) = dumm; end - + JJ = [ [zeros(length(mf),nexo) dYss(mf,:)]; JJ]; - + end -if nargout >2, +if nargout >2 % sy=sy(mf,mf); options_.ar=nlags; nodecomposition = 1; [GAM,stationary_vars] = th_autocovariances(oo_.dr,oo_.dr.order_var(mf),M_,options_,nodecomposition); sy=sqrt(diag(GAM{1})); sy=sy*sy'; - if useautocorr, + if useautocorr sy=sy-diag(diag(sy))+eye(length(mf)); GAM{1}=GAM{1}./sy; else - for j=1:nlags, + for j=1:nlags GAM{j+1}=GAM{j+1}.*sy; end end gam = dyn_vech(GAM{1}); - for j=1:nlags, + for j=1:nlags gam = [gam; vec(GAM{j+1})]; end end diff --git a/matlab/get_Hessian.m b/matlab/get_Hessian.m index bf423e07c..fe74848dd 100644 --- a/matlab/get_Hessian.m +++ b/matlab/get_Hessian.m @@ -10,7 +10,7 @@ function [Hess] = get_Hessian(T,R,Q,H,P,Y,DT,DYss,DOm,DH,DP,D2T,D2Yss,D2Om,D2H,D % NOTE: the derivative matrices (D2T,D2Om ...) are 4-dim. arrays with last % two dimensions equal to the number of structural parameters -% Copyright (C) 2011 Dynare Team +% Copyright (C) 2011-2017 Dynare Team % % This file is part of Dynare. % @@ -55,7 +55,7 @@ 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=start Hess = Hess + Hesst; end - a = T*(a+K*v); + a = T*(a+K*v); P = T*(P-K*P(mf,:))*transpose(T)+Om; DP = DP1; D2P = D2P1; @@ -128,13 +128,13 @@ if t < smpl t = t+1; v = Y(:,t)-a(mf); tmp = (a+K*v); - for ii = 1:k, + 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, + + for jj = 1:ii dFj = DF(:,:,jj); diFj = -iF*DF(:,:,jj)*iF; dKj = DK(:,:,jj); @@ -142,11 +142,11 @@ if t < smpl 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; - + 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; @@ -166,8 +166,8 @@ 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 @@ -182,7 +182,7 @@ 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); @@ -191,7 +191,7 @@ end % end of computeDKalman -function [d2K,d2S,d2P1] = computeD2Kalman(A,dA,d2A,d2Om,P0,dP0,d2P0,DH,mf,iF,K0,dK0); +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. @@ -225,20 +225,20 @@ 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; @@ -253,5 +253,3 @@ for ii = 1:k end % end of computeD2Kalman - - diff --git a/matlab/get_all_parameters.m b/matlab/get_all_parameters.m index 30d325f68..289b6a679 100644 --- a/matlab/get_all_parameters.m +++ b/matlab/get_all_parameters.m @@ -4,18 +4,18 @@ 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. +% 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 -% Copyright (C) 2013 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/get_dynare_random_generator_state.m b/matlab/get_dynare_random_generator_state.m index 4525bc20d..b2789b054 100644 --- a/matlab/get_dynare_random_generator_state.m +++ b/matlab/get_dynare_random_generator_state.m @@ -1,12 +1,12 @@ 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. -% Copyright (C) 2010-2013 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -34,7 +34,7 @@ if matlab_random_streams% Use new matlab interface. if isequal(s.Type,'legacy') state_u = rand('state'); state_n = randn('state'); - else + else state_u = s.State; state_n = state_u; end diff --git a/matlab/get_file_extension.m b/matlab/get_file_extension.m index 3951e8c3c..dad9ee0ac 100644 --- a/matlab/get_file_extension.m +++ b/matlab/get_file_extension.m @@ -2,16 +2,16 @@ 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 +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/get_moments_size.m b/matlab/get_moments_size.m index aa8087c02..6515c39b8 100644 --- a/matlab/get_moments_size.m +++ b/matlab/get_moments_size.m @@ -4,14 +4,14 @@ 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 -% Copyright (C) 2008-2011 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/get_name_of_the_last_mh_file.m b/matlab/get_name_of_the_last_mh_file.m index 763435125..e6732a2ef 100644 --- a/matlab/get_name_of_the_last_mh_file.m +++ b/matlab/get_name_of_the_last_mh_file.m @@ -1,17 +1,17 @@ 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 +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/get_new_or_existing_ei_index.m b/matlab/get_new_or_existing_ei_index.m index 39bec99a3..a6b3b85e1 100644 --- a/matlab/get_new_or_existing_ei_index.m +++ b/matlab/get_new_or_existing_ei_index.m @@ -17,7 +17,7 @@ function indx = get_new_or_existing_ei_index(substructure_name, name1, name2) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2012 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -38,7 +38,7 @@ global estimation_info if eval(['isempty(estimation_info.' substructure_name ')']) indx = 1; - return; + return end if isempty(name2) % parameter or std() statement diff --git a/matlab/get_optimal_policy_discount_factor.m b/matlab/get_optimal_policy_discount_factor.m index fd471a01b..89b605b3b 100644 --- a/matlab/get_optimal_policy_discount_factor.m +++ b/matlab/get_optimal_policy_discount_factor.m @@ -2,18 +2,18 @@ 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 % % SPECIAL REQUIREMENTS % none -% Copyright (C) 2007-2011 Dynare Team +% Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/get_param_by_name.m b/matlab/get_param_by_name.m index 795ac88df..b06ab5f07 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 % @@ -11,7 +11,7 @@ function x = get_param_by_name(pname) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2006-2009 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/get_posterior_parameters.m b/matlab/get_posterior_parameters.m index 495f36565..e10616d20 100644 --- a/matlab/get_posterior_parameters.m +++ b/matlab/get_posterior_parameters.m @@ -2,18 +2,18 @@ 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. -% Copyright (C) 2006-2016 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . -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 cb9b971f5..56c87f286 100644 --- a/matlab/get_subsamples_range_indx.m +++ b/matlab/get_subsamples_range_indx.m @@ -16,7 +16,7 @@ function range_indx = get_subsamples_range_indx(subsamples_indx, range_label) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2012 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/get_variables_list.m b/matlab/get_variables_list.m index 5d6a93c84..b72479b37 100644 --- a/matlab/get_variables_list.m +++ b/matlab/get_variables_list.m @@ -1,22 +1,22 @@ 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. -% Copyright (C) 2007-2012 Dynare Team +% Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/get_variance_of_endogenous_variables.m b/matlab/get_variance_of_endogenous_variables.m index 005ceb8e0..965319b1b 100644 --- a/matlab/get_variance_of_endogenous_variables.m +++ b/matlab/get_variance_of_endogenous_variables.m @@ -6,14 +6,14 @@ 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 -% Copyright (C) 2003-2012 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -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 168fe8d5d..d31c59e54 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. @@ -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 341658ff7..f2c670549 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 @@ -52,7 +52,7 @@ fig_name_long = opts_decomp.fig_name; use_shock_groups = DynareOptions.plot_shock_decomp.use_shock_groups; screen_shocks = opts_decomp.screen_shocks; -if use_shock_groups | comp_nbr<=18, +if use_shock_groups | comp_nbr<=18 screen_shocks=0; end if use_shock_groups @@ -94,20 +94,20 @@ if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.plot_shock_decomp fprintf(fidTeX,' \n'); end -if opts_decomp.vintage && opts_decomp.realtime>1, +if opts_decomp.vintage && opts_decomp.realtime>1 preamble_txt = 'Shock decomposition'; else preamble_txt = 'Historical shock decomposition'; end -if ~(screen_shocks && comp_nbr>18), +if ~(screen_shocks && comp_nbr>18) screen_shocks=0; end comp_nbr0=comp_nbr; %%plot decomposition for j=1:nvar z1 = squeeze(z(i_var(j),:,:)); - if screen_shocks, + if screen_shocks [junk, isort] = sort(mean(abs(z1(1:end-2,:)')), 'descend'); labels = char(char(shock_names(isort(1:16),:)),'Others', 'Initial values'); zres = sum(z1(isort(17:end),:),1); @@ -153,14 +153,14 @@ for j=1:nvar plot(ax,x(2:end),z1(end,:),'k-','LineWidth',2) if ~isempty(SteadyState) plot(ax,[xmin xmax],[0 0],'--','linewidth',1,'color',[0.7 0.7 0.7]) - if ymin+SteadyState(i_var(j))<0 && ymax+SteadyState(i_var(j))>0, + if ymin+SteadyState(i_var(j))<0 && ymax+SteadyState(i_var(j))>0 plot(ax,[xmin xmax],SteadyState(i_var(j))*[-1 -1],'k--','linewidth',1) ytick=get(ax,'ytick'); ytick1=ytick-SteadyState(i_var(j)); ind1=min(find(ytick1>=ymin)); ind2=max(find(ytick1<=ymax)); dytick=ytick(2)-ytick(1); - if ind1>1, + if ind1>1 ytick1 = [ytick1(ind1:end) ytick1(end)+dytick:dytick:ymax]; elseif ind21, +if opts_decomp.vintage && opts_decomp.realtime>1 preamble_txt = 'Shock decomposition'; else preamble_txt = 'Historical shock decomposition'; @@ -124,7 +124,7 @@ ntotrow = nrow; nrow = min(ntotrow, 6); nfigs = ceil(ntotrow/nrow); labels = char(char(shock_names),'Initial values'); -if ~(screen_shocks && comp_nbr>18), +if ~(screen_shocks && comp_nbr>18) screen_shocks=0; end comp_nbr0=comp_nbr; @@ -155,9 +155,9 @@ for j=1:nvar a0=zeros(1,4); a0(3)=inf; a0(4)=-inf; - for ic=1+nrow*ncol*(jf-1):min(nrow*ncol*jf,comp_nbr), + for ic=1+nrow*ncol*(jf-1):min(nrow*ncol*jf,comp_nbr) i = ic-nrow*ncol*(jf-1); - zz = z1(ic,:); + zz = z1(ic,:); zz(2,:)=z1(end,:)-zz; ipos=zz>0; ineg=zz<0; @@ -195,11 +195,11 @@ for j=1:nvar end end end - for isub=1:i, + 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]); @@ -217,9 +217,9 @@ for j=1:nvar hold on x1 = x1 + width; end - - - if nfigs>1, + + + if nfigs>1 suffix = ['_detail_' int2str(jf)]; else suffix = ['_detail']; @@ -233,7 +233,7 @@ for j=1:nvar 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 end diff --git a/matlab/gsa/Morris_Measure_Groups.m b/matlab/gsa/Morris_Measure_Groups.m index cc5921206..1271ed1b6 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 % ------------------------------------------------------------------------- @@ -27,7 +27,7 @@ function [SAmeas, OutMatrix] = Morris_Measure_Groups(NumFact, Sample, Output, p, % % Copyright (C) 2005 European Commission -% Copyright (C) 2012 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -44,7 +44,7 @@ function [SAmeas, OutMatrix] = Morris_Measure_Groups(NumFact, Sample, Output, p, % You should have received a copy of the GNU General Public License % along with Dynare. If not, see . -if nargin==0, +if nargin==0 skipline() disp('[SAmeas, OutMatrix] = Morris_Measure_Groups(NumFact, Sample, Output, p, Group);') return @@ -54,7 +54,7 @@ OutMatrix=[]; if nargin < 5, Group=[]; end NumGroups = size(Group,2); -if nargin < 4 | isempty(p), +if nargin < 4 | isempty(p) p = 4; end Delt = p/(2*p-2); @@ -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 + for j=1:sizea % For each point in the trajectory i.e for each factor % matrix of factor which changes - if NumGroups ~ 0; + 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); + % 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,19 +110,19 @@ 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, + for j=1:NumFact SAm = SAmeas(j,:); SAm = SAm(find(~isnan(SAm))); rr=length(SAm); @@ -143,8 +143,8 @@ for k=1:size(Output,2) % 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 a7260d252..48a8187df 100644 --- a/matlab/gsa/Sampling_Function_2.m +++ b/matlab/gsa/Sampling_Function_2.m @@ -2,23 +2,23 @@ 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. % 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: +% 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 +% 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 @@ -27,16 +27,16 @@ function [Outmatrix, OutFact] = Sampling_Function_2(p, k, r, UB, LB, GroupMat) % 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 % 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 % @@ -56,7 +56,7 @@ function [Outmatrix, OutFact] = Sampling_Function_2(p, k, r, UB, LB, GroupMat) % % Copyright (C) 2005 European Commission -% Copyright (C) 2012 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -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 128e209ac..70fe1f475 100644 --- a/matlab/gsa/cumplot.m +++ b/matlab/gsa/cumplot.m @@ -1,12 +1,12 @@ -function h = cumplot(x); +function h = cumplot(x) %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 +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -29,6 +29,6 @@ y=[0:n n]./n; h0 = stairs(x,y); grid on, -if nargout, +if nargout h=h0; end diff --git a/matlab/gsa/filt_mc_.m b/matlab/gsa/filt_mc_.m index f9510c8af..b2dfb0411 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 @@ -57,11 +57,11 @@ skipline(2) disp('Starting sensitivity analysis') disp('for the fit of EACH observed series ...') skipline() -if ~options_.nograph, +if ~options_.nograph disp('Deleting old SA figures...') a=dir([OutDir,filesep,'*.*']); tmp1='0'; - if options_.opt_gsa.ppost, + if options_.opt_gsa.ppost tmp=['_rmse_post']; else if options_.opt_gsa.pprior @@ -69,40 +69,40 @@ if ~options_.nograph, else tmp=['_rmse_mc']; end - if options_gsa_.lik_only, + 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), + 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), + end + if strmatch([fname_,tmp1],a(j).name) disp(a(j).name) delete([OutDir,filesep,a(j).name]) - end, + end end disp('done !') end nshock=estim_params_.nvx + estim_params_.nvn + estim_params_.ncx + estim_params_.ncn; npar=estim_params_.np; -if ~isempty(options_.mode_file), - load(options_.mode_file,'xparam1'), +if ~isempty(options_.mode_file) + load(options_.mode_file,'xparam1') end -if options_.opt_gsa.ppost, +if options_.opt_gsa.ppost c=load([fname_,'_mean.mat'],'xparam1'); xparam1_mean=c.xparam1; clear c -elseif ~isempty(options_.mode_file) && exist([fname_,'_mean.mat'])==2, +elseif ~isempty(options_.mode_file) && exist([fname_,'_mean.mat'])==2 c=load([fname_,'_mean.mat'],'xparam1'); xparam1_mean=c.xparam1; clear c end -if options_.opt_gsa.ppost, +if options_.opt_gsa.ppost fnamtmp=[fname_,'_post']; DirectoryName = CheckPath('metropolis',M_.dname); else @@ -114,9 +114,9 @@ else DirectoryName = CheckPath(['gsa' filesep 'mc'],M_.dname); end end -if loadSA, +if loadSA tmplist =load([OutDir,filesep,fnamtmp, '.mat'],'vvarvecm'); - if isempty(fieldnames(tmplist)), + if isempty(fieldnames(tmplist)) disp('WARNING: cannot load results since the list of variables used is not present in the mat file') loadSA=0; elseif ~isequal(tmplist.vvarvecm,vvarvecm) @@ -124,7 +124,7 @@ if loadSA, loadSA=0; end end -if ~loadSA, +if ~loadSA if exist('xparam1','var') M_ = set_all_parameters(xparam1,estim_params_,M_); ys_mode=steady_(M_,options_,oo_); @@ -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; @@ -147,7 +147,7 @@ if ~loadSA, filfilt = dir([DirectoryName filesep M_.fname '_filter_step_ahead*.mat']); temp_smooth_file_list = dir([DirectoryName filesep M_.fname '_smooth*.mat']); jfile=0; - for j=1:length(temp_smooth_file_list), + for j=1:length(temp_smooth_file_list) if isempty(strfind(temp_smooth_file_list(j).name,'smoothed')), jfile=jfile+1; filsmooth(jfile)=temp_smooth_file_list(j); @@ -158,7 +158,7 @@ if ~loadSA, x=[]; logpo2=[]; sto_ys=[]; - for j=1:length(filparam), + for j=1:length(filparam) %load([DirectoryName filesep M_.fname '_param',int2str(j),'.mat']); if isempty(strmatch([M_.fname '_param_irf'],filparam(j).name)) load([DirectoryName filesep filparam(j).name]); @@ -173,9 +173,9 @@ if ~loadSA, if options_.opt_gsa.ppost || (options_.opt_gsa.ppost==0 && options_.opt_gsa.lik_only==0) skipline() disp('Computing RMSE''s...') - for i=1:size(vvarvecm,1), + 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]); @@ -189,7 +189,7 @@ if ~loadSA, end y0=-yss; nbb=0; - for j=1:length(filfilt), + for j=1:length(filfilt) load([DirectoryName filesep M_.fname '_filter_step_ahead',num2str(j),'.mat']); nb = size(stock,4); y0(:,:,nbb+1:nbb+nb)=y0(:,:,nbb+1:nbb+nb)+reshape(stock(1,js,1:gend,:),[length(js) gend nb]); @@ -198,7 +198,7 @@ if ~loadSA, end yobs=-yss; nbb=0; - for j=1:length(filupdate), + for j=1:length(filupdate) load([DirectoryName filesep M_.fname '_update',num2str(j),'.mat']); nb = size(stock,3); yobs(:,:,nbb+1:nbb+nb)=yobs(:,:,nbb+1:nbb+nb)+reshape(stock(js,1:gend,:),[length(js) gend nb]); @@ -208,7 +208,7 @@ if ~loadSA, y0M=mean(y0,2); rmse_MC=zeros(nruns,length(js)); r2_MC=zeros(nruns,length(js)); - for j=1:nruns, + for j=1:nruns rmse_MC(j,:) = sqrt(mean((yobs(:,istart:end,j)'-y0(:,istart:end,j)').^2)); r2_MC(j,:) = 1-mean((yobs(:,istart:end,j)'-y0(:,istart:end,j)').^2)./mean((yobs(:,istart:end,j)').^2); end @@ -222,12 +222,12 @@ if ~loadSA, end clear stock_filter; end - for j=1:nruns, + for j=1:nruns lnprior(j,1) = priordens(x(j,:)',bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4); 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,14 +336,14 @@ 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, + if options_.opt_gsa.ppost rmse_txt=rmse_pmean; r2_txt=r2_pmean; else - if options_.opt_gsa.pprior || ~exist('rmse_pmean'), - if exist('rmse_mode'), + if options_.opt_gsa.pprior || ~exist('rmse_pmean') + if exist('rmse_mode') rmse_txt=rmse_mode; r2_txt=r2_mode; else @@ -356,28 +356,28 @@ else r2_txt=r2_pmean; end end - for i=1:size(vvarvecm,1), + for i=1:size(vvarvecm,1) [dum, ixx(:,i)]=sort(rmse_MC(:,i)); end PP=ones(npar+nshock,size(vvarvecm,1)); PPV=ones(size(vvarvecm,1),size(vvarvecm,1),npar+nshock); SS=zeros(npar+nshock,size(vvarvecm,1)); - for j=1:npar+nshock, - for i=1:size(vvarvecm,1), + for j=1:npar+nshock + for i=1:size(vvarvecm,1) [H,P,KSSTAT] = smirnov(x(ixx(nfilt0(i)+1:end,i),j),x(ixx(1:nfilt0(i),i),j), alpha); [H1,P1,KSSTAT1] = smirnov(x(ixx(nfilt0(i)+1:end,i),j),x(ixx(1:nfilt0(i),i),j),alpha,1); [H2,P2,KSSTAT2] = smirnov(x(ixx(nfilt0(i)+1:end,i),j),x(ixx(1:nfilt0(i),i),j),alpha,-1); - if H1 & H2==0, + if H1 & H2==0 SS(j,i)=1; - elseif H1==0, + elseif H1==0 SS(j,i)=-1; else SS(j,i)=0; end PP(j,i)=P; end - for i=1:size(vvarvecm,1), - for l=1:size(vvarvecm,1), + for i=1:size(vvarvecm,1) + for l=1:size(vvarvecm,1) if l~=i && PP(j,i)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,11 +590,11 @@ 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:'; - if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior, + if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior headers=strvcat('Variable','min','max','min','max','posterior mode'); headers_tex=strvcat('\text{Variable}','\text{min}','\text{max}','\text{min}','\text{max}','\text{posterior mode}'); else @@ -602,7 +602,7 @@ else headers_tex=strvcat('\text{Variable}','\text{min}','\text{max}','\text{min}','\text{max}','\text{posterior mean}'); end data_mat=NaN(size(vvarvecm,1),5); - for j=1:size(vvarvecm,1), + 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)) ... @@ -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,22 +631,22 @@ 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, + + 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 optional_header=sprintf([label_format_leftbound,header_string_format,header_string_format,header_string_format,header_string_format],'','','best filtered','','remaining'); end dyntable(options_,title_string,headers,vvarvecm,data_mat, 0, val_width, val_precis,optional_header); if options_.TeX - if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior, + if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior optional_header={[' & \multicolumn{2}{c}{best ',num2str(pfilt*100),' filtered} & \multicolumn{2}{c}{remaining 90\%}\\']}; else optional_header={[' & \multicolumn{2}{c}{best filtered} & \multicolumn{2}{c}{remaining}\\']}; 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,17 +658,17 @@ 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:'; - if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior, + if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior headers=strvcat('Variable','min','max','min','max','posterior mode'); headers_tex=strvcat('\text{Variable}','\text{min}','\text{max}','\text{min}','\text{max}','\text{posterior mode}'); else @@ -676,7 +676,7 @@ else headers_tex=strvcat('\text{Variable}','\text{min}','\text{max}','\text{min}','\text{max}','\text{posterior mean}'); end data_mat=NaN(size(vvarvecm,1),5); - for j=1:size(vvarvecm,1), + 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)) ... @@ -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,32 +705,32 @@ 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, + + 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 optional_header=sprintf([label_format_leftbound,header_string_format,header_string_format,header_string_format,header_string_format],'','','best filtered','','remaining'); end dyntable(options_,title_string,headers,vvarvecm,data_mat, 0, val_width, val_precis,optional_header); if options_.TeX - if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior, + if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior optional_header={[' & \multicolumn{2}{c}{best ',num2str(pfilt*100),' filtered} & \multicolumn{2}{c}{remaining 90\%}\\']}; else optional_header={[' & \multicolumn{2}{c}{best filtered} & \multicolumn{2}{c}{remaining}\\']}; 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), + for j=1:size(vvarvecm,1) ns=find(PP(:,j)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)); @@ -783,7 +783,7 @@ else options_mcf.param_names_tex = param_names_tex; options_mcf.fname_ = fname_; options_mcf.OutputDirectoryName = OutDir; - for iy=1:size(vvarvecm,1), + for iy=1:size(vvarvecm,1) options_mcf.amcf_name = [asname '_' deblank(vvarvecm(iy,:)) '_map' ]; options_mcf.amcf_title = [atitle ' ' deblank(vvarvecm(iy,:))]; options_mcf.beha_title = ['better fit of ' deblank(vvarvecm(iy,:))]; @@ -791,21 +791,21 @@ else options_mcf.title = ['the fit of ' deblank(vvarvecm(iy,:))]; mcf_analysis(x, ixx(1:nfilt0(iy),iy), ixx(nfilt0(iy)+1:end,iy), options_mcf, options_); end - for iy=1:size(vvarvecm,1), + for iy=1:size(vvarvecm,1) ipar = find(any(squeeze(PPV(iy,:,:)). -if nargin==4, +if nargin==4 % inverse transformation yy = (exp(y0)-lam)*isig; return end -if nargin==1, +if nargin==1 xdir0=''; end f=@(lam,y)gsa_skewness(log(y+lam)); @@ -39,8 +39,9 @@ if ~(max(y0)<0 | min(y0)>0) 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); + 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); @@ -60,7 +61,7 @@ if ~(max(y0)<0 | min(y0)>0) end else if max(y0)<0 - isig=-1; + isig=-1; y0=-y0; %yy=log(-y0); xdir=[xdir0,'_minuslog']; @@ -68,7 +69,8 @@ else %yy=log(y0); xdir=[xdir0,'_log']; end - try lam=fzero(f,[-min(y0)+10*eps -min(y0)+median(y0)],[],y0); + 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); diff --git a/matlab/gsa/map_calibration.m b/matlab/gsa/map_calibration.m index 20b8084a4..c7f707d49 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,'$',''); @@ -58,10 +58,10 @@ options_mcf.OutputDirectoryName = OutputDirectoryName; skipline() disp('Sensitivity analysis for calibration criteria') -if DynareOptions.opt_gsa.ppost, +if DynareOptions.opt_gsa.ppost filetoload=dir([Model.dname filesep 'metropolis' filesep fname_ '_param_irf*.mat']); lpmat=[]; - for j=1:length(filetoload), + for j=1:length(filetoload) load([Model.dname filesep 'metropolis' filesep fname_ '_param_irf',int2str(j),'.mat']) lpmat = [lpmat; stock]; clear stock @@ -89,34 +89,34 @@ nbr_moment_restrictions = size(DynareOptions.endogenous_prior_restrictions.momen if init mat_irf=cell(nbr_irf_restrictions,1); - for ij=1:nbr_irf_restrictions, + 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, + 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, + for j=1:Nsam Model = set_all_parameters(lpmat(j,:)',EstimatedParameters,Model); - if nbr_moment_restrictions, + if nbr_moment_restrictions [Tt,Rr,SteadyState,info,Model,DynareOptions,DynareResults] = dynare_resolve(Model,DynareOptions,DynareResults); else [Tt,Rr,SteadyState,info,Model,DynareOptions,DynareResults] = dynare_resolve(Model,DynareOptions,DynareResults,'restrict'); end - if info(1)==0, + if info(1)==0 [info, info_irf, info_moment, data_irf, data_moment]=endogenous_prior_restrictions(Tt,Rr,Model,DynareOptions,DynareResults); if ~isempty(info_irf) - for ij=1:nbr_irf_restrictions, + for ij=1:nbr_irf_restrictions mat_irf{ij}(j,:)=data_irf{ij}(:,2)'; end indx_irf(j,:)=info_irf(:,1); end if ~isempty(info_moment) - for ij=1:nbr_moment_restrictions, + for ij=1:nbr_moment_restrictions mat_moment{ij}(j,:)=data_moment{ij}(:,2)'; end indx_moment(j,:)=info_moment(:,1); @@ -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() @@ -136,36 +136,36 @@ if init else load([OutputDirectoryName,filesep,fname_,'_',type,'_restrictions'],'xmat','mat_irf','mat_moment','irestrictions','indx_irf','indx_moment','endo_prior_restrictions'); end -if ~isempty(indx_irf), +if ~isempty(indx_irf) skipline() disp('Deleting old IRF calibration plots ...') a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_irf_calib*.eps']); - for j=1:length(a), + for j=1:length(a) delete([OutputDirectoryName,filesep,a(j).name]); end a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_irf_calib*.fig']); - for j=1:length(a), + for j=1:length(a) delete([OutputDirectoryName,filesep,a(j).name]); end a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_irf_calib*.pdf']); - for j=1:length(a), + for j=1:length(a) delete([OutputDirectoryName,filesep,a(j).name]); end a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions.eps']); - for j=1:length(a), + for j=1:length(a) delete([OutputDirectoryName,filesep,a(j).name]); end a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions.fig']); - for j=1:length(a), + for j=1:length(a) delete([OutputDirectoryName,filesep,a(j).name]); end a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions.pdf']); - for j=1:length(a), + for j=1:length(a) delete([OutputDirectoryName,filesep,a(j).name]); 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,21 +188,21 @@ 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, + if ~DynareOptions.nograph h1=dyn_figure(DynareOptions.nodisplay,'name',[type ' evaluation of irf restrictions']); nrow=ceil(sqrt(nbr_irf_couples)); ncol=nrow; - if nrow*(nrow-1)>nbr_irf_couples, + if nrow*(nrow-1)>nbr_irf_couples ncol=nrow-1; end end - for ij=1:nbr_irf_restrictions, + for ij=1:nbr_irf_restrictions mat_irf{ij}=mat_irf{ij}(irestrictions,:); irf_matrix{plot_indx(ij)} = [irf_matrix{plot_indx(ij)} mat_irf{ij}]; indx_irf_matrix(:,plot_indx(ij)) = indx_irf_matrix(:,plot_indx(ij)) + indx_irf(:,ij); - for ik=1:size(mat_irf{ij},2), + for ik=1:size(mat_irf{ij},2) [Mean,Median,Var,HPD,Distrib] = ... posterior_moments(mat_irf{ij}(:,ik),0,DynareOptions.mh_conf_sig); irf_mean{plot_indx(ij)} = [irf_mean{plot_indx(ij)}; Mean]; @@ -213,12 +213,12 @@ if ~isempty(indx_irf), end leg = num2str(endo_prior_restrictions.irf{ij,3}(1)); aleg = num2str(endo_prior_restrictions.irf{ij,3}(1)); - if size(mat_irf{ij},2)>1, + if size(mat_irf{ij},2)>1 leg = [leg,':' ,num2str(endo_prior_restrictions.irf{ij,3}(end))]; aleg = [aleg,'-' ,num2str(endo_prior_restrictions.irf{ij,3}(end))]; iplot_indx(ij)=0; end - if ~DynareOptions.nograph && length(time_matrix{plot_indx(ij)})==1, + if ~DynareOptions.nograph && length(time_matrix{plot_indx(ij)})==1 set(0,'currentfigure',h1), subplot(nrow,ncol, plot_indx(ij)), hc = cumplot(mat_irf{ij}(:,ik)); @@ -260,16 +260,16 @@ 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(proba1, - if ~DynareOptions.nograph, + for ij=1:nbr_irf_couples + if length(time_matrix{ij})>1 + if ~DynareOptions.nograph set(0,'currentfigure',h1); subplot(nrow,ncol, ij) itmp = (find(plot_indx==ij)); @@ -277,7 +277,7 @@ if ~isempty(indx_irf), a=axis; delete(htmp); tmp=[]; - for ir=1:length(itmp), + for ir=1:length(itmp) for it=1:length(endo_prior_restrictions.irf{itmp(ir),3}) temp_index = find(time_matrix{ij}==endo_prior_restrictions.irf{itmp(ir),3}(it)); tmp(temp_index,:) = endo_prior_restrictions.irf{itmp(ir),4}; @@ -293,14 +293,14 @@ if ~isempty(indx_irf), plot(time_matrix{ij},irf_median{ij},'k','linewidth',2) plot(time_matrix{ij},[irf_distrib{ij}],'k-') plot(a(1:2),[0 0],'r') - hold off, + hold off axis([max(1,a(1)) a(2:4)]) - box on, + box on %set(gca,'xtick',sort(time_matrix{ij})) itmp = min(itmp); title([endo_prior_restrictions.irf{itmp,1},' vs ',endo_prior_restrictions.irf{itmp,2}],'interpreter','none'), end - if any(iplot_indx.*plot_indx==ij), + if any(iplot_indx.*plot_indx==ij) % MCF of the couples with logical AND itmp = min(find(plot_indx==ij)); indx1 = find(indx_irf_matrix(:,ij)==0); @@ -324,7 +324,7 @@ if ~isempty(indx_irf), end end end - if ~DynareOptions.nograph, + if ~DynareOptions.nograph dyn_saveas(h1,[OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions'],DynareOptions.nodisplay,DynareOptions.graph_format); create_TeX_loader(DynareOptions,[OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions'],[type ' evaluation of irf restrictions'],'irf_restrictions',type,DynareOptions.figures.textwidth*min(ij/ncol,1)) end @@ -335,32 +335,32 @@ if ~isempty(indx_moment) skipline() disp('Deleting old MOMENT calibration plots ...') a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_moment_calib*.eps']); - for j=1:length(a), + for j=1:length(a) delete([OutputDirectoryName,filesep,a(j).name]); end a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_moment_calib*.fig']); - for j=1:length(a), + for j=1:length(a) delete([OutputDirectoryName,filesep,a(j).name]); end a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_moment_calib*.pdf']); - for j=1:length(a), + for j=1:length(a) delete([OutputDirectoryName,filesep,a(j).name]); end a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions.eps']); - for j=1:length(a), + for j=1:length(a) delete([OutputDirectoryName,filesep,a(j).name]); end a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions.fig']); - for j=1:length(a), + for j=1:length(a) delete([OutputDirectoryName,filesep,a(j).name]); end a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions.pdf']); - for j=1:length(a), + for j=1:length(a) delete([OutputDirectoryName,filesep,a(j).name]); end disp('done !') skipline() - + %get parameter names including standard deviations np=size(BayesInfo.name,1); name=cell(np,1); @@ -402,22 +402,22 @@ 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, + if ~DynareOptions.nograph h2=dyn_figure(DynareOptions.nodisplay,'name',[type ' evaluation of moment restrictions']); nrow=ceil(sqrt(nbr_moment_couples)); ncol=nrow; - if nrow*(nrow-1)>nbr_moment_couples, + if nrow*(nrow-1)>nbr_moment_couples ncol=nrow-1; end end - - for ij=1:nbr_moment_restrictions, + + 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}]; indx_moment_matrix(:,plot_indx(ij)) = indx_moment_matrix(:,plot_indx(ij)) + indx_moment(:,ij); - for ik=1:size(mat_moment{ij},2), + for ik=1:size(mat_moment{ij},2) [Mean,Median,Var,HPD,Distrib] = ... posterior_moments(mat_moment{ij}(:,ik),0,DynareOptions.mh_conf_sig); moment_mean{plot_indx(ij)} = [moment_mean{plot_indx(ij)}; Mean]; @@ -428,12 +428,12 @@ if ~isempty(indx_moment) end leg = num2str(endo_prior_restrictions.moment{ij,3}(1)); aleg = num2str(endo_prior_restrictions.moment{ij,3}(1)); - if size(mat_moment{ij},2)>1, + if size(mat_moment{ij},2)>1 leg = [leg,':' ,num2str(endo_prior_restrictions.moment{ij,3}(end))]; aleg = [aleg,'_' ,num2str(endo_prior_restrictions.moment{ij,3}(end))]; iplot_indx(ij)=0; end - if ~DynareOptions.nograph && length(time_matrix{plot_indx(ij)})==1, + if ~DynareOptions.nograph && length(time_matrix{plot_indx(ij)})==1 set(0,'currentfigure',h2); subplot(nrow,ncol,plot_indx(ij)), hc = cumplot(mat_moment{ij}(:,ik)); @@ -443,10 +443,10 @@ if ~isempty(indx_moment) x2val=min(endo_prior_restrictions.moment{ij,4}(2),a(2)); hp = patch([x1val x2val x2val x1val],a([3 3 4 4]),'b'); set(hp,'FaceColor', [0.7 0.8 1]) - hold all, + hold all hc = cumplot(mat_moment{ij}(:,ik)); set(hc,'color','k','linewidth',2) - hold off, + hold off title([endo_prior_restrictions.moment{ij,1},' vs ',endo_prior_restrictions.moment{ij,2},'(',leg,')'],'interpreter','none'), % if ij==maxij % leg1 = num2str(endo_prior_restrictions.moment{ij,3}(:)); @@ -470,15 +470,15 @@ 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(proba1, + for ij=1:nbr_moment_couples + if length(time_matrix{ij})>1 if ~DynareOptions.nograph itmp = (find(plot_indx==ij)); set(0,'currentfigure',h2); @@ -487,7 +487,7 @@ if ~isempty(indx_moment) a=axis; delete(htmp); tmp=[]; - for ir=1:length(itmp), + for ir=1:length(itmp) for it=1:length(endo_prior_restrictions.moment{itmp(ir),3}) temp_index = find(time_matrix{ij}==endo_prior_restrictions.moment{itmp(ir),3}(it)); tmp(temp_index,:) = endo_prior_restrictions.moment{itmp(ir),4}; @@ -498,19 +498,19 @@ if ~isempty(indx_moment) tmp(isinf(tmp(:,2)),2)=a(4); hp = patch([time_matrix{ij} time_matrix{ij}(end:-1:1)],[tmp(:,1); tmp(end:-1:1,2)],'b'); set(hp,'FaceColor',[0.7 0.8 1]) - hold on, + hold on plot(time_matrix{ij},[max(moment_matrix{ij})' min(moment_matrix{ij})'],'k--','linewidth',2) plot(time_matrix{ij},moment_median{ij},'k','linewidth',2) plot(time_matrix{ij},[moment_distrib{ij}],'k-') plot(a(1:2),[0 0],'r') - hold off, + hold off axis(a) - box on, + box on set(gca,'xtick',sort(time_matrix{ij})) itmp = min(itmp); title([endo_prior_restrictions.moment{itmp,1},' vs ',endo_prior_restrictions.moment{itmp,2}],'interpreter','none'), end - if any(iplot_indx.*plot_indx==ij), + if any(iplot_indx.*plot_indx==ij) % MCF of the couples with logical AND itmp = min(find(plot_indx==ij)); indx1 = find(indx_moment_matrix(:,ij)==0); @@ -534,11 +534,11 @@ if ~isempty(indx_moment) end end end - if ~DynareOptions.nograph, + if ~DynareOptions.nograph 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 a93ef006f..fa23574dd 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 @@ -31,21 +31,21 @@ ntra = opt_gsa.morris_ntra; itrans = opt_gsa.trans_ident; np = estim_params_.np; -if opt_gsa.load_ident_files, +if opt_gsa.load_ident_files gsa_flag=0; else 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 load(filetoload,'lpmat','lpmat0','istable','T','yys','nspred','nboth','nfwrd') -if ~isempty(lpmat0), +if ~isempty(lpmat0) lpmatx=lpmat0(istable,:); else lpmatx=[]; @@ -56,24 +56,24 @@ npT = np+nshock; fname_ = M_.fname; -if opt_gsa.load_ident_files==0, +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'), + if exist('T') [vdec, cc, ac] = mc_moments(T, lpmatx, oo_.dr); else - return, + return end - if opt_gsa.morris==2, + 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, + 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 @@ -86,9 +86,9 @@ if opt_gsa.load_ident_files==0, clear GAM gas % end end - if opt_gsa.morris~=1 & M_.exo_nbr>1, + if opt_gsa.morris~=1 & M_.exo_nbr>1 ifig=0; - for j=1:M_.exo_nbr, + for j=1:M_.exo_nbr if mod(j,6)==1 hh=dyn_figure(options_.nodisplay,'name',['Variance decomposition shocks']); ifig=ifig+1; @@ -101,13 +101,13 @@ if opt_gsa.load_ident_files==0, 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), + 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, + 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 @@ -126,7 +126,7 @@ if opt_gsa.load_ident_files==0, 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); @@ -135,24 +135,24 @@ if opt_gsa.load_ident_files==0, % 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), + if ~isempty(lpmatx) set_shocks_param(lpmatx(1,:)); end A(:,:,1)=[Aa, triu(Bb*M_.Sigma_e*Bb')]; - for j=2:length(istable), + 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), + if ~isempty(lpmatx) set_shocks_param(lpmatx(j,:)); end A(:,:,j)=[Aa, triu(Bb*M_.Sigma_e*Bb')]; end - clear T; - clear lpmatx; + clear T + clear lpmatx [nr,nc,nn]=size(A); io=bayestopt_.mf2; @@ -167,7 +167,7 @@ if opt_gsa.load_ident_files==0, [yt, j0]=teff(A,Nsam,istable); yt = [yys yt]; - if opt_gsa.morris==2, + 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)'))); @@ -175,7 +175,7 @@ if opt_gsa.load_ident_files==0, clear TAU A % end else - clear A, + clear A end % [yt1, j01]=teff(T1,Nsam,istable); % [yt2, j02]=teff(T2,Nsam,istable); @@ -184,7 +184,7 @@ if opt_gsa.load_ident_files==0, % yt=[yt1 yt2 ytr]; save([OutputDirectoryName,'/',fname_,'_main_eff.mat'],'ac','cc','vdec','yt','mss') else - if opt_gsa.morris==2, + 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); @@ -205,12 +205,12 @@ end % end % yt = yt(:,j0); -if opt_gsa.morris==1, +if opt_gsa.morris==1 %OutputDir = CheckPath('gsa/screen'); - if ~isempty(vdec), - if opt_gsa.load_ident_files==0, + if ~isempty(vdec) + if opt_gsa.load_ident_files==0 SAMorris = []; - for i=1:size(vdec,2), + for i=1:size(vdec,2) [SAmeas, SAMorris(:,:,i)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], vdec(:,i),nliv); end SAvdec = squeeze(SAMorris(:,1,:))'; @@ -218,7 +218,7 @@ if opt_gsa.morris==1, 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) @@ -227,7 +227,7 @@ if opt_gsa.morris==1, 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, + for ip=1:npT text(ip,-2,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') end xlabel(' ') @@ -236,7 +236,7 @@ if opt_gsa.morris==1, 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; @@ -273,7 +273,7 @@ if opt_gsa.morris==1, % close(gcf) % end % end - % + % % ifig = 0; % for j=1:M_.exo_nbr, % if mod(j,6)==1 @@ -310,10 +310,10 @@ if opt_gsa.morris==1, % end - if opt_gsa.load_ident_files==0, + if opt_gsa.load_ident_files==0 SAMorris = []; ccac = [mss cc ac]; - for i=1:size(ccac,2), + for i=1:size(ccac,2) [SAmeas, SAMorris(:,:,i)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], [ccac(:,i)],nliv); end SAcc = squeeze(SAMorris(:,1,:))'; @@ -324,7 +324,7 @@ if opt_gsa.morris==1, 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) @@ -333,7 +333,7 @@ if opt_gsa.morris==1, ydum = get(gca,'ylim'); set(gca,'ylim',[0 1]) set(gca,'position',[0.13 0.2 0.775 0.7]) - for ip=1:npT, + for ip=1:npT text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') end xlabel(' ') @@ -344,7 +344,7 @@ if opt_gsa.morris==1, % close(gcf), %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % MORRIS FOR DERIVATIVES + % MORRIS FOR DERIVATIVES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if opt_gsa.load_ident_files==0, @@ -357,7 +357,7 @@ if opt_gsa.morris==1, % 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))'; + % sad(:,j) = median(SAddd(find(~isnan(squeeze(SAddd(:,1,j)))),:,j))'; % end % save([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAddd','sad','-append') % else @@ -375,12 +375,12 @@ if opt_gsa.morris==1, % iii = find((im-[1:npT])==0); % disp('Most identified params') % disp(bayestopt_.name(iii)) - - + + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % END OF MORRIS FOR DERIVATIVES + % END OF MORRIS FOR DERIVATIVES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - + % ifig = 0; % for j=1:size(options_.varobs,1) % if mod(j,6)==1 @@ -657,7 +657,7 @@ if opt_gsa.morris==1, % close(gcf), % end % end - % + % % ifig = 0; % for j=1:M_.exo_nbr, % if mod(j,6)==1 @@ -694,9 +694,9 @@ if opt_gsa.morris==1, % end - if opt_gsa.load_ident_files==0, + if opt_gsa.load_ident_files==0 SAMorris = []; - for j=1:j0, + for j=1:j0 [SAmeas, SAMorris(:,:,j)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], yt(:,j),nliv); end @@ -730,7 +730,7 @@ if opt_gsa.morris==1, set(gca,'ylim',[0 1]) set(gca,'position',[0.13 0.2 0.775 0.7]) xlabel(' ') - for ip=1:npT, + 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 @@ -753,7 +753,7 @@ if opt_gsa.morris==1, % 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) @@ -777,12 +777,12 @@ if opt_gsa.morris==1, % eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_redform']); % eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_redform']); -elseif opt_gsa.morris==3, +elseif opt_gsa.morris==3 return - + np=estim_params_.np; na=(4*np+1)*opt_gsa.Nsam; - for j=1:j0, + 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))); @@ -793,10 +793,9 @@ elseif opt_gsa.morris==3, 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), + 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,:)); @@ -811,10 +810,10 @@ elseif opt_gsa.morris==3, ee=ee([end:-1:1])./j0; i0=length(find(ee>0.01)); v0=v0(:,[end:-1:1]); - for j=1:i0, + 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, + 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') @@ -825,51 +824,51 @@ elseif opt_gsa.morris==3, er=er([end:-1:1])./j0; ir0=length(find(er>0.01)); vr=vr(:,[end:-1:1]); - for j=1:ir0, + 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, + for j=1:ir0 ys_pcr(j,:)=yd_pcr(j,:)./max(yd_pcr(j,:)); - end, + 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') - -elseif opt_gsa.morris==2, % ISKREV staff - return, - -else, % main effects analysis - - if itrans==0, +elseif opt_gsa.morris==2 % ISKREV staff + return + + +else % main effects analysis + + if itrans==0 fsuffix = ''; - elseif itrans==1, + elseif itrans==1 fsuffix = '_log'; else fsuffix = '_rank'; end - + imap=[1:npT]; - if isempty(lpmat0), + 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 + % 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); @@ -889,7 +888,7 @@ else, % main effects analysis % 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 @@ -915,7 +914,7 @@ else, % main effects analysis % 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 @@ -951,7 +950,7 @@ else, % main effects analysis % close(gcf), % end % end - % + % % ifig = 0; % for j=1:M_.exo_nbr, % if mod(j,6)==1 @@ -989,8 +988,8 @@ else, % main effects analysis % end % end - if opt_gsa.load_ident_files==0, - try + if opt_gsa.load_ident_files==0 + try EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAcc','ir_cc','ic_cc'); catch EET=[]; @@ -1011,15 +1010,15 @@ else, % main effects analysis % siPCA = sum(siPCA,1); % siPCA = siPCA./max(siPCA); SAcc=zeros(size(ccac,2),npT); - for j=1:npca, %size(ccac,2), - if itrans==0, + for j=1:npca %size(ccac,2), + if itrans==0 y0 = ccac(istable,j); - elseif itrans==1, + elseif itrans==1 y0 = log_trans_(ccac(istable,j)); else y0 = trank(ccac(istable,j)); end - if ~isempty(EET), + if ~isempty(EET) % imap=find(EET.SAvdec(j,:)); % [dum, isort]=sort(-EET.SAvdec(j,:)); imap=find(siPCA(j,:) >= (0.1.*max(siPCA(j,:))) ); @@ -1039,7 +1038,7 @@ else, % main effects analysis 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.') @@ -1098,9 +1097,9 @@ else, % main effects analysis % close(gcf), % end % end - % + % % if opt_gsa.load_ident_files==0, - % try + % try % EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAac','ir_ac','ic_ac'); % catch % EET=[]; @@ -1127,13 +1126,13 @@ else, % main effects analysis % 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) @@ -1151,7 +1150,7 @@ else, % main effects analysis % 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 @@ -1189,12 +1188,12 @@ else, % main effects analysis % close(gcf), % end % end - + % x0=x0(:,nshock+1:end); imap=[1:npT]; % if opt_gsa.load_ident_files==0, - % try + % try % EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAtadj','ir_tadj','ic_tadj'); % ny=size(EET.SAtadj,1); % catch @@ -1232,13 +1231,13 @@ else, % main effects analysis % 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) @@ -1256,7 +1255,7 @@ else, % main effects analysis % 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 @@ -1291,7 +1290,7 @@ else, % main effects analysis % close(gcf), % end % end - % + % % ifig = 0; % for j=1:M_.exo_nbr, % if mod(j,6)==1 @@ -1326,10 +1325,10 @@ else, % main effects analysis % close(gcf), % end % end - % - % + % + % % if opt_gsa.load_ident_files==0, - % try + % try % EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAIF','ir_if','ic_if'); % catch % EET=[]; @@ -1356,13 +1355,13 @@ else, % main effects analysis % 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) @@ -1380,7 +1379,7 @@ else, % main effects analysis % 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 @@ -1415,7 +1414,7 @@ else, % main effects analysis % close(gcf), % end % end - % + % % ifig = 0; % for j=1:M_.exo_nbr, % if mod(j,6)==1 @@ -1453,7 +1452,7 @@ else, % main effects analysis % SAmom = [SAvdec' SAcc' SAac']'; % SAdyn = [SAtadj' SAif']'; % SAall = [SAmom(:,nshock+1:end)' SAdyn']'; - % + % % figure, % % boxplot(SAtadj,'whis',10,'symbol','r.') % myboxplot(SAmom,[],'.',[],10) @@ -1472,7 +1471,7 @@ else, % main effects analysis % 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) @@ -1491,7 +1490,7 @@ else, % main effects analysis % 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) @@ -1523,13 +1522,13 @@ else, % main effects analysis % figure, bar(latent'*SAcc), hh=dyn_figure(options_.nodisplay,'Name',['Identifiability indices in the ',fsuffix,' moments.']); - bar(sum(SAcc)), + 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, + 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 diff --git a/matlab/gsa/mc_moments.m b/matlab/gsa/mc_moments.m index ed492d745..b7464a7e0 100644 --- a/matlab/gsa/mc_moments.m +++ b/matlab/gsa/mc_moments.m @@ -1,6 +1,6 @@ function [vdec, cc, ac] = mc_moments(mm, ss, dr) -% Copyright (C) 2012 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -27,10 +27,10 @@ vdec = zeros(nobs,M_.exo_nbr,nsam); cc = zeros(nobs,nobs,nsam); ac = zeros(nobs,nobs*options_.ar,nsam); -for j=1: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), + if ~isempty(ss) set_shocks_param(ss(j,:)); end [vdec(:,:,j), corr, autocorr, z, zz] = th_moments(oo_.dr,options_.varobs); diff --git a/matlab/gsa/mcf_analysis.m b/matlab/gsa/mcf_analysis.m index 2d6169185..c4de17b8f 100644 --- a/matlab/gsa/mcf_analysis.m +++ b/matlab/gsa/mcf_analysis.m @@ -6,7 +6,7 @@ function indmcf = mcf_analysis(lpmat, ibeha, inobeha, options_mcf, DynareOptions % % Copyright (C) 2014 European Commission -% Copyright (C) 2016 Dynare Team +% Copyright (C) 2016-2017 Dynare Team % % This file is part of Dynare. % @@ -42,9 +42,9 @@ nobeha_title = options_mcf.nobeha_title; title = options_mcf.title; fname_ = options_mcf.fname_; xparam1=[]; -if isfield(options_mcf,'xparam1'), +if isfield(options_mcf,'xparam1') xparam1=options_mcf.xparam1; -end +end OutputDirectoryName = options_mcf.OutputDirectoryName; [proba, dproba] = stab_map_1(lpmat, ibeha, inobeha, [],0); @@ -67,14 +67,14 @@ if ~isempty(indmcf) end -if length(ibeha)>10 && length(inobeha)>10, +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, +if ~isempty(indmcf) && ~DynareOptions.nograph skipline() xx=[]; if ~ isempty(xparam1), xx=xparam1(indmcf); end diff --git a/matlab/gsa/myboxplot.m b/matlab/gsa/myboxplot.m index 054f66430..a83ca922c 100644 --- a/matlab/gsa/myboxplot.m +++ b/matlab/gsa/myboxplot.m @@ -3,10 +3,10 @@ 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 +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -35,7 +35,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 @@ -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)); @@ -172,7 +172,7 @@ else % % % % % outliers2_y, outliers2_x, [symbol(2),"r;;"]); end -if nargout, +if nargout sout=s; end % % % endfunction \ No newline at end of file diff --git a/matlab/gsa/myprctilecol.m b/matlab/gsa/myprctilecol.m index b6f8e2661..15ddcfcd4 100644 --- a/matlab/gsa/myprctilecol.m +++ b/matlab/gsa/myprctilecol.m @@ -1,11 +1,11 @@ -function y = myprctilecol(x,p); +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 +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -27,9 +27,9 @@ xx = sort(x); if m==1 | n==1 m = max(m,n); - if m == 1, + if m == 1 y = x*ones(length(p),1); - return; + return end n = 1; q = 100*(0.5:m - 0.5)./m; diff --git a/matlab/gsa/pick.m b/matlab/gsa/pick.m index 9b6894c8d..fb5ccbfe5 100644 --- a/matlab/gsa/pick.m +++ b/matlab/gsa/pick.m @@ -1,7 +1,8 @@ function pick % % Copyright (C) 2001-2017 European Commission -% +% Copyright (C) 2017 DynareTeam +% % 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 @@ -10,7 +11,7 @@ function pick % 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 +% 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, @@ -20,7 +21,7 @@ function pick % 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 @@ -34,7 +35,7 @@ function pick % '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. +% [4] Beven K., GLUE for Windows User manual, 1998. @@ -55,7 +56,7 @@ dy=get(gca,'ylim'); pos=get(gca,'position'); scalex=dx(2)-dx(1); scaley=dy(2)-dy(1); -if length(X)>1, +if length(X)>1 K = dsearchn([(Y./scaley)' (X./scalex)'],[y/scaley x/scalex]); else az=get(gca,'children'); @@ -68,15 +69,15 @@ 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), +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, + plot(dumx(KK),dumy(KK),'or'); + if dumx(KK) < xmid text(dumx(KK),dumy(KK),[' ',num2str(K)], ... 'FontWeight','Bold',... 'Color','r'); diff --git a/matlab/gsa/prior_draw_gsa.m b/matlab/gsa/prior_draw_gsa.m index cdb795f0a..2694ea159 100644 --- a/matlab/gsa/prior_draw_gsa.m +++ b/matlab/gsa/prior_draw_gsa.m @@ -1,25 +1,25 @@ 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 % -% ALGORITHM -% ... +% OUTPUTS +% o pdraw [double] draw from the joint prior density. +% +% 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 +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -106,10 +106,10 @@ 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 + 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 + case 6% INV-GAMMA2 distribution % TO BE CHECKED pdraw(:,i) = 1./gaminv(rdraw(:,i),p7(i)/2,2/p6(i))+p3(i); case 8 @@ -117,6 +117,4 @@ for i = 1:npar otherwise % Nothing to do here. end -end - - +end \ No newline at end of file diff --git a/matlab/gsa/read_data.m b/matlab/gsa/read_data.m index bbb2d80a7..bb2c71a61 100644 --- a/matlab/gsa/read_data.m +++ b/matlab/gsa/read_data.m @@ -1,10 +1,10 @@ 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 +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/gsa/redform_map.m b/matlab/gsa/redform_map.m index 5f2c71292..a7ae7f712 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,'$',''); @@ -70,7 +70,7 @@ fname_ = M_.fname; bounds = prior_bounds(bayestopt_, options_.prior_trunc); -if nargin==0, +if nargin==0 dirname=''; end @@ -100,7 +100,7 @@ if ~exist('T') else load([dirname,filesep,M_.fname,'_mc'],'T'); end - if ~exist('T'), + if ~exist('T') disp('The model is too large!') disp('Reduced form mapping stopped!') return @@ -114,7 +114,7 @@ adir0=pwd; nspred=size(T,2)-M_.exo_nbr; x0=lpmat(istable,:); -if isempty(lpmat0), +if isempty(lpmat0) xx0=[]; nshocks=0; else @@ -123,7 +123,7 @@ else end [kn, np]=size(x0); offset = length(bayestopt_.pshape)-np; -if options_gsa_.prior_range, +if options_gsa_.prior_range pshape=5*(ones(np,1)); pd = [NaN(np,1) NaN(np,1) bounds.lb(offset+1:end) bounds.ub(offset+1:end)]; else @@ -158,12 +158,12 @@ for j=1:size(anamendo,1) skipline() disp(['[', namendo,' vs ',namexo,']']) - - if ~isempty(iexo), + + if ~isempty(iexo) %y0=squeeze(T(iendo,iexo+nspred,istable)); y0=squeeze(T(iendo,iexo+nspred,:)); - if (max(y0)-min(y0))>1.e-10, - if mod(iplo,9)==0 && isempty(threshold) && ~options_.nograph, + if (max(y0)-min(y0))>1.e-10 + if mod(iplo,9)==0 && isempty(threshold) && ~options_.nograph ifig=ifig+1; hfig = dyn_figure(options_.nodisplay,'name',['Reduced Form Mapping: ', namendo,' vs shocks ',int2str(ifig)]); iplo=0; @@ -171,7 +171,7 @@ for j=1:size(anamendo,1) iplo=iplo+1; js=js+1; xdir0 = [adir,filesep,namendo,'_vs_', namexo]; - if ilog==0 || ~isempty(threshold), + if ilog==0 || ~isempty(threshold) if isempty(threshold) if isempty(dir(xdir0)) mkdir(xdir0) @@ -192,8 +192,8 @@ for j=1:size(anamendo,1) if isempty(dir(xdir)) mkdir(xdir) end - if ~options_.nograph, - hf=dyn_figure(options_.nodisplay,'name',['Reduced Form Mapping (Monte Carlo Filtering): ',namendo,' vs ', namexo]); + if ~options_.nograph + 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,9 +224,9 @@ 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, + if nshocks lpmat0=xx0(iy,:); end istable=[1:length(iy)]; @@ -235,11 +235,11 @@ for j=1:size(anamendo,1) else icheck=[]; end - if isempty(icheck), + if isempty(icheck) atitle0=['Monte Carlo Filtering for ',namendo,' vs ', namexo]; options_mcf.title = atitle0; indmcf = redform_mcf(y0, x0, options_mcf, options_); - + end end else @@ -254,11 +254,11 @@ 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, + + if isempty(threshold) && ~options_.nograph figure(hfig) subplot(3,3,iplo), - if ilog, + if ilog [saso, iso] = sort(-silog(:,js)); bar([silog(iso(1:min(np,10)),js)]) logflag='log'; @@ -270,20 +270,20 @@ for j=1:size(anamendo,1) %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), + for ip=1:min(np,10) 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 - if iplo<9 && iplo>0 && ifig && ~options_.nograph, + if iplo<9 && iplo>0 && ifig && ~options_.nograph 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)],options_.figures.textwidth*min(iplo/3,1)) end @@ -294,12 +294,12 @@ 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), + + if ~isempty(ilagendo) %y0=squeeze(T(iendo,ilagendo,istable)); y0=squeeze(T(iendo,ilagendo,:)); - if (max(y0)-min(y0))>1.e-10, - if mod(iplo,9)==0 && isempty(threshold) && ~options_.nograph, + if (max(y0)-min(y0))>1.e-10 + if mod(iplo,9)==0 && isempty(threshold) && ~options_.nograph ifig=ifig+1; hfig = dyn_figure(options_.nodisplay,'name',['Reduced Form Mapping: ' namendo,' vs lags ',int2str(ifig)]); iplo=0; @@ -307,7 +307,7 @@ for j=1:size(anamendo,1) iplo=iplo+1; js=js+1; xdir0 = [adir,filesep,namendo,'_vs_', namlagendo]; - if ilog==0 || ~isempty(threshold), + if ilog==0 || ~isempty(threshold) if isempty(threshold) if isempty(dir(xdir0)) mkdir(xdir0) @@ -328,8 +328,8 @@ for j=1:size(anamendo,1) if isempty(dir(xdir)) mkdir(xdir) end - if ~options_.nograph, - hf=dyn_figure(options_.nodisplay,'name',['Reduced Form Mapping (Monte Carlo Filtering): ',namendo,' vs lagged ', namlagendo]); + if ~options_.nograph + 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,19 +361,19 @@ 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, + if nshocks lpmat0=xx0(iy,:); end 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 - if isempty(icheck), + if isempty(icheck) atitle0=['Monte Carlo Filtering for ',namendo,' vs ', namlagendo]; options_mcf.title = atitle0; indmcf = redform_mcf(y0, x0, options_mcf, options_); @@ -391,11 +391,11 @@ 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), - if ilog, + if ilog [saso, iso] = sort(-silog(:,js)); bar([silog(iso(1:min(np,10)),js)]) logflag='log'; @@ -407,27 +407,27 @@ for j=1:size(anamendo,1) %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), + for ip=1:min(np,10) text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') end title([logflag,' ',namendo,' vs ',namlagendo,'(-1)'],'interpreter','none') - if iplo==9, + if iplo==9 dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_.nodisplay,options_.graph_format); 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 - if iplo<9 && iplo>0 && ifig && ~options_.nograph, + if iplo<9 && iplo>0 && ifig && ~options_.nograph dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_.nodisplay,options_.graph_format); 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)],options_.figures.textwidth*min(iplo/3,1)); end end -if isempty(threshold) && ~options_.nograph, - if ilog==0, +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.') myboxplot(si',[],'.',[],10) @@ -436,7 +436,7 @@ if isempty(threshold) && ~options_.nograph, 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, + for ip=1:np text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') end title('Reduced form GSA') @@ -452,13 +452,13 @@ if isempty(threshold) && ~options_.nograph, 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, + for ip=1:np text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') end 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 @@ -472,20 +472,20 @@ pnames = options_map.param_names; pd = options_map.pd; pshape = options_map.pshape; xdir = options_map.OutputDirectoryName; -if options_map.prior_range, - for j=1:np, +if options_map.prior_range + for j=1:np x0(:,j)=(x0(:,j)-pd(j,3))./(pd(j,4)-pd(j,3)); end else x0=priorcdf(x0,pshape, pd(:,1), pd(:,2), pd(:,3), pd(:,4)); end -if ilog, +if ilog fname=[xdir filesep options_map.fname_ '_' options_map.amap_name '_log']; else fname=[xdir filesep options_map.fname_ '_' options_map.amap_name]; end -if iload==0, +if iload==0 if isempty(dir(xdir)) mkdir(xdir) end @@ -497,7 +497,7 @@ if iload==0, % 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, + if istep>1 iest = is(floor(istep/2):istep:end); nest = length(iest); irest = is(setdiff([1:nrun],[floor(istep/2):istep:nrun])); @@ -508,7 +508,7 @@ if iload==0, si=nan(np,1); return end - if ~ismember(irest(end),ifit), + if ~ismember(irest(end),ifit) ifit = union(ifit, irest(end)); end nfit=length(ifit); @@ -517,21 +517,21 @@ if iload==0, % nfit=nest; ipred = setdiff([1:nrun],ifit); - if ilog, + if ilog [y1, tmp, isig, lam] = log_trans_(y0(iest)); y1 = log(y0*isig+lam); end - if ~options_.nograph, - hfig=dyn_figure(options_.nodisplay,'name',options_map.figtitle); + if ~options_.nograph + hfig=dyn_figure(options_.nodisplay,'name',options_map.figtitle); subplot(221) - if ilog, - hist(y1,30), + if ilog + hist(y1,30) else - hist(y0,30), + hist(y0,30) end title(options_map.title,'interpreter','none') subplot(222) - if ilog, + if ilog hc = cumplot(y1); else hc = cumplot(y0); @@ -541,7 +541,7 @@ if iload==0, end gsa0 = ss_anova(y0(iest), x0(iest,:), 1); - if ilog, + if ilog [gsa22, gsa1, gsax] = ss_anova_log(y1(iest), x0(iest,:), isig, lam, gsa0); end % if (gsa1.out.bic-gsa0.out.bic) < 10, @@ -551,7 +551,7 @@ if iload==0, % y0=y1; % ilog=1; % end - if nfit>nest, + 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; @@ -602,13 +602,13 @@ if iload==0, save([fname,'_map.mat'],'gsa_') [sidum, iii]=sort(-gsa_.si); gsa_.x0=x00(ifit,:); - if ~options_.nograph, + if ~options_.nograph hmap=gsa_sdp_plot(gsa_,[fname '_map'],pnames,iii(1:min(12,np))); set(hmap,'name',options_map.amap_title); end gsa_.x0=x0(ifit,:); % copyfile([fname,'_est.mat'],[fname,'.mat']) - if ~options_.nograph, + if ~options_.nograph figure(hfig); subplot(223), plot(y0(ifit),[gsa_.fit y0(ifit)],'.'), @@ -616,13 +616,13 @@ if iload==0, % 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 + % else % plot(y0(ifit),[gsa_.fit y0(ifit)],'.'), % r2 = gsa_.r2; % end title(['Learning sample fit - R2=' num2str(r2,2)],'interpreter','none') - if nfit=5 && ~isempty(gsa0), - for j=1:np, +if nargin >=5 && ~isempty(gsa0) + for j=1:np nvr2(j) = var(diff(gsa2.fs(:,j),2)); nvr0(j) = var(diff(gsa0.fs(:,j),2)); end @@ -702,7 +702,7 @@ if nargin >=5 && ~isempty(gsa0), gsa1 = ss_anova(y, x, 1, 0, 2, gsa1.nvr); gsa2 = log2level_map(gsa1, isig, lam); end -if nargin==6, +if nargin==6 gsax = ss_anova(gsa2.y-gsa2.fit, x, 1, 0, 2, nvrs(:,2)); else gsax = ss_anova(gsa2.y-gsa2.fit, x, 1); @@ -713,7 +713,7 @@ 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, +for j=1:np gsa22.fs(:,j) = gsa2.fs(:,j)+gsax.fs(:,j); gsa22.fses(:,j) = gsax.fses(:,j); gsa22.f(:,j) = gsa2.f(:,j)+gsax.f(:,j); @@ -730,7 +730,7 @@ hfig=dyn_figure(options_.nodisplay,'name',options_mcf.amcf_title); density] = posterior_moments(y0,1,0.9); post_deciles = [-inf; post_deciles; inf]; -for jt=1:10, +for jt=1:10 indy{jt}=find( (y0>post_deciles(jt)) & (y0<=post_deciles(jt+1))); leg{jt}=[int2str(jt) '-dec']; end @@ -741,18 +741,18 @@ indmcf = indmcf(jtmp); nbr_par = length(indmcf); nrow=ceil(sqrt(nbr_par+1)); ncol=nrow; -if nrow*(nrow-1)>nbr_par, +if nrow*(nrow-1)>nbr_par ncol=nrow-1; end cmap = colormap(jet(10)); -for jx=1:nbr_par, +for jx=1:nbr_par subplot(nrow,ncol,jx) hold off - for jt=1:10, + for jt=1:10 h=cumplot(x0(indy{jt},indmcf(jx))); set(h,'color', cmap(jt,:), 'linewidth', 2) - hold all, + hold all end title(options_mcf.param_names(indmcf(jx),:),'interpreter','none') end diff --git a/matlab/gsa/redform_screen.m b/matlab/gsa/redform_screen.m index fd09d9cac..d4c007174 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 @@ -39,7 +39,7 @@ iload = options_gsa_.load_redform; nliv = options_gsa_.morris_nliv; pnames = M_.param_names(estim_params_.param_vals(:,1),:); -if nargin==0, +if nargin==0 dirname=''; end @@ -53,7 +53,7 @@ nshock = length(bayestopt_.pshape)-np; nsok = length(find(M_.lead_lag_incidence(M_.maximum_lag,:))); js=0; -for j=1:size(anamendo,1), +for j=1:size(anamendo,1) namendo=deblank(anamendo(j,:)); iendo=strmatch(namendo,M_.endo_names(oo_.dr.order_var,:),'exact'); @@ -63,10 +63,10 @@ for j=1:size(anamendo,1), namexo=deblank(anamexo(jx,:)); iexo=strmatch(namexo,M_.exo_names,'exact'); - if ~isempty(iexo), + if ~isempty(iexo) y0=teff(T(iendo,iexo+nspred,:),kn,istable); - if ~isempty(y0), - if mod(iplo,9)==0, + if ~isempty(y0) + if mod(iplo,9)==0 ifig=ifig+1; hh=dyn_figure(options_.nodisplay,'name',[namendo,' vs. shocks ',int2str(ifig)]); iplo=0; @@ -82,11 +82,11 @@ for j=1:size(anamendo,1), %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), + 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, + 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 @@ -94,7 +94,7 @@ for j=1:size(anamendo,1), end end end - if iplo<9 && iplo>0 && ifig, + 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 @@ -105,10 +105,10 @@ for j=1:size(anamendo,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), + if ~isempty(ilagendo) y0=teff(T(iendo,ilagendo,:),kn,istable); - if ~isempty(y0), - if mod(iplo,9)==0, + 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; @@ -124,25 +124,25 @@ for j=1:size(anamendo,1), %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), + 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, + 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 - if iplo<9 && iplo>0 && ifig, + 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) @@ -150,7 +150,7 @@ 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, +for ip=1:np text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none') end xlabel(' ') @@ -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 ddd4fec3a..d526b3f0e 100644 --- a/matlab/gsa/scatter_analysis.m +++ b/matlab/gsa/scatter_analysis.m @@ -37,12 +37,12 @@ amcf_title = options_scatter.amcf_title; title = options_scatter.title; fname_ = options_scatter.fname_; xparam1=[]; -if isfield(options_scatter,'xparam1'), +if isfield(options_scatter,'xparam1') xparam1=options_scatter.xparam1; -end +end OutputDirectoryName = options_scatter.OutputDirectoryName; -if ~DynareOptions.nograph, +if ~DynareOptions.nograph skipline() xx=[]; if ~isempty(xparam1) diff --git a/matlab/gsa/scatter_callback.m b/matlab/gsa/scatter_callback.m index afba86225..61345107c 100644 --- a/matlab/gsa/scatter_callback.m +++ b/matlab/gsa/scatter_callback.m @@ -34,7 +34,7 @@ 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_); diff --git a/matlab/gsa/scatter_mcf.m b/matlab/gsa/scatter_mcf.m index 3718b23ed..211b2e74b 100644 --- a/matlab/gsa/scatter_mcf.m +++ b/matlab/gsa/scatter_mcf.m @@ -2,7 +2,7 @@ function scatter_mcf(X,Y,vnames,plotsymbol, fnam, dirname, figtitle, xparam1, D % % 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 @@ -49,7 +49,7 @@ clear Z; nflag = 0; if nargin >=3 nflag = 1; -end; +end if nargin<4 || isempty(plotsymbol) if n*p<100, plotsymbol = 'o'; @@ -60,37 +60,37 @@ end if nargin<5 fnam=''; end -if nargin<6, +if nargin<6 dirname=''; nograph=1; else - nograph=0; + nograph=0; end -if nargin<7, +if nargin<7 figtitle=fnam; end -if nargin<8, +if nargin<8 xparam1=[]; end -if nargin<10, +if nargin<10 beha_name = 'BEHAVIOUR'; non_beha_name = 'NON-BEHAVIOUR'; end -if nargin==10, +if nargin==10 non_beha_name = ['NON-' beha_name]; end figtitle_tex=strrep(figtitle,'_','\_'); fig_nam_=[fnam]; -if ~nograph, +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, +if p>1 fL = linspace(bf,1-bf+ffs,p+1); else fL = bf; @@ -129,7 +129,7 @@ for i = 1:p end hold off; % axis([-0.1 1.1 -0.1 1.1]) - if i=3 nflag = 1; -end; +end if nargin<4 || isempty(plotsymbol) if n*p<100, plotsymbol = 'o'; @@ -55,17 +55,17 @@ end if nargin<5 || isempty(fnam) fnam='scatter_plot'; end -if nargin<6 || isempty(dirname), +if nargin<6 || isempty(dirname) dirname=''; nograph=1; DynareOptions.nodisplay=0; else - nograph=0; + nograph=0; end -if nargin<7 || isempty(figtitle), +if nargin<7 || isempty(figtitle) figtitle=fnam; end -if nargin<8, +if nargin<8 xparam1=[]; end @@ -79,7 +79,7 @@ set(hh,'userdata',{X,xp}) bf = 0.1; ffs = 0.05/(p-1); ffl = (1-2*bf-0.05)/p; -if p>1, +if p>1 fL = linspace(bf,1-bf+ffs,p+1); else fL = bf; @@ -135,7 +135,7 @@ for i = 1:p end hold off; % axis([-0.1 1.1 -0.1 1.1]) - if i0, + if np<52 && ilptau>0 [lpmat] = qmc_sequence(np, int64(1), 0, Nsam)'; - if np>30 || ilptau==2, % scrambled lptau - for j=1:np, + if np>30 || ilptau==2 % scrambled lptau + for j=1:np lpmat(:,j)=lpmat(randperm(Nsam),j); end end else %ilptau==0 [lpmat] = NaN(Nsam,np); - for j=1:np, + for j=1:np lpmat(:,j) = randperm(Nsam)'./(Nsam+1); %latin hypercube end @@ -188,9 +188,9 @@ if fload==0, % end % % end - if pprior, - for j=1:nshock, - if opt_gsa.morris~=1, + if pprior + for j=1:nshock + if opt_gsa.morris~=1 lpmat0(:,j) = randperm(Nsam)'./(Nsam+1); %latin hypercube end if opt_gsa.prior_range @@ -204,7 +204,7 @@ if fload==0, % xdelt(:,:,j)=prior_draw_gsa(0,[lpmat0 lpmat]+deltx); % end % end - for j=1:np, + for j=1:np lpmat(:,j)=lpmat(:,j).*(bounds.ub(j+nshock)-bounds.lb(j+nshock))+bounds.lb(j+nshock); end else @@ -254,13 +254,13 @@ if fload==0, % end % end %load([fname_,'_mode']) - if neighborhood_width>0 && isempty(options_.mode_file), + if neighborhood_width>0 && isempty(options_.mode_file) xparam1 = get_all_parameters(estim_params_,M_); else eval(['load ' options_.mode_file '.mat;']); end - if neighborhood_width>0, - for j=1:nshock, + if neighborhood_width>0 + for j=1:nshock if opt_gsa.morris ~= 1 lpmat0(:,j) = randperm(Nsam)'./(Nsam+1); %latin hypercube end @@ -268,10 +268,10 @@ if fload==0, lb=max([bounds.lb(j) xparam1(j)*(1-neighborhood_width)]); lpmat0(:,j)=lpmat0(:,j).*(ub-lb)+lb; end - for j=1:np, + for j=1:np ub=xparam1(j+nshock)*(1+sign(xparam1(j+nshock))*neighborhood_width); lb=xparam1(j+nshock)*(1-sign(xparam1(j+nshock))*neighborhood_width); - if bounds.ub(j+nshock)>=xparam1(j) && bounds.lb(j)<=xparam1(j+nshock), + if bounds.ub(j+nshock)>=xparam1(j) && bounds.lb(j)<=xparam1(j+nshock) ub=min([bounds.ub(j+nshock) ub]); lb=max([bounds.lb(j+nshock) lb]); else @@ -283,7 +283,7 @@ if fload==0, d = chol(inv(hh)); lp=randn(Nsam*2,nshock+np)*d+kron(ones(Nsam*2,1),xparam1'); lnprior=zeros(1,Nsam*2); - for j=1:Nsam*2, + for j=1:Nsam*2 lnprior(j) = any(lp(j,:)'<=bounds.lb | lp(j,:)'>=bounds.ub); end ireal=[1:2*Nsam]; @@ -305,7 +305,7 @@ if fload==0, inorestriction=zeros(1,Nsam); irestriction=zeros(1,Nsam); infox=zeros(Nsam,1); - for j=1:Nsam, + for j=1:Nsam M_ = set_all_parameters([lpmat0(j,:) lpmat(j,:)]',estim_params_,M_); %try stoch_simul([]); try @@ -315,14 +315,14 @@ if fload==0, [Tt,Rr,SteadyState,info,M_,options_,oo_] = dynare_resolve(M_,options_,oo_,'restrict'); end infox(j,1)=info(1); - if infox(j,1)==0 && ~exist('T','var'), + if infox(j,1)==0 && ~exist('T','var') dr_=oo_.dr; - if prepSA, + if prepSA try T=zeros(size(dr_.ghx,1),size(dr_.ghx,2)+size(dr_.ghu,2),Nsam); catch ME = lasterror(); - if strcmp('MATLAB:nomem',ME.identifier), + if strcmp('MATLAB:nomem',ME.identifier) prepSA=0; disp('The model is too large for storing state space matrices ...') disp('for mapping reduced form or for identification') @@ -334,26 +334,26 @@ if fload==0, end egg=zeros(length(dr_.eigval),Nsam); end - if infox(j,1), + if infox(j,1) % disp('no solution'), - if isfield(oo_.dr,'ghx'), + if isfield(oo_.dr,'ghx') oo_.dr=rmfield(oo_.dr,'ghx'); end - if (infox(j,1)<3 || infox(j,1)>5) && isfield(oo_.dr,'eigval'), + if (infox(j,1)<3 || infox(j,1)>5) && isfield(oo_.dr,'eigval') oo_.dr=rmfield(oo_.dr,'eigval'); end end catch ME - if isfield(oo_.dr,'eigval'), + if isfield(oo_.dr,'eigval') oo_.dr=rmfield(oo_.dr,'eigval'); end - if isfield(oo_.dr,'ghx'), + if isfield(oo_.dr,'ghx') oo_.dr=rmfield(oo_.dr,'ghx'); end - disp('No solution could be found'), + disp('No solution could be found') end dr_ = oo_.dr; - if isfield(dr_,'ghx'), + if isfield(dr_,'ghx') egg(:,j) = sort(dr_.eigval); if prepSA jstab=jstab+1; @@ -363,14 +363,14 @@ if fload==0, % bayestopt_.restrict_columns, ... % bayestopt_.restrict_aux); end - if ~exist('nspred','var'), + if ~exist('nspred','var') nspred = dr_.nspred; %size(dr_.ghx,2); nboth = dr_.nboth; nfwrd = dr_.nfwrd; end info=endogenous_prior_restrictions(Tt,Rr,M_,options_,oo_); infox(j,1)=info(1); - if info(1), + if info(1) inorestriction(j)=j; else iunstable(j)=0; @@ -384,13 +384,13 @@ if fload==0, if any(isnan(egg(1:nspred,j))) iwrong(j)=j; else - if (nboth || nfwrd) && abs(egg(nspred+1,j))<=options_.qz_criterium, + if (nboth || nfwrd) && abs(egg(nspred+1,j))<=options_.qz_criterium iindeterm(j)=j; end end end else - if exist('egg','var'), + if exist('egg','var') egg(:,j)=ones(size(egg,1),1).*NaN; end iwrong(j)=j; @@ -402,7 +402,7 @@ if fload==0, dyn_waitbar(j/Nsam,h,['MC iteration ',int2str(j),'/',int2str(Nsam)]) end dyn_waitbar_close(h); - if prepSA && jstab, + if prepSA && jstab T=T(:,:,1:jstab); else T=[]; @@ -454,7 +454,7 @@ if fload==0, bkpprior.p2=bayestopt_.p2; bkpprior.p3=bayestopt_.p3; bkpprior.p4=bayestopt_.p4; - if pprior, + if pprior if ~prepSA save([OutputDirectoryName filesep fname_ '_prior.mat'], ... 'bkpprior','lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun', ... @@ -477,19 +477,19 @@ if fload==0, end end else - if pprior, + if pprior filetoload=[OutputDirectoryName filesep fname_ '_prior.mat']; else filetoload=[OutputDirectoryName filesep fname_ '_mc.mat']; end load(filetoload,'lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun','egg','yys','nspred','nboth','nfwrd','infox') Nsam = size(lpmat,1); - if pprior==0 && ~isempty(options_.mode_file), + if pprior==0 && ~isempty(options_.mode_file) eval(['load ' options_.mode_file '.mat;']); end - if prepSA && isempty(strmatch('T',who('-file', filetoload),'exact')), + if prepSA && isempty(strmatch('T',who('-file', filetoload),'exact')) h = dyn_waitbar(0,'Please wait...'); options_.periods=0; options_.nomoments=1; @@ -499,7 +499,7 @@ else %T=zeros(size(dr_.ghx,1),size(dr_.ghx,2)+size(dr_.ghu,2),length(istable)); ntrans=length(istable); yys=NaN(length(ys_),ntrans); - for j=1:ntrans, + for j=1:ntrans M_.params(estim_params_.param_vals(:,1)) = lpmat(istable(j),:)'; %stoch_simul([]); [Tt,Rr,SteadyState,info,M_,options_,oo_] = dynare_resolve(M_,options_,oo_,'restrict'); @@ -548,51 +548,51 @@ delete([OutputDirectoryName,filesep,fname_,'_',aindname,'.*']); delete([OutputDirectoryName,filesep,fname_,'_',aunstname,'.*']); delete([OutputDirectoryName,filesep,fname_,'_',awrongname,'.*']); -if length(iunstable)>0 || length(iwrong)>0, +if length(iunstable)>0 || length(iwrong)>0 fprintf(['%4.1f%% of the prior support gives unique saddle-path solution.\n'],length(istable)/Nsam*100) fprintf(['%4.1f%% of the prior support gives explosive dynamics.\n'],(length(ixun) )/Nsam*100) - if ~isempty(iindeterm), + if ~isempty(iindeterm) fprintf(['%4.1f%% of the prior support gives indeterminacy.\n'],length(iindeterm)/Nsam*100) end inorestriction = istable(find(~ismember(istable,irestriction))); % violation of prior restrictions - if ~isempty(iwrong) || ~isempty(inorestriction), + if ~isempty(iwrong) || ~isempty(inorestriction) skipline() - if any(infox==49), + if any(infox==49) fprintf(['%4.1f%% of the prior support violates prior restrictions.\n'],(length(inorestriction) )/Nsam*100) end - if ~isempty(iwrong), + if ~isempty(iwrong) skipline() disp(['For ',num2str(length(iwrong)/Nsam*100,'%4.1f'),'% of the prior support dynare could not find a solution.']) skipline() end - if any(infox==1), + if any(infox==1) disp([' For ',num2str(length(find(infox==1))/Nsam*100,'%4.1f'),'% The model doesn''t determine the current variables uniquely.']) end - if any(infox==2), + if any(infox==2) disp([' For ',num2str(length(find(infox==2))/Nsam*100,'%4.1f'),'% MJDGGES returned an error code.']) end - if any(infox==6), + if any(infox==6) disp([' For ',num2str(length(find(infox==6))/Nsam*100,'%4.1f'),'% The jacobian evaluated at the deterministic steady state is complex.']) end - if any(infox==19), + if any(infox==19) disp([' For ',num2str(length(find(infox==19))/Nsam*100,'%4.1f'),'% The steadystate routine thrown an exception (inconsistent deep parameters).']) end - if any(infox==20), + if any(infox==20) disp([' For ',num2str(length(find(infox==20))/Nsam*100,'%4.1f'),'% Cannot find the steady state.']) end - if any(infox==21), + if any(infox==21) disp([' For ',num2str(length(find(infox==21))/Nsam*100,'%4.1f'),'% The steady state is complex.']) end - if any(infox==22), + if any(infox==22) disp([' For ',num2str(length(find(infox==22))/Nsam*100,'%4.1f'),'% The steady has NaNs.']) end - if any(infox==23), + if any(infox==23) disp([' For ',num2str(length(find(infox==23))/Nsam*100,'%4.1f'),'% M_.params has been updated in the steadystate routine and has complex valued scalars.']) end - if any(infox==24), + if any(infox==24) disp([' For ',num2str(length(find(infox==24))/Nsam*100,'%4.1f'),'% M_.params has been updated in the steadystate routine and has some NaNs.']) end - if any(infox==30), + if any(infox==30) disp([' For ',num2str(length(find(infox==30))/Nsam*100,'%4.1f'),'% Ergodic variance can''t be computed.']) end @@ -602,7 +602,7 @@ if length(iunstable)>0 || length(iwrong)>0, itot = [1:Nsam]; isolve = itot(find(~ismember(itot,iwrong))); % dynare could find a solution % Blanchard Kahn - if neighborhood_width, + if neighborhood_width options_mcf.xparam1 = xparam1(nshock+1:end); end itmp = itot(find(~ismember(itot,istable))); @@ -613,7 +613,7 @@ if length(iunstable)>0 || length(iwrong)>0, options_mcf.title = 'unique solution'; mcf_analysis(lpmat, istable, itmp, options_mcf, options_); - if ~isempty(iindeterm), + if ~isempty(iindeterm) itmp = isolve(find(~ismember(isolve,iindeterm))); options_mcf.amcf_name = aindname; options_mcf.amcf_title = aindtitle; @@ -622,8 +622,8 @@ if length(iunstable)>0 || length(iwrong)>0, options_mcf.title = 'indeterminacy'; mcf_analysis(lpmat, itmp, iindeterm, options_mcf, options_); end - - if ~isempty(ixun), + + if ~isempty(ixun) itmp = isolve(find(~ismember(isolve,ixun))); options_mcf.amcf_name = aunstname; options_mcf.amcf_title = aunsttitle; @@ -632,10 +632,10 @@ 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), + if ~isempty(iwrong) itmp = itot(find(~ismember(itot,iwrong))); options_mcf.amcf_name = awrongname; options_mcf.amcf_title = awrongtitle; @@ -644,9 +644,9 @@ 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, + + if ~isempty(irestriction) + if neighborhood_width options_mcf.xparam1 = xparam1; end np=size(bayestopt_.name,1); @@ -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([]); @@ -699,12 +699,8 @@ xparam1=x0; save prior_ok.mat xparam1; options_.periods=opt.periods; -if isfield(opt,'nomoments'), +if isfield(opt,'nomoments') options_.nomoments=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 6a23fe63d..092b50daa 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 @@ -40,11 +40,11 @@ function [proba, dproba] = stab_map_1(lpmat, ibehaviour, inonbehaviour, aname, i global estim_params_ bayestopt_ M_ options_ -if nargin<5, +if nargin<5 iplot=1; end fname_ = M_.fname; -if nargin<7, +if nargin<7 dirname=''; end if nargin<9, @@ -59,20 +59,20 @@ nshock = nshock + estim_params_.ncn; npar=size(lpmat,2); ishock= npar>estim_params_.np; -if nargin<6, +if nargin<6 ipar=[]; end -if nargin<8 || isempty(pcrit), +if nargin<8 || isempty(pcrit) pcrit=1; end -% Smirnov test for Blanchard; -for j=1:npar, +% Smirnov test for Blanchard; +for j=1:npar [H,P,KSSTAT] = smirnov(lpmat(ibehaviour,j),lpmat(inonbehaviour,j)); proba(j)=P; dproba(j)=KSSTAT; end -if isempty(ipar), +if isempty(ipar) % ipar=find(dproba>dcrit); ipar=find(proba12, + if nparplot>12 dyn_saveas(hh,[dirname,filesep,fname_,'_',aname,'_SA_',int2str(i)],options_.nodisplay,options_.graph_format); if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) fidTeX = fopen([dirname,filesep,fname_,'_',aname,'_SA_',int2str(i) '.tex'],'w'); diff --git a/matlab/gsa/stab_map_2.m b/matlab/gsa/stab_map_2.m index 80d140e15..f4b958355 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 @@ -29,17 +29,17 @@ npar=size(x,2); nsam=size(x,1); ishock= npar>estim_params_.np; nograph = options_.nograph; -if nargin<4, +if nargin<4 fnam=''; end -if nargin<5, +if nargin<5 dirname=''; nograph=1; end -if nargin<6, +if nargin<6 xparam1=[]; end -if nargin<7, +if nargin<7 figtitle=fnam; end @@ -61,7 +61,7 @@ ifig=0; j2=0; if ishock==0 npar=estim_params_.np; - if ~isempty(xparam1), + if ~isempty(xparam1) xparam1=xparam1(nshock+1:end); end else @@ -73,14 +73,14 @@ title_string_tex=['Correlation analysis for ',strrep(fnam,'_','\\_')]; indcorr = []; entry_iter=1; -for j=1:npar, +for j=1:npar i2=find(abs(c00(:,j))>alpha2); - if length(i2)>0, - for jx=1:length(i2), - if pvalue(j,i2(jx))0 + for jx=1:length(i2) + if pvalue(j,i2(jx))0 && (mod(j2,12)~=0), + if ~nograph && (j==(npar)) && j2>0 && (mod(j2,12)~=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'); @@ -177,10 +177,10 @@ for j=1:npar, fprintf(fidTeX,'%% End Of TeX file. \n'); fclose(fidTeX); end - end + end end -if j2==0, +if j2==0 disp(['No correlation term with pvalue <', num2str(pvalue_crit),' and |corr. coef.| >',num2str(alpha2),' found for ',fnam]) else headers=strvcat('Parameters','corrcoef'); diff --git a/matlab/gsa/stand_.m b/matlab/gsa/stand_.m index f1547c3c6..0a53f1a3b 100644 --- a/matlab/gsa/stand_.m +++ b/matlab/gsa/stand_.m @@ -11,10 +11,10 @@ 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% +% Copyright (C) 2012-2017 Dynare Team% % This file is part of Dynare. % % Dynare is free software: you can redistribute it and/or modify @@ -30,11 +30,11 @@ function [y, meany, stdy] = stand_(x) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see . -if nargin==0, - return; +if nargin==0 + return end -for j=1:size(x,2); +for j=1:size(x,2) 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); diff --git a/matlab/gsa/tcrit.m b/matlab/gsa/tcrit.m index 560d90175..d65b97a39 100644 --- a/matlab/gsa/tcrit.m +++ b/matlab/gsa/tcrit.m @@ -1,15 +1,15 @@ 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 +% Copyright (C) 2011-2017 Dynare Team % % This file is part of Dynare. % @@ -27,16 +27,16 @@ function t_crit = tcrit(n,pval0) % along with Dynare. If not, see . -if nargin==1 || isempty(pval0), +if nargin==1 || isempty(pval0) pval0=0.05; end -if pval0==1, +if pval0==1 t_crit=0; - return, + return end -if pval0==0, +if pval0==0 t_crit=inf; - return, + return end pval = [ 0.10 0.05 0.025 0.01 0.005 0.001]; pval0=max(pval0,min(pval)); @@ -146,7 +146,7 @@ t_crit=[ inf 1.282 1.645 1.960 2.326 2.576 3.090 ]; -if n<=100, +if n<=100 t_crit=t_crit(n,ncol); else t_crit=t_crit(end,ncol); diff --git a/matlab/gsa/teff.m b/matlab/gsa/teff.m index 622abca94..8ebea8d1c 100644 --- a/matlab/gsa/teff.m +++ b/matlab/gsa/teff.m @@ -3,13 +3,13 @@ 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. % Copyright (C) 2012 European Commission -% Copyright (C) 2012 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -27,8 +27,8 @@ function [yt, j0, ir, ic]=teff(T,Nsam,istable) % along with Dynare. If not, see . ndim = (length(size(T))); -if ndim==3, - if nargin==1, +if ndim==3 + if nargin==1 Nsam=size(T,3); istable = [1:Nsam]'; end @@ -38,7 +38,7 @@ if ndim==3, j0 = length(ir); yt=zeros(Nsam, j0); - for j=1:j0, + for j=1:j0 y0=squeeze(T(ir(j),ic(j),:)); %y1=ones(size(lpmat,1),1)*NaN; y1=ones(Nsam,1)*NaN; @@ -54,6 +54,6 @@ else 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 5616b4045..9b886e851 100644 --- a/matlab/gsa/th_moments.m +++ b/matlab/gsa/th_moments.m @@ -1,7 +1,7 @@ function [vdec, corr, autocorr, z, zz] = th_moments(dr,var_list) % [vdec, corr, autocorr, z, zz] = th_moments(dr,var_list) -% Copyright (C) 2012-2016 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -56,13 +56,13 @@ var = gamma_y{1}; z; %'VARIANCE DECOMPOSITION (in percent)'; -if M_.exo_nbr>1, +if M_.exo_nbr>1 vdec = 100*gamma_y{options_.ar+2}(i1,:); else vdec = 100*ones(size(gamma_y{1}(i1,1))); end %'MATRIX OF CORRELATIONS'; -if options_.opt_gsa.useautocorr, +if options_.opt_gsa.useautocorr corr = gamma_y{1}(i1,i1)./(sd(i1)*sd(i1)'); corr = corr-diag(diag(corr))+diag(diag(gamma_y{1}(i1,i1))); else @@ -71,7 +71,7 @@ end if options_.ar > 0 %'COEFFICIENTS OF AUTOCORRELATION'; for i=1:options_.ar - if options_.opt_gsa.useautocorr, + if options_.opt_gsa.useautocorr autocorr{i} = gamma_y{i+1}(i1,i1); else autocorr{i} = gamma_y{i+1}(i1,i1).*(sd(i1)*sd(i1)'); @@ -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 a47c91262..eb39f1647 100644 --- a/matlab/gsa/trank.m +++ b/matlab/gsa/trank.m @@ -1,4 +1,4 @@ -function yr = trank(y); +function yr = trank(y) % yr = trank(y); % yr is the rank transformation of y % @@ -10,7 +10,7 @@ function yr = trank(y); % M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006. % Copyright (C) 2012 European Commission -% Copyright (C) 2012 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -28,7 +28,7 @@ function yr = trank(y); % along with Dynare. If not, see . [nr, nc] = size(y); -for j=1:nc, +for j=1:nc [dum, is]=sort(y(:,j)); yr(is,j)=[1:nr]'./nr; end diff --git a/matlab/hessian.m b/matlab/hessian.m index cf2f549bd..844251f7c 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 . -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); @@ -95,7 +95,7 @@ for i=1:n 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 d63534e79..1d7a75dbe 100644 --- a/matlab/hessian_sparse.m +++ b/matlab/hessian_sparse.m @@ -16,9 +16,9 @@ function hessian_mat = hessian_sparse(func,x,gstep,varargin) % % SPECIAL REQUIREMENTS % none -% +% -% Copyright (C) 2001-2012 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . -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 +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 + % 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 e2c144554..580c9be92 100644 --- a/matlab/histvalf.m +++ b/matlab/histvalf.m @@ -1,6 +1,6 @@ function histvalf(fname) -% Copyright (C) 2014 Dynare Team +% Copyright (C) 2014-2017 Dynare Team % % This file is part of Dynare. % @@ -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 e7de1f16a..e849fceca 100644 --- a/matlab/homotopy1.m +++ b/matlab/homotopy1.m @@ -30,7 +30,7 @@ function [M,oo,info,ip,ix,ixd] = homotopy1(values, step_nbr, M, options, oo) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2008-2012 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -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 8e1318a86..7ec87258d 100644 --- a/matlab/homotopy2.m +++ b/matlab/homotopy2.m @@ -25,7 +25,7 @@ function homotopy2(values, step_nbr) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2008-2012 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -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 a506bb6b6..b4b46d6f2 100644 --- a/matlab/homotopy3.m +++ b/matlab/homotopy3.m @@ -33,7 +33,7 @@ function [M,oo,info,ip,ix,ixd]=homotopy3(values, step_nbr, M, options, oo) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2008-2012 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -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 ea68deaea..34725ade4 100644 --- a/matlab/ident_bruteforce.m +++ b/matlab/ident_bruteforce.m @@ -12,12 +12,12 @@ 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 -% Copyright (C) 2009-2016 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -52,7 +52,7 @@ tittxt1=strrep(tittxt1, '.', ''); cosnJ=zeros(k,n); pars{k,n}=[]; -for ll = 1:n, +for ll = 1:n h = dyn_waitbar(0,['Brute force collinearity for ' int2str(ll) ' parameters.']); for ii = 1:k tmp = find([1:k]~=ii); @@ -63,8 +63,8 @@ for ll = 1:n, [cosnJ2(jj,1), b(:,jj)] = cosn([J(:,ii),J(:,tmp2(jj,:))]); end cosnJ(ii,ll) = max(cosnJ2(:,1)); - if cosnJ(ii,ll)>1.e-8, - if ll>1 && ((cosnJ(ii,ll)-cosnJ(ii,ll-1))<1.e-8), + if cosnJ(ii,ll)>1.e-8 + if ll>1 && ((cosnJ(ii,ll)-cosnJ(ii,ll-1))<1.e-8) pars{ii,ll} = [pars{ii,ll-1} NaN]; cosnJ(ii,ll) = cosnJ(ii,ll-1); else @@ -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 ']); @@ -101,10 +101,10 @@ for ll = 1:n, fprintf(fidTeX,'\\midrule \\endhead \n'); fprintf(fidTeX,'\\bottomrule \\multicolumn{3}{r}{(Continued on next page)}\\endfoot \n'); fprintf(fidTeX,'\\bottomrule\\endlastfoot \n'); - for i=1:k, + for i=1:k plist=''; - for ii=1:ll, - if ~isnan(pars{i,ll}(ii)), + for ii=1:ll + if ~isnan(pars{i,ll}(ii)) plist = [plist ' $' pnames_TeX(pars{i,ll}(ii),:) '\;\; $ ']; else plist = [plist ' ---- ']; diff --git a/matlab/identification_analysis.m b/matlab/identification_analysis.m index f83bcf1a6..c59e08ec6 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,11 +24,11 @@ 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 -% Copyright (C) 2008-2016 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . global oo_ M_ options_ bayestopt_ estim_params_ @@ -51,7 +51,7 @@ persistent indH indJJ indLRE nparam=length(params); np=length(indx); offset=nparam-np; -if ~isempty(estim_params_), +if ~isempty(estim_params_) M_ = set_all_parameters(params,estim_params_,M_); end @@ -73,7 +73,7 @@ ide_lre = struct(); derivatives_info = struct(); [A,B,ys,info,M_,options_,oo_] = dynare_resolve(M_,options_,oo_); -if info(1)==0, +if info(1)==0 oo0=oo_; tau=[oo_.dr.ys(oo_.dr.order_var); vec(A); dyn_vech(B*M_.Sigma_e*B')]; yy0=oo_.dr.ys(I); @@ -86,16 +86,16 @@ if info(1)==0, derivatives_info.DT=dA; derivatives_info.DOm=dOm; derivatives_info.DYss=dYss; - if init, + if init indJJ = (find(max(abs(JJ'),[],1)>1.e-8)); if isempty(indJJ) && any(any(isnan(JJ))) error('There are NaN in the JJ matrix. Please check whether your model has units roots and you forgot to set diffuse_filter=1.' ) elseif any(any(isnan(gam))) error('There are NaN''s in the theoretical moments: make sure that for non-stationary models stationary transformations of non-stationary observables are used for checking identification. [TIP: use first differences].') end - while length(indJJ)1.e-8)); end - if length(indJJ)1.e-8)); @@ -117,50 +117,50 @@ 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); - if init, %~isempty(indok), + if init normaliz = NaN(1,nparam); - if prior_exist, - if ~isempty(estim_params_.var_exo), + if prior_exist + if ~isempty(estim_params_.var_exo) normaliz1 = estim_params_.var_exo(:,7)'; % normalize with prior standard deviation else normaliz1=[]; end - if ~isempty(estim_params_.corrx), + if ~isempty(estim_params_.corrx) normaliz1 = [normaliz1 estim_params_.corrx(:,8)']; % normalize with prior standard deviation end - if ~isempty(estim_params_.param_vals), + if ~isempty(estim_params_.param_vals) normaliz1 = [normaliz1 estim_params_.param_vals(:,7)']; % normalize with prior standard deviation end % normaliz = max([normaliz; normaliz1]); normaliz1(isinf(normaliz1)) = 1; - + else normaliz1 = NaN(1,nparam); end - try, + try options_.irf = 0; options_.noprint = 1; options_.order = 1; options_.SpectralDensity.trigger = 0; options_.periods = periods+100; - if options_.kalman_algo > 2, + if options_.kalman_algo > 2 options_.kalman_algo = 1; end 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,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, + if min(eig(AHess))<-1.e-10 error('identification_analysis: Analytic Hessian is not positive semi-definite!') end % chol(AHess); @@ -168,7 +168,7 @@ if info(1)==0, deltaM = sqrt(diag(AHess)); iflag=any((deltaM.*deltaM)==0); tildaM = AHess./((deltaM)*(deltaM')); - if iflag || rank(AHess)>rank(tildaM), + if iflag || rank(AHess)>rank(tildaM) [ide_hess.cond, ide_hess.ind0, ide_hess.indno, ide_hess.ino, ide_hess.Mco, ide_hess.Pco] = identification_checks(AHess, 1); else [ide_hess.cond, ide_hess.ind0, ide_hess.indno, ide_hess.ino, ide_hess.Mco, ide_hess.Pco] = identification_checks(tildaM, 1); @@ -187,7 +187,7 @@ if info(1)==0, rhoM=sqrt(1./diag(inv(tildaM(indok,indok)))); % deltaM = deltaM.*abs(params'); flag_score=1; - catch, + catch % replic = max([replic, nparam*(nparam+1)/2*10]); replic = max([replic, length(indJJ)*3]); cmm = simulated_moment_uncertainty(indJJ, periods, replic,options_,M_,oo_); @@ -197,7 +197,7 @@ if info(1)==0, 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); @@ -225,7 +225,7 @@ if info(1)==0, deltaM = sqrt(diag(MIM)); iflag=any((deltaM.*deltaM)==0); tildaM = MIM./((deltaM)*(deltaM')); - if iflag || rank(MIM)>rank(tildaM), + if iflag || rank(MIM)>rank(tildaM) [ide_hess.cond, ide_hess.ind0, ide_hess.indno, ide_hess.ino, ide_hess.Mco, ide_hess.Pco] = identification_checks(MIM, 1); else [ide_hess.cond, ide_hess.ind0, ide_hess.indno, ide_hess.ino, ide_hess.Mco, ide_hess.Pco] = identification_checks(tildaM, 1); @@ -239,7 +239,7 @@ if info(1)==0, % 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), + if ~isempty(indok) rhoM(indok)=sqrt(1./diag(inv(tildaM(indok,indok)))); normaliz(indok) = (sqrt(diag(inv(tildaM(indok,indok))))./deltaM(indok))'; %sqrt(diag(inv(MIM(indok,indok))))'; end @@ -253,7 +253,7 @@ if info(1)==0, deltaM = deltaM.*abs(params'); deltaM(params==0)=deltaM_prior(params==0); quant = siJ./repmat(sqrt(diag(cmm)),1,nparam); - if size(quant,1)==1, + if size(quant,1)==1 siJnorm = abs(quant).*normaliz1; else siJnorm = vnorm(quant).*normaliz1; @@ -268,9 +268,9 @@ if info(1)==0, iy = find(diag_chh); indH=indH(iy); siH=siH(iy,:); - if ~isempty(iy), + if ~isempty(iy) quant = siH./repmat(sqrt(diag_chh(iy)),1,nparam); - if size(quant,1)==1, + if size(quant,1)==1 siHnorm = abs(quant).*normaliz1; else siHnorm = vnorm(quant).*normaliz1; @@ -288,9 +288,9 @@ if info(1)==0, iy = find(diag_clre); indLRE=indLRE(iy); siLRE=siLRE(iy,:); - if ~isempty(iy), + if ~isempty(iy) quant = siLRE./repmat(sqrt(diag_clre(iy)),1,np); - if size(quant,1)==1, + if size(quant,1)==1 siLREnorm = abs(quant).*normaliz1(offset+1:end); else siLREnorm = vnorm(quant).*normaliz1(offset+1:end); @@ -299,16 +299,16 @@ 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; - end, - if normalize_jacobians, + 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)')'; normH = normH(:,ones(nparam,1)); normJ = max(abs(siJ)')'; @@ -354,9 +354,8 @@ if info(1)==0, ide_moments.S = S; ide_moments.V = V; end - indok = find(max(ide_moments.indno,[],1)==0); - if advanced, + if advanced [ide_moments.pars, ide_moments.cosnJ] = ident_bruteforce(JJ(indJJ,:)./normJ,max_dim_cova_group,options_.TeX,name_tex,tittxt); end -end +end diff --git a/matlab/identification_checks.m b/matlab/identification_checks.m index 735682ec7..e52fa960d 100644 --- a/matlab/identification_checks.m +++ b/matlab/identification_checks.m @@ -7,21 +7,21 @@ 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 -% Copyright (C) 2008-2011 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -45,23 +45,23 @@ function [condJ, ind0, indnoJ, ixnoJ, McoJ, PcoJ, jweak, jweak_pair] = identific npar = size(JJ,2); indnoJ = zeros(1,npar); -if size(JJ,1)>1, +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); rankJ = rank(JJ); rankJJ = rankJ; icheck=0; -if npar>0 && (rankJ0 && (rankJ 1.e-3))==1, + for j=1:length(ee0) + if length(find(abs(ee1(:,ee0(j))) > 1.e-3))==1 icheck=1; ind11 = ind11.*(abs(ee1(:,ee0(j))) <= 1.e-3); % take non-zero columns end @@ -69,26 +69,26 @@ if npar>0 && (rankJ0 && (rankJ 1.e-3)'; end -else %rank(J)==length(theta) => - % disp('All parameters are identified at theta by the moments included in J') end % here there is no exact linear dependence, but there are several @@ -134,19 +132,19 @@ jweak_pair=zeros(npar,npar); if hess_flag==0, PcoJ = NaN(npar,npar); - for ii = 1:size(JJ1,2); + for ii = 1:size(JJ1,2) PcoJ(ind1(ii),ind1(ii)) = 1; - for jj = ii+1:size(JJ1,2); + 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 - for j=1:npar, - if McoJ(j)>(1-1.e-10), + 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), + for jx=1:length(jpair) jweak_pair(j, jpair(jx)+j)=1; jweak_pair(jpair(jx)+j, j)=1; end @@ -155,4 +153,3 @@ if hess_flag==0, end jweak_pair=dyn_vech(jweak_pair)'; - diff --git a/matlab/imcforecast.m b/matlab/imcforecast.m index 9f7bdc480..66841319a 100644 --- a/matlab/imcforecast.m +++ b/matlab/imcforecast.m @@ -2,31 +2,31 @@ 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-2016 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -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); diff --git a/matlab/indnv.m b/matlab/indnv.m index 1df707786..0cc88ab5b 100644 --- a/matlab/indnv.m +++ b/matlab/indnv.m @@ -13,7 +13,7 @@ function a=indnv(x,y) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2001-2009 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -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 24bd3ea65..3e22f6998 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 @@ -9,7 +9,7 @@ function plan = init_plan(date) % plan [structure] Returns a structure containing a new forecast scenario % % -% Copyright (C) 2013-2014 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % @@ -36,17 +36,16 @@ plan.exo_names = deblank(mat2cell(M_.exo_names(1:M_.exo_nbr,:),ones(1,M_.exo_nbr plan.constrained_vars_ = []; plan.constrained_paths_ = []; plan.constrained_date_ = []; -plan.constrained_int_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_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 = []; - +plan.options_cond_fcst_.controlled_varexo = []; \ No newline at end of file diff --git a/matlab/initial_condition_decomposition.m b/matlab/initial_condition_decomposition.m index f99bcd622..cee5335a8 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 @@ -50,7 +50,8 @@ if size(varlist,1) == 0 varlist = M_.endo_names(1:M_.orig_endo_nbr,:); end -[i_var,nvar] = varlist_indices(varlist,M_.endo_names); +[i_var,nvar,index_uniques] = varlist_indices(varlist,M_.endo_names); +varlist=varlist(index_uniques,:); % number of variables endo_nbr = M_.endo_nbr; @@ -60,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 ' ... @@ -92,7 +93,7 @@ if ~isfield(oo_,'initval_decomposition') z = zeros(endo_nbr,endo_nbr+2,gend); z(:,end,:) = Smoothed_Variables_deviation_from_mean; - for i=1:endo_nbr, + for i=1:endo_nbr z(i,i,1) = Smoothed_Variables_deviation_from_mean(i,1); end @@ -104,7 +105,7 @@ if ~isfield(oo_,'initval_decomposition') 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); diff --git a/matlab/initial_estimation_checks.m b/matlab/initial_estimation_checks.m index 7155552a6..7dfc4d9a2 100644 --- a/matlab/initial_estimation_checks.m +++ b/matlab/initial_estimation_checks.m @@ -20,7 +20,7 @@ function DynareResults = initial_estimation_checks(objective_function,xparam1,Dy % SPECIAL REQUIREMENTS % none -% Copyright (C) 2003-2016 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -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 @@ -75,29 +75,29 @@ if isfield(EstimatedParameters,'param_vals') && ~isempty(EstimatedParameters.par 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 diff --git a/matlab/initialize_from_mode.m b/matlab/initialize_from_mode.m index d7c11a9d0..4521ec255 100644 --- a/matlab/initialize_from_mode.m +++ b/matlab/initialize_from_mode.m @@ -1,20 +1,20 @@ 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 % % SPECIAL REQUIREMENTS % none -% Copyright (C) 2003-2011 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -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 28292ed61..afffede43 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 @@ -13,7 +13,7 @@ function initvalf(fname_) % All variables local to this function have an underscore appended to % their name, to minimize clashes with model variables loaded by this function. -% Copyright (C) 2003-2012 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -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/internals.m b/matlab/internals.m index 4fc079ec2..a7b96a81f 100644 --- a/matlab/internals.m +++ b/matlab/internals.m @@ -56,7 +56,7 @@ function internals(flag, varargin) %! @end deftypefn %@eod: -% Copyright (C) 2011 Dynare Team +% Copyright (C) 2011-2014 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/interpret_resol_info.m b/matlab/interpret_resol_info.m index a80a23f5d..45b3993ff 100644 --- a/matlab/interpret_resol_info.m +++ b/matlab/interpret_resol_info.m @@ -3,13 +3,13 @@ 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 +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/irf.m b/matlab/irf.m index f4be40503..c80b65b1b 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,11 +13,11 @@ function y = irf(dr, e1, long, drop, replic, iorder) % % OUTPUTS % y: impulse response matrix -% +% % SPECIAL REQUIREMENTS % none -% Copyright (C) 2003-2010 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -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/isoctave.m b/matlab/isoctave.m index 15c6fb38d..22941ce9e 100644 --- a/matlab/isoctave.m +++ b/matlab/isoctave.m @@ -1,6 +1,6 @@ function A = isoctave() -% Copyright (C) 2013 Dynare Team +% Copyright (C) 2013-2016 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/isolder.m b/matlab/isolder.m index 127393854..d364c5c62 100644 --- a/matlab/isolder.m +++ b/matlab/isolder.m @@ -2,14 +2,14 @@ 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 +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/k_order_pert.m b/matlab/k_order_pert.m index 4c6917f5f..de982c8a1 100644 --- a/matlab/k_order_pert.m +++ b/matlab/k_order_pert.m @@ -1,7 +1,7 @@ function [dr,info] = k_order_pert(dr,M,options) % Compute decision rules using the k-order DLL from Dynare++ -% Copyright (C) 2009-2013 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -27,8 +27,8 @@ 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 ' ... @@ -40,32 +40,32 @@ switch(order) [err, g_1] = k_order_perturbation(dr,M,options); if err info(1)=9; - return; + 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; + 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; + return end else [err, g_0, g_1, g_2, g_3] = k_order_perturbation(dr, ... M,options); if err info(1)=9; - return; + 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); @@ -202,8 +202,4 @@ for i=1:n1 m = m + 1; end end -end - - - - +end \ No newline at end of file diff --git a/matlab/kalman/build_selection_matrix.m b/matlab/kalman/build_selection_matrix.m index f78662ddb..e9899591c 100644 --- a/matlab/kalman/build_selection_matrix.m +++ b/matlab/kalman/build_selection_matrix.m @@ -2,7 +2,7 @@ function Z = build_selection_matrix(mf,m,p) % Builds the selection matrix of the measurement equation from the vector % of indices mf. -% Copyright (C) 2004-2009 Dynare Team +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . +% along with Dynare. If not, see . 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 eab34c3ba..0fc417220 100644 --- a/matlab/kalman/likelihood/computeDLIK.m +++ b/matlab/kalman/likelihood/computeDLIK.m @@ -1,6 +1,6 @@ function [Da,DP,DLIK,D2a,D2P,Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,P,iF,Da,DYss,DT,DOm,DP,DH,notsteady,D2a,D2Yss,D2T,D2Om,D2P) -% Copyright (C) 2012 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -24,20 +24,20 @@ 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, + 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, + if nargout>4 [D2K,D2F,D2P] = computeD2Kalman(T,DT,D2T,D2Om,P,DP,D2P,DH,Z,iF,K,DK); end end DP=DP1; - clear DP1, + clear DP1 else DP=DP; - if nargout>4, + if nargout>4 D2P=D2P; end end @@ -71,8 +71,8 @@ for ii = 1:k % dai = da(:,:,ii); dKi = DK(:,:,ii); dtmp(:,ii) = Da(:,ii)+dKi*v+K*Dv(:,ii); - - if nargout>4, + + if nargout>4 diFi = -iF*DF(:,:,ii)*iF; for jj = 1:ii jcount=jcount+1; @@ -83,7 +83,7 @@ for ii = 1:k 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); if Zflag d2vij = -Z*D2Yss(:,jj,ii) - Z*D2a(:,jj,ii); @@ -93,28 +93,28 @@ 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, + + 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 -if nargout==4, +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 @@ -122,7 +122,7 @@ end % end of computeDLIK -function Hesst_ij = getHesst_ij(e,dei,dej,d2eij,iS,diSi,diSj,d2iSij,dSj,d2Sij); +function Hesst_ij = getHesst_ij(e,dei,dej,d2eij,iS,diSi,diSj,d2iSij,dSj,d2Sij) % computes (i,j) term in the Hessian Hesst_ij = trace(diSi*dSj + iS*d2Sij) + e'*d2iSij*e + 2*(dei'*diSj*e + dei'*iS*dej + e'*diSi*dej + e'*iS*d2eij); @@ -165,7 +165,7 @@ end % end of computeDKalmanZ -function [d2K,d2S,d2P1] = computeD2Kalman(A,dA,d2A,d2Om,P0,dP0,d2P1,DH,Z,iF,K0,dK0); +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. @@ -189,7 +189,7 @@ for ii = 1:k % d2Omi = d2Om(:,:,ii); diFi = -iF*dFi*iF; dKi = dK0(:,:,ii); - for jj = 1:ii, + for jj = 1:ii jcount=jcount+1; dAj = dA(:,:,jj); dFj = dP0(Z,Z,jj); @@ -201,20 +201,20 @@ 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; @@ -233,7 +233,7 @@ end % end of computeD2Kalman -function [d2K,d2S,d2P1] = computeD2KalmanZ(A,dA,d2A,d2Om,P0,dP0,d2P1,DH,Z,iF,K0,dK0); +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. @@ -251,13 +251,13 @@ d2S = zeros(no,no,k,k); % d2P1 = zeros(ns,ns,k,k); jcount=0; -for ii = 1:k, +for ii = 1:k dAi = dA(:,:,ii); dFi = Z*dP0(:,:,ii)*Z; % d2Omi = d2Om(:,:,ii); diFi = -iF*dFi*iF; dKi = dK0(:,:,ii); - for jj = 1:ii, + for jj = 1:ii jcount=jcount+1; dAj = dA(:,:,jj); dFj = Z*dP0(:,:,jj)*Z; @@ -269,20 +269,20 @@ 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; @@ -300,5 +300,3 @@ for ii = 1:k, end % end of computeD2KalmanZ - - diff --git a/matlab/kalman/likelihood/kalman_filter.m b/matlab/kalman/likelihood/kalman_filter.m index e0dcafadc..441ee8525 100644 --- a/matlab/kalman/likelihood/kalman_filter.m +++ b/matlab/kalman/likelihood/kalman_filter.m @@ -71,7 +71,7 @@ function [LIK, LIKK, a, P] = kalman_filter(Y,start,last,a,P,kalman_tol,riccati_t %! @end deftypefn %@eod: -% Copyright (C) 2004-2013 Dynare Team +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % @@ -123,7 +123,7 @@ notsteady = 1; F_singular = true; asy_hess=0; -if analytic_derivation == 0, +if analytic_derivation == 0 DLIK=[]; Hess=[]; LIKK=[]; @@ -132,15 +132,15 @@ else DLIK = zeros(k,1); % Initialization of the score. Da = zeros(mm,k); % Derivative State vector. dlikk = zeros(smpl,k); - - if Zflag==0, + + 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) + for ii=1:pp, C(ii,Z(ii))=1; end % SELECTION MATRIX IN MEASUREMENT EQ. (FOR WHEN IT IS NOT CONSTANT) else C=Z; end dC = zeros(pp,mm,k); % either selection matrix or schur have zero derivatives - if analytic_derivation==2, + if analytic_derivation==2 Hess = zeros(k,k); % Initialization of the Hessian D2a = zeros(mm,k,k); % State vector. d2C = zeros(pp,mm,k,k); @@ -151,7 +151,7 @@ else D2T=[]; D2Yss=[]; end - if asy_hess, + if asy_hess Hess = zeros(k,k); % Initialization of the Hessian end LIK={inf,DLIK,Hess}; @@ -188,7 +188,7 @@ while notsteady && t<=last end else F_singular = false; - if rescale_prediction_error_covariance, + if rescale_prediction_error_covariance log_dF = log(det(F./(sig*sig')))+2*sum(log(sig)); iF = inv(F./(sig*sig'))./(sig*sig'); else @@ -204,15 +204,15 @@ while notsteady && t<=last Ptmp = T*(P-K*P(Z,:))*transpose(T)+QQ; end tmp = (a+K*v); - if analytic_derivation, - if analytic_derivation==2, + if analytic_derivation + if analytic_derivation==2 [Da,DP,DLIKt,D2a,D2P, Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,P,iF,Da,DYss,DT,DOm,DP,DH,notsteady,D2a,D2Yss,D2T,D2Om,D2P); else [Da,DP,DLIKt,Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,P,iF,Da,DYss,DT,DOm,DP,DH,notsteady); end if t>presample DLIK = DLIK + DLIKt; - if analytic_derivation==2 || asy_hess, + if analytic_derivation==2 || asy_hess Hess = Hess + Hesst; end end @@ -232,11 +232,11 @@ end % Add observation's densities constants and divide by two. likk(1:s) = .5*(likk(1:s) + pp*log(2*pi)); -if analytic_derivation, +if analytic_derivation DLIK = DLIK/2; dlikk = dlikk/2; - if analytic_derivation==2 || asy_hess, - if asy_hess==0, + if analytic_derivation==2 || asy_hess + if asy_hess==0 Hess = Hess + tril(Hess,-1)'; end Hess = -Hess/2; @@ -245,8 +245,8 @@ end % Call steady state Kalman filter if needed. if t <= last - if analytic_derivation, - if analytic_derivation==2, + 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); else [tmp, tmp2] = kalman_filter_ss(Y, t, last, a, T, K, iF, dF, Z, pp, Zflag, analytic_derivation, Da, DT, DYss, asy_hess); @@ -263,14 +263,14 @@ if t <= last end % Compute minus the log-likelihood. -if presample>diffuse_periods, +if presample>diffuse_periods LIK = sum(likk(1+(presample-diffuse_periods):end)); else LIK = sum(likk); end -if analytic_derivation, - if analytic_derivation==2 || asy_hess, +if analytic_derivation + if analytic_derivation==2 || asy_hess LIK={LIK, DLIK, Hess}; else LIK={LIK, DLIK}; diff --git a/matlab/kalman/likelihood/kalman_filter_d.m b/matlab/kalman/likelihood/kalman_filter_d.m index 61c4b53fe..79b3607fb 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,33 +10,33 @@ 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 -% Copyright (C) 2004-2016 Dynare Team +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % @@ -70,7 +70,7 @@ while rank(Pinf,diffuse_kalman_tol) && (t<=last) 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 + 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. return @@ -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 cc8c3d1f9..db3dec3b7 100644 --- a/matlab/kalman/likelihood/kalman_filter_fast.m +++ b/matlab/kalman/likelihood/kalman_filter_fast.m @@ -74,7 +74,7 @@ function [LIK, LIKK, a, P] = kalman_filter_fast(Y,start,last,a,P,kalman_tol,ricc %! @end deftypefn %@eod: -% Copyright (C) 2004-2013 Dynare Team +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % @@ -152,7 +152,7 @@ while notsteady && t<=last end if rcond(F) < kalman_tol if ~all(abs(F(:))diffuse_periods, +if presample>diffuse_periods LIK = sum(likk(1+(presample-diffuse_periods):end)); else LIK = sum(likk); end -if analytic_derivation, - if analytic_derivation==2 || asy_hess, +if analytic_derivation + if analytic_derivation==2 || asy_hess LIK={LIK, DLIK, Hess}; else LIK={LIK, DLIK}; diff --git a/matlab/kalman/likelihood/kalman_filter_ss.m b/matlab/kalman/likelihood/kalman_filter_ss.m index 8e5f92733..5510de9f3 100644 --- a/matlab/kalman/likelihood/kalman_filter_ss.m +++ b/matlab/kalman/likelihood/kalman_filter_ss.m @@ -54,7 +54,7 @@ function [LIK, likk, a] = kalman_filter_ss(Y,start,last,a,T,K,iF,log_dF,Z,pp,Zfl %! @end deftypefn %@eod: -% Copyright (C) 2011-2012 Dynare Team +% Copyright (C) 2011-2017 Dynare Team % % This file is part of Dynare. % @@ -86,18 +86,18 @@ if nargin<12 analytic_derivation = 0; end -if analytic_derivation == 0, +if analytic_derivation == 0 DLIK=[]; Hess=[]; else k = size(DT,3); % number of structural parameters DLIK = zeros(k,1); % Initialization of the score. dlikk = zeros(smpl,k); - if analytic_derivation==2, + if analytic_derivation==2 Hess = zeros(k,k); % Initialization of the Hessian else asy_hess=D2a; - if asy_hess, + if asy_hess Hess = zeros(k,k); % Initialization of the Hessian else Hess=[]; @@ -112,14 +112,14 @@ while t <= last v = Y(:,t)-a(Z); end tmp = (a+K*v); - if analytic_derivation, - if analytic_derivation==2, + if analytic_derivation + if analytic_derivation==2 [Da,junk,DLIKt,D2a,junk2, Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,[],iF,Da,DYss,DT,[],[],[],notsteady,D2a,D2Yss,D2T,[],[]); else [Da,junk,DLIKt,Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,[],iF,Da,DYss,DT,[],[],[],notsteady); end DLIK = DLIK + DLIKt; - if analytic_derivation==2 || asy_hess, + if analytic_derivation==2 || asy_hess Hess = Hess + Hesst; end dlikk(t-start+1,:)=DLIKt; @@ -137,17 +137,17 @@ likk = .5*(likk + pp*log(2*pi)); % Sum the observation's densities (minus the likelihood) LIK = sum(likk); -if analytic_derivation, +if analytic_derivation dlikk = dlikk/2; DLIK = DLIK/2; likk = {likk, dlikk}; end -if analytic_derivation==2 || asy_hess, - if asy_hess==0, +if analytic_derivation==2 || asy_hess + if asy_hess==0 Hess = Hess + tril(Hess,-1)'; end Hess = -Hess/2; LIK={LIK,DLIK,Hess}; -elseif analytic_derivation==1, +elseif analytic_derivation==1 LIK={LIK,DLIK}; end diff --git a/matlab/kalman/likelihood/missing_observations_kalman_filter.m b/matlab/kalman/likelihood/missing_observations_kalman_filter.m index 4d357cd29..f1bd40cb5 100644 --- a/matlab/kalman/likelihood/missing_observations_kalman_filter.m +++ b/matlab/kalman/likelihood/missing_observations_kalman_filter.m @@ -5,34 +5,34 @@ 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-2012 Dynare Team +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % @@ -123,7 +123,7 @@ while notsteady && t<=last end else F_singular = false; - if rescale_prediction_error_covariance, + if rescale_prediction_error_covariance log_dF = log(det(F./(sig*sig')))+2*sum(log(sig)); iF = inv(F./(sig*sig'))./(sig*sig'); else diff --git a/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m b/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m index 5334c301e..ec8c286a4 100644 --- a/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m +++ b/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m @@ -5,7 +5,7 @@ function [dLIK,dlik,a,Pstar] = missing_observations_kalman_filter_d(data_index,n 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,32 +17,32 @@ 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 +% +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % @@ -87,9 +87,9 @@ 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. return @@ -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 3601ba754..083fb12db 100644 --- a/matlab/kalman/likelihood/univariate_computeDLIK.m +++ b/matlab/kalman/likelihood/univariate_computeDLIK.m @@ -1,6 +1,6 @@ function [Da,DP1,DLIK,D2a,D2P,Hesst] = univariate_computeDLIK(k,indx,Z,Zflag,v,K,PZ,F,Da,DYss,DP,DH,notsteady,D2a,D2Yss,D2P) -% Copyright (C) 2012 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -21,12 +21,12 @@ function [Da,DP1,DLIK,D2a,D2P,Hesst] = univariate_computeDLIK(k,indx,Z,Zflag,v,K persistent DDK DDF DD2K DD2F -if notsteady, +if notsteady if Zflag Dv = -Z*Da(:,:) - Z*DYss(:,:); DF = zeros(k,1); DK = zeros([rows(K),k]); - for j=1:k, + for j=1:k DF(j)=Z*DP(:,:,j)*Z'+DH; DK(:,j) = (DP(:,:,j)*Z')/F-PZ*DF(j)/F^2; end @@ -35,9 +35,9 @@ if notsteady, D2v = zeros(k,k); D2K = zeros(rows(K),k,k); jcount=0; - for j=1:k, + for j=1:k D2v(:,j) = -Z*D2a(:,:,j) - Z*D2Yss(:,:,j); - for i=1:j, + for i=1:j jcount=jcount+1; D2F(j,i)=Z*dyn_unvech(D2P(:,jcount))*Z'; D2F(i,j)=D2F(j,i); @@ -47,7 +47,7 @@ if notsteady, end end end - + else Dv = -Da(Z,:) - DYss(Z,:); DF = squeeze(DP(Z,Z,:))+DH'; @@ -57,8 +57,8 @@ if notsteady, D2K = zeros(rows(K),k,k); D2v = squeeze(-D2a(Z,:,:) - D2Yss(Z,:,:)); jcount=0; - for j=1:k, - for i=1:j, + for j=1:k + for i=1:j jcount=jcount+1; tmp = dyn_unvech(D2P(:,jcount)); D2F(j,i) = tmp(Z,Z); @@ -89,7 +89,7 @@ else Dv = -Z*Da(:,:) - Z*DYss(:,:); if nargout>4 D2v = zeros(k,k); - for j=1:k, + for j=1:k D2v(:,j) = -Z*D2a(:,:,j) - Z*D2Yss(:,:,j); end end @@ -105,7 +105,7 @@ 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'); -elseif nargout==4, +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'); @@ -114,34 +114,34 @@ end Da = Da + DK*v+K*Dv; if nargout>4 - + D2a = D2a + D2K*v; - for j=1:k, + for j=1:k % D2a(:,:,j) = D2a(:,:,j) + DK*Dv(j) + DK(:,j)*Dv + K*D2v(j,:); - for i=1:j, + for i=1:j D2a(:,j,i) = D2a(:,j,i) + DK(:,i)*Dv(j) + DK(:,j)*Dv(i) + K*D2v(j,i); D2a(:,i,j) = D2a(:,j,i); end end - - + + end -if notsteady, +if notsteady DP1 = DP*0; - if Zflag, - for j=1:k, + if Zflag + for j=1:k DP1(:,:,j)=DP(:,:,j) - (DP(:,:,j)*Z')*K'-PZ*DK(:,j)'; end else - for j=1:k, + for j=1:k DP1(:,:,j)=DP(:,:,j) - (DP(:,Z,j))*K'-PZ*DK(:,j)'; end end - if nargout>4, - if Zflag, - for j=1:k, - for i=1:j, + if nargout>4 + if Zflag + for j=1:k + for i=1:j jcount = jcount+1; tmp = dyn_unvech(D2P(:,jcount)); tmp = tmp - (tmp*Z')*K' - (DP(:,:,j)*Z')*DK(:,i)' ... @@ -153,8 +153,8 @@ if notsteady, else DPZ = squeeze(DP(:,Z,:)); jcount = 0; - for j=1:k, - for i=1:j, + for j=1:k + for i=1:j jcount = jcount+1; tmp = dyn_unvech(D2P(:,jcount)); D2PZ = tmp(:,Z); @@ -163,11 +163,9 @@ if notsteady, % 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 52e85c255..eecee428e 100644 --- a/matlab/kalman/likelihood/univariate_computeDstate.m +++ b/matlab/kalman/likelihood/univariate_computeDstate.m @@ -1,6 +1,6 @@ function [Da1,DP1,D2a,D2P] = univariate_computeDstate(k,a,P,T,Da,DP,DT,DOm,notsteady,D2a,D2P,D2T,D2Om) -% Copyright (C) 2012 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -22,25 +22,25 @@ function [Da1,DP1,D2a,D2P] = univariate_computeDstate(k,a,P,T,Da,DP,DT,DOm,notst DP1=DP*0; Da1=Da*0; -for j=1:k, +for j=1:k Da1(:,j) = T*Da(:,j) + DT(:,:,j)*a; - if notsteady, + if notsteady DP1(:,:,j) = T*DP(:,:,j)*T'+DT(:,:,j)*P*T'+T*P*DT(:,:,j)'; else DP1=DP; end end -if notsteady, +if notsteady DP1 = DP1 + DOm; end -if nargout>2, +if nargout>2 jcount=0; - for j=1:k, - for i=1:j, + for j=1:k + for i=1:j jcount=jcount+1; D2a(:,j,i) = DT(:,:,i)*Da(:,j) + DT(:,:,j)*Da(:,i) + T*D2a(:,j,i)+ reshape(D2T(:,jcount),size(T))*a; D2a(:,i,j) = D2a(:,j,i); - if notsteady, + 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)' + ... @@ -52,5 +52,5 @@ if nargout>2, end end end - + end diff --git a/matlab/kalman/likelihood/univariate_kalman_filter.m b/matlab/kalman/likelihood/univariate_kalman_filter.m index 9f9571a64..add638a54 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,15 +76,15 @@ 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 -% Copyright (C) 2004-2016 Dynare Team +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % @@ -128,7 +128,7 @@ oldK = Inf; K = NaN(mm,pp); asy_hess=0; -if analytic_derivation == 0, +if analytic_derivation == 0 DLIK=[]; Hess=[]; else @@ -136,15 +136,15 @@ else DLIK = zeros(k,1); % Initialization of the score. Da = zeros(mm,k); % Derivative State vector. dlik = zeros(smpl,k); - - if Zflag==0, + + 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) + for ii=1:pp, C(ii,Z(ii))=1; end % SELECTION MATRIX IN MEASUREMENT EQ. (FOR WHEN IT IS NOT CONSTANT) else C=Z; end dC = zeros(pp,mm,k); % either selection matrix or schur have zero derivatives - if analytic_derivation==2, + if analytic_derivation==2 Hess = zeros(k,k); % Initialization of the Hessian D2a = zeros(mm,k,k); % State vector. d2C = zeros(pp,mm,k,k); @@ -155,7 +155,7 @@ else D2T=[]; D2Yss=[]; end - if asy_hess, + if asy_hess Hess = zeros(k,k); % Initialization of the Hessian end LIK={inf,DLIK,Hess}; @@ -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) @@ -186,15 +186,15 @@ while notsteady && t<=last %loop over t K(:,i) = Ki; end lik(s,i) = log(Fi) + (prediction_error*prediction_error)/Fi + l2pi; %Top equation p. 175 in DK (2012) - if analytic_derivation, - if analytic_derivation==2, + if analytic_derivation + if analytic_derivation==2 [Da,DP,DLIKt,D2a,D2P, Hesst] = univariate_computeDLIK(k,i,z(i,:),Zflag,prediction_error,Ki,PZ,Fi,Da,DYss,DP,DH(d_index(i),:),notsteady,D2a,D2Yss,D2P); else [Da,DP,DLIKt,Hesst] = univariate_computeDLIK(k,i,z(i,:),Zflag,prediction_error,Ki,PZ,Fi,Da,DYss,DP,DH(d_index(i),:),notsteady); end if t>presample DLIK = DLIK + DLIKt; - if analytic_derivation==2 || asy_hess, + if analytic_derivation==2 || asy_hess Hess = Hess + Hesst; end end @@ -207,14 +207,14 @@ while notsteady && t<=last %loop over t % p. 157, DK (2012) end end - if analytic_derivation, - if analytic_derivation==2, + if analytic_derivation + if analytic_derivation==2 [Da,DP,D2a,D2P] = univariate_computeDstate(k,a,P,T,Da,DP,DT,DOm,notsteady,D2a,D2P,D2T,D2Om); else [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; @@ -225,10 +225,10 @@ end % Divide by two. lik(1:s,:) = .5*lik(1:s,:); -if analytic_derivation, +if analytic_derivation DLIK = DLIK/2; dlik = dlik/2; - if analytic_derivation==2 || asy_hess, + if analytic_derivation==2 || asy_hess % Hess = (Hess + Hess')/2; Hess = -Hess/2; end @@ -236,8 +236,8 @@ end % Call steady state univariate kalman filter if needed. if t <= last - if analytic_derivation, - if analytic_derivation==2, + 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); else @@ -247,7 +247,7 @@ if t <= last lik(s+1:end,:)=tmp2{1}; dlik(s+1:end,:)=tmp2{2}; DLIK = DLIK + tmp{2}; - if analytic_derivation==2 || asy_hess, + if analytic_derivation==2 || asy_hess Hess = Hess + tmp{3}; end else @@ -262,8 +262,8 @@ else LIK = sum(sum(lik)); end -if analytic_derivation, - if analytic_derivation==2 || asy_hess, +if analytic_derivation + if analytic_derivation==2 || asy_hess LIK={LIK, DLIK, Hess}; else LIK={LIK, DLIK}; diff --git a/matlab/kalman/likelihood/univariate_kalman_filter_d.m b/matlab/kalman/likelihood/univariate_kalman_filter_d.m index ac121ee33..ce78d2421 100644 --- a/matlab/kalman/likelihood/univariate_kalman_filter_d.m +++ b/matlab/kalman/likelihood/univariate_kalman_filter_d.m @@ -80,14 +80,14 @@ 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 -% Copyright (C) 2004-2016 Dynare Team +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % @@ -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 dd2623b8e..9d8cbff06 100644 --- a/matlab/kalman/likelihood/univariate_kalman_filter_ss.m +++ b/matlab/kalman/likelihood/univariate_kalman_filter_ss.m @@ -54,10 +54,10 @@ 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-2016 Dynare Team +% Copyright (C) 2011-2017 Dynare Team % % This file is part of Dynare. % @@ -90,18 +90,18 @@ if nargin<12 analytic_derivation = 0; end -if analytic_derivation == 0, +if analytic_derivation == 0 DLIK=[]; Hess=[]; else k = size(DT,3); % number of structural parameters DLIK = zeros(k,1); % Initialization of the score. dlikk = zeros(smpl,k); - if analytic_derivation==2, + if analytic_derivation==2 Hess = zeros(k,k); % Initialization of the Hessian else asy_hess=D2a; - if asy_hess, + if asy_hess Hess = zeros(k,k); % Initialization of the Hessian else Hess=[]; @@ -113,9 +113,9 @@ end while t<=last s = t-start+1; PP = P; - if analytic_derivation, + if analytic_derivation DPP = DP; - if analytic_derivation==2, + if analytic_derivation==2 D2PP = D2P; end end @@ -134,14 +134,14 @@ while t<=last a = a + Ki*prediction_error; PP = PP - PPZ*Ki'; likk(s,i) = log(Fi) + prediction_error*prediction_error/Fi + l2pi; - if analytic_derivation, - if analytic_derivation==2, + if analytic_derivation + if analytic_derivation==2 [Da,DPP,DLIKt,D2a,D2PP, Hesst] = univariate_computeDLIK(k,i,Z(i,:),Zflag,prediction_error,Ki,PPZ,Fi,Da,DYss,DPP,DH(i,:),0,D2a,D2Yss,D2PP); else [Da,DPP,DLIKt,Hesst] = univariate_computeDLIK(k,i,Z(i,:),Zflag,prediction_error,Ki,PPZ,Fi,Da,DYss,DPP,DH(i,:),0); end DLIK = DLIK + DLIKt; - if analytic_derivation==2 || asy_hess, + if analytic_derivation==2 || asy_hess Hess = Hess + Hesst; end dlikk(s,:)=dlikk(s,:)+DLIKt'; @@ -151,8 +151,8 @@ while t<=last % p. 157, DK (2012) end end - if analytic_derivation, - if analytic_derivation==2, + if analytic_derivation + if analytic_derivation==2 [Da,junk,D2a] = univariate_computeDstate(k,a,P,T,Da,DP,DT,[],0,D2a,D2P,D2T); else Da = univariate_computeDstate(k,a,P,T,Da,DP,DT,[],0); @@ -165,15 +165,15 @@ end likk = .5*likk; LIK = sum(sum(likk)); -if analytic_derivation, +if analytic_derivation dlikk = dlikk/2; DLIK = DLIK/2; likk = {likk, dlikk}; end -if analytic_derivation==2 || asy_hess, +if analytic_derivation==2 || asy_hess % Hess = (Hess + Hess')/2; Hess = -Hess/2; LIK={LIK,DLIK,Hess}; -elseif analytic_derivation==1, +elseif analytic_derivation==1 LIK={LIK,DLIK}; end \ No newline at end of file diff --git a/matlab/kalman/steady_state_kalman_gain.m b/matlab/kalman/steady_state_kalman_gain.m index 460534e1b..c40761d4a 100644 --- a/matlab/kalman/steady_state_kalman_gain.m +++ b/matlab/kalman/steady_state_kalman_gain.m @@ -1,23 +1,23 @@ 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) -% Copyright (C) 2004-2009 Dynare Team +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/kalman_transition_matrix.m b/matlab/kalman_transition_matrix.m index 77b3a4d3a..f79b436cd 100644 --- a/matlab/kalman_transition_matrix.m +++ b/matlab/kalman_transition_matrix.m @@ -1,21 +1,21 @@ 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 -% Copyright (C) 2003-2016 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -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 172097c87..c04927681 100644 --- a/matlab/kernel_density_estimate.m +++ b/matlab/kernel_density_estimate.m @@ -1,30 +1,30 @@ -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 +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % @@ -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 603a9f2e1..01964a89a 100644 --- a/matlab/list_of_parameters_calibrated_as_NaN.m +++ b/matlab/list_of_parameters_calibrated_as_NaN.m @@ -1,19 +1,19 @@ 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 -% Copyright (C) 2010-2011 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/lmmcp/catstruct.m b/matlab/lmmcp/catstruct.m index 040c0b7ed..3f1784367 100644 --- a/matlab/lmmcp/catstruct.m +++ b/matlab/lmmcp/catstruct.m @@ -6,13 +6,13 @@ function A = catstruct(varargin) % % A.name = 'Me' ; % B.income = 99999 ; -% X = catstruct(A,B) +% 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 +% 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' ; @@ -28,7 +28,7 @@ function A = catstruct(varargin) % 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. +% 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. % @@ -36,7 +36,7 @@ function A = catstruct(varargin) % struct (0x0 struct array with no fields). % % NOTE: To concatenate similar arrays of structs, you can use simple -% concatenation: +% concatenation: % A = dir('*.mat') ; B = dir('*.m') ; C = [A ; B] ; % % See also CAT, STRUCT, FIELDNAMES, STRUCT2CELL, ORDERFIELDS @@ -48,18 +48,18 @@ function A = catstruct(varargin) % Copyright (C) 2005 Jos van der Geest % Copyright (C) 2013 Christophe Gouel -% Copyright (C) 2016 Dynare Team +% Copyright (C) 2016-2017 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 @@ -87,8 +87,8 @@ function A = catstruct(varargin) narginchk(1, Inf); N = nargin ; -if ~isstruct(varargin{end}), - if isequal(varargin{end},'sorted'), +if ~isstruct(varargin{end}) + if isequal(varargin{end},'sorted') sorted = 1 ; N = N-1 ; if N<1 @@ -104,7 +104,7 @@ end sz0 = [] ; % used to check that all inputs have the same size % used to check for a few trivial cases -NonEmptyInputs = false(N,1) ; +NonEmptyInputs = false(N,1) ; NonEmptyInputsN = 0 ; % used to collect the fieldnames and the inputs @@ -112,13 +112,13 @@ FN = cell(N,1) ; VAL = cell(N,1) ; % parse the inputs -for ii=1:N, +for ii=1:N X = varargin{ii} ; - if ~isstruct(X), + if ~isstruct(X) error('catstruct:InvalidArgument',['Argument #' num2str(ii) ' is not a structure.']) ; end - - if ~isempty(X), + + if ~isempty(X) % empty structs are ignored if ii > 1 && ~isempty(sz0) if ~isequal(size(X), sz0) @@ -137,38 +137,35 @@ end if NonEmptyInputsN == 0 % all structures were empty A = struct([]) ; -elseif NonEmptyInputsN == 1, +elseif NonEmptyInputsN == 1 % there was only one non-empty structure A = varargin{NonEmptyInputs} ; - if sorted, + if sorted A = orderfields(A) ; end else % there is actually something to concatenate - FN = cat(1,FN{:}) ; - VAL = cat(1,VAL{:}) ; + 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) ; + [UFN,ind] = unique(FN) ; else [UFN,ind] = unique(FN,'legacy') ; end - - if numel(UFN) ~= numel(FN), + + if numel(UFN) ~= numel(FN) warning('catstruct:DuplicatesFound','Fieldnames are not unique between structures.') ; sorted = 1 ; end - - if sorted, + + if sorted VAL = VAL(ind,:) ; FN = FN(ind,:) ; end - + A = cell2struct(VAL, FN); A = reshape(A, sz0) ; % reshape into original format -end - - - +end \ No newline at end of file diff --git a/matlab/lmmcp/dyn_lmmcp_func.m b/matlab/lmmcp/dyn_lmmcp_func.m index f08da101e..c25eff690 100644 --- a/matlab/lmmcp/dyn_lmmcp_func.m +++ b/matlab/lmmcp/dyn_lmmcp_func.m @@ -3,7 +3,7 @@ function [F,A] = dyn_lmmcp_func(x, model_dynamic, Y0, YT, exo_simul, params, ... i_cols_A1, i_cols_1, i_cols_T, i_cols_j, ... nnzA,eq_index) -% Copyright (C) 2014 Dynare Team +% Copyright (C) 2014-2017 Dynare Team % % This file is part of Dynare. % @@ -32,11 +32,11 @@ 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); @@ -46,7 +46,6 @@ for it = 2:(periods+1) 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 @@ -54,3 +53,9 @@ for it = 2:(periods+1) 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 291627f59..fb48ece9a 100644 --- a/matlab/lmmcp/get_complementarity_conditions.m +++ b/matlab/lmmcp/get_complementarity_conditions.m @@ -2,17 +2,17 @@ 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 -% Copyright (C) 2014-16 Dynare Team +% Copyright (C) 2014-2017 Dynare Team % % This file is part of Dynare. % @@ -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 76cb49a98..50404ac7c 100644 --- a/matlab/lmmcp/lmmcp.m +++ b/matlab/lmmcp/lmmcp.m @@ -24,7 +24,7 @@ function [x,FVAL,EXITFLAG,OUTPUT,JACOB] = lmmcp(FUN,x,lb,ub,options,varargin) % Termination parameters % MaxIter : Maximum number of iterations (default = 500) % tmin : safeguard stepsize (default = 1E-12) -% TolFun : Termination tolerance on the function value, a positive +% 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 @@ -92,7 +92,7 @@ function [x,FVAL,EXITFLAG,OUTPUT,JACOB] = lmmcp(FUN,x,lb,ub,options,varargin) % Copyright (C) 2005 Christian Kanzow and Stefania Petra % Copyright (C) 2013 Christophe Gouel -% Copyright (C) 2014 Dynare Team +% Copyright (C) 2014-2017 Dynare Team % % Unlimited permission is granted to everyone to use, copy, modify or % distribute this software. @@ -249,11 +249,11 @@ 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 @@ -273,7 +273,7 @@ if preprocess==1 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); @@ -285,7 +285,7 @@ if preprocess==1 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); @@ -303,7 +303,7 @@ if preprocess==1 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 @@ -357,7 +357,7 @@ while (k < kmax) && (Psix > eps2) mu = 1e-1/(k+1); end end - + % compute a Levenberg-Marquard direction if i @@ -378,7 +378,7 @@ while (k < kmax) && (Psix > eps2) 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; @@ -398,7 +398,7 @@ while (k < kmax) && (Psix > eps2) normDPsix = norm(DPsix); k = k+1; k_main = k_main+1; - + if k_main<=5 aux(mod(k_main,m)+1) = Psix; MaxPsi = Psix; @@ -406,7 +406,7 @@ while (k < kmax) && (Psix > eps2) aux(mod(k_main,m)+1) = Psix; MaxPsi = max(aux); end - + % updatings for the watchdog strategy if watchdog ==1 if Psix1 +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 e8d8af521..6f0dd0fd8 100644 --- a/matlab/lpdfgbeta.m +++ b/matlab/lpdfgbeta.m @@ -1,20 +1,20 @@ -function [ldens,Dldens,D2ldens] = lpdfgbeta(x,a,b,aa,bb); -% Evaluates the logged BETA PDF at x. +function [ldens,Dldens,D2ldens] = lpdfgbeta(x,a,b,aa,bb) +% 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 -% Copyright (C) 2003-2011 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -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 5aeb05f90..2b14c8fab 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. @@ -17,7 +17,7 @@ function [ldens,Dldens,D2ldens] = lpdfig1(x,s,nu) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2004-2011 Dynare Team +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % @@ -35,7 +35,7 @@ function [ldens,Dldens,D2ldens] = lpdfig1(x,s,nu) % along with Dynare. If not, see . 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 00de3abb1..e1b3ca2a1 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. @@ -17,7 +17,7 @@ function [ldens,Dldens,D2ldens] = lpdfig2(x,s,nu) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2004-2011 Dynare Team +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % @@ -35,7 +35,7 @@ function [ldens,Dldens,D2ldens] = lpdfig2(x,s,nu) % along with Dynare. If not, see . 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 bb9da98d8..2c1249996 100644 --- a/matlab/lpdfnorm.m +++ b/matlab/lpdfnorm.m @@ -1,19 +1,19 @@ 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 -% Copyright (C) 2003-2012 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -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 a7b96c997..98d782cdf 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,10 +20,10 @@ 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 Dynare Team +% Copyright (C) 2016-2017 Dynare Team % % This file is part of Dynare. % @@ -60,10 +60,10 @@ 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; +end %@test:1 %$ t = NaN(10,1); @@ -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 a4618b171..53eaf9e4c 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) @@ -25,7 +25,7 @@ function [x,u] = lyapunov_symm(a,b,lyapunov_fixed_point_tol,qz_criterium,lyapuno % SPECIAL REQUIREMENTS % None -% Copyright (C) 2006-2016 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -54,7 +54,7 @@ if method == 3 persistent X method1; if ~isempty(method1) method = method1; - end; + end if debug fprintf('lyapunov_symm:: [method=%d] \n',method); end @@ -67,16 +67,16 @@ if method == 3 max_it_fp = 2000; else max_it_fp = 300; - end; + end at = a'; %fixed point iterations - while evol > lyapunov_fixed_point_tol && it_fp < max_it_fp; + while evol > lyapunov_fixed_point_tol && it_fp < max_it_fp 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 it_fp = it_fp + 1; - end; + end if debug fprintf('lyapunov_symm:: lyapunov fixed_point iterations=%d norm=%g\n',it_fp,evol); end @@ -87,9 +87,9 @@ if method == 3 else method1 = 3; x = X; - return; - end; - end; + return + end + end end if method @@ -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 58e293da8..e5683da2c 100644 --- a/matlab/marginal_density.m +++ b/matlab/marginal_density.m @@ -15,7 +15,7 @@ function [marginal,oo_] = marginal_density(M_, options_, estim_params_, oo_, bay % SPECIAL REQUIREMENTS % none -% Copyright (C) 2005-2011 Dynare Team +% Copyright (C) 2005-2017 Dynare Team % % This file is part of Dynare. % @@ -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'); @@ -76,7 +76,7 @@ linee = 0; check_coverage = 1; increase = 1; while check_coverage - for p = 0.1:0.1:0.9; + for p = 0.1:0.1:0.9 critval = chi2inv(p,npar); ifil = FirstLine; tmp = 0; @@ -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 diff --git a/matlab/matlab_ver_less_than.m b/matlab/matlab_ver_less_than.m index 53dd8d7ef..10cd640d2 100644 --- a/matlab/matlab_ver_less_than.m +++ b/matlab/matlab_ver_less_than.m @@ -8,14 +8,14 @@ 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 % % SPECIAL REQUIREMENTS % none -% Copyright (C) 2008-2014 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/maximize_prior_density.m b/matlab/maximize_prior_density.m index 72df861a4..9f79e44a4 100644 --- a/matlab/maximize_prior_density.m +++ b/matlab/maximize_prior_density.m @@ -1,21 +1,21 @@ 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. -% Copyright (C) 2009-2015 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/mcforecast3.m b/matlab/mcforecast3.m index 3e1de2888..b318d46f4 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,8 +30,8 @@ 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-2013 Dynare Team +% +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/mcompare.m b/matlab/mcompare.m index 9bf0f1713..f3f052f68 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 @@ -10,7 +10,7 @@ function mcompare(s1,s2) % value of the base simulation, the absolute difference is ploted % instead of the relative one. -% Copyright (C) 2001-2011 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/mcp_func.m b/matlab/mcp_func.m index 424b9203f..30494b95a 100644 --- a/matlab/mcp_func.m +++ b/matlab/mcp_func.m @@ -1,17 +1,17 @@ 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 -% Copyright (C) 2016 Dynare Team +% Copyright (C) 2016-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/metropolis_draw.m b/matlab/metropolis_draw.m index a8e1e602d..94c421278 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,12 +19,12 @@ 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 -% Copyright (C) 2003-2015 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -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 ? @@ -89,9 +89,9 @@ else %not initialization, return one draw 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 97a454eee..e9d97a0ea 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 @@ -37,7 +37,7 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa % SPECIAL REQUIREMENTS % None. -% Copyright (C) 2006-2016 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -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.') @@ -223,7 +223,7 @@ if ~options_.load_mh_file && ~options_.mh_recover fprintf(fidlog,[' Expected number of files per block.......: ' int2str(AnticipatedNumberOfFiles) '.\n']); fprintf(fidlog,[' Expected number of lines in the last file: ' int2str(AnticipatedNumberOfLinesInTheLastFile) '.\n']); fprintf(fidlog,['\n']); - for j = 1:NumberOfBlocks, + for j = 1:NumberOfBlocks fprintf(fidlog,[' Initial state of the Gaussian random number generator for chain number ',int2str(j),':\n']); for i=1:length(record.InitialSeeds(j).Normal) fprintf(fidlog,[' ' num2str(record.InitialSeeds(j).Normal(i)') '\n']); @@ -232,7 +232,7 @@ if ~options_.load_mh_file && ~options_.mh_recover for i=1:length(record.InitialSeeds(j).Unifor) fprintf(fidlog,[' ' num2str(record.InitialSeeds(j).Unifor(i)') '\n']); end - end, + end fprintf(fidlog,' \n'); fclose(fidlog); elseif options_.load_mh_file && ~options_.mh_recover @@ -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,8 +335,8 @@ 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 + %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); @@ -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 + 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). + % % 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. % 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 7355fddbd..7d1858285 100644 --- a/matlab/mh_optimal_bandwidth.m +++ b/matlab/mh_optimal_bandwidth.m @@ -1,30 +1,30 @@ -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-2015 Dynare Team +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % @@ -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); @@ -98,23 +98,23 @@ end %% Compute the standard deviation of the draws. sigma = std(data); %% Optimal bandwidth parameter. -if bandwidth == 0; % Rule of thumb bandwidth parameter (Silverman [1986]. +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 op 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.']); @@ -135,9 +135,9 @@ elseif bandwidth == -2; % Bump killing... I compute local bandwith parameter T = zeros(n,1); for i=1:n j = i; - while j<= n && (data(j,1)-data(i,1))<2*eps; + 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 @@ -151,11 +151,11 @@ elseif bandwidth == -2; % Bump killing... I compute local bandwith parameter Ihat3 = -Ihat3/((n^2)*g3^7); g2 = abs(2*correction*k4(0)/(mu21*Ihat3*n))^(1/7); Ihat2 = 0; - for i=1:number_of_draws; + 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.'); @@ -169,7 +169,7 @@ function correction = correction_for_repeated_draws(draws,n) correction = 0; for i=1:n j = i; - while j<=n && ( draws(j,1) - draws(i,1) )<2*eps; + while j<=n && ( draws(j,1) - draws(i,1) )<2*eps j = j+1; end correction = correction + 2*(j-i) - 1; diff --git a/matlab/minus_logged_prior_density.m b/matlab/minus_logged_prior_density.m index 60208647f..0b5b1e815 100644 --- a/matlab/minus_logged_prior_density.m +++ b/matlab/minus_logged_prior_density.m @@ -1,19 +1,19 @@ 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. % -% Copyright (C) 2009-2016 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -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 ec3b67091..893fd7c57 100644 --- a/matlab/missing/corrcoef/corrcoef.m +++ b/matlab/missing/corrcoef/corrcoef.m @@ -91,7 +91,7 @@ function [R,sig,ci1,ci2,nan_sig] = corrcoef(X,Y,varargin) % $Id: corrcoef.m 9387 2011-12-15 10:42:14Z schloegl $ % Copyright (C) 2000-2004,2008,2009,2011 by Alois Schloegl -% Copyright (C) 2014 Dynare Team +% Copyright (C) 2014-2017 Dynare Team % This function is part of the NaN-toolbox % http://pub.ist.ac.at/~schloegl/matlab/NaN/ @@ -138,22 +138,22 @@ elseif nargin>1 Y=[]; else varg = varargin; - end; + end - if length(varg)<1, + if length(varg)<1 Mode = 'Pearson'; - elseif length(varg)==1, + elseif length(varg)==1 Mode = varg{1}; else - for k = 2:2:length(varg), + for k = 2:2:length(varg) mode = setfield(mode,lower(varg{k-1}),varg{k}); - end; + end if isfield(mode,'mode') Mode = mode.mode; - end; - end; -end; -if isempty(Mode) Mode='pearson'; end; + end + end +end +if isempty(Mode), Mode='pearson'; end Mode=[Mode,' ']; @@ -164,19 +164,19 @@ warning('off'); [r1,c1]=size(X); if ~isempty(Y) [r2,c2]=size(Y); - if r1~=r2, + if r1~=r2 fprintf(2,'Error CORRCOEF: X and Y must have the same number of observations (rows).\n'); - return; - end; + return + end NN = real(~isnan(X)')*real(~isnan(Y)); else [r2,c2]=size(X); NN = real(~isnan(X)')*real(~isnan(X)); -end; +end %%%%% generate combinations using indices for pairwise calculation of the correlation YESNAN = any(isnan(X(:))) | any(isnan(Y(:))); -if YESNAN, +if YESNAN FLAG_NANS_OCCURED=(1==1); if isfield(mode,'rows') if strcmp(mode.rows,'complete') @@ -184,7 +184,7 @@ if YESNAN, X = X(ix,:); if ~isempty(Y) Y = Y(ix,:); - end; + end YESNAN = 0; NN = size(X,1); elseif strcmp(mode.rows,'all') @@ -192,10 +192,10 @@ if YESNAN, %%NN(NN < size(X,1)) = NaN; elseif strcmp(mode.rows,'pairwise') %%% default - end; - end; -end; -if isempty(Y), + end + end +end +if isempty(Y) IX = ones(c1)-diag(ones(c1,1)); [jx, jy ] = find(IX); [jxo,jyo] = find(IX); @@ -208,13 +208,13 @@ else IX = ones(c1,c2); [jxo,jyo] = find(IX); R = zeros(c1,c2); -end; +end -if strcmp(lower(Mode(1:7)),'pearson'); +if strcmp(lower(Mode(1:7)),'pearson') % see http://mathworld.wolfram.com/CorrelationCoefficient.html - if ~YESNAN, + if ~YESNAN [S,N,SSQ] = sumskipnan(X,1); - if ~isempty(Y), + if ~isempty(Y) [S2,N2,SSQ2] = sumskipnan(Y,1); CC = X'*Y; M1 = S./N; @@ -227,12 +227,12 @@ if strcmp(lower(Mode(1:7)),'pearson'); cc = CC./NN - M'*M; v = SSQ./N - M.*M; %max(N-1,0); R = cc./sqrt(v'*v); - end; + end else - if ~isempty(Y), + if ~isempty(Y) X = [X,Y]; - end; - for k = 1:length(jx), + 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); @@ -241,83 +241,83 @@ if strcmp(lower(Mode(1:7)),'pearson'); cc = cc/n(1) - prod(s./n); %r(k) = cc./sqrt(prod(v)); R(jxo(k),jyo(k)) = cc./sqrt(prod(v)); - end; + end end -elseif strcmp(lower(Mode(1:4)),'rank'); +elseif strcmp(lower(Mode(1:4)),'rank') % see [ 6] http://mathworld.wolfram.com/SpearmanRankCorrelationCoefficient.html - if ~YESNAN, + if ~YESNAN if isempty(Y) R = corrcoef(ranks(X)); else R = corrcoef(ranks(X),ranks(Y)); - end; + end else - if ~isempty(Y), + if ~isempty(Y) X = [X,Y]; - end; - for k = 1:length(jx), + 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; + end X = ranks(X); - end; + end -elseif strcmp(lower(Mode(1:8)),'spearman'); +elseif strcmp(lower(Mode(1:8)),'spearman') % see [ 6] http://mathworld.wolfram.com/SpearmanRankCorrelationCoefficient.html - if ~isempty(Y), + if ~isempty(Y) X = [X,Y]; - end; + end n = repmat(nan,c1,c2); - if ~YESNAN, + if ~YESNAN iy = ranks(X); % calculates ranks; - for k = 1:length(jx), + 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; + end else - for k = 1:length(jx), + 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; + end X = ranks(X); - end; + end R = 1 - 6 * R ./ (n.*(n.*n-1)); -elseif strcmp(lower(Mode(1:7)),'partial'); +elseif strcmp(lower(Mode(1:7)),'partial') fprintf(2,'Error CORRCOEF: use PARTCORRCOEF \n',Mode); - return; + return -elseif strcmp(lower(Mode(1:7)),'kendall'); +elseif strcmp(lower(Mode(1:7)),'kendall') fprintf(2,'Error CORRCOEF: mode ''%s'' not implemented yet.\n',Mode); - return; + return else fprintf(2,'Error CORRCOEF: unknown mode ''%s''\n',Mode); -end; +end -if (NARG<2), +if (NARG<2) warning(FLAG_WARNING); % restore warning status - return; -end; + return +end % CONFIDENCE INTERVAL if isfield(mode,'alpha') alpha = mode.alpha; -elseif exist('flag_implicit_significance','file'), +elseif exist('flag_implicit_significance','file') alpha = flag_implicit_significance; else alpha = 0.01; -end; +end % fprintf(1,'CORRCOEF: confidence interval is based on alpha=%f\n',alpha); @@ -327,21 +327,21 @@ tmp = 1 - R.*R; 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'); +if exist('t_cdf','file') sig = t_cdf(t,NN-2); -elseif exist('tcdf','file')>1; +elseif exist('tcdf','file')>1 sig = tcdf(t,NN-2); else fprintf('CORRCOEF: significance test not completed because of missing TCDF-function\n') sig = repmat(nan,size(R)); -end; +end sig = 2 * min(sig,1 - sig); -if NARG<3, +if NARG<3 warning(FLAG_WARNING); % restore warning status - return; -end; + return +end tmp = R; @@ -356,11 +356,11 @@ ci2 = tanh(z+sz); %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, +if (NARG<5) || ~YESNAN nan_sig = repmat(NaN,size(R)); warning(FLAG_WARNING); % restore warning status - return; -end; + return +end %%%%% ----- check independence of NaNs (missing values) ----- [nan_R, nan_sig] = corrcoef(X,double(isnan(X))); @@ -370,7 +370,7 @@ nan_sig(isnan(nan_R)) = nan; % remove diagonal elements, because these have not any meaning % nan_R(isnan(nan_R)) = 0; -if 0, any(nan_sig(:) < alpha), +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); @@ -378,10 +378,8 @@ if 0, any(nan_sig(:) < alpha), 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 %%%%% ----- end of independence check ------ warning(FLAG_WARNING); % restore warning status -return; - diff --git a/matlab/missing/corrcoef/flag_implicit_skip_nan.m b/matlab/missing/corrcoef/flag_implicit_skip_nan.m index bf162f071..e8fd0fec6 100644 --- a/matlab/missing/corrcoef/flag_implicit_skip_nan.m +++ b/matlab/missing/corrcoef/flag_implicit_skip_nan.m @@ -41,8 +41,10 @@ function FLAG = flag_implicit_skip_nan(i) % 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 $ + % Copyright (C) 2001-2003,2009 by Alois Schloegl -% Copyright (C) 2014 Dynare Team +% Copyright (C) 2014-2017 Dynare Team +% % This function is part of the NaN-toolbox % http://pub.ist.ac.at/~schloegl/matlab/NaN/ @@ -52,15 +54,14 @@ persistent FLAG_implicit_skip_nan; %% 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), +if isempty(FLAG_implicit_skip_nan) FLAG_implicit_skip_nan = (1==1); %logical(1); % logical.m not available on 2.0.16 -end; +end FLAG = FLAG_implicit_skip_nan; -if nargin>0, +if nargin>0 FLAG_implicit_skip_nan = (i~=0); %logical(i); %logical.m not available in 2.0.16 if (~i) 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; - + end +end diff --git a/matlab/missing/corrcoef/sumskipnan.m b/matlab/missing/corrcoef/sumskipnan.m index 15768dc09..a1054c3f8 100644 --- a/matlab/missing/corrcoef/sumskipnan.m +++ b/matlab/missing/corrcoef/sumskipnan.m @@ -48,20 +48,21 @@ function [o,count,SSQ] = sumskipnan(x, DIM, W) % along with this program; If not, see . % $Id: sumskipnan.m 9033 2011-11-08 20:58:07Z schloegl $ +% % Copyright (C) 2000-2005,2009,2011 by Alois Schloegl -% Copyright (C) 2014 Dynare Team +% Copyright (C) 2014-2017 Dynare Team % This function is part of the NaN-toolbox % http://pub.ist.ac.at/~schloegl/matlab/NaN/ global FLAG_NANS_OCCURED; -if nargin<2, +if nargin<2 DIM = []; -end; -if nargin<3, +end +if nargin<3 W = []; -end; +end % an efficient implementation in C of the following lines % could significantly increase performance @@ -78,19 +79,19 @@ end; % o3 += tmp.*tmp; % }; -if isempty(DIM), +if isempty(DIM) DIM = find(size(x)>1,1); - if isempty(DIM), DIM = 1; end; + if isempty(DIM), DIM = 1; end end -if (DIM<1), DIM = 1; end; %% Hack, because min([])=0 for FreeMat v3.5 +if (DIM<1), DIM = 1; end %% Hack, because min([])=0 for FreeMat v3.5 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % non-float data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -if (isempty(W) && (~(isa(x,'float') || isa(x,'double')))) || ~flag_implicit_skip_nan(), %%% skip always NaN's +if (isempty(W) && (~(isa(x,'float') || isa(x,'double')))) || ~flag_implicit_skip_nan() %%% skip always NaN's if ~isempty(W) error('SUMSKIPNAN: weighted sum of integers not supported, yet'); - end; + end x = double(x); o = sum(x,DIM); if nargout>1 @@ -101,16 +102,16 @@ if (isempty(W) && (~(isa(x,'float') || isa(x,'double')))) || ~flag_implicit_ski if nargout>2 x = x.*x; SSQ = sum(x,DIM); - end; - end; - return; -end; + end + end + return +end if (length(size(x))=3), + end + end + return + elseif (nargout>=3) [o,count,SSQ] = sumskipnan_mex(real(x),DIM,FLAG_NANS_OCCURED,W); if (~isreal(x)) [io,icount,iSSQ] = sumskipnan_mex(imag(x),DIM,FLAG_NANS_OCCURED,W); @@ -155,23 +156,23 @@ try else o = o+i*io; SSQ = SSQ+iSSQ; - end; - end; - return; - end; -end; + end + end + return + end +end if ~isempty(W) error('weighted sumskipnan requires sumskipnan_mex'); -end; +end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % count non-NaN's %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -if nargout>1, +if nargout>1 count = sum(x==x,DIM); FLAG_NANS_OCCURED = any(count(:)2, +if nargout>2 x = real(x).^2 + imag(x).^2; SSQ = sum(x,DIM); -end; +end %!assert(sumskipnan([1,2],1),[1,2]) %!assert(sumskipnan([1,NaN],2),1) %!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 b3827862a..8d76f7657 100644 --- a/matlab/missing/corrcoef/tcdf.m +++ b/matlab/missing/corrcoef/tcdf.m @@ -12,8 +12,10 @@ 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 -% Copyright (C) 2014 Dynare Team + +% Copyright (C) 2000-2003,2009 by Alois Schloegl +% Copyright (C) 2014-2017 Dynare Team +% % This is part of the NaN-toolbox. For more details see % http://pub.ist.ac.at/~schloegl/matlab/NaN/ @@ -37,10 +39,10 @@ if all(size(x)==1) elseif all(size(n)==1) n = repmat(n,size(x)); elseif all(size(x)==size(n)) - ; %% OK, do nothing + % OK, do nothing else error('size of input arguments must be equal or scalar') -end; +end % allocate memory p = zeros(size(x)); diff --git a/matlab/missing/ilu/ilu.m b/matlab/missing/ilu/ilu.m index 0b8f8df73..6e53e59df 100644 --- a/matlab/missing/ilu/ilu.m +++ b/matlab/missing/ilu/ilu.m @@ -1,7 +1,7 @@ function [L, U, P] = ilu(A, setup) % Partially implement function ilu using the (now deprecated) luinc -% Copyright (C) 2013 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/missing/issquare/issquare.m b/matlab/missing/issquare/issquare.m index dfbfe8925..0b28884a0 100644 --- a/matlab/missing/issquare/issquare.m +++ b/matlab/missing/issquare/issquare.m @@ -27,7 +27,7 @@ function i = issquare(A) %! @end deftypefn %@eod: -% Copyright (C) 2012 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/missing/ordeig/ordeig.m b/matlab/missing/ordeig/ordeig.m index 6004fd86f..e7ddfd744 100644 --- a/matlab/missing/ordeig/ordeig.m +++ b/matlab/missing/ordeig/ordeig.m @@ -11,7 +11,7 @@ function eigs = ordeig(t) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2003-2009 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -34,7 +34,7 @@ i = 1; while i <= n if i == n eigs(n) = t(n,n); - break; + break elseif t(i+1,i) == 0 eigs(i) = t(i,i); i = i+1; diff --git a/matlab/missing/stats/betacdf.m b/matlab/missing/stats/betacdf.m index 2ba7cc53e..d1ac509f7 100644 --- a/matlab/missing/stats/betacdf.m +++ b/matlab/missing/stats/betacdf.m @@ -10,7 +10,7 @@ function cdf = betacdf (x, a, b) % Original author: KH % Copyright (C) 1995, 1996, 1997, 2005, 2006, 2007 Kurt Hornik -% Copyright (C) 2008-2009 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -61,4 +61,3 @@ if (any (k)) end end - diff --git a/matlab/missing/stats/betainv.m b/matlab/missing/stats/betainv.m index 8273fc356..a7300d1b1 100644 --- a/matlab/missing/stats/betainv.m +++ b/matlab/missing/stats/betainv.m @@ -84,7 +84,7 @@ if (any (k)) end h = y_old - y_new; if (max (abs (h)) < sqrt (eps)) - break; + break end y_old = y_new; end diff --git a/matlab/missing/stats/betarnd.m b/matlab/missing/stats/betarnd.m index f27fca441..a2d0c9fe8 100644 --- a/matlab/missing/stats/betarnd.m +++ b/matlab/missing/stats/betarnd.m @@ -1,19 +1,19 @@ 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 +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/missing/stats/corr.m b/matlab/missing/stats/corr.m index c862e1e67..ec2f719a1 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) @@ -39,7 +39,7 @@ function retval = corr(x, y) % --*-- Unitary tests --*-- % Copyright (C) 1993-1996 Kurt Hornik % Copyright (C) 1996-2015 John W. Eaton % Copyright (C) 2013-2015 Julien Bect -% Copyright (C) 2016 Dynare Team +% Copyright (C) 2016-2017 Dynare Team % % This file is part of Dynare. % @@ -82,14 +82,14 @@ if isscalar(x) if nargin==1 retval = NaN; else - retval = NaN(size(y)); + retval = NaN(size(y)); end - return; + return end if nargin==2 && isscalar(y) - retval = NaN(size(x')); - return; + retval = NaN(size(x')); + return end n = size (x, 1); diff --git a/matlab/missing/stats/exprnd.m b/matlab/missing/stats/exprnd.m index 65855db6e..b59daf904 100644 --- a/matlab/missing/stats/exprnd.m +++ b/matlab/missing/stats/exprnd.m @@ -2,22 +2,22 @@ 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 +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/missing/stats/gaminv.m b/matlab/missing/stats/gaminv.m index e879616c4..96c4a0a3f 100644 --- a/matlab/missing/stats/gaminv.m +++ b/matlab/missing/stats/gaminv.m @@ -76,7 +76,7 @@ if (any (k)) h = y_old - y_new; end if (max (abs (h)) < sqrt (eps)) - break; + break end y_old = y_new; end diff --git a/matlab/missing/stats/gamrnd.m b/matlab/missing/stats/gamrnd.m index b75b7868f..af2124753 100644 --- a/matlab/missing/stats/gamrnd.m +++ b/matlab/missing/stats/gamrnd.m @@ -1,19 +1,19 @@ 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 +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -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 54c77c3f9..a63baada0 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,9 +47,9 @@ 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) 2016 Dynare Team +% +% Copyright (C) 2014-2016 University of Surrey (Christopher Hummersone) +% Copyright (C) 2016-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/missing/stats/stdnormal_inv.m b/matlab/missing/stats/stdnormal_inv.m index bc52845a5..9859efde7 100644 --- a/matlab/missing/stats/stdnormal_inv.m +++ b/matlab/missing/stats/stdnormal_inv.m @@ -10,7 +10,7 @@ function inv = stdnormal_inv (x) % Copyright (C) 1995, 1996, 1997, 1998, 2000, 2002, 2005, 2006, 2007 % Kurt Hornik -% Copyright (C) 2008-2009 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -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 14b0fc8e8..6246a01cf 100644 --- a/matlab/missing/stats/wblcdf.m +++ b/matlab/missing/stats/wblcdf.m @@ -2,15 +2,15 @@ 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 +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -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 1b87c9fcb..363d51801 100644 --- a/matlab/missing/stats/wblinv.m +++ b/matlab/missing/stats/wblinv.m @@ -2,15 +2,15 @@ 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 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -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 2f55bc8b7..e2a6911d9 100644 --- a/matlab/missing/stats/wblrnd.m +++ b/matlab/missing/stats/wblrnd.m @@ -1,14 +1,14 @@ 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 +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/missing/struct2array/struct2array.m b/matlab/missing/struct2array/struct2array.m index b1c1370dd..92aaab35f 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 225c5f9ec..fd9e36b79 100644 --- a/matlab/missing/vec/vec.m +++ b/matlab/missing/vec/vec.m @@ -1,13 +1,13 @@ 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 +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/missing_DiffuseKalmanSmootherH1_Z.m b/matlab/missing_DiffuseKalmanSmootherH1_Z.m index 6595daf67..5ba614f94 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,20 +36,20 @@ 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 -% Copyright (C) 2004-2016 Dynare Team +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % @@ -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,7 +127,7 @@ while rank(Pinf(:,:,t+1),diffuse_kalman_tol) && td+1 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); + 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 diff --git a/matlab/missing_DiffuseKalmanSmootherH3_Z.m b/matlab/missing_DiffuseKalmanSmootherH3_Z.m index 665f28532..de40741fc 100644 --- a/matlab/missing_DiffuseKalmanSmootherH3_Z.m +++ b/matlab/missing_DiffuseKalmanSmootherH3_Z.m @@ -43,20 +43,20 @@ 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-2016 Dynare Team +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % @@ -78,7 +78,7 @@ 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 @@ -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) 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 kalman_tol a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t); %filtering according to (6.13) in DK (2012) @@ -216,17 +216,17 @@ while notsteady && t1 - 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) + 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)))) 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 @@ -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 bd003bd8e..2df26ff0c 100644 --- a/matlab/mode_check.m +++ b/matlab/mode_check.m @@ -58,13 +58,13 @@ function mode_check(fun,x,hessian_mat,DynareDataset,DatasetInfo,DynareOptions,Mo % along with Dynare. If not, see . TeX = DynareOptions.TeX; -if ~isempty(hessian_mat); +if ~isempty(hessian_mat) [ s_min, k ] = min(diag(hessian_mat)); end fval = feval(fun,x,DynareDataset,DatasetInfo,DynareOptions,Model,EstimatedParameters,BayesInfo,BoundsInfo,DynareResults); -if ~isempty(hessian_mat); +if ~isempty(hessian_mat) skipline() disp('MODE CHECK') skipline() @@ -85,13 +85,13 @@ if TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format))) end ll = DynareOptions.mode_check.neighbourhood_size; -if isinf(ll), +if isinf(ll) DynareOptions.mode_check.symmetric_plots = 0; end mcheck = struct('cross',struct(),'emode',struct()); -for plt = 1:nbplt, +for plt = 1:nbplt if TeX NAMES = []; TeXNAMES = []; @@ -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 @@ -134,7 +134,7 @@ for plt = 1:nbplt, z1 = l1:((x(kk)-l1)/(DynareOptions.mode_check.number_of_points/2)):x(kk); z2 = x(kk):((l2-x(kk))/(DynareOptions.mode_check.number_of_points/2)):l2; z = union(z1,z2); - if DynareOptions.mode_check.nolik==0, + if DynareOptions.mode_check.nolik==0 y = zeros(length(z),2); dy = priordens(xx,BayesInfo.pshape,BayesInfo.p6,BayesInfo.p7,BayesInfo.p3,BayesInfo.p4); end @@ -174,7 +174,7 @@ for plt = 1:nbplt, hold off drawnow end - if DynareOptions.mode_check.nolik==0, + if DynareOptions.mode_check.nolik==0 if isoctave axes('outerposition',[0.3 0.93 0.42 0.07],'box','on'), else diff --git a/matlab/model_comparison.m b/matlab/model_comparison.m index fd179b454..07935af6f 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 @@ -20,7 +20,7 @@ function oo = model_comparison(ModelNames,ModelPriors,oo,options_,fname) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2007-2015 Dynare Team +% Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. % @@ -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 5b4b4221e..673429115 100644 --- a/matlab/model_diagnostics.m +++ b/matlab/model_diagnostics.m @@ -1,22 +1,22 @@ 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-2013 Dynare Team +% Copyright (C) 1996-2017 Dynare Team % % This file is part of Dynare. % @@ -67,7 +67,7 @@ end info=test_for_deep_parameters_calibration(M); if info problem_dummy=1; -end; +end % check if ys is steady state options.debug=1; %locally set debug option to 1 @@ -83,7 +83,7 @@ if check1(1) if any(isinf(dr.ys)) disp(['MODEL_DIAGNOSTICS: Steady state contains Inf']) end - return; + return end if ~isreal(dr.ys) @@ -174,7 +174,7 @@ for b=1:nb end end -if singularity_problem +if singularity_problem try options_check=options; options_check.noprint=1; @@ -210,7 +210,7 @@ if ~options.block else [junk,jacobia_] = feval([M.fname '_dynamic'],z(iyr0),exo_simul, ... M.params, dr.ys, it_); - end; + end elseif options.order >= 2 if (options.bytecode) [chck, junk, loc_dr] = bytecode('dynamic','evaluate', z,exo_simul, ... @@ -220,14 +220,14 @@ if ~options.block [junk,jacobia_,hessian1] = feval([M.fname '_dynamic'],z(iyr0),... exo_simul, ... M.params, dr.ys, it_); - end; + 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)); 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 281bfa09a..e27779225 100644 --- a/matlab/model_info.m +++ b/matlab/model_info.m @@ -1,7 +1,7 @@ -function model_info(varargin); +function model_info(varargin) %function model_info; -% Copyright (C) 2008-2012 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -23,12 +23,12 @@ if sum(strcmp(varargin,'static')) > 0 static_ = 1; else static_ = 0; -end; +end if sum(strcmp(varargin,'incidence')) > 0 incidence = 1; else incidence = 0; -end; +end if static_ fprintf(' Informations about %s (static model)\n',M_.fname); block_structre_str = 'block_structure_stat'; @@ -37,13 +37,13 @@ else fprintf(' Informations about %s (dynamic model)\n',M_.fname); block_structre_str = 'block_structure'; nb_leadlag = 3; -end; +end if(isfield(M_,block_structre_str)) if static_ block_structure = M_.block_structure_stat; else block_structure = M_.block_structure; - end; + end fprintf(strcat(' ===================',char(ones(1,length(M_.fname))*'='),'\n\n')); nb_blocks=length(block_structure.block); fprintf('The model has %d equations and is decomposed in %d blocks as follow:\n',M_.endo_nbr,nb_blocks); @@ -54,15 +54,15 @@ if(isfield(M_,block_structre_str)) size_block=length(block_structure.block(i).equation); if(i>1) fprintf('|------------|------------|--------------------------------|----------------|---------------------------------|\n'); - end; + end for j=1:size_block if(j==1) fprintf('| %10d | %10d | %30s | %14d | %-6d %24s |\n',i,size_block,Sym_type(block_structure.block(i).Simulation_Type),block_structure.block(i).equation(j),block_structure.block(i).variable(j),M_.endo_names(block_structure.block(i).variable(j),:)); else fprintf('| %10s | %10s | %30s | %14d | %-6d %24s |\n','','','',block_structure.block(i).equation(j),block_structure.block(i).variable(j),M_.endo_names(block_structure.block(i).variable(j),:)); - end; - end; - end; + end + end + end fprintf('===============================================================================================================\n'); fprintf('\n'); if static_ @@ -71,16 +71,16 @@ if(isfield(M_,block_structre_str)) IM=sortrows(block_structure.incidence.sparse_IM,2); else IM=[]; - end; + end size_IM=size(IM,1); last=99999999; for i=1:size_IM if(last~=IM(i,2)) fprintf('\n%-30s',M_.endo_names(IM(i,2),:)); - end; + end fprintf(' %5d',IM(i,1)); last=IM(i,2); - end; + end fprintf('\n\n'); else for k=1:M_.maximum_endo_lag+M_.maximum_endo_lead+1 @@ -90,25 +90,25 @@ if(isfield(M_,block_structre_str)) fprintf('%-30s %s %d','the variable','is used in equations with lag ',M_.maximum_endo_lag+1-k); else fprintf('%-30s %s %d','the variable','is used in equations with lead ',k-(M_.maximum_endo_lag+1)); - end; + end if(size(block_structure.incidence(k).sparse_IM,1)>0) IM=sortrows(block_structure.incidence(k).sparse_IM,2); else IM=[]; - end; + end size_IM=size(IM,1); last=99999999; for i=1:size_IM if(last~=IM(i,2)) fprintf('\n%-30s',M_.endo_names(IM(i,2),:)); - end; + end fprintf(' %5d',IM(i,1)); last=IM(i,2); - end; + end fprintf('\n\n'); - end; - end; - + 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 @@ -118,9 +118,9 @@ if(isfield(M_,block_structre_str)) IM_star(block_structure.incidence(i).sparse_IM(j,1), 3 * (block_structure.incidence(i).sparse_IM(j,2) - 1) + 1) = 'X'; else IM_star(block_structure.incidence(i).sparse_IM(j,1), 3 * (block_structure.incidence(i).sparse_IM(j,2) - 1) + 1) = '1'; - end; - end; - end; + end + end + end seq = 1: M_.endo_nbr; blank = [ blanks(size(M_.endo_names,2)); blanks(size(M_.endo_names,2))]; for i = 1:M_.endo_nbr @@ -128,15 +128,15 @@ if(isfield(M_,block_structre_str)) var_names = [blank; M_.endo_names(i,:)]; else var_names = [var_names; blank; M_.endo_names(i,:)]; - end; - end; + end + end if incidence topp = [char(kron(double(blanks(ceil(log10(M_.endo_nbr)))),ones(size(M_.endo_names,2),1))) var_names' ]; bott = [int2str(seq') blanks(M_.endo_nbr)' blanks(M_.endo_nbr)' IM_star]; 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; @@ -145,9 +145,9 @@ if(isfield(M_,block_structre_str)) cur_block = 1; for i = 1:M_.endo_nbr past_block = cur_block; - while ismember(block_structure.variable_reordered(i), block_structure.block(cur_block).variable) == 0; + while ismember(block_structure.variable_reordered(i), block_structure.block(cur_block).variable) == 0 cur_block = cur_block + 1; - end; + end if i == 1 var_names = [blank; M_.endo_names(block_structure.variable_reordered(i),:)]; else @@ -156,8 +156,8 @@ if(isfield(M_,block_structre_str)) else var_names = [var_names; blank; M_.endo_names(block_structure.variable_reordered(i),:)]; end - end; - end; + end + end topp = [char(kron(double(blanks(ceil(log10(M_.endo_nbr)))),ones(size(M_.endo_names,2),1))) var_names' ]; n_state_var = length(M_.state_var); IM_state_var = zeros(n_state_var, n_state_var); @@ -172,49 +172,49 @@ if(isfield(M_,block_structre_str)) [tfi, loci] = ismember(block_structure.incidence(i).sparse_IM(j,1), state_equation); if tfi IM_state_var(loci, loc) = 1; - end; + end else IM_star_reordered(eq(block_structure.incidence(i).sparse_IM(j,1)), 3 * (va(block_structure.incidence(i).sparse_IM(j,2)) - 1) + 1) = '1'; - end; - end; - end; + end + end + end fprintf('1: non nul element, X: non nul element related to a state variable\n'); - + cur_block = 1; i_last = 0; block = {}; - for i = 1:n_state_var; + for i = 1:n_state_var past_block = cur_block; - while ismember(M_.state_var(i), block_structure.block(cur_block).variable) == 0; + while ismember(M_.state_var(i), block_structure.block(cur_block).variable) == 0 cur_block = cur_block + 1; - end; + end if (past_block ~= cur_block) || (past_block == cur_block && i == n_state_var) block(past_block).IM_state_var(1:(i - 1 - i_last), 1:i - 1) = IM_state_var(i_last+1:i - 1, 1:i - 1); i_last = i - 1; - end; - end; + end + end cur_block = 1; for i = 1:M_.endo_nbr past_block = cur_block; - while ismember(block_structure.variable_reordered(i), block_structure.block(cur_block).variable) == 0; + while ismember(block_structure.variable_reordered(i), block_structure.block(cur_block).variable) == 0 cur_block = cur_block + 1; - end; + end if past_block ~= cur_block for j = 1:i-1 IM_star_reordered(j, 3 * (i - 1) - 1) = '|'; - end; - end; + 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; +end function ret=Sym_type(type) UNKNOWN=0; @@ -229,33 +229,30 @@ SOLVE_TWO_BOUNDARIES_COMPLETE=8; EVALUATE_FORWARD_R=9; EVALUATE_BACKWARD_R=10; switch (type) - case (UNKNOWN), + case (UNKNOWN) ret='UNKNOWN '; - case {EVALUATE_FORWARD,EVALUATE_FORWARD_R}, + case {EVALUATE_FORWARD,EVALUATE_FORWARD_R} ret='EVALUATE FORWARD '; - case {EVALUATE_BACKWARD,EVALUATE_BACKWARD_R}, + case {EVALUATE_BACKWARD,EVALUATE_BACKWARD_R} ret='EVALUATE BACKWARD '; - case SOLVE_FORWARD_SIMPLE, + case SOLVE_FORWARD_SIMPLE ret='SOLVE FORWARD SIMPLE '; - case SOLVE_BACKWARD_SIMPLE, + case SOLVE_BACKWARD_SIMPLE ret='SOLVE BACKWARD SIMPLE '; - case SOLVE_TWO_BOUNDARIES_SIMPLE, + case SOLVE_TWO_BOUNDARIES_SIMPLE ret='SOLVE TWO BOUNDARIES SIMPLE '; - case SOLVE_FORWARD_COMPLETE, + case SOLVE_FORWARD_COMPLETE ret='SOLVE FORWARD COMPLETE '; - case SOLVE_BACKWARD_COMPLETE, + case SOLVE_BACKWARD_COMPLETE ret='SOLVE BACKWARD COMPLETE '; - case SOLVE_TWO_BOUNDARIES_COMPLETE, + case SOLVE_TWO_BOUNDARIES_COMPLETE ret='SOLVE TWO BOUNDARIES COMPLETE'; -end; +end function ret = barre(n) s = []; -for i=1:n; +for i=1:n s = [s '|']; -end; +end ret = s; - - - diff --git a/matlab/model_inversion.m b/matlab/model_inversion.m index 75594ecca..4d01412f9 100644 --- a/matlab/model_inversion.m +++ b/matlab/model_inversion.m @@ -2,18 +2,18 @@ function [endogenousvariables, exogenousvariables] = model_inversion(constraints 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/modules/reporting b/matlab/modules/reporting index af39a2c97..bc59736f5 160000 --- a/matlab/modules/reporting +++ b/matlab/modules/reporting @@ -1 +1 @@ -Subproject commit af39a2c97ea01de6a1451071e58d4fce8f4b9d03 +Subproject commit bc59736f5b50454cea925c99b98a757a0494f3e8 diff --git a/matlab/moment_function.m b/matlab/moment_function.m index af0488a59..fb42db9e8 100644 --- a/matlab/moment_function.m +++ b/matlab/moment_function.m @@ -3,19 +3,19 @@ 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. % % SPECIAL REQUIREMENTS % The user has to provide a file where the moment conditions are defined. -% Copyright (C) 2010-2012 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . +% along with Dynare. If not, see . global M_ options_ persistent mainStream mainState @@ -61,7 +61,7 @@ end if penalty>0 flag = 0; - return; + return end save('estimated_parameters.mat','xparams'); @@ -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 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 6bc0ea32e..40af07015 100644 --- a/matlab/multivariate_sample_autocovariance.m +++ b/matlab/multivariate_sample_autocovariance.m @@ -1,17 +1,17 @@ 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 -% Copyright (C) 2009 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/myboxplot.m b/matlab/myboxplot.m index fc54607e2..b3490a4b3 100644 --- a/matlab/myboxplot.m +++ b/matlab/myboxplot.m @@ -4,7 +4,7 @@ function sout = myboxplot (data,notched,symbol,vertical,maxwhisker) % sout = myboxplot (data,notched,symbol,vertical,maxwhisker) % -% Copyright (C) 2010-2011 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -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,12 +144,12 @@ 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)); MM=max(max(data)); -if isnan(mm), mm=0; MM=0; end, +if isnan(mm), mm=0; MM=0; end if vertical plot (quartile_x, quartile_y, 'b', ... @@ -171,7 +171,7 @@ else % % % % % outliers2_y, outliers2_x, [symbol(2),"r;;"]); end -if nargout, +if nargout sout=s; end % % % endfunction \ No newline at end of file diff --git a/matlab/mydelete.m b/matlab/mydelete.m index 13ef6ee9d..c28d5ad94 100644 --- a/matlab/mydelete.m +++ b/matlab/mydelete.m @@ -1,7 +1,7 @@ function mydelete(fname,pname) % Specialized version of delete() function -% Copyright (C) 2009 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -18,16 +18,16 @@ function mydelete(fname,pname) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see . -if nargin ==0, +if nargin ==0 disp('mydelete(fname)') return end -if nargin ==1, +if nargin ==1 pname=''; end file_to_delete = dir([pname,fname]); -for j=1:length(file_to_delete), +for j=1:length(file_to_delete) delete([pname,file_to_delete(j).name]); end diff --git a/matlab/name2index.m b/matlab/name2index.m index b653e71c6..22d116c79 100644 --- a/matlab/name2index.m +++ b/matlab/name2index.m @@ -2,21 +2,21 @@ 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]. % % SPECIAL REQUIREMENTS % none -% Copyright (C) 2008-2013 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -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 43574d4e9..1f56c3be4 100644 --- a/matlab/non_linear_dsge_likelihood.m +++ b/matlab/non_linear_dsge_likelihood.m @@ -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 d7a83c836..65b98c431 100755 --- a/matlab/occbin/call_solve_one_constraint.m +++ b/matlab/occbin/call_solve_one_constraint.m @@ -1,12 +1,12 @@ % Solve model, generate model IRFs -[zdatalinear zdatapiecewise zdatass oobase_ Mbase_ ] = ... +[zdatalinear, zdatapiecewise, zdatass, oobase_, Mbase_ ] = ... solve_one_constraint(modnam,modnamstar,... constraint, constraint_relax,... shockssequence,irfshock,nperiods,maxiter); -% unpack the IRFs +% 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);']); diff --git a/matlab/occbin/call_solve_two_constraints.m b/matlab/occbin/call_solve_two_constraints.m index 1b54718e5..5bbc1beb8 100755 --- a/matlab/occbin/call_solve_two_constraints.m +++ b/matlab/occbin/call_solve_two_constraints.m @@ -1,4 +1,4 @@ -[zdatalinear zdatapiecewise zdatass oobase_ Mbase_] = solve_two_constraints(... +[zdatalinear, zdatapiecewise, zdatass, oobase_, Mbase_] = solve_two_constraints(... modnam_00,modnam_10,modnam_01,modnam_11,... constraint1, constraint2,... constraint_relax1, constraint_relax2,... diff --git a/matlab/occbin/get_deriv.m b/matlab/occbin/get_deriv.m index 19fe87001..214b1cf42 100755 --- a/matlab/occbin/get_deriv.m +++ b/matlab/occbin/get_deriv.m @@ -13,11 +13,11 @@ if size(iy_,1)==3 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 + + % 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 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,:)); @@ -29,7 +29,7 @@ elseif size(iy_,1)==2 con_cols = find(iy_(2,:)); lea_cols = []; end - + end @@ -45,7 +45,7 @@ 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 + % 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_);']); @@ -77,7 +77,6 @@ for i=1:nlea_cols end -for i = 1:M_.exo_nbr; +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 6ef8c8ec7..99888b806 100755 --- a/matlab/occbin/get_pq.m +++ b/matlab/occbin/get_pq.m @@ -1,4 +1,4 @@ -function [p,q]=get_pq(dr_,nstatic,nfwrd); +function [p,q]=get_pq(dr_,nstatic,nfwrd) nvars = size(dr_.ghx,1); nshocks = size(dr_.ghu,2); @@ -21,8 +21,8 @@ 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)); + p_reordered(i,j)=p(inverse_order(i),inverse_order(j)); end - q(i,:)=dr_.ghu(inverse_order(i),:); + 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 496a136ba..934e8463b 100755 --- a/matlab/occbin/makechart.m +++ b/matlab/occbin/makechart.m @@ -22,7 +22,7 @@ nobs = size(zdata1,1); xvalues = (1:nobs)'; nvars = size(titlelist,1); -if nvars==1 +if nvars==1 nrows=1; ncols = 1; elseif nvars==2 @@ -40,7 +40,7 @@ elseif (nvars==7 | nvars==8) elseif (nvars==9 | nvars==10) nrows = 5; ncols = 2; -else +else error('too many variables (makechart)') end @@ -49,15 +49,15 @@ for i = 1:nvars 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)); + [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); @@ -66,13 +66,13 @@ for i = 1:nvars 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 diff --git a/matlab/occbin/makechart9.m b/matlab/occbin/makechart9.m index e87618959..264f9f58f 100755 --- a/matlab/occbin/makechart9.m +++ b/matlab/occbin/makechart9.m @@ -54,31 +54,31 @@ else end nvars = size(titlelist,1); -if nvars==1 +if nvars==1 nrows=1; ncols = 1; elseif nvars==2 nrows =2; ncols = 1; -elseif nvars == 3 +elseif nvars == 3 nrows = 3; ncols = 1; -elseif nvars==4 +elseif nvars==4 nrows = 2; ncols = 2; elseif (nvars==5 | nvars ==6) nrows = 3; - ncols = 2; + ncols = 2; elseif (nvars==7 | nvars==8) nrows = 4; ncols = 2; -elseif nvars>8 & nvars<=12; +elseif nvars>8 & nvars<=12 nrows = 3; ncols = 4; -elseif nvars>12 & nvars<=15; +elseif nvars>12 & nvars<=15 nrows = 5; ncols = 3; -else +else error('too many variables (makechart)') end @@ -92,20 +92,20 @@ for i = 1:nvars 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)); + [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 @@ -123,10 +123,10 @@ for i = 1:nvars 'FontSize',13,'FontWeight','bold','HorizontalAlignment','center'); end end - + %set(gca,'XTick',xtick) %set(gca,'XTickLabel',xticklabel) - + title(titlelist(i,:),'Fontsize',11); ylabel(ylabels(i,:)) diff --git a/matlab/occbin/map_regime.m b/matlab/occbin/map_regime.m index 64a87250e..1a8b8e796 100755 --- a/matlab/occbin/map_regime.m +++ b/matlab/occbin/map_regime.m @@ -1,4 +1,4 @@ -function [regime regimestart]=map_regime(violvecbool) +function [regime, regimestart]=map_regime(violvecbool) nperiods = length(violvecbool)-1; @@ -21,5 +21,4 @@ end if (regime(end)==1) warning('Increase nperiods'); -end - +endx \ No newline at end of file diff --git a/matlab/occbin/mkdata.m b/matlab/occbin/mkdata.m index 02b2eb703..f22fb45f6 100755 --- a/matlab/occbin/mkdata.m +++ b/matlab/occbin/mkdata.m @@ -2,7 +2,7 @@ function [zdata]=mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshoc %[nsim, ksim, ysim, isim, csim] = mkdata(nperiods,cofb,endog_) -% given decision rule +% given decision rule neqs = size(endog_,1); if nargin<9 diff --git a/matlab/occbin/mkdatap_anticipated.m b/matlab/occbin/mkdatap_anticipated.m index 6e745e0a4..a9c924966 100755 --- a/matlab/occbin/mkdatap_anticipated.m +++ b/matlab/occbin/mkdatap_anticipated.m @@ -12,7 +12,7 @@ if nargin<16 init=zeros(nvars,1); end -if nargin<15; +if nargin<15 scalefactormod=1; end @@ -48,21 +48,21 @@ Tmax = regimestart(nregimes)-1; % Tmax is the position of the last period 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; @@ -74,7 +74,7 @@ if Tmax > 0 end end - if Tmax > 1 + if Tmax > 1 if violvecbool(1) E = -invmat*Jstarbarmat; else @@ -86,7 +86,7 @@ if Tmax > 0 end - + end % generate data diff --git a/matlab/occbin/mkdatap_anticipated_2constraints.m b/matlab/occbin/mkdatap_anticipated_2constraints.m index c18cef2f9..496f5a931 100755 --- a/matlab/occbin/mkdatap_anticipated_2constraints.m +++ b/matlab/occbin/mkdatap_anticipated_2constraints.m @@ -16,7 +16,7 @@ if nargin<16 init=zeros(nvars,1); end -if nargin<15; +if nargin<15 scalefactormod=1; end @@ -63,17 +63,17 @@ Tmax = max([regimestart1(nregimes1) regimestart2(nregimes2)])-1; % Tmax is the 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; + D(:,Tmax) = -invmat*Dbarmat10; elseif (violvecbool(Tmax,1) & violvecbool(Tmax,2)) invmat = inv((Abarmat11*decrulea+Bbarmat11)); P(:,:,Tmax) = -invmat*Cbarmat11; @@ -81,14 +81,14 @@ if Tmax > 0 else invmat = inv((Abarmat01*decrulea+Bbarmat01)); P(:,:,Tmax) = -invmat*Cbarmat01; - D(:,Tmax) = -invmat*Dbarmat01; + D(:,Tmax) = -invmat*Dbarmat01; end - - - - - for i = Tmax-1:-1:1 - + + + + + for i = Tmax-1:-1:1 + if (violvecbool(i,1) & ~violvecbool(i,2)) invmat = inv(Bbarmat10+Abarmat10*P(:,:,i+1)); P(:,:,i)=-invmat*Cbarmat10; @@ -106,14 +106,14 @@ if Tmax > 0 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) ) @@ -123,26 +123,26 @@ if Tmax > 0 else E = -invmat*Jbarmat; end - - else % Tmax is equal to 1 + + 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; + E = -invmat*Jbarmat01; elseif ( violvecbool(1,1) & violvecbool(1,2) ) invmat = inv((Abarmat11*decrulea+Bbarmat11)); - E = -invmat*Jbarmat11; + E = -invmat*Jbarmat11; else invmat = inv((Abarmat10*decrulea+Bbarmat10)); E = -invmat*Jbarmat10; - + end - + end - + end % generate data diff --git a/matlab/occbin/pickaxes.m b/matlab/occbin/pickaxes.m index c2e2d5e0d..26c9b6b1a 100755 --- a/matlab/occbin/pickaxes.m +++ b/matlab/occbin/pickaxes.m @@ -9,7 +9,7 @@ miny = min(yvalues); y0 = miny - .05*abs(miny); -if (miny>0 & y0<0) +if (miny>0 & y0<0) y0 = 0; end diff --git a/matlab/occbin/process_constraint.m b/matlab/occbin/process_constraint.m index 0573eb641..2d2b35f36 100755 --- a/matlab/occbin/process_constraint.m +++ b/matlab/occbin/process_constraint.m @@ -22,7 +22,7 @@ for i=1:ntokens % suffix tokens(i) = cellstr([char(tokens(i)),suffix]); end - + % if the invert_switch is true % reverse the direction of the inequality if invert_switch diff --git a/matlab/occbin/setss.m b/matlab/occbin/setss.m index 39e269d51..8d2e71763 100755 --- a/matlab/occbin/setss.m +++ b/matlab/occbin/setss.m @@ -10,5 +10,4 @@ nparams = size(Mbase_.param_names); for i = 1:nparams eval([Mbase_.param_names(i,:),'= M_.params(i);']); -end - +end \ No newline at end of file diff --git a/matlab/occbin/solve_no_constraint.m b/matlab/occbin/solve_no_constraint.m index d4f61a3f4..169c74ebd 100755 --- a/matlab/occbin/solve_no_constraint.m +++ b/matlab/occbin/solve_no_constraint.m @@ -46,5 +46,4 @@ wishlist = endog_; nwishes = size(wishlist,1); -zdata_ = mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,shockssequence); - +zdata_ = mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,shockssequence); \ No newline at end of file diff --git a/matlab/occbin/solve_no_constraint_noclear.m b/matlab/occbin/solve_no_constraint_noclear.m index b899708e2..8012f9126 100755 --- a/matlab/occbin/solve_no_constraint_noclear.m +++ b/matlab/occbin/solve_no_constraint_noclear.m @@ -1,6 +1,6 @@ -function [zdata oobase_ Mbase_ ] = ... +function [zdata, oobase_, Mbase_ ] = ... solve_no_constraint_noclear(modnam,... - shockssequence,irfshock,nperiods); + shockssequence,irfshock,nperiods) global M_ oo_ @@ -45,4 +45,3 @@ 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 344e85f5a..aa155c234 100755 --- a/matlab/occbin/solve_one_constraint.1.m +++ b/matlab/occbin/solve_one_constraint.1.m @@ -1,11 +1,11 @@ % solve_one_constraint [zdatalinear zdatapiecewise zdatass oo base M base] = solve one constraint(modnam, modnamstar, constraint, constraint relax, shockssequence, irfshock, nperiods, maxiter, init); -% -% Inputs: +% +% 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). +% 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). @@ -115,7 +115,7 @@ if ~exist('nperiods_') end -% set some initial conditions and loop through the shocks +% set some initial conditions and loop through the shocks % period by period init_orig_ = init_; zdatapiecewise_ = zeros(nperiods_,nvars_); @@ -125,35 +125,35 @@ violvecbool_ = zeros(nperiods_+1,1); for ishock_ = 1:nshocks_ - + changes_=1; iter_ = 0; - - + + while (changes_ & iter_0)) | sum(relaxconstraint_(find(violvecbool_==1))>0) @@ -161,24 +161,24 @@ for ishock_ = 1:nshocks_ 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 + + % 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 +% 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,:); diff --git a/matlab/occbin/solve_one_constraint.m b/matlab/occbin/solve_one_constraint.m index ee59e9a3d..5959636bf 100755 --- a/matlab/occbin/solve_one_constraint.m +++ b/matlab/occbin/solve_one_constraint.m @@ -1,11 +1,11 @@ % solve_one_constraint [zdatalinear zdatapiecewise zdatass oo base M base] = solve one constraint(modnam, modnamstar, constraint, constraint relax, shockssequence, irfshock, nperiods, maxiter, init); -% -% Inputs: +% +% 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). +% 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). @@ -24,7 +24,7 @@ % 6/17/2013 -- Luca replaced external .m file setss.m -function [zdatalinear_ zdatapiecewise_ zdatass_ oobase_ Mbase_ ] = ... +function [zdatalinear_, zdatapiecewise_, zdatass_, oobase_, Mbase_ ] = ... solve_one_constraint(modnam_,modnamstar_,... constraint_, constraint_relax_,... shockssequence_,irfshock_,nperiods_,maxiter_,init_) @@ -121,7 +121,7 @@ if ~exist('nperiods_') end -% set some initial conditions and loop through the shocks +% set some initial conditions and loop through the shocks % period by period init_orig_ = init_; zdatapiecewise_ = zeros(nperiods_,nvars_); @@ -131,36 +131,36 @@ violvecbool_ = zeros(nperiods_+1,1); for ishock_ = 1:nshocks_ - + changes_=1; iter_ = 0; - - + + while (changes_ & iter_0)) | sum(relaxconstraint_(find(violvecbool_==1))>0) @@ -168,25 +168,25 @@ for ishock_ = 1:nshocks_ 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 + + % 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 +% 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,:); diff --git a/matlab/occbin/solve_two_constraints.m b/matlab/occbin/solve_two_constraints.m index 0ca5d559a..775adc30a 100755 --- a/matlab/occbin/solve_two_constraints.m +++ b/matlab/occbin/solve_two_constraints.m @@ -1,5 +1,5 @@ % [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. @@ -29,7 +29,7 @@ % to be processed. % 6/17/2013 -- Luca replaced external .m file setss.m -function [ zdatalinear_ zdatapiecewise_ zdatass_ oo00_ M00_ ] = ... +function [ zdatalinear_, zdatapiecewise_, zdatass_, oo00_ , M00_ ] = ... solve_two_constraints(modnam_00_,modnam_10_,modnam_01_,modnam_11_,... constrain1_, constrain2_,... constraint_relax1_, constraint_relax2_,... @@ -140,7 +140,7 @@ 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); + [decrulea,decruleb]=get_pq(oo00_.dr,oo00_.dr.nstatic,oo00_.dr.nfwrd); end endog_ = M00_.endo_names; exog_ = M00_.exo_names; @@ -210,20 +210,20 @@ violvecbool_ = zeros(nperiods_+1,2); % This sets the first guess for when wishlist_ = endog_; nwishes_ = size(wishlist_,1); for ishock_ = 1:nshocks - - + + changes_=1; iter_ = 0; - + while (changes_ & iter_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 @@ -278,28 +278,27 @@ for ishock_ = 1:nshocks 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_ = mkdata(nperiods_,decrulea,decruleb,endog_,exog_,wishlist_,irfshock_,shockssequence_,init_orig_); \ No newline at end of file diff --git a/matlab/occbin/tokenize.m b/matlab/occbin/tokenize.m index 257be9131..1789d095a 100755 --- a/matlab/occbin/tokenize.m +++ b/matlab/occbin/tokenize.m @@ -28,7 +28,7 @@ else ndelims = length(posdelims); % build positions for substrings delims = zeros(ndelims+1,2); - for i=1:ndelims+1; + for i=1:ndelims+1 if i==1 if posdelims(1) == 1 tokens = cellstr(source(1)); @@ -51,5 +51,4 @@ else end end -end - +end \ No newline at end of file diff --git a/matlab/octave_ver_less_than.m b/matlab/octave_ver_less_than.m index 9d702d597..3c1a6a6a0 100644 --- a/matlab/octave_ver_less_than.m +++ b/matlab/octave_ver_less_than.m @@ -8,14 +8,14 @@ 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 % % SPECIAL REQUIREMENTS % none -% Copyright (C) 2008-2011 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/one_sided_hp_filter.m b/matlab/one_sided_hp_filter.m index 46fed2343..9715a3351 100644 --- a/matlab/one_sided_hp_filter.m +++ b/matlab/one_sided_hp_filter.m @@ -32,13 +32,13 @@ 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'. % Copyright (C) 200?-2015 Alexander Meyer-Gohde -% Copyright (C) 2015 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -66,23 +66,23 @@ F=[2,-1; 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 9f16e4466..2d79f0489 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 at a % point used in solveopt -% +% % Inputs: % x: point at which to evaluate gradient % f: calculated function value at a point x; @@ -14,10 +14,10 @@ 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 +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -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; @@ -51,7 +51,7 @@ for i=1:n y(i)=x(i)+di(i); fi=feval(fun,y,varargin{:}); if obj - if fi==f, + if fi==f for j=1:3 di(i)=di(i)*10; y(i)=x(i)+di(i); fi=feval(fun,y,varargin{:}); diff --git a/matlab/optimization/bfgsi1.m b/matlab/optimization/bfgsi1.m index 696ee410b..7a76a89b2 100644 --- a/matlab/optimization/bfgsi1.m +++ b/matlab/optimization/bfgsi1.m @@ -1,22 +1,22 @@ 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 +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/optimization/cmaes.m b/matlab/optimization/cmaes.m index b4790786a..2ead9b50e 100644 --- a/matlab/optimization/cmaes.m +++ b/matlab/optimization/cmaes.m @@ -9,26 +9,26 @@ function [xmin, ... % minimum search point of last iteration 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 + 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 + % 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 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. + % 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: + % 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 @@ -59,7 +59,7 @@ function [xmin, ... % minimum search point of last iteration % 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. + % (==size(X0,1)) and 'popsize' to the population size. % % [XMIN, FMIN, COUNTEVAL, STOPFLAG, OUT, BESTEVER] = ... % CMAES(FITFUN, X0, SIGMA) @@ -74,9 +74,9 @@ function [xmin, ... % minimum search point of last iteration % '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. + % 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 @@ -84,7 +84,7 @@ function [xmin, ... % minimum search point of last iteration % 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 @@ -96,30 +96,30 @@ function [xmin, ... % minimum search point of last iteration % % To find the best ever evaluated point load the variables typing % "es=load('variablescmaes')" and investigate the variable - % es.out.solutions.bestever. + % es.out.solutions.bestever. % % In case of a noisy objective function (uncertainties) set - % OPTS.Noise.on = 1. This option interferes presumably with some + % 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. + % 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. + % 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. + % 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 @@ -135,7 +135,7 @@ function [xmin, ... % minimum search point of last iteration % program, all others including MaxIter invoke another restart, where % the iteration counter is reset to zero. % - % Examples: + % 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 @@ -143,22 +143,22 @@ function [xmin, ... % minimum search point of last iteration % 'myfun' is a name of a function that returns a scalar from a 10D % column vector. % - % opts.LBounds = 0; opts.UBounds = 10; + % 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. + % 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); + % + % [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 +% Copyright (C) 2001-2012 Nikolaus Hansen, +% Copyright (C) 2012-2017 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 . -cmaVersion = '3.60.beta'; +cmaVersion = '3.60.beta'; % ----------- Set Defaults for Input Parameters and Options ------------- % These defaults may be edited for convenience @@ -197,47 +197,47 @@ 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'; +% 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 +if flg_future_setting disp('in the future') % damps setting from Brockhoff et al 2010 @@ -247,29 +247,29 @@ if flg_future_setting % 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!? + % 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'; @@ -283,20 +283,20 @@ if nargin < 1 || isequal(fitfun, 'defaults') % pass default options if nargin > 1 % supplement second argument with default options xmin = getoptions(xstart, defopts); end - return; + return end if isequal(fitfun, 'displayoptions') - names = fieldnames(defopts); + names = fieldnames(defopts); for name = names' - disp([name{:} repmat(' ', 1, 20-length(name{:})) ': ''' defopts.(name{:}) '''']); + disp([name{:} repmat(' ', 1, 20-length(name{:})) ': ''' defopts.(name{:}) '''']); end - return; + return end input.fitfun = fitfun; % record used input if isempty(fitfun) - % fitfun = definput.fitfun; + % fitfun = definput.fitfun; % warning(['Objective function not determined, ''' fitfun ''' used']); error(['Objective function not determined']); end @@ -305,7 +305,7 @@ if ~ischar(fitfun) end -if nargin < 2 +if nargin < 2 xstart = []; end @@ -316,7 +316,7 @@ if isempty(xstart) error('Initial search point, and problem dimension, not determined'); end -if nargin < 3 +if nargin < 3 insigma = []; end if isa(insigma, 'struct') @@ -326,7 +326,7 @@ end input.sigma = insigma; if isempty(insigma) if all(size(myeval(xstart)) > 1) - insigma = std(xstart, 0, 2); + insigma = std(xstart, 0, 2); if any(insigma == 0) error(['Initial search volume is zero, choose SIGMA or X0 appropriate']); end @@ -338,7 +338,7 @@ end % Compose options opts if nargin < 4 || isempty(inopts) % no input options available - inopts = []; + inopts = []; opts = defopts; else opts = getoptions(inopts, defopts); @@ -348,59 +348,59 @@ if ~isempty(i) 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; + irun = irun + 1; % ------------------------ Initialization ------------------------------- % Handle resuming of old run flgresume = myevalbool(opts.Resume); - xmean = myeval(xstart); + 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 + 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)); + 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]) + 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'); + 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); + load(opts.SaveFilename); varargin = local.varargin; flgresume = 1; % Overwrite old stopping and display options - opts.StopFitness = local.opts.StopFitness; + 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.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.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; @@ -409,38 +409,38 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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); + 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); + 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); + 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); + 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') + if strfind(opts.SaveVariables, '-v6') i = strfind(opts.SaveVariables, '%'); if isempty(i) || i == 0 || strfind(opts.SaveVariables, '-v6') < i strsaving = '-v6'; @@ -464,7 +464,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume opts.LogFilenamePrefix = opts.LogFilenamePrefix(1:i(1)-1); end - % TODO here silent option? set disp, save and log options to 0 + % TODO here silent option? set disp, save and log options to 0 %-------------------------------------------------------------- @@ -473,27 +473,27 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume end - % Do more checking and initialization + % Do more checking and initialization if flgresume % resume is on time.t0 = clock; if flgdisplay - disp([' resumed from ' opts.SaveFilename ]); + disp([' resumed from ' opts.SaveFilename ]); end - if counteval >= stopMaxFunEvals + if counteval >= stopMaxFunEvals error(['MaxFunEvals exceeded, use StopFunEvals as stopping ' ... 'criterion before resume']); end - if countiter >= stopMaxIter + 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 + mindx = myeval(opts.DiffMinChange); % minimal sensible variable change % can both also be defined as Nx1 vectors - lbounds = myeval(opts.LBounds); + lbounds = myeval(opts.LBounds); ubounds = myeval(opts.UBounds); if length(lbounds) == 1 lbounds = repmat(lbounds, N, 1); @@ -540,9 +540,9 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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) + if any(insigma <= 0) error(['Initial search volume (SIGMA) must be greater than zero']); end if max(insigma)/min(insigma) > 1e6 @@ -555,14 +555,14 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume insigma = insigma * ones(N,1) ; end diagD = insigma/max(insigma); % diagonal matrix D defines the scaling - diagC = diagD.^2; + 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; + B = 1; end fitness.hist=NaN*ones(1,10+ceil(3*10*N/lambda)); % history of fitness values @@ -571,30 +571,30 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume fitness.histmedian=[]; % history of fitness values % Initialize boundary handling - bnd.isactive = any(lbounds > -Inf) || any(ubounds < Inf); + 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 + [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.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; + bnd.isbounded(find(idx)) = 1; maxdx = min(maxdx, (ubounds - lbounds)/2); if any(sigma*sqrt(diagC) > maxdx) fac = min(maxdx ./ sqrt(diagC))/sigma; @@ -611,7 +611,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume '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 ' ... + 'each coordinate. If all coordinates have ' ... 'lower and upper bounds SIGMA can be empty']); end bnd.dfithist = 1; % delta fit for setting weights @@ -622,27 +622,27 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume end % ooo initial feval, for output only - if irun == 1 + 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.hist(1)=feval(fitfun, xmean, varargin{:}); fitness.histsel(1)=fitness.hist(1); counteval = counteval + 1; - if fitness.hist(1) < out.solutions.bestever.f + 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; + 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 @@ -656,22 +656,22 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume % 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 + 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? + + % 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; + % Write headers to output data files + filenameprefix = opts.LogFilenamePrefix; if savemodulo && savetime filenames = {}; filenames(end+1) = {'axlen'}; @@ -685,7 +685,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume name = namecell{:}; [fid, err] = fopen(['./' filenameprefix name '.dat'], 'w'); - if fid < 1 % err ~= 0 + if fid < 1 % err ~= 0 warning(['could not open ' filenameprefix name '.dat']); filenames(find(strcmp(filenames,name))) = []; else @@ -719,20 +719,20 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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, '%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'); + fprintf(fid, '\n'); end - fclose(fid); - clear fid; % preventing + fclose(fid); + clear fid; % preventing end end % for files end % savemodulo end % irun == 1 - - end % else flgresume + + end % else flgresume % -------------------- Generation Loop -------------------------------- stopflag = {}; @@ -744,15 +744,15 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume disp([' lambda = ' num2str(lambda)]); lambda_hist(:,end+1) = [countiter+1; lambda]; else - lambda_hist = [countiter+1; lambda]; + lambda_hist = [countiter+1; lambda]; end lambda_last = lambda; - % Strategy internal parameter setting: Selection + % 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)'; + 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 @@ -767,50 +767,50 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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); + 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)); + % + (1-1/mucov) * min(1,(2*mucov-1)/((N+2)^2+mucov)); % new way - if myevalbool(opts.CMA.on) - ccov1 = myeval(opts.CMA.ccov1); + 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; + 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); + 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 + %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); + % 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); + 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 @@ -818,25 +818,25 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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. + % 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 + end % Display initial message - if countiter == 0 && flgdisplay + if countiter == 0 && flgdisplay if mu == 1 strw = '100'; elseif mu < 8 - strw = [sprintf('%.0f', 100*weights(1)) ... + 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)') ']%, ']; + sprintf(' %.2g', 100*weights(end-1:end)') ']%, ']; end if irun > 1 strrun = [', run ' num2str(irun)]; @@ -858,10 +858,10 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume flush; - countiter = countiter + 1; + countiter = countiter + 1; % Generate and evaluate lambda offspring - + fitness.raw = repmat(NaN, 1, lambda + noiseReevals); % parallel evaluation @@ -871,20 +871,20 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume if ~flgDiagonalOnly arx = repmat(xmean, 1, lambda) + sigma * (BD * arz); % Eq. (1) else - arx = repmat(xmean, 1, lambda) + repmat(sigma * diagD, 1, lambda) .* arz; + arx = repmat(xmean, 1, lambda) + repmat(sigma * diagD, 1, lambda) .* arz; end - if noiseHandling + if noiseHandling if noiseEpsilon == 0 - arx = [arx arx(:,1:noiseReevals)]; + arx = [arx arx(:,1:noiseReevals)]; elseif flgDiagonalOnly arx = [arx arx(:,1:noiseReevals) + ... repmat(noiseEpsilon * sigma * diagD, 1, noiseReevals) ... - .* randn(N,noiseReevals)]; - else + .* randn(N,noiseReevals)]; + else arx = [arx arx(:,1:noiseReevals) + ... noiseEpsilon * sigma * ... - (BD * randn(N,noiseReevals))]; + (BD * randn(N,noiseReevals))]; end end @@ -893,7 +893,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume % (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 @@ -902,41 +902,41 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume % 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{:}); + fitness.raw = feval(fitfun, arxvalid, varargin{:}); countevalNaN = countevalNaN + sum(isnan(fitness.raw)); - counteval = counteval + 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; + 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 + 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 + 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 @@ -945,7 +945,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume % 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{:}); + fitness.raw(k) = feval(fitfun, arxvalid(:,k), varargin{:}); tries = tries + 1; if isnan(fitness.raw(k)) countevalNaN = countevalNaN + 1; @@ -959,7 +959,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume counteval = counteval + 1; % retries due to NaN are not counted end - fitness.sel = fitness.raw; + fitness.sel = fitness.raw; % ----- handle boundaries ----- if 1 < 3 && bnd.isactive @@ -969,10 +969,10 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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 + % Catch non-sensible values if ~isfinite(val) warning('Non-finite fitness range'); - val = max(bnd.dfithist); + 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 @@ -987,17 +987,17 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume bnd.dfithist = [bnd.dfithist(2:end) val]; end - [tx ti] = xintobounds(xmean, lbounds, ubounds); + [tx, ti] = xintobounds(xmean, lbounds, ubounds); % Set initial weights - if bnd.iniphase - if any(ti) + 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 = diagC; + idx = find(bnd.isbounded); dd = dd(idx) / mean(dd); % remove mean scaling - bnd.weights(idx) = bnd.weights(idx) ./ dd; + bnd.weights(idx) = bnd.weights(idx) ./ dd; end if bnd.validfitval && countiter > 2 bnd.iniphase = 0; @@ -1009,40 +1009,40 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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) ... + 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); + 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)))); + 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; + 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 + if noiseHandling [noiseS] = local_noisemeasurement(fitness.sel(1:lambda), ... fitness.sel(lambda+(1:noiseReevals)), ... - noiseReevals, noiseTheta, noiseCutOff); + 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); + noiseSS = noiseSS + noisecum * (noiseS - noiseSS); % noise-handling could be done here, but the original sigma is still needed % disp([noiseS noiseSS noisecum]) @@ -1050,19 +1050,19 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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 + 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); + (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); + + % 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 @@ -1071,17 +1071,17 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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(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 + % 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; + 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); @@ -1090,7 +1090,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume % 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); @@ -1112,7 +1112,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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 + 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)); @@ -1120,37 +1120,37 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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 + % "active" CMA update: negative update, in case controlling pos. definiteness if flgActiveCMA > 0 % set parameters - neg.mu = mu; + neg.mu = mu; neg.mueff = mueff; if flgActiveCMA > 10 % flat weights with mu=lambda/2 - neg.mu = floor(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. + % 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? + % 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; + % 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 @@ -1158,7 +1158,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume % 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) + 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; @@ -1172,14 +1172,14 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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 + % 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: + % 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]), ... @@ -1187,22 +1187,22 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume % 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); + 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!? + % 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 + 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 + 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'); @@ -1212,12 +1212,12 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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 + if 11 < 2 && ~flgscience % remove momentum in ps, if ps is large and fitness is getting worse. - % this should rarely happen. + % 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)) @@ -1238,7 +1238,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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|| ******************'); @@ -1248,23 +1248,23 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume % 75e3 with def (1.5) % 35e3 with damps=0.25 end - if 11 < 3 + 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); + diagD = diag(tmp); if any(~isfinite(diagD)) - clear idx; % prevents error under octave + clear idx; % prevents error under octave save(['tmp' opts.SaveFilename]); error(['function eig returned non-finited eigenvalues, cond(C)=' ... num2str(cond(C)) ]); @@ -1285,21 +1285,21 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume ': Eigenvalue (smaller) zero']); diagD(diagD<0) = 0; tmp = max(diagD)/1e14; - C = C + tmp*eye(N,N); diagD = diagD + tmp*ones(N,1); + C = C + tmp*eye(N,N); diagD = diagD + tmp*ones(N,1); end end - if max(diagD) > 1e14*min(diagD) + 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); + C = C + tmp*eye(N,N); diagD = diagD + tmp*ones(N,1); end end - diagC = diag(C); + 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) @@ -1311,23 +1311,23 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume fac = sigma / max(diagD); sigma = sigma/fac; pc = fac * pc; - diagD = fac * diagD; + 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; + diagC = fac^2 * diagC; end - if flgDiagonalOnly > 1 && countiter > flgDiagonalOnly - % full covariance matrix from now on - flgDiagonalOnly = 0; + 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 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 @@ -1342,18 +1342,18 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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? + 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 + % 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; + + sigma = sigma * noiseAlpha; % lambda = ceil(0.1 * sqrt(lambda) + lambda); % TODO: find smallest increase of lambda with log-linear % convergence in iterations @@ -1361,9 +1361,9 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume % qqq experimental: take a mean to estimate the true optimum noiseN = noiseN + 1; if noiseN == 1 - noiseX = xmean; + noiseX = xmean; else - noiseX = noiseX + (3/noiseN) * (xmean - noiseX); + noiseX = noiseX + (3/noiseN) * (xmean - noiseX); end end end @@ -1378,13 +1378,13 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume end % Adjust minimal coordinate axis deviations if any(sigma*sqrt(diagC) < mindx) - sigma = max(mindx ./ sqrt(diagC)) * exp(0.05+cs/damps); + 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 any(xmean == xmean + 0.2*sigma*sqrt(diagC)) if stopOnWarnings stopflag(end+1) = {'warnnoeffectcoord'}; else @@ -1397,12 +1397,12 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume C = C + (ccov1+ccovmu) * diag(diagC .* ... (xmean == xmean + 0.2*sigma*sqrt(diagC))); end - sigma = sigma * exp(0.05+cs/damps); + sigma = sigma * exp(0.05+cs/damps); end end - % Adjust step size in case of (numerical) precision problem + % Adjust step size in case of (numerical) precision problem if flgDiagonalOnly - tmp = 0.1*sigma*diagD; + tmp = 0.1*sigma*diagD; else tmp = 0.1*sigma*BD(:,1+floor(mod(countiter,N))); end @@ -1414,18 +1414,18 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume warning(['Iteration ' num2str(countiter) ... ': main axis standard deviation ' ... num2str(sigma*diagD(i)) ' has no effect' ]); - sigma = sigma * exp(0.2+cs/damps); + sigma = sigma * exp(0.2+cs/damps); end end % Adjust step size in case of equal function values (flat fitness) - % isequalfuncvalues = 0; + % isequalfuncvalues = 0; if fitness.sel(1) == fitness.sel(1+ceil(0.1+lambda/4)) - % isequalfuncvalues = 1; + % 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'}; + stopflag(end+1) = {'equalfunvals'}; end else if flgWarnOnEqualFunctionValues @@ -1434,23 +1434,23 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume ' at maximal main axis sigma ' ... num2str(sigma*max(diagD))]); end - sigma = sigma * exp(0.2+cs/damps); + 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 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); + sigma = sigma * exp(0.2+cs/damps); end end - + % ----- end numerical error management ----- - + % Keep overall best solution out.evals = counteval; out.solutions.evals = counteval; @@ -1474,25 +1474,25 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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) + if all(sigma*(max(abs(pc), sqrt(diagC))) < stopTolX) stopflag(end+1) = {'tolx'}; end - if any(sigma*sqrt(diagC) > stopTolUpX) + 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 + if countiter > 2 && myrange([fitness.sel fitness.hist]) <= stopTolFun stopflag(end+1) = {'tolfun'}; end - if countiter >= length(fitness.hist) && myrange(fitness.hist) <= stopTolHistFun + 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 && ... + 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'}; @@ -1504,19 +1504,19 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume error('To resume later the saving option needs to be set'); end end - % read stopping message from file signals.par + % read stopping message from file signals.par if flgreadsignals - fid = fopen('./signals.par', 'rt'); % can be performance critical + 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; + break end % 'stop filename' sets stopflag to manual str = sscanf(strline, ' %s %s', 2); - if strcmp(str, ['stop' opts.LogFilenamePrefix]) + if strcmp(str, ['stop' opts.LogFilenamePrefix]) stopflag(end+1) = {'manual'}; - break; + break end % 'skip filename run 3' skips a run, but not the last str = sscanf(strline, ' %s %s %s', 3); @@ -1524,29 +1524,29 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume i = strfind(strline, 'run'); if irun == sscanf(strline(i+3:end), ' %d ', 1) && irun <= myeval(opts.Restarts) stopflag(end+1) = {'skipped'}; - end + end end - end % while, break + 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 + if countiter == 1 || mod(countiter, 10*verbosemodulo) < 1 disp(['Iterat, #Fevals: Function Value (median,worst) ' ... '|Axis Ratio|' ... - 'idx:Min SD idx:Max SD']); + '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)); + [minstd, minstdidx] = min(sigma*sqrt(diagC)); + [maxstd, maxstdidx] = max(sigma*sqrt(diagC)); % format display nicely disp([repmat(' ',1,4-floor(log10(countiter))) ... num2str(countiter) ' , ' ... @@ -1565,7 +1565,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume end % measure time for recording data - if countiter < 3 + if countiter < 3 time.c = 0.05; time.nonoutput = 0; time.recording = 0; @@ -1573,93 +1573,93 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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 = 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.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 + outiter = countiter; + % Save output data to files for namecell = filenames(:)' name = namecell{:}; [fid, err] = fopen(['./' filenameprefix name '.dat'], 'a'); - if fid < 1 % err ~= 0 + 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)); + 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)); + 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 + 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, '%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); + fprintf(fid, '%ld %ld 0 0 0 ', countiter, counteval); else - fprintf(fid, '%ld %ld 0 0 %e ', countiter, counteval, fmean); + fprintf(fid, '%ld %ld 0 0 %e ', countiter, counteval, fmean); end - fprintf(fid, '%e ', xmean); + 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, '%ld %ld %25.18e 0 0 ', countiter, counteval, fitness.raw(1)); + fprintf(fid, '%e ', arx(:,fitness.idx(1))); fprintf(fid, '\n'); end - fclose(fid); + 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)); - + 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) || ... + if ~isempty(stopflag) || ... ((time.nonoutput+time.recording) * (countiter - iterplotted) > 1 && ... time.plotting < 0.05 * (time.nonoutput+time.recording)) local_plotcmaesdat(324, filenameprefix); - iterplotted = countiter; + 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)); + 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 + time.recording > savetime * (time.nonoutput+time.recording) / 100 savemodulo = floor(1.1 * savemodulo) + 1; % disp('++savemodulo'); %qqq end @@ -1674,11 +1674,11 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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', 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)); + time.saving = time.saving + time.c * max(0,etime(clock, time.t3)); end end time.t0 = clock; @@ -1703,7 +1703,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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); + out.solutions.bestever.x = xintobounds(xmean, lbounds, ubounds); bestever = out.solutions.bestever; end end @@ -1712,8 +1712,8 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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', strsaving, opts.SaveFilename); % for inspection and possible restart + else save('-mat', opts.SaveFilename); % for inspection and possible restart end message = [' (saved to ' opts.SaveFilename ')']; @@ -1725,7 +1725,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume disp(['#Fevals: f(returned x) | bestever.f | stopflag' ... message]); if isoctave - strstop = stopflag(:); + strstop = stopflag(:); else strcat(stopflag(:), '.'); end @@ -1739,8 +1739,8 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume 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]); + if exist('sfile', 'var') + disp(['Results saved in ' sfile]); end end @@ -1749,12 +1749,12 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume || any(strcmp(stopflag, 'maxfunevals')) ... || any(strcmp(stopflag, 'stoptoresume')) ... || any(strcmp(stopflag, 'manual')) - break; + 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 @@ -1783,10 +1783,10 @@ if ~isempty(ubounds) else idx2 = 0; end -idx = idx2-idx; +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,40 +1823,40 @@ 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; + return elseif isempty(inopts) % empty inopts invoke default options opts = defopts; - return; + return elseif ~isstruct(defopts) % handle a single option value - if isempty(inopts) + 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(inopts) % no valid input options error('The options need to be a struct or empty'); end -opts = defopts; % start from defopts +opts = defopts; % start from defopts % if necessary overwrite opts fields by inopts values defnames = fieldnames(defopts); idxmatched = []; % indices of defopts that already matched @@ -1875,7 +1875,7 @@ for name = fieldnames(inopts)' ''') to remove the field from the struct.']); end if sum(idx) == 1 - defname = defnames{find(idx)}; + defname = defnames{find(idx)}; if ismember(find(idx), idxmatched) error(['input options match more than ones with "' ... defname '". ' ... @@ -1888,26 +1888,26 @@ for name = fieldnames(inopts)' % 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 + 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)']); + % 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); + % opts.(defname) = inopts.(name); end else warning(['option "' name '" disregarded (unknown field name)']); end end -% --------------------------------------------------------------- -% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- function res=myeval(s) if ischar(s) res = evalin('caller', s); @@ -1915,8 +1915,8 @@ else res = s; end -% --------------------------------------------------------------- -% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- function res=myevalbool(s) if ~ischar(s) % s may not and cannot be empty res = s; @@ -1938,8 +1938,8 @@ else % evaluation string s end -% --------------------------------------------------------------- -% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- function res = isoctave % any hack to find out whether we are running octave s = version; @@ -1948,23 +1948,23 @@ if exist('fflush', 'builtin') && eval(s(1)) < 7 res = 1; end -% --------------------------------------------------------------- -% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- function flush if isoctave feval('fflush', stdout); end -% --------------------------------------------------------------- -% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- % ----- replacements for statistic toolbox functions ------------ -% --------------------------------------------------------------- -% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- function res=myrange(x) res = max(x) - min(x); -% --------------------------------------------------------------- -% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- function res = myprctile(inar, perc, idx) % % Computes the percentiles in vector perc from vector inar @@ -1975,7 +1975,7 @@ function res = myprctile(inar, perc, idx) N = length(inar); flgtranspose = 0; -% sizes +% sizes if size(perc,1) > 1 perc = perc'; flgtranspose = 1; @@ -1989,7 +1989,7 @@ end % sort inar if nargin < 3 || isempty(idx) - [sar idx] = sort(inar); + [sar, idx] = sort(inar); else sar = inar(idx); end @@ -2017,41 +2017,41 @@ if flgtranspose end -% --------------------------------------------------------------- -% --------------------------------------------------------------- -% --------------------------------------------------------------- -% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------------------------------------------------------- -function [s ranks rankDelta] = local_noisemeasurement(arf1, arf2, lamreev, theta, cutlimit) +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 @@ -2089,9 +2089,9 @@ 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) ... + theta*50) ... + myprctile(abs((1:2*lam-1) - (ranks(2,i) - (ranks(2,i)>ranks(1,i)))), ... - theta*50)); + theta*50)); end %%% compute measurement @@ -2101,39 +2101,39 @@ 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. % @@ -2149,14 +2149,14 @@ if nargin < 3 || isempty(filenameextension) filenameextension = '.dat'; end if nargin < 4 || isempty(objectvarname) - objectvarname = 'xmean'; + 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.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]); @@ -2180,9 +2180,9 @@ if mod(figNb,100) == 1 iabscissa = 1; % a short hack end if iabscissa == 1 - xlab ='iterations'; + xlab ='iterations'; elseif iabscissa == 2 - xlab = 'function evaluations'; + xlab = 'function evaluations'; end if size(d.x, 2) < 1000 @@ -2195,7 +2195,7 @@ end if manual_mode figure(figNb); % just create and raise the figure window else - if 1 < 3 && evalin('caller', 'iterplotted') == 0 && evalin('caller', 'irun') == 1 + 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 @@ -2206,18 +2206,18 @@ end % plot fitness etc foffset = 1e-99; -dfit = d.f(:,6)-min(d.f(:,6)); -[ignore idxbest] = min(dfit); +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; +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; end @@ -2225,11 +2225,11 @@ 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; + 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; + 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; @@ -2247,37 +2247,37 @@ 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)); +ax(2) = max(minxend, ax(2)); axis(ax); -yannote = 10^(log10(ax(3)) + 0.05*(log10(ax(4))-log10(ax(3)))); +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; +grid on; -subplot(2,2,2); hold off; +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); +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))); +% 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([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'; +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 @@ -2286,16 +2286,16 @@ title(['Object Variables (' num2str(size(d.x, 2)-5) ... subplot(2,2,3); hold off; semilogy(d.D(:,iabscissa), d.D(:,6:end), '-'); ax = axis; -ax(2) = max(minxend, ax(2)); +ax(2) = max(minxend, ax(2)); axis(ax); title('Principal Axes Lengths');grid on; -xlabel(xlab); +xlabel(xlab); -subplot(2,2,4); hold off; -% semilogy(d.std(:,iabscissa), d.std(:,6:end), 'k-'); hold on; +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; +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); @@ -2305,16 +2305,16 @@ if 11 < 3 % max and min std text(d.std(end,iabscissa), d.std(end,3)*minval, sprintf('min=%.0e', minval)); end ax = axis; -ax(2) = max(minxend, ax(2)); +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))); +[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([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)]); @@ -2327,9 +2327,9 @@ if figNb ~= 324 end drawnow; -% --------------------------------------------------------------- -% --------------- TEST OBJECTIVE FUNCTIONS ---------------------- -% --------------------------------------------------------------- +% --------------------------------------------------------------- +% --------------- TEST OBJECTIVE FUNCTIONS ---------------------- +% --------------------------------------------------------------- %%% Unimodal functions @@ -2356,12 +2356,12 @@ f = max(abs(x), [], 1); function f=fssphere(x) f=sqrt(sum(x.^2, 1)); -% lb = -0.512; ub = 512; -% xfeas = x; +% lb = -0.512; ub = 512; +% xfeas = x; % xfeas(xub) = 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) @@ -2369,11 +2369,11 @@ if nargin < 2 || isempty(Nevals) 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)); @@ -2387,13 +2387,13 @@ 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 +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); @@ -2441,7 +2441,7 @@ end xopt = 0.1; x(idxM) = x(idxM) + xopt; f = scale.^2*x.^2; -f = f - sum((xopt*scale(idxM)).^2); +f = f - sum((xopt*scale(idxM)).^2); % f = exp(f) - 1; % f = log10(f+1e-19) + 19; @@ -2460,12 +2460,12 @@ 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) scal = 1e3; @@ -2509,7 +2509,7 @@ else f=sum(abs(scale.*x).^e); end -function f=fneumaier3(x) +function f=fneumaier3(x) % in -n^2..n^2 % x^*-i = i(n+1-i) N = size(x,1); @@ -2520,15 +2520,15 @@ 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 +% 8 1.03527618 +% 10 0.842535997 +% 20 0.5997 pop = size(y,2); N = size(y,1)/2; -f = []; +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; @@ -2565,7 +2565,7 @@ f = 1e5 - 1/(1e-5 + sum(abs(y))); function f=fschwefel(x) f = 0; -for i = 1:size(x,1), +for i = 1:size(x,1) f = f+sum(x(1:i))^2; end @@ -2600,7 +2600,7 @@ f=((10^(lgscal*expon)).^((0:N-1)/(N-1)) * abs(x).^expon).^(1/expon2); function f=fellitest(x) beta = 0.9; N = size(x,1); -f = (1e6.^((0:(N-1))/(N-1))).^beta * (x.^2).^beta; +f = (1e6.^((0:(N-1))/(N-1))).^beta * (x.^2).^beta; function f=fellii(x, scal) @@ -2637,16 +2637,16 @@ else arN = N; end global ORTHOGONALCOORSYSTEM_G -ORTHOGONALCOORSYSTEM_G{1} = 1; +ORTHOGONALCOORSYSTEM_G{1} = 1; for N = arN ar = randn(N,N); - for i = 1: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)); end - ORTHOGONALCOORSYSTEM_G{N} = ar; + ORTHOGONALCOORSYSTEM_G{N} = ar; end function f=fplane(x) @@ -2662,11 +2662,11 @@ function f=fsharpR(x) 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); +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)); +% 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 @@ -2679,7 +2679,7 @@ 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(any(abs(x)>30,1)) = NaN; function f=frosenrot(x) N = size(x,1); @@ -2696,46 +2696,46 @@ 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] +% in [-10 10] f=sum((x.^2-x(1)).^2 + (x-1).^2); function f=fschwefelrosen2(x) -% in [-10 10] +% 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 = sqrt(f); function f=fabsprod(x) 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); -%%% Multimodal functions +%%% Multimodal functions function f=fbirastrigin(x) -% todo: the volume needs to be a constant -N = size(x,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); +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); +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, +% 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)); +% +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); @@ -2784,15 +2784,15 @@ end if nargin < 2 || isempty(scal) scal = 1; end -N = size(x,1); +N = size(x,1); scale = 1; if N > 1 - scale=scal.^((0:N-1)'/(N-1)); + scale=scal.^((0:N-1)'/(N-1)); end -% simple version: +% simple version: % f = amplitude*(N - sum(cos(2*pi*(scale.*x)))) + sum((scale.*x).^2); -% skew version: +% skew version: y = repmat(scale, 1, size(x,2)) .* x; idx = find(x > skewstart); if ~isempty(idx) @@ -2815,18 +2815,18 @@ end if nargin < 2 || isempty(scal) scal = 1; end -N = size(x,1); +N = size(x,1); scale = 1; if N > 1 - scale=scal.^((0:N-1)'/(N-1)); + scale=scal.^((0:N-1)'/(N-1)); end -% simple version: +% simple version: % f = amplitude*(N - sum(cos(2*pi*(scale.*x)))) + sum((scale.*x).^2); -% skew version: +% skew version: y = repmat(scale, 1, size(x,2)) .* x; idx = find(x > skewstart); -% idx = intersect(idx, 2:2:10); +% idx = intersect(idx, 2:2:10); if ~isempty(idx) y(idx) = skewfac*y(idx); end @@ -2845,21 +2845,21 @@ f = sum(s.^0.25 .* (sin(50*s.^0.1).^2+1), 1); function f=fschwefelmult(x) % -500..500 -% -N = size(x,1); +% +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 +% 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); +N = size(x,1); f = -abs(sum(x)) + 5*N; function f=ftwomaxtwo(x) % Boundaries at +/-10 -N = size(x,1); +N = size(x,1); f = abs(sum(x)); if f > 30 f = f - 30; @@ -2872,117 +2872,117 @@ 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 @@ f=1./(1-rand(1, size(x,2))) - 1; % 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 @@ f=1./(1-rand(1, size(x,2))) - 1; % --------------------------------------------------------------- %%% 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 @@ f=1./(1-rand(1, size(x,2))) - 1; % 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 633e7dc9b..22391027e 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,12 +33,12 @@ 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 +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -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 @@ -216,7 +216,7 @@ else end end lambda=lambda*factor; - if abs(lambda) > 1e20; + if abs(lambda) > 1e20 retcode = 5; done =1; end diff --git a/matlab/optimization/csminwel1.m b/matlab/optimization/csminwel1.m index af341b11d..cfa869932 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,19 +30,19 @@ 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 +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . -% initialize variable penalty +% initialize variable penalty penalty = 1e8; fh = []; xh = []; @@ -139,7 +139,7 @@ while ~done else if NumGrad [g1, badg1]=get_num_grad(method,fcn,penalty,f1,x1,epsilon,varargin{:}); - elseif ischar(grad), + elseif ischar(grad) [g1, badg1] = grad(x1,varargin{:}); else [junk1,cost_flag,g1] = penalty_objective_function(x1,fcn,penalty,varargin{:}); @@ -166,7 +166,7 @@ while ~done else if NumGrad [g2, badg2]=get_num_grad(method,fcn,penalty,f2,x2,epsilon,varargin{:}); - elseif ischar(grad), + elseif ischar(grad) [g2, badg2] = grad(x2,varargin{:}); else [junk2,cost_flag,g2] = penalty_objective_function(x1,fcn,penalty,varargin{:}); @@ -193,12 +193,12 @@ 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 [g3, badg3]=get_num_grad(method,fcn,penalty,f3,x3,epsilon,varargin{:}); - elseif ischar(grad), + elseif ischar(grad) [g3, badg3] = grad(x3,varargin{:}); else [junk3,cost_flag,g3] = penalty_objective_function(x1,fcn,penalty,varargin{:}); @@ -258,7 +258,7 @@ while ~done if nogh if NumGrad [gh, badgh]=get_num_grad(method,fcn,penalty,fh,xh,epsilon,varargin{:}); - elseif ischar(grad), + elseif ischar(grad) [gh, badgh] = grad(xh,varargin{:}); else [junkh,cost_flag,gh] = penalty_objective_function(x1,fcn,penalty,varargin{:}); @@ -302,7 +302,7 @@ while ~done error('Unaccounted Case, please contact the developers',Verbose) end end - + f=fh; x=xh; g=gh; diff --git a/matlab/optimization/dynare_minimize_objective.m b/matlab/optimization/dynare_minimize_objective.m index 8aca0d2e1..025d41189 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,12 +21,12 @@ 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-2016 Dynare Team +% +% +% Copyright (C) 2014-2017 Dynare Team % % This file is part of Dynare. % @@ -77,7 +77,7 @@ switch minimizer_algorithm if options_.silent_optimizer optim_options = optimset(optim_options,'display','off'); end - if options_.analytic_derivation, + if options_.analytic_derivation optim_options = optimset(optim_options,'GradObj','on','TolX',1e-7); end [opt_par_values,fval,exitflag,output,lamdba,grad,hessian_mat] = ... @@ -148,7 +148,7 @@ switch minimizer_algorithm if ~isempty(options_.optim_opt) eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']); end - if options_.analytic_derivation, + if options_.analytic_derivation optim_options = optimset(optim_options,'GradObj','on'); end if options_.silent_optimizer @@ -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; @@ -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{:}); @@ -390,7 +390,7 @@ switch minimizer_algorithm simpsaOptions.DISPLAY = 'none'; else simpsaOptions.DISPLAY = 'iter'; - end + end otherwise warning(['simpsa: Unknown option (' options_list{i,1} ')!']) end diff --git a/matlab/optimization/gmhmaxlik.m b/matlab/optimization/gmhmaxlik.m index bc800f8f8..4f1db628d 100644 --- a/matlab/optimization/gmhmaxlik.m +++ b/matlab/optimization/gmhmaxlik.m @@ -1,6 +1,6 @@ function [PostMode, HessianMatrix, Scale, ModeValue] = gmhmaxlik(fun, xinit, Hinit, iscale, bounds, priorstd, gmhmaxlikOptions, OptimizationOptions, varargin) -% Copyright (C) 2006-2015 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -19,7 +19,7 @@ function [PostMode, HessianMatrix, Scale, ModeValue] = gmhmaxlik(fun, xinit, Hin % Set default options -if ~isempty(Hinit); +if ~isempty(Hinit) gmhmaxlikOptions.varinit = 'previous'; else gmhmaxlikOptions.varinit = 'prior'; diff --git a/matlab/optimization/gmhmaxlik_core.m b/matlab/optimization/gmhmaxlik_core.m index 2d7a3cb81..3e94d30ab 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,12 +51,12 @@ 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. -% Copyright (C) 2006-2015 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -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 605508d2c..0836a7a87 100644 --- a/matlab/optimization/mr_gstep.m +++ b/matlab/optimization/mr_gstep.m @@ -11,7 +11,7 @@ function [f0, x, ig] = mr_gstep(h1,x,bounds,func0,penalty,htol0,Verbose,Save_fil % varargin{6} --> BayesInfo % varargin{1} --> DynareResults -% Copyright (C) 2006-2016 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -29,7 +29,7 @@ function [f0, x, ig] = mr_gstep(h1,x,bounds,func0,penalty,htol0,Verbose,Save_fil % along with Dynare. If not, see . n=size(x,1); -if isempty(h1), +if isempty(h1) h1=varargin{3}.gradient_epsilon*ones(n,1); end @@ -39,7 +39,7 @@ if isempty(htol0) else htol = htol0; end -if length(htol)==1, +if length(htol)==1 htol=htol*ones(n,1); end f0=penalty_objective_function(x,func0,penalty,varargin{:}); @@ -72,7 +72,7 @@ while i htol(i) - [f0 x fc retcode] = csminit1(func0,x,penalty,f0,gg,0,diag(hh),Verbose,varargin{:}); + [f0, x, fc, retcode] = csminit1(func0,x,penalty,f0,gg,0,diag(hh),Verbose,varargin{:}); ig(i)=1; if Verbose fprintf(['Done for param %s = %8.4f\n'],varargin{6}.name{i},x(i)) @@ -95,13 +95,11 @@ return function x = check_bounds(x,bounds) inx = find(x>=bounds(:,2)); -if ~isempty(inx), +if ~isempty(inx) x(inx) = bounds(inx,2)-eps; end inx = find(x<=bounds(:,1)); -if ~isempty(inx), +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 c3ed29345..b234df9b7 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 @@ -44,7 +44,7 @@ function [hessian_mat, gg, htol1, ihh, hh_mat0, hh1, hess_info] = mr_hessian(x,f % - hh1 updated hess_info.h1 % - hess_info structure with updated step length -% Copyright (C) 2004-2016 Dynare Team +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % @@ -67,7 +67,7 @@ n=size(x,1); h2=varargin{7}.ub-varargin{7}.lb; hmax=varargin{7}.ub-x; hmax=min(hmax,x-varargin{7}.lb); -if isempty(ff0), +if isempty(ff0) outer_product_gradient=0; else outer_product_gradient=1; @@ -109,7 +109,7 @@ while i(3*hess_info.htol)) && icount<10 && ic==0 icount=icount+1; if abs(dx(it))<0.5*hess_info.htol - if abs(dx(it)) ~= 0, + if abs(dx(it)) ~= 0 hess_info.h1(i)=min(max(1.e-10,0.3*abs(x(i))), 0.9*hess_info.htol/abs(dx(it))*hess_info.h1(i)); else hess_info.h1(i)=2.1*hess_info.h1(i); @@ -147,8 +147,8 @@ while i BayesInfo % varargin{7} --> Bounds % varargin{8} --> DynareResults -% +% % Outputs % - xparam1 parameter vector at optimum % - hh hessian @@ -39,7 +39,7 @@ function [xparam1, hh, gg, fval, igg, hess_info] = newrat(func0, x, bounds, anal % - igg inverted outer product hessian % - hess_info structure with updated step length -% Copyright (C) 2004-2016 Dynare Team +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . -% initialize variable penalty +% initialize variable penalty penalty = 1e8; icount=0; @@ -86,7 +86,7 @@ fval=fval0; outer_product_gradient=1; if isempty(hh) [dum, gg, htol0, igg, hhg, h1, hess_info]=mr_hessian(x,func0,penalty,flagit,htol,hess_info,varargin{:}); - if isempty(dum), + if isempty(dum) outer_product_gradient=0; igg = 1e-4*eye(nx); else @@ -154,7 +154,7 @@ while norm(gg)>gtol && check==0 && jitgtol && check==0 && jitgtol && check==0 && jit1.e-12 && analytic_derivation==0, + if norm(x(:,icount)-xparam1)>1.e-12 && analytic_derivation==0 try if Save_files save('m1.mat','x','fval0','nig','-append') @@ -244,7 +244,7 @@ while norm(gg)>gtol && check==0 && jithtol @@ -253,7 +253,7 @@ while norm(gg)>gtol && check==0 && jitgtol && check==0 && jit=bounds(:,2)); -if ~isempty(inx), +if ~isempty(inx) x(inx) = bounds(inx,2)-eps; end inx = find(x<=bounds(:,1)); -if ~isempty(inx), +if ~isempty(inx) x(inx) = bounds(inx,1)+eps; end diff --git a/matlab/optimization/penalty_objective_function.m b/matlab/optimization/penalty_objective_function.m index c245800c2..e0c249251 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 aff23b246..ccd81367e 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,13 +23,13 @@ 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 % a minimum). -% Copyright (C) 2010-2013 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -396,7 +396,7 @@ while (func_count < max_func_calls) && (iter_count < max_iterations) && (simplex disp(['Crit. x: ' num2str(critX)]) skipline() end - if verbose && max(abs(best_point-v(:,1)))>x_tolerance; + if verbose && max(abs(best_point-v(:,1)))>x_tolerance if verbose<2 disp(['Simplex iteration number: ' int2str(simplex_iterations) '-' int2str(simplex_init) '-' int2str(simplex_algo_iterations)]) disp(['Objective function value: ' num2str(fv(1))]) diff --git a/matlab/optimization/simpsa.m b/matlab/optimization/simpsa.m index 228a6bad2..87b881a2c 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,54 +11,54 @@ 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 % Copyright (C) 2005 Henning Schmidt, FCC, henning@fcc.chalmers.se % Copyright (C) 2006 Brecht Donckels, BIOMATH, brecht.donckels@ugent.be -% Copyright (C) 2013 Dynare Team. +% Copyright (C) 2013-2017 Dynare Team. % % This file is part of Dynare. % @@ -77,11 +77,11 @@ function [X,FVAL,EXITFLAG,OUTPUT] = simpsa(FUN,X0,LB,UB,OPTIONS,varargin) % handle variable input arguments -if nargin < 5, +if nargin < 5 OPTIONS = []; - if nargin < 4, + if nargin < 4 UB = 1e5; - if nargin < 3, + if nargin < 3 LB = -1e5; end end @@ -89,22 +89,22 @@ end % check input arguments -if ~ischar(FUN), +if ~ischar(FUN) error('''FUN'' incorrectly specified in ''SIMPSA'''); end -if ~isfloat(X0), +if ~isfloat(X0) error('''X0'' incorrectly specified in ''SIMPSA'''); end -if ~isfloat(LB), +if ~isfloat(LB) error('''LB'' incorrectly specified in ''SIMPSA'''); end -if ~isfloat(UB), +if ~isfloat(UB) error('''UB'' incorrectly specified in ''SIMPSA'''); end -if length(X0) ~= length(LB), +if length(X0) ~= length(LB) error('''LB'' and ''X0'' have incompatible dimensions in ''SIMPSA'''); end -if length(X0) ~= length(UB), +if length(X0) ~= length(UB) error('''UB'' and ''X0'' have incompatible dimensions in ''SIMPSA'''); end @@ -167,7 +167,7 @@ TEMP_LOOP_NUMBER = 1; % loop as described by Cardoso et al., 1996 (recommended) % therefore, the temperature is set to YBEST*1e5 in the first loop -if isempty(OPTIONS.TEMP_START), +if isempty(OPTIONS.TEMP_START) TEMP = abs(YBEST)*1e5; else TEMP = OPTIONS.TEMP_START; @@ -195,51 +195,51 @@ nITERATIONS = 0; % temperature loop: run SIMPSA till stopping criterion is met % ----------------------------------------------------------- -while 1, - +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, + + if EXITFLAG ~= -2 break end - + % set MAXITERTEMP: maximum number of iterations at current temperature % -------------------------------------------------------------------- - - if TEMP_LOOP_NUMBER == 1, + + 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), + if isempty(OPTIONS.TEMP_START) [SUCCESSFUL_MOVES,UNSUCCESSFUL_MOVES,UNSUCCESSFUL_COSTS] = deal(0); end - elseif TEMP < OPTIONS.TEMP_END, + elseif TEMP < OPTIONS.TEMP_END TEMP = 0; MAXITERTEMP = OPTIONS.MAX_ITER_TEMP_LAST*NDIM; 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), + if ~isempty(OPTIONS.OUTPUT_FCN) feval(OPTIONS.OUTPUT_FCN,transpose(P(1,:)),Y(1)); end - + % remaining vertices of simplex - for k = 1:NDIM, + for k = 1:NDIM % copy first vertex in new vertex P(k+1,:) = P(1,:); % alter new vertex @@ -247,20 +247,20 @@ 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, + if strcmp(OPTIONS.DISPLAY,'iter') + if nITERATIONS == 0 disp(' Nr Iter Nr Fun Eval Min function Best function TEMP Algorithm Step'); else disp(sprintf('%5.0f %5.0f %12.6g %15.6g %12.6g %s',nITERATIONS,nFUN_EVALS,Y(1),YBEST,TEMP,'best point')); @@ -269,111 +269,111 @@ 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, - + 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'), + + 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), + 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'), + + 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).') end EXITFLAG = 1; - break; + break end - - if (max(max(abs(P(2:NDIM+1,:)-P(1:NDIM,:)))) < OPTIONS.TOLX) && (TEMP_LOOP_NUMBER ~= 1), - if strcmp(OPTIONS.DISPLAY,'iter'), + + 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).') end EXITFLAG = 2; - break; + break end - - if (nITERATIONS >= OPTIONS.MAX_ITER_TOTAL*NDIM) || (nFUN_EVALS >= OPTIONS.MAX_FUN_EVALS*NDIM*(NDIM+1)), - if strcmp(OPTIONS.DISPLAY,'iter'), + + 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.'); end EXITFLAG = 0; - break; + break end - - if toc/60 > OPTIONS.MAX_TIME, - if strcmp(OPTIONS.DISPLAY,'iter'), + + if toc/60 > OPTIONS.MAX_TIME + if strcmp(OPTIONS.DISPLAY,'iter') disp('Exceeded maximum time.'); end EXITFLAG = -1; - break; + 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), + if YFTRY <= YFLUCT(1) %% gives a result better than the best point,so try an additional %% extrapolation by a factor 2 [YFTRYEXP,YTRYEXP,PTRYEXP] = AMOTRY(FUN,P,-2,LB,UB,varargin{:}); - if YFTRYEXP < YFTRY, + if YFTRYEXP < YFTRY P(end,:) = PTRYEXP; Y(end) = YTRYEXP; ALGOSTEP = 'reflection and expansion'; @@ -382,12 +382,12 @@ while 1, Y(end) = YTRY; ALGOSTEP = 'reflection'; end - elseif YFTRY >= YFLUCT(NDIM), + elseif YFTRY >= YFLUCT(NDIM) %% the reflected point is worse than the second-highest, so look %% for an intermediate lower point, i.e., do a one-dimensional %% contraction [YFTRYCONTR,YTRYCONTR,PTRYCONTR] = AMOTRY(FUN,P,-0.5,LB,UB,varargin{:}); - if YFTRYCONTR < YFLUCT(end), + if YFTRYCONTR < YFLUCT(end) P(end,:) = PTRYCONTR; Y(end) = YTRYCONTR; ALGOSTEP = 'one dimensional contraction'; @@ -396,7 +396,7 @@ while 1, %% around the lowest (best) point X = ones(NDIM,NDIM)*diag(P(1,:)); P(2:end,:) = 0.5*(P(2:end,:)+X); - for k=2:NDIM, + for k=2:NDIM Y(k) = CALCULATE_COST(FUN,P(k,:),LB,UB,varargin{:}); end ALGOSTEP = 'multiple contraction'; @@ -407,15 +407,15 @@ 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), + + if TEMP_LOOP_NUMBER == 1 && isempty(OPTIONS.TEMP_START) + if Y(1) > Y(end) SUCCESSFUL_MOVES = SUCCESSFUL_MOVES+1; - elseif Y(1) <= Y(end), + elseif Y(1) <= Y(end) UNSUCCESSFUL_MOVES = UNSUCCESSFUL_MOVES+1; UNSUCCESSFUL_COSTS = UNSUCCESSFUL_COSTS+(Y(end)-Y(1)); end @@ -424,28 +424,28 @@ while 1, end % stop if previous for loop was broken due to some stop criterion - if ITERTEMP < MAXITERTEMP, - break; + 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), + + 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, + elseif TEMP_LOOP_NUMBER ~= 0 STDEV_Y = std(COSTS); 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 @@ -502,14 +502,14 @@ function [YTRY] = CALCULATE_COST(FUN,PTRY,LB,UB,varargin) global YBEST PBEST NDIM nFUN_EVALS -for i = 1:NDIM, +for i = 1:NDIM % check lower bounds - if PTRY(i) < LB(i), + if PTRY(i) < LB(i) YTRY = 1e12+(LB(i)-PTRY(i))*1e6; return end % check upper bounds - if PTRY(i) > UB(i), + if PTRY(i) > UB(i) YTRY = 1e12+(PTRY(i)-UB(i))*1e6; return end @@ -522,7 +522,7 @@ YTRY = feval(FUN,PTRY(:),varargin{:}); nFUN_EVALS = nFUN_EVALS + 1; % save the best point ever -if YTRY < YBEST, +if YTRY < YBEST YBEST = YTRY; PBEST = PTRY; end diff --git a/matlab/optimization/simpsaget.m b/matlab/optimization/simpsaget.m index c22c82df4..96eb36dc9 100644 --- a/matlab/optimization/simpsaget.m +++ b/matlab/optimization/simpsaget.m @@ -18,7 +18,7 @@ function o = simpsaget(options,name,default,flag) % See also SIMPSASET, SIMPSA % Copyright (C) 2006 Brecht Donckels, BIOMATH, brecht.donckels@ugent.be -% Copyright (C) 2013-2016 Dynare Team. +% Copyright (C) 2013-2017 Dynare Team. % % This file is part of Dynare. % @@ -56,7 +56,7 @@ end if isempty(options) o = default; - return; + return end Names = [ @@ -122,4 +122,3 @@ if isfield(s,f) % s could be empty. else v = d; end - diff --git a/matlab/optimization/simpsaset.m b/matlab/optimization/simpsaset.m index 1944e024f..1d63c7bdc 100644 --- a/matlab/optimization/simpsaset.m +++ b/matlab/optimization/simpsaset.m @@ -28,7 +28,7 @@ function options = simpsaset(varargin) % Copyright (C) 2005 Henning Schmidt, FCC, henning@fcc.chalmers.se % Copyright (C) 2006 Brecht Donckels, BIOMATH, brecht.donckels@ugent.be -% Copyright (C) 2013 Dynare Team. +% Copyright (C) 2013-2017 Dynare Team. % % This file is part of Dynare. % @@ -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 = [ @@ -97,7 +97,7 @@ i = 1; while i <= nargin arg = varargin{i}; if ischar(arg) % arg is an option name - break; + break end if ~isempty(arg) % [] is a valid options argument if ~isa(arg,'struct') @@ -127,13 +127,13 @@ 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 @@ -155,11 +155,11 @@ while i <= nargin end end expectval = 1; % we expect a value next - + else options.(deblank(Names(j,:))) = arg; expectval = 0; - + end i = i + 1; end diff --git a/matlab/optimization/simulated_annealing.m b/matlab/optimization/simulated_annealing.m index b2cfc52ee..7088685b3 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,28 +142,28 @@ 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 +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -194,17 +194,17 @@ xopt=x; nacp=zeros(n,1); fstar=1e20*ones(optim.neps,1); %* If the initial temperature is not positive, notify the user and abort. * -if(t<=0.0); +if(t<=0.0) fprintf('\nThe initial temperature is not positive. Reset the variable t\n'); exitflag=3; - return; -end; + return +end %* If the initial value is out of bounds, notify the user and abort. * -if(sum(x>ub)+sum(x0); +if(sum(x>ub)+sum(x0) fprintf('\nInitial condition out of bounds\n'); exitflag=2; - return; -end; + return +end %* Evaluate the function with input x and return value as f. * f=feval(fcn,x,varargin{:}); %* @@ -212,98 +212,98 @@ f=feval(fcn,x,varargin{:}); % Note that all intermediate and final output switches the sign back % to eliminate any possible confusion for the user. %* -if(optim.maximizer_indicator==0); +if(optim.maximizer_indicator==0) f=-f; -end; +end n_total_draws=n_total_draws+1; fopt=f; fstar(1)=f; -if(optim.verbosity >1); +if(optim.verbosity >1) disp ' '; disp(['initial x ' num2str(x(:)')]); - if(optim.maximizer_indicator); + if(optim.maximizer_indicator) disp(['initial f ' num2str(f)]); else disp(['initial f ' num2str(-f)]); - end; -end; + end +end % Start the main loop. Note that it terminates if (i) the algorithm % succesfully optimizes the function or (ii) there are too many % function evaluations (more than optim.MaxIter). -while (1>0); +while (1>0) nup=0; nrej=0; nnew=0; ndown=0; lnobds=0; m=1; - while m<=optim.nt; + while m<=optim.nt j=1; - while j<=optim.ns; + while j<=optim.ns h=1; - while h<=n; + while h<=n %* Generate xp, the trial value of x. Note use of vm to choose xp. * i=1; - while i<=n; - if(i==h); + while i<=n + if(i==h) xp(i)=x(i)+(rand(1,1)*2.0-1.0)*vm(i); else xp(i)=x(i); - end; + end %* If xp is out of bounds, select a point in bounds for the trial. * - if((xp(i)ub(i))); + if((xp(i)ub(i))) xp(i)=lb(i)+(ub(i)-lb(i))*rand(1,1); lnobds=lnobds+1; n_out_of_bounds_draws=n_out_of_bounds_draws+1; - if(optim.verbosity >=3); + if(optim.verbosity >=3) if exist('fp','var') print_current_invalid_try(optim.maximizer_indicator,xp,x,fp,f); end - end; - end; + end + end i=i+1; - end; + end %* Evaluate the function with the trial point xp and return as fp. * % fp=feval(fcn,xp,listarg); fp=feval(fcn,xp,varargin{:}); - if(optim.maximizer_indicator==0); + if(optim.maximizer_indicator==0) fp=-fp; - end; + end n_total_draws=n_total_draws+1; - if(optim.verbosity >=3); + if(optim.verbosity >=3) print_current_valid_try(optim.maximizer_indicator,xp,x,fp,f); - end; + end %* If too many function evaluations occur, terminate the algorithm. * - if(n_total_draws>=optim.MaxIter); + if(n_total_draws>=optim.MaxIter) fprintf('Too many function evaluations; consider\n'); fprintf('increasing optim.MaxIter or optim.TolFun or decreasing\n'); fprintf('optim.nt or optim.rt. These results are likely to be poor\n'); - if(optim.maximizer_indicator==0); + if(optim.maximizer_indicator==0) fopt=-fopt; - end; + end exitflag=1; - return; - end; + return + end %* Accept the new point if the function value increases. * - if(fp>=f); - if(optim.verbosity >=3); + if(fp>=f) + if(optim.verbosity >=3) fprintf('point accepted\n'); - end; + end x=xp; f=fp; n_accepted_draws=n_accepted_draws+1; nacp(h)=nacp(h)+1; nup=nup+1; %* If greater than any other point, record as new optimum. * - if(fp>fopt); - if(optim.verbosity >=3); + if(fp>fopt) + if(optim.verbosity >=3) fprintf('new optimum\n'); - end; + end xopt=xp; fopt=fp; nnew=nnew+1; - end; + end %* % If the point is lower, use the Metropolis criteria to decide on % acceptance or rejection. @@ -311,14 +311,14 @@ while (1>0); else p=exp((fp-f)/t); pp=rand(1,1); - if(pp=3); - if(optim.maximizer_indicator); + if(pp=3) + if(optim.maximizer_indicator) fprintf('though lower, point accepted\n'); else fprintf('though higher, point accepted\n'); - end; - end; + end + end x=xp; f=fp; n_accepted_draws=n_accepted_draws+1; @@ -326,87 +326,87 @@ while (1>0); ndown=ndown+1; else nrej=nrej+1; - if(optim.verbosity >=3); - if(optim.maximizer_indicator); + if(optim.verbosity >=3) + if(optim.maximizer_indicator) fprintf('lower point rejected\n'); else fprintf('higher point rejected\n'); - end; - end; - end; - end; + end + end + end + end h=h+1; - end; + end j=j+1; - end; + end %* Adjust vm so that approximately half of all evaluations are accepted. * i=1; - while i<=n; + while i<=n ratio=nacp(i)/optim.ns; - if(ratio>.6); + if(ratio>.6) vm(i)=vm(i)*(1.+c(i)*(ratio-.6)/.4); - elseif(ratio<.4); + elseif(ratio<.4) vm(i)=vm(i)/(1.+c(i)*((.4-ratio)/.4)); - end; - if(vm(i)>(ub(i)-lb(i))); + end + if(vm(i)>(ub(i)-lb(i))) vm(i)=ub(i)-lb(i); - end; + end i=i+1; - end; - if(optim.verbosity >=2); + end + if(optim.verbosity >=2) fprintf('intermediate results after step length adjustment\n'); fprintf('new step length(vm) %4.3f', vm(:)'); fprintf('current optimal x %4.3f', xopt(:)'); fprintf('current x %4.3f', x(:)'); - end; + end nacp=zeros(n,1); m=m+1; - end; - if(optim.verbosity >=1); + end + if(optim.verbosity >=1) print_intermediate_statistics(optim.maximizer_indicator,t,xopt,vm,fopt,nup,ndown,nrej,lnobds,nnew); - end; + end %* Check termination criteria. * quit=0; fstar(1)=f; - if((fopt-fstar(1))<=optim.TolFun); + if((fopt-fstar(1))<=optim.TolFun) quit=1; - end; - if(sum(abs(f-fstar)>optim.TolFun)>0); + end + if(sum(abs(f-fstar)>optim.TolFun)>0) quit=0; - end; + end %* Terminate SA if appropriate. * - if(quit); + if(quit) exitflag=0; - if(optim.maximizer_indicator==0); + if(optim.maximizer_indicator==0) fopt=-fopt; - end; - if(optim.verbosity >=1); + end + if(optim.verbosity >=1) fprintf('SA achieved termination criteria.exitflag=0\n'); - end; - return; - end; + end + return + end %* If termination criteria are not met, prepare for another loop. * t=optim.rt*t; i=optim.neps; - while i>=2; + while i>=2 fstar(i)=fstar(i-1); i=i-1; - end; + end f=fopt; x=xopt; %* Loop again. * -end; +end end function print_current_invalid_try(max,xp,x,fp,f) fprintf('\n'); disp(['Current x ' num2str(x(:)')]); -if(max); +if(max) disp(['Current f ' num2str(f)]); else disp(['Current f ' num2str(-f)]); -end; +end disp(['Trial x ' num2str(xp(:)')]); disp 'Point rejected since out of bounds'; end @@ -414,7 +414,7 @@ end function print_current_valid_try(max,xp,x,fp,f) disp(['Current x ' num2str(x(:)')]); -if(max); +if(max) disp(['Current f ' num2str(f)]); disp(['Trial x ' num2str(xp(:)')]); disp(['Resulting f ' num2str(fp)]); @@ -422,7 +422,7 @@ else disp(['Current f ' num2str(-f)]); disp(['Trial x ' num2str(xp(:)')]); disp(['Resulting f ' num2str(-fp)]); -end; +end end diff --git a/matlab/optimization/solvopt.m b/matlab/optimization/solvopt.m index 6d5693e86..c4a819a26 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,15 +51,15 @@ 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 +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -162,7 +162,7 @@ if isempty(func) constr=0; else constr=1; % Constrained problem - if isempty(gradc), + if isempty(gradc) appconstr=1; else appconstr=0; % Exact gradients of constraints are supplied @@ -201,7 +201,7 @@ end epsnorm=1.e-15; epsnorm2=1.e-30; % epsilon & epsilon^2 -if constr, h1=-1; % NLP: restricted to minimization +if constr, h1=-1 % NLP: restricted to minimization cnteps=optim.TolXConstraint; % Max. admissible residual else h1=sign(optim.minimizer_indicator); % Minimize resp. maximize a function @@ -217,10 +217,10 @@ 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; +if optim.verbosity<=0, dispdata=0 if optim.verbosity==-1 dispwarn=0; else @@ -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; @@ -276,30 +276,79 @@ else f=feval(fun,x,varargin{:}); end n_f_evals=n_f_evals+1; -if isempty(f), if dispwarn,disp(errmes);disp(error30);end - exitflag=-3; if trx, x=x';end, return -elseif isnan(f), if dispwarn,disp(errmes);disp(error31);disp(error6);end - exitflag=-3; if trx, x=x';end, return -elseif abs(f)==Inf, if dispwarn,disp(errmes);disp(error32);disp(error6);end - exitflag=-3; if trx, x=x';end, return +if isempty(f) + if dispwarn + disp(errmes) + disp(error30) + end + exitflag=-3; + if trx + x=x'; + end + return +elseif isnan(f) + if dispwarn + disp(errmes) + disp(error31) + disp(error6) + end + exitflag=-3; + if trx + x=x'; + end + return +elseif abs(f)==Inf + if dispwarn + disp(errmes) + disp(error32) + disp(error6) + end + exitflag=-3; + if trx + x=x'; + end + return end xrec=x; frec=f; % record point and function value -% Constrained problem -if constr, fp=f; kless=0; - if trx, + % Constrained problem +if constr, fp=f; kless=0 + if trx fc=feval(func,x'); else fc=feval(func,x); end - if isempty(fc), - if dispwarn,disp(errmes);disp(error50);end - exitflag=-5; if trx, x=x';end, return - elseif isnan(fc), - if dispwarn,disp(errmes);disp(error51);disp(error6);end - exitflag=-5; if trx, x=x';end, return - elseif abs(fc)==Inf, - if dispwarn,disp(errmes);disp(error52);disp(error6);end - exitflag=-5; if trx, x=x';end, return + if isempty(fc) + if dispwarn + disp(errmes) + disp(error50) + end + exitflag=-5; + if trx + x=x'; + end + return + elseif isnan(fc) + if dispwarn + disp(errmes) + disp(error51) + disp(error6) + end + exitflag=-5; + if trx + x=x'; + end + return + elseif abs(fc)==Inf + if dispwarn + disp(errmes) + disp(error52) + disp(error6) + end + exitflag=-5; + if trx + x=x'; + end + return end n_constraint_evals=n_constraint_evals+1; PenCoef=1; % first rough approximation @@ -318,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; @@ -332,114 +381,151 @@ 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 -if size(g,2)==1, g=g'; end, ng=norm(g); -if size(g,2)~=n, if dispwarn,disp(errmes);disp(error40);end - exitflag=-4; if trx, x=x';end, return -elseif isnan(ng), if dispwarn,disp(errmes);disp(error41);disp(error6);end - exitflag=-4; if trx, x=x';end, return -elseif ng==Inf, if dispwarn,disp(errmes);disp(error42);disp(error6);end - exitflag=-4; if trx, x=x';end, return -elseif ng2*kd, kd=kd+1; warnno=1; - if any(abs(x-xx)2*kd + kd=kd+1; + warnno=1; + if any(abs(x-xx)1 idx=find(abs(g)>ZeroGrad); numelem=size(idx,2); - if numelem>0, grbnd=epsnorm*numelem^2; - if all(abs(g1(idx))<=abs(g(idx))*grbnd) | nrmz==0 - if dispwarn, disp(wrnmes); disp(warn20); end + if numelem>0, grbnd=epsnorm*numelem^2 + if all(abs(g1(idx))<=abs(g(idx))*grbnd) || nrmz==0 + if dispwarn + disp(wrnmes) + disp(warn20) + end if abs(fst-f)1.2*PenCoef, + if PenCoefNew>1.2*PenCoef PenCoef=PenCoefNew; Reset=1; kless=0; f=f+PenCoef*fc; break end end @@ -547,98 +665,123 @@ while 1, f=f+PenCoef*fc; end if abs(f)==Inf || isnan(f) - if dispwarn, disp(wrnmes); + if dispwarn, disp(wrnmes) if isnan(f) - disp(error31); + disp(error31) else - disp(error32); + disp(error32) end end if ksm || kc>=mxtc - exitflag=-3; + exitflag=-3; if trx x=x'; end return else k2=k2+1; - k1=0; - hp=hp/dq; + k1=0; + 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 - elseif all(abs(x-x1)=5, + if stepvanish>=5 exitflag=-14; - if dispwarn, disp(termwarn1); - disp(endwarn(4,:)); end - if trx,x=x';end, return + if dispwarn + disp(termwarn1) + disp(endwarn(4,:)) + end + if trx + x=x'; + 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=mxtc, break, end % 1-D OPTIMIZER IS LEFT BEHIND - else if h1*f<=h1*f1, break, end + else + if h1*f<=h1*f1 + break + end % USE LARGER STEP - k1=k1+1; if k2>0, kc=kc+1; end, k2=0; - if k1>=20, hp=du20*hp; - elseif k1>=10, hp=du10*hp; - elseif k1>=3, hp=du03*hp; + k1=k1+1; + if k2>0 + kc=kc+1; + end + k2=0; + if k1>=20 + hp=du20*hp; + elseif k1>=10 + hp=du10*hp; + elseif k1>=3 + hp=du03*hp; end end end % ----} End of 1-D search % ADJUST THE TRIAL STEP SIZE ----{ dx=norm(xopt-x); - if kg=2, nsteps(2:kg)=nsteps(1:kg-1); end + if kg=2 + nsteps(2:kg)=nsteps(1:kg-1); + end nsteps(1)=dx/(abs(h)*norm(g0)); kk=sum(nsteps(1:kg).*[kg:-1:1])/sum([kg:-1:1]); if kk>des if kg==1 h=h*(kk-des+1); else - h=h*sqrt(kk-des+1); + h=h*sqrt(kk-des+1); end elseif kk=20, PenCoef=PenCoef/10; Reset=1; kless=0; end + if kless>=20 + PenCoef=PenCoef/10; + Reset=1; + kless=0; + end else kless=0; end - if appconstr, + if appconstr deltax=sign(x); idx=find(deltax==0); 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'; end, ngc=norm(gc); - if isnan(ngc), - if dispwarn,disp(errmes);disp(error61);end - exitflag=-6; if trx, x=x';end, return - elseif ngc==Inf, - if dispwarn,disp(errmes);disp(error62);end - exitflag=-6; if trx, x=x';end, return - elseif ngch1*frec, frec=f; xrec=x; grec=g; end + end + end + if h1*f>h1*frec + frec=f; + xrec=x; + grec=g; + end % ----} - if ng>ZeroGrad, - if knorms<10, knorms=knorms+1; end - if knorms>=2, gnorms(2:knorms)=gnorms(1:knorms-1); end + if ng>ZeroGrad + if knorms<10 + knorms=knorms+1; + end + if knorms>=2 + gnorms(2:knorms)=gnorms(1:knorms-1); + end 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 '); @@ -721,10 +925,20 @@ while 1, %----} % CHECK THE STOPPING CRITERIA ----{ termflag=1; - if constr, if ~FP, termflag=0; end, end - if kcheck<=5, termflag=0; end - if knan, termflag=0; end - if kc>=mxtc, termflag=0; end + if constr + if ~FP + termflag=0; + end + end + if kcheck<=5 + termflag=0; + end + if knan + termflag=0 + end + if kc>=mxtc + termflag=0; + end % ARGUMENT if termflag idx=find(abs(x)>=lowxbound); @@ -737,40 +951,48 @@ while 1, ~constr if any(abs(xrec(idx)-x(idx))> detxr * abs(x(idx))) if dispwarn - disp(wrnmes); - disp(warn09); + 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)=limxterm ) if stopf if dx<=laststep - if warnno==1 && ng=limxterm exitflag=-14; - if dispwarn, disp(termwarn1); disp(endwarn(4,:)); - if app, disp(appwarn); end + if dispwarn + disp(termwarn1) + disp(endwarn(4,:)) + if app + disp(appwarn) + end end x=xrec; f=frec; - if trx,x=x';end, return + if trx + x=x'; + end + return else stopf=0; end @@ -795,57 +1024,67 @@ while 1, end % ITERATIONS LIMIT if(k==optim.MaxIter) - exitflag=-9; + exitflag=-9; if trx - x=x'; - end, - if dispwarn, disp(wrnmes); disp(warn4); end + x=x'; + end + if dispwarn + disp(wrnmes) + disp(warn4) + end return end % ----} % ZERO GRADIENT ----{ if constr - if ng<=ZeroGrad, - if dispwarn, disp(termwarn1); disp(warn1); end - exitflag=-8; + if ng<=ZeroGrad + if dispwarn + disp(termwarn1) + disp(warn1) + end + exitflag=-8; if trx x=x'; end return end else - if ng<=ZeroGrad, nzero=nzero+1; - if dispwarn, disp(wrnmes); disp(warn1); end + if ng<=ZeroGrad + nzero=nzero+1; + if dispwarn + disp(wrnmes) + disp(warn1) + end if nzero>=3 - exitflag=-8; + exitflag=-8; if trx x=x'; end return end g0=-h*g0/2; - for i=1:10, + for i=1:10 x=x+g0; 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(errmes) + disp(error32) end exitflag=-3; if trx x=x'; end return - elseif isnan(f), + elseif isnan(f) if dispwarn - disp(errmes); - disp(error32); + disp(errmes) + disp(error32) end exitflag=-3; if trx @@ -853,47 +1092,47 @@ while 1, end return end - if app, - deltax=sign(g0); + if app + 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(errmes) + 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 @@ -901,41 +1140,54 @@ while 1, break end end - if ng<=ZeroGrad, + if ng<=ZeroGrad if dispwarn - disp(termwarn1); - disp(warn1); + 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)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; - if dispwarn, disp(wrnmes); disp(warn31); end, warnno=1; + if ni>=1 && ni<=n/2 && kflat<=3 + kflat=kflat+1; + if dispwarn + disp(wrnmes) + disp(warn31) + end + warnno=1; x1=x; fm=f; - for j=idx, y=x(j); f2=fm; - if y==0, x1(j)=1; elseif abs(y)<1, x1(j)=sign(y); else, x1(j)=y; end - for i=1:20, x1(j)=x1(j)/1.15; + for j=idx + y=x(j); f2=fm; + if y==0 + x1(j)=1; + elseif abs(y)<1 + x1(j)=sign(y); + else + x1(j)=y; + end + for i=1:20 + x1(j)=x1(j)/1.15; 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 abs(f1)~=Inf && ~isnan(f1) if h1*f1>h1*fm - y=x1(j); + y=x1(j); fm=f1; elseif h1*f2>h1*f1 break @@ -948,36 +1200,36 @@ while 1, x1(j)=y; end if h1*fm>h1*f - if app, + if app deltax=h1*ddx*ones(size(deltax)); 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, + if ~isnan(ngt) && ngt>epsnorm2 if dispwarn - disp(warn32); + 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 @@ -986,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/optimize_prior.m b/matlab/optimize_prior.m index cdb03ecff..adf4d9c0e 100644 --- a/matlab/optimize_prior.m +++ b/matlab/optimize_prior.m @@ -2,7 +2,7 @@ function optimize_prior(DynareOptions, ModelInfo, DynareResults, BayesInfo, Esti % This routine computes the mode of the prior density using an optimization algorithm. -% Copyright (C) 2015 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -34,7 +34,7 @@ while look_for_admissible_initial_condition look_for_admissible_initial_condition = 0; end else - if iter == 2000; + if iter == 2000 scale = scale/1.1; iter = 0; else diff --git a/matlab/options2cell.m b/matlab/options2cell.m index 1296df22d..697c24b87 100644 --- a/matlab/options2cell.m +++ b/matlab/options2cell.m @@ -2,13 +2,13 @@ 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. +% Copyright (C) 2013-2017 Dynare Team. % % This file is part of Dynare. % @@ -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 d579c63ec..60039ac45 100644 --- a/matlab/osr.m +++ b/matlab/osr.m @@ -9,19 +9,19 @@ 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 +% +% Copyright (C) 2001-2017 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 . -global M_ options_ oo_ +global M_ options_ oo_ options_.order = 1; diff --git a/matlab/osr1.m b/matlab/osr1.m index a92dfedd5..b73db2b24 100644 --- a/matlab/osr1.m +++ b/matlab/osr1.m @@ -9,14 +9,14 @@ 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-2014 Dynare Team +% +% Copyright (C) 2005-2017 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 @@ -102,12 +102,12 @@ i_var=unique(i_var); [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 +else if ~options_.noprint fprintf('\nOSR: Initial value of the objective function: %g \n\n',loss); end end -if ~options_.noprint && isinf(loss) +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'); @@ -120,13 +120,13 @@ 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.') + 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,... diff --git a/matlab/osr_obj.m b/matlab/osr_obj.m index 5bea8e760..76db1da69 100644 --- a/matlab/osr_obj.m +++ b/matlab/osr_obj.m @@ -17,7 +17,7 @@ function [loss,info,exit_flag,vx,junk]=osr_obj(x,i_params,i_var,weights) % % SPECIAL REQUIREMENTS % none -% Copyright (C) 2005-2016 Dynare Team +% Copyright (C) 2005-2017 Dynare Team % % This file is part of Dynare. % @@ -58,7 +58,7 @@ if info(1) 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 ff9920abf..d00ca1b69 100644 --- a/matlab/parallel/AnalyseComputationalEnvironment.m +++ b/matlab/parallel/AnalyseComputationalEnvironment.m @@ -31,7 +31,7 @@ function [ErrorCode] = AnalyseComputationalEnvironment(DataInput, DataInputAdd) % field RemoteTmpFolder (the temporary directory created/destroyed on remote % computer) is used. -if ispc, +if ispc [tempo, MasterName]=system('hostname'); MasterName=deblank(MasterName); end @@ -83,7 +83,7 @@ dynareParallelMkDir(RemoteTmpFolder,DataInput); % Currently when errors are detected execution simply stops and users can % fix configuration errors according to the error type. -% Copyright (C) 2009-2013 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -106,38 +106,38 @@ 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), + if isempty(DataInput(Node).OperatingSystem) OStargetUnix=OScallerUnix; end OStargetWindows=strcmpi('windows',DataInput(Node).OperatingSystem); - if isempty(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() + skipline() else disp('The variable "Local" has a bad value!'); skipline() @@ -146,33 +146,33 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' 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]); @@ -182,7 +182,7 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' 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() @@ -193,16 +193,16 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' 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() @@ -213,9 +213,9 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' end disp('Check on UserName Variable ..... Ok!') skipline(2) - + % This check can be removed ... according to the dynare parser - % strategy. + % strategy. if (~isempty(DataInput(Node).Password)) disp('[WARNING] The field Password should be empty under unix or mac!'); skipline() @@ -229,10 +229,10 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' 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() @@ -246,15 +246,15 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' 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() @@ -263,10 +263,10 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' 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() @@ -276,17 +276,17 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' skipline(2) ErrorCode=5; end - + si2=[]; de2=[]; - if ~isempty(DataInput(Node).Port), + 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() @@ -295,16 +295,16 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' 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() @@ -313,12 +313,12 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' 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() @@ -327,31 +327,31 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' 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), + if isempty(SBS) DPStrNew=DPStr; else DPStrNew=[DPStr(1:SBS(1)),'\']; - for j=2:length(SBS), + for j=2:length(SBS) DPStrNew=[DPStrNew,DPStr(SBS(j-1)+1:SBS(j)),'\']; end DPStrNew=[DPStrNew,DPStr(SBS(end)+1:end)]; @@ -370,7 +370,7 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' 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'); @@ -378,12 +378,12 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' 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() @@ -395,14 +395,14 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' 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), + + if Environment + if ~isempty(DataInput(Node).Port) ssh_token = ['-p ',DataInput(Node).Port]; else ssh_token = ''; @@ -413,7 +413,7 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' 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 ~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 @@ -426,21 +426,22 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' [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; + + if t1(5)+1>60 t2=2; - else t2=t1(5)+1; + else + t2=t1(5)+1; end - + Flag=0; - - while (1); + + while (1) if Flag==0 disp('Try to run matlab/octave on remote machine ... ') skipline() @@ -450,18 +451,18 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' 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.') @@ -472,18 +473,18 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' 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() @@ -497,21 +498,21 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' if isempty(dynareParallelDir('IsMac.txt',RemoteTmpFolder,DataInput(Node))) RemoteEnvironment=Environment; else - RemoteEnvironment=2; + 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) @@ -523,16 +524,16 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' 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!') @@ -542,21 +543,21 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' 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 Environment if ~ismac [si0 de0]=system('grep processor /proc/cpuinfo'); else @@ -567,14 +568,14 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' [si0 de0]=system(['psinfo \\']); end else - if Environment, - if ~isempty(DataInput(Node).Port), + if Environment + if ~isempty(DataInput(Node).Port) ssh_token = ['-p ',DataInput(Node).Port]; else ssh_token = ''; end - if OStargetUnix, - if RemoteEnvironment ==1 , + 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']); @@ -587,16 +588,16 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' [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, + if isempty (RealCPUnbr) && Environment1==0 [si0 de0]=system(['psinfo \\',DataInput(Node).ComputerName]); - end + end RealCPUnbr=GiveCPUnumber(de0,Environment1); if isempty (RealCPUnbr) @@ -615,23 +616,23 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' 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, + 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) @@ -642,7 +643,7 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' 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),'!']) @@ -651,7 +652,7 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for' skipline() ErrorCode=2.3; end - + disp(['Test for Cluster computation, computer ',DataInput(Node).ComputerName, ' ..... Passed!']) - skipline(2) + skipline(2) end \ No newline at end of file diff --git a/matlab/parallel/CreateTimeString.m b/matlab/parallel/CreateTimeString.m index 8b82b1cc6..e78f8836a 100644 --- a/matlab/parallel/CreateTimeString.m +++ b/matlab/parallel/CreateTimeString.m @@ -6,9 +6,9 @@ function [TiSt] = CreateTimeString() % None % % OUTPUTS -% o TiSt [] ... +% o TiSt [] ... % -% Copyright (C) 2009-2010 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/parallel/GiveCPUnumber.m b/matlab/parallel/GiveCPUnumber.m index b45d3f879..cc2d45aa3 100644 --- a/matlab/parallel/GiveCPUnumber.m +++ b/matlab/parallel/GiveCPUnumber.m @@ -13,7 +13,7 @@ function [nCPU]= GiveCPUnumber (ComputerInformations, Environment) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2010-2013 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -33,7 +33,7 @@ function [nCPU]= GiveCPUnumber (ComputerInformations, Environment) nCPU=''; -if nargin < 2, +if nargin < 2 % Determine a specific operating system or software version when necessary % for different command (sintax, name, ...). Environment=~ispc; @@ -41,7 +41,7 @@ end switch Environment case 0 %WINDOWS OPERATING SYSTEM - + OffSet=27; SringPosition=strfind(ComputerInformations, 'Processors:'); @@ -64,7 +64,7 @@ switch Environment return case 1 %LIKE UNIX OPERATING SYSTEM - + % Da generalizzare a un numero di CPu maggiore di 9!!! nCPU=str2num(ComputerInformations(length(ComputerInformations)-1))+1; diff --git a/matlab/parallel/InitializeComputationalEnvironment.m b/matlab/parallel/InitializeComputationalEnvironment.m index 02df7aad4..18ce19f11 100644 --- a/matlab/parallel/InitializeComputationalEnvironment.m +++ b/matlab/parallel/InitializeComputationalEnvironment.m @@ -10,7 +10,7 @@ function InitializeComputationalEnvironment() % OUTPUTS % None % -% Copyright (C) 2009-2013 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -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 @@ -46,15 +46,15 @@ end global options_ isHybridMatlabOctave = false; -for j=1:length(options_.parallel), - if isempty(options_.parallel(j).MatlabOctavePath), +for j=1:length(options_.parallel) + if isempty(options_.parallel(j).MatlabOctavePath) if isoctave options_.parallel(j).MatlabOctavePath = 'octave'; else options_.parallel(j).MatlabOctavePath = 'matlab'; end end - if options_.parallel(j).Local && isempty(options_.parallel(j).DynarePath), + if options_.parallel(j).Local && isempty(options_.parallel(j).DynarePath) dynareroot = strrep(which('dynare'),'dynare.m',''); options_.parallel(j).DynarePath=dynareroot; end @@ -62,7 +62,7 @@ for j=1:length(options_.parallel), end isHybridMatlabOctave = isHybridMatlabOctave && ~isoctave; options_.parallel_info.isHybridMatlabOctave = isHybridMatlabOctave; -if isHybridMatlabOctave, +if isHybridMatlabOctave % Reset dynare random generator and seed. set_dynare_seed('default'); end @@ -94,7 +94,7 @@ CPUWeightTemp=ones(1,lP)*(-1); CPUWeightTemp=CPUWeight; for i=1:lP - [NoNServes mP]=max(CPUWeightTemp); + [NoNServes, mP]=max(CPUWeightTemp); NewPosition(i)=mP; CPUWeightTemp(mP)=-1; end diff --git a/matlab/parallel/closeSlave.m b/matlab/parallel/closeSlave.m index 03e310606..49c14deb3 100644 --- a/matlab/parallel/closeSlave.m +++ b/matlab/parallel/closeSlave.m @@ -1,4 +1,4 @@ -function closeSlave(Parallel,TmpFolder,partial), +function closeSlave(Parallel,TmpFolder,partial) % PARALLEL CONTEXT % In parallel context, this utility closes all remote matlab instances % called by masterParallel when strategy (1) is active i.e. always open (which leaves @@ -10,12 +10,12 @@ 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 % -% Copyright (C) 2010-2013 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -32,7 +32,7 @@ function closeSlave(Parallel,TmpFolder,partial), % You should have received a copy of the GNU General Public License % along with Dynare. If not, see . -if nargin<3, +if nargin<3 partial=0; end @@ -40,8 +40,8 @@ s=warning('off'); if partial==1 save('slaveParallel_break.mat','partial') - for indPC=1:length(Parallel), - if (Parallel(indPC).Local==0), + for indPC=1:length(Parallel) + if (Parallel(indPC).Local==0) dynareParallelSendFiles('slaveParallel_break.mat',TmpFolder,Parallel(indPC)); end end @@ -50,8 +50,8 @@ if partial==1 end if partial==-1 delete('slaveParallel_break.mat') - for indPC=1:length(Parallel), - if (Parallel(indPC).Local==0), + for indPC=1:length(Parallel) + if (Parallel(indPC).Local==0) dynareParallelDelete( 'slaveParallel_break.mat',TmpFolder,Parallel(indPC)); end end @@ -59,31 +59,30 @@ if partial==-1 return end -for indPC=1:length(Parallel), - if (Parallel(indPC).Local==0), +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) - if isempty(dynareParallelDir(['P_slave_',int2str(j),'End.txt'],TmpFolder,Parallel)); - for indPC=1:length(Parallel), - if (Parallel(indPC).Local==0), - dynareParallelRmDir(TmpFolder,Parallel(indPC)), + if isempty(dynareParallelDir(['P_slave_',int2str(j),'End.txt'],TmpFolder,Parallel)) + for indPC=1:length(Parallel) + if (Parallel(indPC).Local==0) + dynareParallelRmDir(TmpFolder,Parallel(indPC)) end end break - + end end -s=warning('on'); - +s=warning('on'); \ No newline at end of file diff --git a/matlab/parallel/distributeJobs.m b/matlab/parallel/distributeJobs.m index 65f2627a2..c0c41925f 100644 --- a/matlab/parallel/distributeJobs.m +++ b/matlab/parallel/distributeJobs.m @@ -21,7 +21,7 @@ function [nCPU, totCPU, nBlockPerCPU, totSLAVES] = distributeJobs(Parallel, fBlo % It is a number between 1 and length(Parallel). -% Copyright (C) 2010-2011 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -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; @@ -48,7 +48,7 @@ totCPU=0; lP=length(Parallel); CPUWeight=ones(1,length(Parallel))*(-1); -for j=1:lP, +for j=1:lP if mod(length(Parallel(j).CPUnbr),Parallel(j).NumberOfThreadsPerJob) skipline() disp(['PARALLEL_ERROR:: NumberOfThreadsPerJob = ',int2str(Parallel(j).NumberOfThreadsPerJob),' is not an exact divisor of number of CPUs = ',int2str(length(Parallel(j).CPUnbr)),'!']) @@ -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 @@ -77,7 +77,7 @@ NumbersOfJobs=nBlock-fBlock+1; SumOfJobs=0; JobsForNode=zeros(1,nC); -for j=1:lP, +for j=1:lP CPUWeight(j)=str2num(Parallel(j).NodeWeight)*nCPUoriginal(j); end CPUWeight=CPUWeight./sum(CPUWeight); @@ -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)); - + 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=JobsForNode(i) - break; + 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. -if nargin ==0, +if nargin ==0 disp('dynareParallelDelete(fname)') return end -if nargin ==1, +if nargin ==1 pname=''; else pname=[pname,filesep]; end -for indPC=1:length(Parallel), - if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem), - if ~isempty(Parallel(indPC).Port), +for indPC=1:length(Parallel) + if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem) + if ~isempty(Parallel(indPC).Port) ssh_token = ['-p ',Parallel(indPC).Port]; else ssh_token = ''; @@ -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 4f12357dd..34fdab44b 100644 --- a/matlab/parallel/dynareParallelDeleteNewFiles.m +++ b/matlab/parallel/dynareParallelDeleteNewFiles.m @@ -15,7 +15,7 @@ function dynareParallelDeleteNewFiles(PRCDir,Parallel,PRCDirSnapshot,varargin) % % % -% Copyright (C) 2009-2013 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -35,11 +35,11 @@ function dynareParallelDeleteNewFiles(PRCDir,Parallel,PRCDirSnapshot,varargin) NewFilesFromSlaves={}; % try -for indPC=1:length(Parallel), - - if Parallel(indPC).Local==0; +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), + if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem) fS='/'; else fS='\'; @@ -59,7 +59,7 @@ for indPC=1:length(Parallel), for indexc=1:length(varargin) exception_flag=exception_flag+(~isempty(strfind(fileaddress{2},varargin{indexc}))); end - if exception_flag==0, + if exception_flag==0 dynareParallelDelete(fileaddress{2},[PRCDir,fS,fileaddress{1}],Parallel(indPC)); disp('New file deleted in remote -->'); @@ -75,6 +75,3 @@ for indPC=1:length(Parallel), end end - - - diff --git a/matlab/parallel/dynareParallelDir.m b/matlab/parallel/dynareParallelDir.m index 6a9dd492c..0625dd8e7 100644 --- a/matlab/parallel/dynareParallelDir.m +++ b/matlab/parallel/dynareParallelDir.m @@ -10,7 +10,7 @@ function dirlist = dynareParallelDir(filename,PRCDir,Parallel) % OUTPUTS % o dirlist [] ... % -% Copyright (C) 2009-2013 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -28,10 +28,10 @@ function dirlist = dynareParallelDir(filename,PRCDir,Parallel) % along with Dynare. If not, see . dirlist=[]; -for indPC=1:length(Parallel), - if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem), - if Parallel(indPC).Local==0, - if ~isempty(Parallel(indPC).Port), +for indPC=1:length(Parallel) + if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem) + if Parallel(indPC).Local==0 + if ~isempty(Parallel(indPC).Port) ssh_token = ['-p ',Parallel(indPC).Port]; else ssh_token = ''; @@ -45,7 +45,7 @@ for indPC=1:length(Parallel), else [check, ax]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' ls ',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',filename]); end - if check ~= 0 || ~isempty(strfind(ax,'No such file or directory')); + if check ~= 0 || ~isempty(strfind(ax,'No such file or directory')) ax=[]; else indax=regexp(ax,'\n'); @@ -57,11 +57,11 @@ 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')); + + if check ~= 0 || ~isempty(strfind(ax,'No such file or directory')) ax=[]; end else @@ -75,32 +75,32 @@ for indPC=1:length(Parallel), end else if isoctave % Patch for peculiar behaviour of ls under Windows. - if Parallel(indPC).Local==0, + if Parallel(indPC).Local==0 ax0=dir(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',filename]); else ax0=dir(filename); end - if isempty(ax0), + if isempty(ax0) ax=''; else clear ax1; - for jax=1:length(ax0); + for jax=1:length(ax0) ax1{jax}=ax0(jax).name; end ax=char(ax1{:}); end else - if Parallel(indPC).Local==0, + if Parallel(indPC).Local==0 ax=ls(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',filename]); else ax=ls(filename); end end end - if isempty(dirlist), + if isempty(dirlist) dirlist=ax; - elseif ~isempty(ax), + elseif ~isempty(ax) dirlist = char(dirlist, ax); end end diff --git a/matlab/parallel/dynareParallelFindNewFiles.m b/matlab/parallel/dynareParallelFindNewFiles.m index 143f20870..d8cb6a9d7 100644 --- a/matlab/parallel/dynareParallelFindNewFiles.m +++ b/matlab/parallel/dynareParallelFindNewFiles.m @@ -15,7 +15,7 @@ function [NewFilesFrom, NewFileList]=dynareParallelFindNewFiles(FileList,Paralle % o NewFilesFrom [] ... % o NewFileList [] ... % -% Copyright (C) 2009-2011 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -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 9ec95f386..6669f21a8 100644 --- a/matlab/parallel/dynareParallelGetFiles.m +++ b/matlab/parallel/dynareParallelGetFiles.m @@ -14,7 +14,7 @@ function dynareParallelGetFiles(NamFileInput,PRCDir,Parallel) % % % -% Copyright (C) 2009-2013 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -33,32 +33,32 @@ function dynareParallelGetFiles(NamFileInput,PRCDir,Parallel) NamFileInput0=NamFileInput; -for indPC=1:length(Parallel), - if Parallel(indPC).Local==0, - if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem), - if ~isempty(Parallel(indPC).Port), +for indPC=1:length(Parallel) + if Parallel(indPC).Local==0 + if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem) + if ~isempty(Parallel(indPC).Port) ssh_token = ['-p ',Parallel(indPC).Port]; else ssh_token = ''; end - if ~isempty(Parallel(indPC).Port), + if ~isempty(Parallel(indPC).Port) scp_token = ['-P ',Parallel(indPC).Port]; else scp_token = ''; end - if ischar(NamFileInput0), - for j=1:size(NamFileInput0,1), + if ischar(NamFileInput0) + for j=1:size(NamFileInput0,1) NamFile(j,:)={['./'],deblank(NamFileInput0(j,:))}; end NamFileInput = NamFile; end - for jfil=1:size(NamFileInput,1), + for jfil=1:size(NamFileInput,1) if isoctave % Patch for peculiar behaviour of ls under Linux. % 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 @@ -92,14 +92,14 @@ for indPC=1:length(Parallel), end else - if ischar(NamFileInput0), - for j=1:size(NamFileInput0,1), + if ischar(NamFileInput0) + for j=1:size(NamFileInput0,1) NamFile(j,:)={['.\'],deblank(NamFileInput0(j,:))}; end NamFileInput = NamFile; end - for jfil=1:size(NamFileInput,1), - if ~isempty(dynareParallelDir(NamFileInput{jfil,2},[PRCDir,filesep,NamFileInput{jfil,1}],Parallel(indPC))), + for jfil=1:size(NamFileInput,1) + if ~isempty(dynareParallelDir(NamFileInput{jfil,2},[PRCDir,filesep,NamFileInput{jfil,1}],Parallel(indPC))) copyfile(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInput{jfil,1},NamFileInput{jfil,2}],NamFileInput{jfil,1}); end end diff --git a/matlab/parallel/dynareParallelGetNewFiles.m b/matlab/parallel/dynareParallelGetNewFiles.m index 5f7eb43a3..8d42bd375 100644 --- a/matlab/parallel/dynareParallelGetNewFiles.m +++ b/matlab/parallel/dynareParallelGetNewFiles.m @@ -15,7 +15,7 @@ function [PRCDirSnapshot]=dynareParallelGetNewFiles(PRCDir,Parallel,PRCDirSnapsh % % % -% Copyright (C) 2009-2013 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -36,11 +36,11 @@ function [PRCDirSnapshot]=dynareParallelGetNewFiles(PRCDir,Parallel,PRCDirSnapsh NewFilesFromSlaves={}; % try -for indPC=1:length(Parallel), - - if Parallel(indPC).Local==0; +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), + if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem) fS='/'; else fS='\'; @@ -71,6 +71,3 @@ for indPC=1:length(Parallel), end end - - - diff --git a/matlab/parallel/dynareParallelListAllFiles.m b/matlab/parallel/dynareParallelListAllFiles.m index 189908b71..eab713422 100644 --- a/matlab/parallel/dynareParallelListAllFiles.m +++ b/matlab/parallel/dynareParallelListAllFiles.m @@ -14,7 +14,7 @@ function fileList = dynareParallelListAllFiles(dirName,PRCDir,Parallel) % OUTPUTS % o fileList [] ... % -% Copyright (C) 2009-2013 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -34,33 +34,33 @@ function fileList = dynareParallelListAllFiles(dirName,PRCDir,Parallel) if (~ispc || strcmpi('unix',Parallel.OperatingSystem)) - + fileList={}; currentPath=[]; - if ~isempty(Parallel.Port), + if ~isempty(Parallel.Port) ssh_token = ['-p ',Parallel.Port]; else ssh_token = ''; end % 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']); + [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 @@ -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 9e8d7b7de..e85d1af3a 100644 --- a/matlab/parallel/dynareParallelMkDir.m +++ b/matlab/parallel/dynareParallelMkDir.m @@ -3,14 +3,14 @@ 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 % % -% Copyright (C) 2009-2013 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -29,24 +29,22 @@ function dynareParallelMkDir(PRCDir,Parallel) -if nargin ==0, +if nargin ==0 disp('dynareParallelMkDir(dirname,Parallel)') return end for indPC=1:length(Parallel) - if Parallel(indPC).Local==0, - if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem), - if ~isempty(Parallel(indPC).Port), + if Parallel(indPC).Local==0 + if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem) + if ~isempty(Parallel(indPC).Port) ssh_token = ['-p ',Parallel(indPC).Port]; else ssh_token = ''; end - [NonServeS NonServeD]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' mkdir -p ',Parallel(indPC).RemoteDirectory,'/',PRCDir]); + [NonServeS, NonServeD]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' mkdir -p ',Parallel(indPC).RemoteDirectory,'/',PRCDir]); else - [NonServeS NonServeD]=mkdir(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir]); + [NonServeS, NonServeD]=mkdir(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir]); end end -end - -return \ No newline at end of file +end \ No newline at end of file diff --git a/matlab/parallel/dynareParallelRmDir.m b/matlab/parallel/dynareParallelRmDir.m index fbf7b7790..64f3c4fde 100644 --- a/matlab/parallel/dynareParallelRmDir.m +++ b/matlab/parallel/dynareParallelRmDir.m @@ -3,15 +3,15 @@ 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 % % % -% Copyright (C) 2009-2013 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -30,7 +30,7 @@ function dynareParallelRmDir(PRCDir,Parallel) -if nargin ==0, +if nargin ==0 disp('dynareParallelRmDir(fname)') return end @@ -45,7 +45,7 @@ ok(5)=~isempty(strfind(PRCDir,'m')); ok(6)=~isempty(strfind(PRCDir,'s')); ok(7)=~isempty(PRCDir); -if sum(ok)<7, +if sum(ok)<7 error('The name of the remote tmp folder does not comply the security standards!'), end @@ -53,34 +53,32 @@ if isoctave confirm_recursive_rmdir(false, 'local'); end -for indPC=1:length(Parallel), +for indPC=1:length(Parallel) ok(1)=isempty(strfind(Parallel(indPC).RemoteDirectory,'..')); - if sum(ok)<7, + if sum(ok)<7 error('The remote folder path structure does not comply the security standards!'), end while (1) - if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem), - if ~isempty(Parallel(indPC).Port), + if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem) + if ~isempty(Parallel(indPC).Port) ssh_token = ['-p ',Parallel(indPC).Port]; else ssh_token = ''; end - [stat NonServe] = system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' rm -fr ',Parallel(indPC).RemoteDirectory,'/',PRCDir,]); - break; + [stat, NonServe] = system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' rm -fr ',Parallel(indPC).RemoteDirectory,'/',PRCDir,]); + break else [stat, mess, id] = rmdir(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir],'s'); - if stat==1, - break, + if stat==1 + break else - if isempty(dynareParallelDir(PRCDir,'',Parallel)); - break, + if isempty(dynareParallelDir(PRCDir,'',Parallel)) + break else pause(1); end end end end -end - -return \ No newline at end of file +end \ No newline at end of file diff --git a/matlab/parallel/dynareParallelSendFiles.m b/matlab/parallel/dynareParallelSendFiles.m index f65697286..6a3c8904c 100644 --- a/matlab/parallel/dynareParallelSendFiles.m +++ b/matlab/parallel/dynareParallelSendFiles.m @@ -14,7 +14,7 @@ function dynareParallelSendFiles(NamFileInput,PRCDir,Parallel) % % % -% Copyright (C) 2009-2013 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -32,83 +32,83 @@ function dynareParallelSendFiles(NamFileInput,PRCDir,Parallel) % along with Dynare. If not, see . -if ischar(NamFileInput), - for j=1:size(NamFileInput,1), +if ischar(NamFileInput) + for j=1:size(NamFileInput,1) NamFile(j,:)={'',deblank(NamFileInput(j,:))}; end NamFileInput = NamFile; end -for indPC=1:length(Parallel), - if Parallel(indPC).Local==0, - if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem), - if ~isempty(Parallel(indPC).Port), +for indPC=1:length(Parallel) + if Parallel(indPC).Local==0 + if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem) + if ~isempty(Parallel(indPC).Port) ssh_token = ['-p ',Parallel(indPC).Port]; else ssh_token = ''; end - if ~isempty(Parallel(indPC).Port), + if ~isempty(Parallel(indPC).Port) scp_token = ['-P ',Parallel(indPC).Port]; else scp_token = ''; end - for jfil=1:size(NamFileInput,1), + for jfil=1:size(NamFileInput,1) if ~isempty(NamFileInput{jfil,1}) - [NonServeL NonServeR]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' mkdir -p ',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',NamFileInput{jfil,1}]); + [NonServeL, NonServeR]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' mkdir -p ',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',NamFileInput{jfil,1}]); end - [NonServeL NonServeR]=system(['scp ',scp_token,' ',NamFileInput{jfil,1},NamFileInput{jfil,2},' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,':',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',NamFileInput{jfil,1}]); + [NonServeL, NonServeR]=system(['scp ',scp_token,' ',NamFileInput{jfil,1},NamFileInput{jfil,2},' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,':',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',NamFileInput{jfil,1}]); end else 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. - + NamFileInputTemp=NamFileInput{jfil,1}; while(1) Bs=strfind(NamFileInputTemp,'/'); - if isempty(Bs), - break; + if isempty(Bs) + break else NamFileInputTemp(1,Bs)='\'; end end - - [NonServeL NonServeR]=system(['mkdir \\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInputTemp]); + + [NonServeL, NonServeR]=system(['mkdir \\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInputTemp]); else mkdir(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInput{jfil,1}]); 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. - + NamFileInputTemp=NamFileInput{jfil,1}; while(1) Bs=strfind(NamFileInputTemp,'/'); - if isempty(Bs), - break; + if isempty(Bs) + break else NamFileInputTemp(1,Bs)='\'; end end - - [NonServeS NonServeD]=system(['copy ',NamFileInputTemp, NamFileInput{jfil,2},' \\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInputTemp]); - + + [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 ebff7a33c..8566ebfe0 100644 --- a/matlab/parallel/dynareParallelSnapshot.m +++ b/matlab/parallel/dynareParallelSnapshot.m @@ -14,7 +14,7 @@ function [PRCDirSnapshot]=dynareParallelSnapshot(PRCDir,Parallel) % % % -% Copyright (C) 2009-2011 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -33,10 +33,10 @@ function [PRCDirSnapshot]=dynareParallelSnapshot(PRCDir,Parallel) PRCDirSnapshot={}; -for indPC=1:length(Parallel), - if Parallel(indPC).Local==0; +for indPC=1:length(Parallel) + if Parallel(indPC).Local==0 % 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 6d84705ab..2c9f8ab5f 100644 --- a/matlab/parallel/fMessageStatus.m +++ b/matlab/parallel/fMessageStatus.m @@ -3,18 +3,18 @@ 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-2012 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -33,18 +33,17 @@ function fMessageStatus(prtfrc, njob, waitbarString, waitbarTitle, Parallel) global funcName -if nargin<5, +if nargin<5 Parallel.Local=1; end try save(['comp_status_',funcName,int2str(njob),'.mat'],'prtfrc','njob','waitbarString','waitbarTitle'); -catch +catch end fslave = dir( ['slaveParallel_input',int2str(njob),'.mat']); fbreak = dir( ['slaveParallel_break.mat']); -if isempty(fslave) || ~isempty(fbreak), +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 51e6ebe16..4bce41008 100644 --- a/matlab/parallel/fParallel.m +++ b/matlab/parallel/fParallel.m @@ -18,7 +18,7 @@ function fParallel(fblck,nblck,whoiam,ThisMatlab,fname) % OUTPUTS % None % -% Copyright (C) 2006-2012 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -53,7 +53,7 @@ load( [fname,'_input']) if exist('fGlobalVar') && ~isempty (fGlobalVar) globalVars = fieldnames(fGlobalVar); - for j=1:length(globalVars), + for j=1:length(globalVars) eval(['global ',globalVars{j},';']) evalin('base',['global ',globalVars{j},';']) end @@ -67,12 +67,12 @@ fInputVar.Parallel = Parallel; % Launch the routine to be run in parallel. -try, - tic, - +try + tic + fOutputVar = feval(fname, fInputVar ,fblck, nblck, whoiam, ThisMatlab); - toc, - if isfield(fOutputVar,'OutputFileName'), + toc + if isfield(fOutputVar,'OutputFileName') OutputFileName = fOutputVar.OutputFileName; else OutputFileName = ''; @@ -81,15 +81,15 @@ try, % Save the output result. save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' ) end - if isfield(fOutputVar,'CloseAllSlaves'), + if isfield(fOutputVar,'CloseAllSlaves') CloseAllSlaves = 1; fOutputVar = rmfield(fOutputVar,'CloseAllSlaves'); save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' ) save(['comp_status_',funcName,int2str(whoiam),'.mat'],'CloseAllSlaves'); end - + disp(['fParallel ',int2str(whoiam),' completed.']) -catch, +catch theerror = lasterror; if strfind(theerror.message,'Master asked to break the job') fOutputVar.message = theerror; @@ -101,14 +101,14 @@ catch, save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' ) waitbarString = theerror.message; % waitbarTitle=['Metropolis-Hastings ',options_.parallel(ThisMatlab).ComputerName]; - if Parallel(ThisMatlab).Local, + if Parallel(ThisMatlab).Local waitbarTitle='Local '; else waitbarTitle=[Parallel(ThisMatlab).ComputerName]; 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 f5a5b50fd..e51c6d023 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 @@ -62,7 +62,7 @@ function [fOutVar,nBlockPerCPU, totCPU] = masterParallel(Parallel,fBlock,nBlock, % the number of CPUs declared in "Parallel", if % the number of required threads is lower) -% Copyright (C) 2009-2015 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -91,11 +91,11 @@ Strategy=Parallel_info.leaveSlaveOpen; islocal = 1; isHybridMatlabOctave = Parallel_info.isHybridMatlabOctave; -for j=1:length(Parallel), +for j=1:length(Parallel) islocal=islocal*Parallel(j).Local; end if nargin>8 && initialize==1 - if islocal == 0, + if islocal == 0 PRCDir=CreateTimeString(); assignin('base','PRCDirTmp',PRCDir), evalin('base','options_.parallel_info.RemoteTmpFolder=PRCDirTmp;') @@ -108,7 +108,7 @@ if nargin>8 && initialize==1 end if isfield(Parallel_info,'local_files') - if isempty(NamFileInput), + if isempty(NamFileInput) NamFileInput=Parallel_info.local_files; else NamFileInput=[NamFileInput;Parallel_info.local_files]; @@ -120,26 +120,26 @@ end % in Octave! if isoctave - warning('off'); + warning('off') end % check if there are function_handles in the input or global vars when % octave is used if isHybridMatlabOctave || isoctave fInputNames = fieldnames(fInputVar); - for j=1:length(fInputNames), + for j=1:length(fInputNames) TargetVar = fInputVar.(fInputNames{j}); - if isa(TargetVar,'function_handle'), + if isa(TargetVar,'function_handle') TargetVar=func2str(TargetVar); fInputVar.(fInputNames{j})=TargetVar; end end - - if exist('fGlobalVar','var') && ~isempty(fGlobalVar), + + if exist('fGlobalVar','var') && ~isempty(fGlobalVar) fInputNames = fieldnames(fGlobalVar); - for j=1:length(fInputNames), + for j=1:length(fInputNames) TargetVar = fGlobalVar.(fInputNames{j}); - if isa(TargetVar,'function_handle'), + if isa(TargetVar,'function_handle') TargetVar=func2str(TargetVar); fGlobalVar.(fInputNames{j})=TargetVar; end @@ -156,7 +156,7 @@ end DyMo=pwd; % fInputVar.DyMo=DyMo; -if ispc, +if ispc [tempo, MasterName]=system('hostname'); MasterName=deblank(MasterName); end @@ -168,9 +168,9 @@ switch Strategy case 0 storeGlobalVars([fname,'_input.mat']); save([fname,'_input.mat'],'fInputVar','Parallel','-append') - + case 1 - if exist('fGlobalVar','var'), + if exist('fGlobalVar','var') save(['temp_input.mat'],'fInputVar','fGlobalVar') else save(['temp_input.mat'],'fInputVar') @@ -184,7 +184,7 @@ end % to run on each CPU. [nCPU, totCPU, nBlockPerCPU, totSlaves] = distributeJobs(Parallel, fBlock, nBlock); -for j=1:totSlaves, +for j=1:totSlaves PRCDirSnapshot{j}={}; end offset0 = fBlock-1; @@ -206,7 +206,7 @@ fid = fopen('ConcurrentCommand1.bat','w+'); % Create the directory devoted to remote computation. -if isempty(PRCDir) && ~islocal, +if isempty(PRCDir) && ~islocal error('PRCDir not initialized!') else dynareParallelMkDir(PRCDir,Parallel(1:totSlaves)); @@ -238,27 +238,27 @@ end % End -for j=1:totCPU, - +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), + + + if strcmp('true',Parallel(indPC).SingleCompThread) compThread = '-singleCompThread'; else compThread = ''; end - + nthreads=Parallel(indPC).NumberOfThreadsPerJob; if indPC>1 nCPU0 = nCPU(indPC-1); @@ -266,20 +266,20 @@ 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, - + + if Strategy==1 + fblck = offset+1; nblck = sum(nBlockPerCPU(1:j)); save temp_input.mat fblck nblck fname -append; copyfile('temp_input.mat',['slaveJob',int2str(j),'.mat']); - if Parallel(indPC).Local ==0, + if Parallel(indPC).Local ==0 fid1=fopen(['stayalive',int2str(j),'.txt'],'w+'); fclose(fid1); dynareParallelSendFiles(['stayalive',int2str(j),'.txt'],PRCDir,Parallel(indPC)); @@ -289,57 +289,57 @@ 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))); + if isempty(dynareParallelDir(['P_slave_',int2str(j),'End.txt'],PRCDir,Parallel(indPC))) fid1=fopen(['P_slave_',int2str(j),'End.txt'],'w+'); fclose(fid1); - if Parallel(indPC).Local==0, + if Parallel(indPC).Local==0 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, + + 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), + for jaff=2:length(affinity_range) my_affinity = [my_affinity ',' int2str(Parallel(indPC).CPUnbr(affinity_range(jaff)))]; end % % % 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 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 @@ -353,16 +353,18 @@ for j=1:totCPU, end end else % 0.2 Parallel(indPC).Local==0: Run using network on remote machine or also on local machine. - if j==nCPU0+1, + 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 = ''; + + if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)) % Hybrid computing Windows <-> Unix! + if ispc + token='start /B '; + else + token = ''; end - if ~isempty(Parallel(indPC).Port), + if ~isempty(Parallel(indPC).Port) ssh_token = ['-p ',Parallel(indPC).Port]; else ssh_token = ''; @@ -370,7 +372,7 @@ 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! + 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 @@ -382,13 +384,13 @@ for j=1:totCPU, 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) % 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=['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 @@ -404,11 +406,11 @@ for j=1:totCPU, 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 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 @@ -421,21 +423,23 @@ for j=1:totCPU, 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, + 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, + 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 = ''; + if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)) % Hybrid computing Windows <-> Unix! + if ispc + token='start /B '; + else + token = ''; end - if ~isempty(Parallel(indPC).Port), + if ~isempty(Parallel(indPC).Port) ssh_token = ['-p ',Parallel(indPC).Port]; else ssh_token = ''; @@ -455,8 +459,8 @@ for j=1:totCPU, 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 ~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),')"']; @@ -479,8 +483,8 @@ for j=1:totCPU, % When the user user strategy is equal to 1, you must % do PRCDirSnapshot here to to avoid problems of % synchronization. - - if isempty(PRCDirSnapshot{indPC}), + + if isempty(PRCDirSnapshot{indPC}) PRCDirSnapshot(indPC)=dynareParallelSnapshot(PRCDir,Parallel(indPC)); PRCDirSnapshotInit(indPC) = PRCDirSnapshot(indPC); else @@ -488,14 +492,14 @@ for j=1:totCPU, 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 @@ -511,16 +515,16 @@ end % the slaves ... % If the compuation is 'Local' it is not necessary to do it ... -if Strategy==0 || newInstance, % See above. +if Strategy==0 || newInstance % See above. PRCDirSnapshot=dynareParallelSnapshot(PRCDir,Parallel(1:totSlaves)); PRCDirSnapshotInit = PRCDirSnapshot; - + % Run the slaves. - if ~ispc, + 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. @@ -556,7 +560,7 @@ else '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], ... @@ -569,16 +573,16 @@ else set(hstatus(1),'Units','normalized'), vspace = max(0.1,1/totCPU); vstart = 1-vspace+0.2*vspace; - for j=1:totCPU, + for j=1:totCPU 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]); 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); @@ -592,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)=' '; @@ -613,27 +617,27 @@ if options_.console_mode || isoctave fnameTemp(i)='.'; end end - + for i=1:L - if fnameTemp(i)=='_'; + 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 @@ -649,26 +653,26 @@ statusString = ''; flag_CloseAllSlaves=0; while (ForEver) - + waitbarString = ''; statusString0 = repmat('\b',1,length(sprintf(statusString, 100 .* pcerdone))); statusString = ''; - + pause(1) - + try - if islocal ==0, + if islocal ==0 dynareParallelGetFiles(['comp_status_',fname,'*.mat'],PRCDir,Parallel(1:totSlaves)); end catch end - - for j=1:totCPU, + + 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']); - if exist('CloseAllSlaves') && flag_CloseAllSlaves==0, + if exist('CloseAllSlaves') && flag_CloseAllSlaves==0 flag_CloseAllSlaves=1; whoiamCloseAllSlaves=j; closeSlave(Parallel(1:totSlaves),PRCDir,1); @@ -706,20 +710,20 @@ while (ForEver) end end else - for j=1:totCPU, + for j=1:totCPU try 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); @@ -728,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))); + + if isempty(dynareParallelDir(['P_',fname,'_*End.txt'],PRCDir,Parallel(1:totSlaves))) HoTuttiGliOutput=0; - for j=1:totCPU, - + 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; @@ -741,8 +745,8 @@ while (ForEver) dynareParallelGetFiles([fname,'_output_',int2str(j),'.mat'],PRCDir,Parallel(indPC)); end end - - if HoTuttiGliOutput==totCPU, + + if HoTuttiGliOutput==totCPU mydelete(['comp_status_',fname,'*.mat']); if isoctave || options_.console_mode if isoctave @@ -754,15 +758,15 @@ while (ForEver) end diary on; else - close(hfigstatus), + close(hfigstatus) end - + break else disp('Waiting for output files from slaves ...') end end - + end @@ -770,19 +774,19 @@ end iscrash = 0; PRCDirSnapshot=dynareParallelGetNewFiles(PRCDir,Parallel(1:totSlaves),PRCDirSnapshot); -for j=1:totCPU, +for j=1:totCPU indPC=min(find(nCPU>=j)); load([fname,'_output_',int2str(j),'.mat'],'fOutputVar'); delete([fname,'_output_',int2str(j),'.mat']); - if isfield(fOutputVar,'OutputFileName') && Parallel(indPC).Local==0, + 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), + for i=1:size(NamFileInput,1) FileList = regexp(strrep(PRCDirSnapshot{indPC},'\','/'),strrep(strrep([NamFileInput{i,:}],'\','/'),'*','(\w*)'),'match'); - for k=1:length(FileList), - if ~isempty(FileList{k}), - if isempty(tmp0), + for k=1:length(FileList) + if ~isempty(FileList{k}) + if isempty(tmp0) tmp0=FileList{k}{1}; else tmp0=char(tmp0,FileList{k}{1}); @@ -790,78 +794,78 @@ for j=1:totCPU, end end end - for i=1:size(OutputFileName,1), + for i=1:size(OutputFileName,1) tmp1=''; FileList = regexp(cellstr(tmp0),strrep(strrep([OutputFileName{i,:}],'\','/'),'*','(\w*)'),'match'); FileList0 = regexp(cellstr(tmp0),strrep([OutputFileName{i,2}],'*','(\w*)'),'match'); - for k=1:length(FileList), - if ~isempty(FileList{k}), - if isempty(tmp1), + for k=1:length(FileList) + if ~isempty(FileList{k}) + if isempty(tmp1) tmp1=FileList0{k}{1}; else tmp1=char(tmp1,FileList0{k}{1}); end end end - for k=1:size(tmp1,1), + for k=1:size(tmp1,1) dynareParallelGetFiles([OutputFileName(i,1) {tmp1(k,:)}],PRCDir,Parallel(indPC)); end end % check if some output file is missing! - for i=1:size(OutputFileName,1), + for i=1:size(OutputFileName,1) tmp1=dynareParallelDir([OutputFileName{i,:}],PRCDir,Parallel(indPC)); tmp1 = regexp(cellstr(tmp1),strrep([OutputFileName{i,2}],'*','(\w*)'),'match'); tmp1 = char(tmp1{:}); tmp2=ls([OutputFileName{i,:}]); - for ij=1:size(tmp1,1), + for ij=1:size(tmp1,1) icheck = regexp(cellstr(tmp2),tmp1(ij,:),'once'); isOutputFileMissing=1; - for ik=1:size(tmp2,1), - if ~isempty(icheck{ik}), + for ik=1:size(tmp2,1) + if ~isempty(icheck{ik}) isOutputFileMissing=0; end end - if isOutputFileMissing, + if isOutputFileMissing dynareParallelGetFiles([OutputFileName(i,1) {tmp1(ij,:)}],PRCDir,Parallel(indPC)); end end end end - if isfield(fOutputVar,'error'), + if isfield(fOutputVar,'error') disp(['Job number ',int2str(j),' crashed with error:']); iscrash=1; disp([fOutputVar.error.message]); for jstack=1:length(fOutputVar.error.stack) - fOutputVar.error.stack(jstack), + fOutputVar.error.stack(jstack) end - elseif flag_CloseAllSlaves==0, + elseif flag_CloseAllSlaves==0 fOutVar(j)=fOutputVar; - elseif j==whoiamCloseAllSlaves, - fOutVar=fOutputVar; + elseif j==whoiamCloseAllSlaves + fOutVar=fOutputVar; end end -if flag_CloseAllSlaves==1, +if flag_CloseAllSlaves==1 closeSlave(Parallel(1:totSlaves),PRCDir,-1); end -if iscrash, +if iscrash error('Remote jobs crashed'); end -pause(1), % Wait for all remote diary off completed +pause(1) % Wait for all remote diary off completed % Cleanup. dynareParallelGetFiles('*.log',PRCDir,Parallel(1:totSlaves)); switch Strategy case 0 - for indPC=1:min(find(nCPU>=totCPU)), + 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'); @@ -871,29 +875,29 @@ switch Strategy mydelete([fname,'*.log']); catch end - + mydelete(['*_core*_input*.mat']); - + end - + delete ConcurrentCommand1.bat case 1 delete(['temp_input.mat']) - if newInstance, + if newInstance if isempty(dir('dynareParallelLogFiles')) [A B C]=rmdir('dynareParallelLogFiles'); mkdir('dynareParallelLogFiles'); end end copyfile('*.log','dynareParallelLogFiles'); - if newInstance, + 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, + 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), + for ifil=1:size(NamFileInput,1) dynareParallelDelete([NamFileInput{ifil,:}],PRCDir,Parallel(indPC)); end end diff --git a/matlab/parallel/slaveParallel.m b/matlab/parallel/slaveParallel.m index 5de311575..5e3fe460c 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,10 +12,10 @@ function slaveParallel(whoiam,ThisMatlab) % cluster. % o ThisMatlab [int] index number of this slave machine in the cluster. % -% OUTPUTS -% None +% OUTPUTS +% None -% Copyright (C) 2006-2012 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -48,9 +48,9 @@ dynareroot = dynare_config(); load( ['slaveParallel_input',int2str(whoiam)]); %Loads fGlobalVar Parallel. -if exist('fGlobalVar'), +if exist('fGlobalVar') globalVars = fieldnames(fGlobalVar); - for j=1:length(globalVars), + for j=1:length(globalVars) eval(['global ',globalVars{j},';']); evalin('base',['global ',globalVars{j},';']); end @@ -65,50 +65,50 @@ end t0=clock; fslave = dir( ['slaveParallel_input',int2str(whoiam),'.mat']); -while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',int2str(whoiam),'.txt'])), - if ~isempty(dir(['stayalive',int2str(whoiam),'.txt'])), +while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',int2str(whoiam),'.txt'])) + if ~isempty(dir(['stayalive',int2str(whoiam),'.txt'])) t0=clock; delete(['stayalive',int2str(whoiam),'.txt']); end % I wait for 20 min or while mater asks to exit (i.e. it cancels fslave file) - pause(1); - + pause(1) + fjob = dir(['slaveJob',int2str(whoiam),'.mat']); - - if ~isempty(fjob), + + 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); + 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) globalVars = fieldnames(fGlobalVar); - for j=1:length(globalVars), + for j=1:length(globalVars) info_whos = whos(globalVars{j}); - if isempty(info_whos) || ~info_whos.global, + if isempty(info_whos) || ~info_whos.global eval(['global ',globalVars{j},';']); evalin('base',['global ',globalVars{j},';']); end @@ -120,13 +120,13 @@ 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, + try + tic fOutputVar = feval(fname, fInputVar ,fblck, nblck, whoiam, ThisMatlab); - toc, - if isfield(fOutputVar,'OutputFileName'), + toc + if isfield(fOutputVar,'OutputFileName') OutputFileName = fOutputVar.OutputFileName; else OutputFileName = ''; @@ -137,7 +137,7 @@ while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',in % Save the output result. save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' ); % keyboard, - if isfield(fOutputVar,'CloseAllSlaves'), + if isfield(fOutputVar,'CloseAllSlaves') CloseAllSlaves = 1; fOutputVar = rmfield(fOutputVar,'CloseAllSlaves'); save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' ) @@ -150,7 +150,7 @@ while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',in disp(['Job ',fname,' on CPU ',int2str(whoiam),' completed.']); t0 =clock; % Re-set waiting time of 20 mins - catch, + catch theerror = lasterror; if strfind(theerror.message,'Master asked to break the job') disp(['Job ',fname,' on CPU ',int2str(whoiam),' broken from master.']); @@ -162,7 +162,7 @@ while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',in fOutputVar.error = lasterror; save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' ); waitbarString = fOutputVar.error.message; - if Parallel(ThisMatlab).Local, + if Parallel(ThisMatlab).Local waitbarTitle='Local '; else waitbarTitle=[Parallel(ThisMatlab).ComputerName]; @@ -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 cd0470c37..79b86aa35 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 @@ -12,7 +12,7 @@ function storeGlobalVars(fname,append) % None % % -% Copyright (C) 2009-2011 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -32,12 +32,12 @@ function storeGlobalVars(fname,append) GlobalNames = who('global'); % varlist = ''; -for j=1:length(GlobalNames); +for j=1:length(GlobalNames) eval(['global ',GlobalNames{j},';']); eval(['fGlobalVar.',GlobalNames{j},'=',GlobalNames{j},';']); end -if nargin<2, +if nargin<2 save(fname,'fGlobalVar'); else save(fname,'fGlobalVar','-append'); diff --git a/matlab/parallel/struct2local.m b/matlab/parallel/struct2local.m index fbe9666f0..d45bc12b8 100644 --- a/matlab/parallel/struct2local.m +++ b/matlab/parallel/struct2local.m @@ -6,11 +6,11 @@ function struct2local(S) % % INPUTS % o S [struc] This structure possibly containing several fields ... -% +% % OUTPUTS % None % -% Copyright (C) 2009-2010 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -30,6 +30,6 @@ function struct2local(S) vnam = fieldnames(S); -for j=1:length(vnam), +for j=1:length(vnam) assignin('caller',vnam{j},getfield(S,vnam{j})); end diff --git a/matlab/partial_information/PCL_Part_info_irf.m b/matlab/partial_information/PCL_Part_info_irf.m index 2fc0ff1d8..0c3c17c2b 100644 --- a/matlab/partial_information/PCL_Part_info_irf.m +++ b/matlab/partial_information/PCL_Part_info_irf.m @@ -1,11 +1,11 @@ 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-2011 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -23,8 +23,8 @@ function y=PCL_Part_info_irf( H, varobs, ivar, M_, dr, irfpers,ii) % along with Dynare. If not, see . -% 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; +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 fdebe317f..bb16b6604 100644 --- a/matlab/partial_information/PCL_Part_info_moments.m +++ b/matlab/partial_information/PCL_Part_info_moments.m @@ -1,11 +1,11 @@ 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-2012 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . -% 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 @@ -48,13 +48,13 @@ LL = sparse(1:NOBS,OBS,ones(NOBS,1),NY,NY); if exist( 'irfpers')==1 if ~isempty(irfpers) - if irfpers<=0, irfpers=20, end; + if irfpers<=0, irfpers=20, end else irfpers=20; 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,9 +168,9 @@ end ar = options_.ar; if ar > 0 - COV_YRk= zeros(nn,ar); - AutoCOR_YRk= zeros(nn,ar); - for k=1: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); COV_YRk = VV*COV_OMEGA*VV'; diff --git a/matlab/partial_information/PCL_resol.m b/matlab/partial_information/PCL_resol.m index ba0b1666f..8f6bf4239 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 @@ -25,7 +25,7 @@ function [dr,info]=PCL_resol(ys,check_flag) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2001-2012 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -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 c46d45d07..589e39dc1 100644 --- a/matlab/partial_information/PI_gensys.m +++ b/matlab/partial_information/PI_gensys.m @@ -16,7 +16,7 @@ function [G1pi,C,impact,nmat,TT1,TT2,gev,eu, DD, E2, E5, GAMMA, FL_RANK ]=PI_gen % Corrected 10/28/96 by CAS % Copyright (C) 1996-2009 Christopher Sims -% Copyright (C) 2010-2011 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -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 @@ -96,7 +96,7 @@ try else warning('PI_gensys: Evading inversion of zero matrix UAVinv=inv(U02''*a1*V02)!'); eu=[0,0]; - return; + return end end catch @@ -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; @@ -171,14 +171,14 @@ if(options_.ACES_solver==1) zeros(num_inst,size(E3,2)), II; ]; eu =[1; 1], nmat=[], gev=[]; - return; % do not check B&K compliancy + return % do not check B&K compliancy 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 5dc26ec63..b0c085faf 100644 --- a/matlab/partial_information/PI_gensys_singularC.m +++ b/matlab/partial_information/PI_gensys_singularC.m @@ -1,13 +1,13 @@ 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 -% Copyright (C) 1996-2011 Dynare Team +% Copyright (C) 1996-2017 Dynare Team % % This file is part of Dynare. % @@ -86,7 +86,4 @@ catch [errmsg, errcode]=lasterr; warning(['error callig PI_gensys_singularC: ' errmsg ],'errcode'); error('errcode',['error callig PI_gensys_singularC: ' errmsg ]); -end - -return; - +end \ No newline at end of file diff --git a/matlab/partial_information/add_auxiliary_variables_to_steadystate.m b/matlab/partial_information/add_auxiliary_variables_to_steadystate.m index d99e36ebb..f90e7f6b0 100644 --- a/matlab/partial_information/add_auxiliary_variables_to_steadystate.m +++ b/matlab/partial_information/add_auxiliary_variables_to_steadystate.m @@ -2,7 +2,7 @@ function ys1 = add_auxiliary_variables_to_steadystate(ys,aux_vars,fname, ... exo_steady_state, exo_det_steady_state,params, byte_code) % Add auxiliary variables to the steady state vector -% Copyright (C) 2009-2011 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -21,7 +21,7 @@ function ys1 = add_auxiliary_variables_to_steadystate(ys,aux_vars,fname, ... n = length(aux_vars); ys1 = [ys;zeros(n,1)]; -for i=1:n+1; +for i=1:n+1 if byte_code [info, res] = bytecode('static','evaluate',ys1,... [exo_steady_state; ... @@ -30,7 +30,7 @@ for i=1:n+1; res = feval([fname '_static'],ys1,... [exo_steady_state; ... exo_det_steady_state],params); - end; + end for j=1:n el = aux_vars(j).endo_index; ys1(el) = ys1(el)-res(el); diff --git a/matlab/partial_information/disc_riccati_fast.m b/matlab/partial_information/disc_riccati_fast.m index 4a0bd0401..c97da7a12 100644 --- a/matlab/partial_information/disc_riccati_fast.m +++ b/matlab/partial_information/disc_riccati_fast.m @@ -1,17 +1,17 @@ function Z=disc_riccati_fast(F,D,R,H,ch) % function Z=disc_riccati_fast(F,D,R,H,ch) -% -% Solves discrete Riccati Equation: -% Z=FZF' - FZD'inv(DZD'+R)DZF' + H -% Using the Doubling Algorithm % -% George Perendia: based on the doubling algorithm for Riccati -% and the disclyap_fast function provided by Prof. Joe Pearlman +% Solves discrete Riccati Equation: +% Z=FZF' - FZD'inv(DZD'+R)DZF' + H +% Using the Doubling Algorithm +% +% 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 % ================================================================= -% Copyright (C) 2006-2011 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . -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 3e101a7a6..5dfcfe4b5 100644 --- a/matlab/partial_information/disclyap_fast.m +++ b/matlab/partial_information/disclyap_fast.m @@ -3,23 +3,23 @@ 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-2016 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . -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 0475d4bef..04fe8d926 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,31 +16,31 @@ 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-2012 Dynare Team +% Copyright (C) 1996-2017 Dynare Team % % This file is part of Dynare. % @@ -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,8 +449,6 @@ end % end if useAIM and... end end - % TODO: + % TODO: % if options_.loglinear == 1 - % if exogenous deterministic variables - - return; + % if exogenous deterministic variables \ No newline at end of file diff --git a/matlab/particles b/matlab/particles index 823d94748..84d213ea3 160000 --- a/matlab/particles +++ b/matlab/particles @@ -1 +1 @@ -Subproject commit 823d947484675c8d409a4eb2377a57dc59bdf713 +Subproject commit 84d213ea3e705f36871bc8f960d175a330fd71de diff --git a/matlab/perfect-foresight-models/det_cond_forecast.m b/matlab/perfect-foresight-models/det_cond_forecast.m index df64df222..ee177d830 100644 --- a/matlab/perfect-foresight-models/det_cond_forecast.m +++ b/matlab/perfect-foresight-models/det_cond_forecast.m @@ -12,7 +12,7 @@ function data_set = det_cond_forecast(varargin) % dataset [dseries] Returns a dseries containing the forecasted endgenous variables and shocks % % -% Copyright (C) 2013-2016 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % @@ -35,8 +35,8 @@ initial_conditions = oo_.steady_state; verbosity = options_.verbosity; if options_.periods == 0 options_.periods = 25; -end; -%We have to get an initial guess for the conditional forecast +end +%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)) @@ -64,7 +64,7 @@ if length(varargin) > 3 nvars = length(constrained_vars); for i = 1:max_periods_simulation constraint_index{i} = 1:nvars; - end; + end direct_mode = 0; shocks_present = 0; controlled_varexo = options_cond_fcst.controlled_varexo; @@ -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,7 +102,7 @@ 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; @@ -113,9 +113,9 @@ 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) @@ -123,7 +123,7 @@ else initial_conditions(iy) = sym_dset.data(1, i); else ix = find(strcmp(strtrim(sym_dset.name{i}), strtrim(plan.exo_names))); - if ~isempty(ix) + 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!!']); @@ -147,7 +147,7 @@ else % steady-state %for jj = 2 : (options_.periods + 2) for jj = 2 : (range.ndat + 2) - oo_.endo_simul(:, jj) = oo_.steady_state; + oo_.endo_simul(:, jj) = oo_.steady_state; end missings = isnan(oo_.endo_simul(:,1)); if any(missings) @@ -169,7 +169,7 @@ else 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) @@ -193,30 +193,30 @@ else end end data_set = merge(dset(dset.dates(1):(plan.date(1)-1)), data_set); - return; + return union_names = union(data_set.name, dset.name); dif = setdiff(union_names, data_set.name); data_set_nobs = data_set.nobs; for i = 1:length(dif) data_set{dif{i}} = dseries(nan(data_set_nobs,1),plan.date(1), dif(i), dif(i)); - end; + end dif = setdiff(union_names, dset.name); dset_nobs = dset.nobs; for i = 1:length(dif) dset{dif{i}} = dseries(nan(dset_nobs,1),dset.dates(1), dif(i), dif(i)); - end; + end data_set = [dset(dset.dates(1):(plan.date(1)-1)) ; data_set]; - return; - end; + return + end else - error('impossible case'); - end; - + 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; + +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); @@ -260,7 +260,7 @@ if direct_mode == 1 else init_periods = period_i; tp_end = period_i; - end; + end tp0 = tp; while tp < init_periods tp = tp + 1; @@ -271,18 +271,18 @@ if direct_mode == 1 constrained_paths(i, tp - tp0 + 1) = constrained_paths_cell{i}(j + 1); tp = tp + 1; j = j + 1; - end; - if tp - tp0 > max_periods_simulation + end + if tp - tp0 > max_periods_simulation max_periods_simulation = tp - tp0; - end; + end end n_nnz = length(sum(is_constraint,2)); if n_nnz > 0 constraint_index = cell(n_nnz,1); for i= 1:n_nnz constraint_index{i} = find(is_constraint(i,:)); - end; - end; + end + end if shocks_present n_periods = length(shock_periods); shock_paths_cell = shock_paths; @@ -299,7 +299,7 @@ if direct_mode == 1 else init_periods = period_i; tp_end = period_i; - end; + end tp0 = tp; while tp < init_periods tp = tp + 1; @@ -310,17 +310,17 @@ if direct_mode == 1 shock_paths(i, tp - tp0 + 1) = shock_paths_cell{i}(j + 1); tp = tp + 1; j = j + 1; - end; - if tp - tp0 > max_periods_simulation + end + if tp - tp0 > max_periods_simulation max_periods_simulation = tp - tp0; - end; - end; + end + end n_nnz = length(sum(is_shock,2)); if n_nnz > 0 shock_index = cell(n_nnz, 1); for i= 1:n_nnz shock_index{i} = find(is_shock(i,:)); - end; + end end end else @@ -336,16 +336,16 @@ 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); if n_control_exo ~= n_endo_constrained error(['det_cond_forecast: the number of exogenous controlled variables (' int2str(n_control_exo) ') has to be equal to the number of constrained endogenous variabes (' int2str(n_endo_constrained) ')']) - end; + end else error('det_cond_forecast: to run a deterministic conditional forecast you have to specified the exogenous variables controlled using the option controlled_varexo in forecast command'); -end; +end % if n_endo_constrained == 0 % options_.ep.use_bytecode = options_.bytecode; @@ -377,14 +377,14 @@ if isempty(indx_endo_solve_pf) pf = 0; else pf = length(indx_endo_solve_pf); -end; +end indx_endo_solve_surprise = setdiff(constrained_vars, indx_endo_solve_pf); if isempty(indx_endo_solve_surprise) surprise = 0; else surprise = length(indx_endo_solve_surprise); -end; +end eps = options_.solve_tolf; @@ -414,7 +414,7 @@ if pf && ~surprise for j = 1:length(constrained_vars) indx_endo(col_count : col_count + constrained_periods - 1) = constrained_vars(j) + (time_index_constraint - 1) * ny; col_count = col_count + constrained_periods; - end; + end oo_=make_ex_(M_,options_,oo_); oo_=make_y_(M_,options_,oo_); it = 1; @@ -436,9 +436,9 @@ if pf && ~surprise y = oo_.endo_simul(constrained_vars(j), time_index_constraint); r(col_count:col_count+constrained_periods - 1) = (y - constrained_paths(j,1:constrained_periods))'; col_count = col_count + constrained_periods; - end; + end normr = norm(r, 1); - end; + end if (~oo_.deterministic_simulation.status || ~result || normr > normra) && it > 1 not_achieved = 1; alpha = alpha / 2; @@ -446,14 +446,14 @@ if pf && ~surprise for j = controlled_varexo' oo_.exo_simul(time_index_constraint,j) = (old_exo(:,j) + alpha * D_exo(col_count: (col_count + constrained_periods - 1))); col_count = col_count + constrained_periods; - end; + end disp(['Divergence in Newton: reducing the path length alpha=' num2str(alpha)]); oo_.endo_simul = repmat(oo_.steady_state, 1, options_cond_fcst.periods + 2); else not_achieved = 0; - end; - end; - + end + end + per = 30; z = oo_.endo_simul(:, 1 : per + 2 ); zx = oo_.exo_simul(1: per + 2,:); @@ -473,7 +473,7 @@ if pf && ~surprise else data1 = M_; Size = 1; - end; + end data1 = M_; if (options_.bytecode) [chck, zz, data1]= bytecode('dynamic','evaluate', z, zx, M_.params, oo_.steady_state, k, data1); @@ -482,16 +482,16 @@ if pf && ~surprise data1.g1_x = g1b(:,end - M_.exo_nbr + 1:end); data1.g1 = g1b(:,1 : end - M_.exo_nbr); chck = 0; - end; + end mexErrCheck('bytecode', chck); - end; - if k == 1 + end + 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; + end l2 = 1; pf_c = 1; if k <= constrained_periods @@ -504,17 +504,17 @@ if pf && ~surprise for ii = 2:constrained_periods indx_x(l2) = length(controlled_varexo) + pf * (ii - 2) + constraint_index{k + ii - 1}(pf_c); l2 = l2 + 1; - end; + end pf_c = pf_c + 1; cum_index_d_y_x = [cum_index_d_y_x; constrained_vars(l)]; else cum_index_d_y_x = [cum_index_d_y_x; constrained_vars(l) + (k - 1) * M_.endo_nbr]; end cum_l1 = cum_l1 + length(l1); - end; - end; - end; - + end + end + end + d_y_x = - g1 \ g1_x; cum_l1 = 0; @@ -533,9 +533,9 @@ if pf && ~surprise cum_l1 = cum_l1 + length(l1); end cum_l1 = cum_l1 + length(constrained_vars(j1)); - end; - - + end + + % col_count = 1; % for j = controlled_varexo' % for time = time_index_constraint @@ -545,13 +545,13 @@ if pf && ~surprise % J1(:,col_count) = (oo_.endo_simul(indx_endo) - ys) / eps1; % oo_.exo_simul(time,j) = saved; % col_count = col_count + 1; - % end; - % end; + % end + % end % J1 % sdfmlksdf; - + disp(['iteration ' int2str(it) ' error = ' num2str(normr)]); - + if normr <= eps convg = 1; disp('convergence achieved'); @@ -564,25 +564,25 @@ if pf && ~surprise for j = controlled_varexo' oo_.exo_simul(time_index_constraint,j) = oo_.exo_simul(time_index_constraint,j) + D_exo(col_count: (col_count + constrained_periods - 1)); col_count = col_count + constrained_periods - 1; - end; - end; + end + end it = it + 1; normra = normr; - end; + end endo = oo_.endo_simul'; 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) pf = 0; else pf = length(indx_endo_solve_pf); - end; - + end + [pos_constrained_surprise, junk] = find((1-constrained_perfect_foresight) .* is_constraint(t, :)'); indx_endo_solve_surprise = constrained_vars(pos_constrained_surprise); @@ -590,18 +590,18 @@ else surprise = 0; else surprise = length(indx_endo_solve_surprise); - end; - end; - - if direct_mode && ~isempty(is_shock) + end + end + + 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) b_pf = 0; else b_pf = length(indx_endo_solve_pf); - end; - + end + [pos_shock_surprise, junk] = find((1-shock_perfect_foresight) .* is_shock(t, :)'); indx_endo_solve_surprise = shock_vars(pos_shock_surprise); @@ -609,9 +609,9 @@ else b_surprise = 0; else b_surprise = length(indx_endo_solve_surprise); - end; - end; - + 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('==============================================================================================='); @@ -623,20 +623,20 @@ else exo_init = zeros(size(oo_.exo_simul)); end oo_=make_y_(M_,options_,oo_); - end; + end %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; @@ -668,11 +668,11 @@ else else indx_endo(col_count) = constrained_vars(j) + maximum_lag * ny; col_count = col_count + 1; - end; - end; - + end + end + r = zeros(second_system_size,1); - + convg = 0; it = 1; while ~convg && it <= maxit @@ -696,20 +696,20 @@ else else oo_.exo_simul(maximum_lag + 1,j) = old_exo(maximum_lag + 1,j) + alpha * D_exo(col_count); col_count = col_count + 1; - end; - end; + end + end disp(['Divergence in Newton: reducing the path length alpha=' num2str(alpha) ' result=' num2str(result) ' sum(sum)=' num2str(sum(sum(isfinite(oo_.endo_simul(:,time_index_constraint))))) ' ny * length(time_index_constraint)=' num2str(ny * length(time_index_constraint)) ' oo_.deterministic_simulation.status=' num2str(oo_.deterministic_simulation.status)]); oo_.endo_simul = [initial_conditions repmat(oo_.steady_state, 1, options_cond_fcst.periods + 1)]; else not_achieved = 0; - end; - end; + end + end if t==constrained_periods ycc = oo_.endo_simul; - end; + 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) @@ -720,9 +720,9 @@ else y = yc(constrained_vars(j)); r(col_count) = y - constrained_paths(j,t); col_count = col_count + 1; - end; + end end - + disp('computation of derivatives w.r. to exogenous shocks'); per = 30; @@ -745,7 +745,7 @@ else else data1 = M_; Size = 1; - end; + end data1 = M_; if (options_.bytecode) [chck, zz, data1]= bytecode('dynamic','evaluate', z, zx, M_.params, oo_.steady_state, k, data1); @@ -754,17 +754,17 @@ else data1.g1_x = g1b(:,end - M_.exo_nbr + 1:end); data1.g1 = g1b(:,1 : end - M_.exo_nbr); chck = 0; - end; + end mexErrCheck('bytecode', chck); - end; - if k == 1 + end + 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; - + end + l2 = 1; pf_c = 1; if t + k - 1 <= constrained_periods @@ -779,25 +779,25 @@ else for ii = 2:constrained_periods - t + 1 indx_x(l2) = length(controlled_varexo) + pf * (ii - 2) + constraint_index{k + ii - 1}(pf_c); l2 = l2 + 1; - end; + end pf_c = pf_c + 1; else indx_x(l2) = l; l2 = l2 + 1; - end; + end cum_index_d_y_x = [cum_index_d_y_x; constrained_vars_t(l)]; else cum_index_d_y_x = [cum_index_d_y_x; constrained_vars_t(l) + (k - 1) * M_.endo_nbr]; end cum_l1 = cum_l1 + length(l1); - end; - end; - end; - end; - + end + 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)); @@ -819,10 +819,10 @@ else count_col = count_col + 1; end cum_l1 = cum_l1 + length(constrained_vars_t(j1)); - end; + end - - % % Numerical computation of the derivatives in the second systme + + % % Numerical computation of the derivatives in the second systme % J1 = []; % col_count = 1; % for j = constraint_index_t @@ -835,7 +835,7 @@ else % J1(:,col_count) = (oo_.endo_simul(indx_endo) - ys) / eps1; % oo_.exo_simul(time,j_pos) = saved; % col_count = col_count + 1; - % end; + % 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; @@ -845,15 +845,15 @@ else % % 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; + % 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 @@ -870,7 +870,7 @@ else z_root = find(abs(ev) < 1e-4); z_root disp(V(:,z_root)); - end; + end old_exo = oo_.exo_simul; col_count = 1; for j = constraint_index_t @@ -881,14 +881,14 @@ else else oo_.exo_simul(maximum_lag + 1,j_pos) = oo_.exo_simul(maximum_lag + 1,j_pos) + D_exo(col_count); col_count = col_count + 1; - end; - end; - end; + end + end + end it = it + 1; - end; + end if ~convg error(['convergence not achived at time ' int2str(t) ' after ' int2str(it) ' iterations']); - end; + end for j = constraint_index_t j_pos=controlled_varexo(j); if constrained_perfect_foresight(j) @@ -900,20 +900,20 @@ else end else exo(maximum_lag + t,j_pos) = oo_.exo_simul(maximum_lag + 1,j_pos); - end; - end; + end + end past_val = past_val + length(time_index_constraint); if t < constrained_periods endo(maximum_lag + t,:) = yc; else endo(maximum_lag + t :maximum_lag + options_cond_fcst.periods ,:) = ycc(:,maximum_lag + 1:maximum_lag + options_cond_fcst.periods - constrained_periods + 1)'; - end; + end initial_conditions = yc; if maximum_lag > 0 exo_init(1,:) = exo(maximum_lag + t,:); - end; - end; -end; + end + end +end options_.periods = save_options_periods; options_.dynatol.f = save_options_dynatol_f; options_.initval_file = save_options_initval_file; @@ -922,4 +922,4 @@ oo_.endo_simul = endo'; oo_.exo_simul = exo; if direct_mode data_set = dseries([endo(2:end,1:M_.orig_endo_nbr) exo(2:end,:)], total_periods(1), {plan.endo_names{:} plan.exo_names{:}}, {plan.endo_names{:} plan.exo_names{:}}); -end; +end diff --git a/matlab/perfect-foresight-models/linear_approximation_accuracy.m b/matlab/perfect-foresight-models/linear_approximation_accuracy.m index e3f9eb521..289997176 100644 --- a/matlab/perfect-foresight-models/linear_approximation_accuracy.m +++ b/matlab/perfect-foresight-models/linear_approximation_accuracy.m @@ -2,15 +2,15 @@ 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 +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/perfect-foresight-models/linear_perfect_foresight_problem.m b/matlab/perfect-foresight-models/linear_perfect_foresight_problem.m index b8f710bd4..78d9fed41 100644 --- a/matlab/perfect-foresight-models/linear_perfect_foresight_problem.m +++ b/matlab/perfect-foresight-models/linear_perfect_foresight_problem.m @@ -5,7 +5,7 @@ function [residuals,JJacobian] = linear_perfect_foresight_problem(y, dynamicjaco 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. % @@ -19,7 +19,7 @@ function [residuals,JJacobian] = linear_perfect_foresight_problem(y, dynamicjaco % SPECIAL REQUIREMENTS % None. -% Copyright (C) 2015 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/perfect-foresight-models/make_ex_.m b/matlab/perfect-foresight-models/make_ex_.m index 73ab28f43..4f7259048 100644 --- a/matlab/perfect-foresight-models/make_ex_.m +++ b/matlab/perfect-foresight-models/make_ex_.m @@ -5,16 +5,16 @@ 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 +% Copyright (C) 1996-2017 Dynare Team % % This file is part of Dynare. % @@ -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 f3c8f686f..e96333825 100644 --- a/matlab/perfect-foresight-models/make_y_.m +++ b/matlab/perfect-foresight-models/make_y_.m @@ -1,22 +1,22 @@ 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 +% Copyright (C) 1996-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . -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 ed6553201..eb898322d 100644 --- a/matlab/perfect-foresight-models/perfect_foresight_mcp_problem.m +++ b/matlab/perfect-foresight-models/perfect_foresight_mcp_problem.m @@ -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 @@ -45,7 +45,7 @@ function [residuals,JJacobian] = perfect_foresight_mcp_problem(y, dynamic_functi % SPECIAL REQUIREMENTS % None. -% Copyright (C) 1996-2016 Dynare Team +% Copyright (C) 1996-2017 Dynare Team % % This file is part of Dynare. % @@ -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 diff --git a/matlab/perfect-foresight-models/perfect_foresight_problem.m b/matlab/perfect-foresight-models/perfect_foresight_problem.m index 2f4cee6fd..a4df03f80 100644 --- a/matlab/perfect-foresight-models/perfect_foresight_problem.m +++ b/matlab/perfect-foresight-models/perfect_foresight_problem.m @@ -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 @@ -42,7 +42,7 @@ function [residuals,JJacobian] = perfect_foresight_problem(y, dynamic_function, % SPECIAL REQUIREMENTS % None. -% Copyright (C) 1996-2016 Dynare Team +% Copyright (C) 1996-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/perfect-foresight-models/perfect_foresight_setup.m b/matlab/perfect-foresight-models/perfect_foresight_setup.m index 7d7312fc0..341d70aad 100644 --- a/matlab/perfect-foresight-models/perfect_foresight_setup.m +++ b/matlab/perfect-foresight-models/perfect_foresight_setup.m @@ -1,18 +1,18 @@ 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 -% Copyright (C) 1996-2016 Dynare Team +% Copyright (C) 1996-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/perfect-foresight-models/perfect_foresight_simulation.m b/matlab/perfect-foresight-models/perfect_foresight_simulation.m index ffef743ed..15f1b8b76 100644 --- a/matlab/perfect-foresight-models/perfect_foresight_simulation.m +++ b/matlab/perfect-foresight-models/perfect_foresight_simulation.m @@ -18,7 +18,7 @@ function info = perfect_foresight_simulation(compute_linear_solution,steady_stat % SPECIAL REQUIREMENTS % None. -% Copyright (C) 2009-2011 Dynare Team +% Copyright (C) 2009-2015 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/perfect-foresight-models/perfect_foresight_solver.m b/matlab/perfect-foresight-models/perfect_foresight_solver.m index b159f2aea..8e7c3bcbc 100644 --- a/matlab/perfect-foresight-models/perfect_foresight_solver.m +++ b/matlab/perfect-foresight-models/perfect_foresight_solver.m @@ -12,7 +12,7 @@ function perfect_foresight_solver() % SPECIAL REQUIREMENTS % none -% Copyright (C) 1996-2016 Dynare Team +% Copyright (C) 1996-2017 Dynare Team % % This file is part of Dynare. % @@ -192,12 +192,12 @@ if ~isreal(oo_.endo_simul(:)) %can only happen without bytecode 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 c01333f0b..272cd3833 100644 --- a/matlab/perfect-foresight-models/perfect_foresight_solver_core.m +++ b/matlab/perfect-foresight-models/perfect_foresight_solver_core.m @@ -2,16 +2,16 @@ 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 -% Copyright (C) 2015-2016 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -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 affb808e0..fc50114d0 100644 --- a/matlab/perfect-foresight-models/private/check_input_arguments.m +++ b/matlab/perfect-foresight-models/private/check_input_arguments.m @@ -3,7 +3,7 @@ function check_input_arguments(DynareOptions, DynareModel, DynareResults) %Conducts checks for inconsistent/missing inputs to deterministic %simulations -% Copyright (C) 2015 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -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 3f4ead4d1..014bb9acb 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 @@ -27,7 +27,7 @@ function [options, y0, yT, z, i_cols, i_cols_J1, i_cols_T, i_cols_j, i_cols_1, . % M.lead_lag_incidence in dynamic Jacobian (relevant in first period) % - dynamicmodel [handle] function handle to _dynamic-file -% Copyright (C) 2015-16 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/perfect-foresight-models/private/simulation_core.m b/matlab/perfect-foresight-models/private/simulation_core.m index 1b8b1d51e..0c944c2a6 100644 --- a/matlab/perfect-foresight-models/private/simulation_core.m +++ b/matlab/perfect-foresight-models/private/simulation_core.m @@ -1,7 +1,7 @@ function [oo_, maxerror] = simulation_core(options_, M_, oo_) %function [oo_, maxerror] = simulation_core(options_, M_, oo_) -% Copyright (C) 2015 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/perfect-foresight-models/sim1.m b/matlab/perfect-foresight-models/sim1.m index f00bb43f8..28a777eb9 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 @@ -329,6 +329,5 @@ if 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 - + fprintf('\n'), +end \ No newline at end of file diff --git a/matlab/perfect-foresight-models/sim1_lbj.m b/matlab/perfect-foresight-models/sim1_lbj.m index d4d8c24f2..a9b585907 100644 --- a/matlab/perfect-foresight-models/sim1_lbj.m +++ b/matlab/perfect-foresight-models/sim1_lbj.m @@ -15,7 +15,7 @@ function [endogenousvariables, info] = sim1_lbj(endogenousvariables, exogenousva % SPECIAL REQUIREMENTS % None. -% Copyright (C) 1996-2015 Dynare Team +% Copyright (C) 1996-2017 Dynare Team % % This file is part of Dynare. % @@ -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 6820c92bc..85dc38405 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). @@ -38,7 +38,7 @@ function [endogenousvariables, info] = sim1_linear(endogenousvariables, exogenou % to center the variables around the deterministic steady state to solve the % perfect foresight model. -% Copyright (C) 2015 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/perfect-foresight-models/sim1_purely_backward.m b/matlab/perfect-foresight-models/sim1_purely_backward.m index b4f1decd4..a2ec8db13 100644 --- a/matlab/perfect-foresight-models/sim1_purely_backward.m +++ b/matlab/perfect-foresight-models/sim1_purely_backward.m @@ -2,7 +2,7 @@ function [endogenousvariables, info] = sim1_purely_backward(endogenousvariables, % Performs deterministic simulation of a purely backward model -% Copyright (C) 2012-2015 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/perfect-foresight-models/sim1_purely_forward.m b/matlab/perfect-foresight-models/sim1_purely_forward.m index 5032e0498..31cd12b77 100644 --- a/matlab/perfect-foresight-models/sim1_purely_forward.m +++ b/matlab/perfect-foresight-models/sim1_purely_forward.m @@ -1,7 +1,7 @@ function [endogenousvariables, info] = sim1_purely_forward(endogenousvariables, exogenousvariables, steadystate, M, options) % Performs deterministic simulation of a purely forward model -% Copyright (C) 2012-2015 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/perfect-foresight-models/solve_stacked_linear_problem.m b/matlab/perfect-foresight-models/solve_stacked_linear_problem.m index cd50c1cbe..5464c9e06 100644 --- a/matlab/perfect-foresight-models/solve_stacked_linear_problem.m +++ b/matlab/perfect-foresight-models/solve_stacked_linear_problem.m @@ -1,6 +1,6 @@ function [endogenousvariables, info] = solve_stacked_linear_problem(endogenousvariables, exogenousvariables, steadystate_y, steadystate_x, M, options) -% Copyright (C) 2015 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/perfect-foresight-models/solve_stacked_problem.m b/matlab/perfect-foresight-models/solve_stacked_problem.m index 1c29f565e..dd3bc6363 100644 --- a/matlab/perfect-foresight-models/solve_stacked_problem.m +++ b/matlab/perfect-foresight-models/solve_stacked_problem.m @@ -1,19 +1,19 @@ -function [endogenousvariables, info] = solve_stacked_problem(endogenousvariables, exogenousvariables, steadystate, M, options); +function [endogenousvariables, info] = solve_stacked_problem(endogenousvariables, exogenousvariables, steadystate, M, options) % [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. -% Copyright (C) 2015-16 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -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 1d4b61eb7..c4e3c2b2b 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 0c1f48b2c..12da56804 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 @@ -42,7 +42,7 @@ if nargin <10 || isempty(tit_TeX) tit_TeX=tittxt; end -if nargin <11 +if nargin <11 name_TeX=name; end @@ -58,7 +58,7 @@ siLREnorm = idelre.siLREnorm; % end tittxt1=regexprep(tittxt, ' ', '_'); tittxt1=strrep(tittxt1, '.', ''); -if SampleSize == 1, +if SampleSize == 1 siJ = idemoments.siJ; hh = dyn_figure(options_.nodisplay,'Name',[tittxt, ' - Identification using info from observables']); subplot(211) @@ -72,7 +72,7 @@ if SampleSize == 1, set(gca,'xlim',[0 nparam+1]) set(gca,'xticklabel','') dy = get(gca,'ylim'); - for ip=1:nparam, + for ip=1:nparam text(ip,dy(1),name{is(ip)},'rotation',90,'HorizontalAlignment','right','interpreter','none') end if ~all(isnan(idehess.ide_strength_J_prior)) @@ -80,12 +80,12 @@ if SampleSize == 1, else legend('relative to param value','Location','Best') end - if idehess.flag_score, + if idehess.flag_score title('Identification strength with asymptotic Information matrix (log-scale)') 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)])) @@ -96,7 +96,7 @@ if SampleSize == 1, set(gca,'xlim',[0 nparam+1]) set(gca,'xticklabel','') dy = get(gca,'ylim'); - for ip=1:nparam, + for ip=1:nparam text(ip,dy(1),name{is(ip)},'rotation',90,'HorizontalAlignment','right','interpreter','none') end if ~all(isnan(idehess.deltaM_prior)) @@ -104,7 +104,7 @@ if SampleSize == 1, else legend('relative to param value','Location','Best') end - if idehess.flag_score, + if idehess.flag_score title('Sensitivity component with asymptotic Information matrix (log-scale)') else title('Sensitivity component with moments Information matrix (log-scale)') @@ -123,9 +123,9 @@ 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, + + if advanced + if ~options_.nodisplay skipline() disp('Press ENTER to plot advanced diagnostics'), pause(5), end @@ -146,7 +146,7 @@ if SampleSize == 1, set(gca,'xlim',[0 nparam+1]) set(gca,'xticklabel','') dy = get(gca,'ylim'); - for ip=1:nparam, + for ip=1:nparam text(ip,dy(1),name{is(ip)},'rotation',90,'HorizontalAlignment','right','interpreter','none') end legend('Moments','Model','LRE model','Location','Best') @@ -167,16 +167,16 @@ if SampleSize == 1, end end % identificaton patterns - for j=1:size(idemoments.cosnJ,2), + 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') - for i=1:nparam, + for i=1:nparam namx=''; - for in=1:j, + for in=1:j dumpindx = idemoments.pars{i,j}(in); - if isnan(dumpindx), + if isnan(dumpindx) namx=[namx ' ' sprintf('%-15s','--')]; else namx=[namx ' ' sprintf('%-15s',name{dumpindx})]; @@ -189,7 +189,7 @@ if SampleSize == 1, imagesc(pax,[0 1]); set(gca,'xticklabel','') set(gca,'yticklabel','') - for ip=1:nparam, + for ip=1:nparam text(ip,(0.5),name{ip},'rotation',90,'HorizontalAlignment','left','interpreter','none') text(0.5,ip,name{ip},'rotation',0,'HorizontalAlignment','right','interpreter','none') end @@ -198,7 +198,7 @@ if SampleSize == 1, ax=colormap; ax(1,:)=[0.9 0.9 0.9]; colormap(ax); - if nparam>10, + if nparam>10 set(gca,'xtick',(5:5:nparam)) set(gca,'ytick',(5:5:nparam)) end @@ -223,8 +223,8 @@ if SampleSize == 1, skipline() [U,S,V]=svd(idehess.AHess,0); S=diag(S); - if idehess.flag_score, - if nparam<5, + if idehess.flag_score + if nparam<5 f1 = dyn_figure(options_.nodisplay,'Name',[tittxt,' - Identification patterns (Information matrix)']); tex_tit_1=[tittxt,' - Identification patterns (Information matrix)']; else @@ -236,7 +236,7 @@ if SampleSize == 1, else % S = idemoments.S; % V = idemoments.V; - if nparam<5, + if nparam<5 f1 = dyn_figure(options_.nodisplay,'Name',[tittxt,' - Identification patterns (moments Information matrix)']); tex_tit_1=[tittxt,' - Identification patterns (moments Information matrix)']; else @@ -246,25 +246,25 @@ if SampleSize == 1, tex_tit_2=[tittxt,' - Identification patterns (moments Information matrix): HIGHEST SV']; end end - for j=1:min(nparam,8), - if j<5, + for j=1:min(nparam,8) + if j<5 set(0,'CurrentFigure',f1), jj=j; else set(0,'CurrentFigure',f2), jj=j-4; end - subplot(4,1,jj), + subplot(4,1,jj) if j<5 - bar(abs(V(:,end-j+1))), + bar(abs(V(:,end-j+1))) Stit = S(end-j+1); else bar(abs(V(:,jj))), Stit = S(jj); end set(gca,'xticklabel','') - if j==4 || j==nparam || j==8, - for ip=1:nparam, + if j==4 || j==nparam || j==8 + for ip=1:nparam text(ip,-0.02,name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') end end @@ -284,7 +284,7 @@ if SampleSize == 1, fprintf(fidTeX,'%% End Of TeX file. \n'); fclose(fidTeX); end - if nparam>4, + if nparam>4 dyn_saveas(f2,[ IdentifDirectoryName '/' M_.fname '_ident_pattern_' tittxt1 '_2' ],options_.nodisplay,options_.graph_format); if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) fidTeX = fopen([ IdentifDirectoryName '/' M_.fname '_ident_pattern_' tittxt1 '_2.tex'],'w'); @@ -301,7 +301,7 @@ if SampleSize == 1, end end end - + else hh = dyn_figure(options_.nodisplay,'Name',['MC sensitivities']); subplot(211) @@ -309,23 +309,23 @@ else [ss, is] = sort(mmm); mmm = mean(siJnorm)'; mmm = mmm./max(mmm); - if advanced, + if advanced mmm1 = mean(siHnorm)'; mmm=[mmm mmm1./max(mmm1)]; mmm1 = mean(siLREnorm)'; 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','') dy = get(gca,'ylim'); - for ip=1:nparam, + for ip=1:nparam text(ip,dy(1),name{is(ip)},'rotation',90,'HorizontalAlignment','right','interpreter','none') end - if advanced, + if advanced legend('Moments','Model','LRE model','Location','Best') end title('MC mean of sensitivity measures') @@ -343,8 +343,8 @@ else fprintf(fidTeX,'%% End Of TeX file. \n'); fclose(fidTeX); end - - if advanced, + + if advanced if ~options_.nodisplay, skipline() disp('Press ENTER to display advanced diagnostics'), pause(5), @@ -397,7 +397,7 @@ else % [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, + if nparam<5 f1 = dyn_figure(options_.nodisplay,'Name',[tittxt,' - MC Identification patterns (moments): HIGHEST SV']); tex_tit_1=[tittxt,' - MC Identification patterns (moments): HIGHEST SV']; else @@ -407,13 +407,13 @@ else tex_tit_2=[tittxt,' - MC Identification patterns (moments): HIGHEST SV']; end nplots=min(nparam,8); - if nplots>4, + if nplots>4 nsubplo=ceil(nplots/2); else nsubplo=nplots; end - for j=1:nplots, - if (nparam>4 && j<=ceil(nplots/2)) || nparam<5, + for j=1:nplots + if (nparam>4 && j<=ceil(nplots/2)) || nparam<5 set(0,'CurrentFigure',f1), jj=j; VVV=squeeze(abs(idemoments.V(:,:,end-j+1))); @@ -424,8 +424,8 @@ else VVV=squeeze(abs(idemoments.V(:,:,jj))); SSS = idemoments.S(:,jj); end - subplot(nsubplo,1,jj), - for i=1:nparam, + subplot(nsubplo,1,jj) + for i=1:nparam [post_mean, post_median(:,i), post_var, hpd_interval(i,:), post_deciles] = posterior_moments(VVV(:,i),0,0.9); end bar(post_median) @@ -433,8 +433,8 @@ else Stit=mean(SSS); set(gca,'xticklabel','') - if j==4 || j==nparam || j==8, - for ip=1:nparam, + if j==4 || j==nparam || j==8 + for ip=1:nparam text(ip,-0.02,name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none') end end @@ -454,7 +454,7 @@ else fprintf(fidTeX,'%% End Of TeX file. \n'); fclose(fidTeX); end - if nparam>4, + if nparam>4 dyn_saveas(f2,[ IdentifDirectoryName '/' M_.fname '_MC_ident_pattern_2' ],options_.nodisplay,options_.graph_format); if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format))) fidTeX = fopen([ IdentifDirectoryName '/' M_.fname '_MC_ident_pattern_2.tex'],'w'); diff --git a/matlab/plot_priors.m b/matlab/plot_priors.m index 04f371566..2b2fc83f6 100644 --- a/matlab/plot_priors.m +++ b/matlab/plot_priors.m @@ -42,7 +42,7 @@ if TeX && any(strcmp('eps',cellstr(options_.graph_format))) fprintf(fidTeX,['%% ' datestr(now,0) '\n']); fprintf(fidTeX,' \n'); end -for plt = 1:nbplt, +for plt = 1:nbplt hplt = dyn_figure(options_.nodisplay,'Name',figurename); if TeX TeXNAMES = []; @@ -73,7 +73,7 @@ for plt = 1:nbplt, dyn_saveas(hplt,[M_.fname '_Priors' int2str(plt)],options_.nodisplay,options_.graph_format); if TeX && any(strcmp('eps',cellstr(options_.graph_format))) fprintf(fidTeX,'\\begin{figure}[H]\n'); - for jj = 1:nstar0, + 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'); diff --git a/matlab/plot_shock_decomposition.m b/matlab/plot_shock_decomposition.m index 81602d059..78488d6c6 100644 --- a/matlab/plot_shock_decomposition.m +++ b/matlab/plot_shock_decomposition.m @@ -38,7 +38,8 @@ if size(varlist,1) == 0 varlist = M_.endo_names(1:M_.orig_endo_nbr,:); end -[i_var,nvar] = varlist_indices(varlist,M_.endo_names); +[i_var,nvar,index_uniques] = varlist_indices(varlist,M_.endo_names); +varlist=varlist(index_uniques,:); % number of variables endo_nbr = M_.endo_nbr; @@ -54,7 +55,7 @@ fig_name=''; % steadystate=0; % write_xls=0; -if isfield(options_.plot_shock_decomp,'expand'), % private trap for uimenu calls +if isfield(options_.plot_shock_decomp,'expand') % private trap for uimenu calls expand=options_.plot_shock_decomp.expand; else expand=0; @@ -71,15 +72,15 @@ forecast_ = options_.shock_decomp.forecast; steadystate = options_.plot_shock_decomp.steadystate; write_xls = options_.plot_shock_decomp.write_xls; -if vintage_, +if vintage_ forecast_ = min(forecast_,options_.nobs-vintage_); end initial_date = options_.initial_date; -if isfield(options_.plot_shock_decomp,'q2a'), % private trap for aoa calls +if isfield(options_.plot_shock_decomp,'q2a') % private trap for aoa calls q2a=options_.plot_shock_decomp.q2a; - if isstruct(q2a) && isempty(fieldnames(q2a)), + if isstruct(q2a) && isempty(fieldnames(q2a)) q2a=0; end else @@ -87,11 +88,11 @@ 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_)]); @@ -100,7 +101,7 @@ switch realtime_ 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_)]); @@ -110,7 +111,7 @@ switch realtime_ 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_)]); @@ -125,12 +126,12 @@ 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, + if initial_date.time(2)==1 t0=1; initial_date1=initial_date0; else @@ -141,25 +142,25 @@ if isequal(type,'aoa') && isstruct(q2a) && realtime_ 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 + if ~isfield(q2a,'var_type') % private trap for aoa calls q2a.var_type=1; end - if ~isfield(q2a,'islog'), % private trap for aoa calls + if ~isfield(q2a,'islog') % private trap for aoa calls q2a.islog=0; end - if ~isfield(q2a,'GYTREND0'), % private trap for aoa calls + if ~isfield(q2a,'GYTREND0') % private trap for aoa calls q2a.GYTREND0=0; end - if ~isfield(q2a,'aux'), % private trap for aoa calls + if ~isfield(q2a,'aux') % private trap for aoa calls q2a.aux=0; end - if ~isfield(q2a,'cumfix'), % private trap for aoa calls + if ~isfield(q2a,'cumfix') % private trap for aoa calls q2a.cumfix=1; end - if ~isfield(q2a,'plot'), % private trap for aoa calls + 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'; @@ -188,7 +189,7 @@ if options_.plot_shock_decomp.use_shock_groups ngroups = length(shock_ind); fig_name=[fig_name ' group ' options_.plot_shock_decomp.use_shock_groups]; shock_names = shock_ind; - for i=1:ngroups, + for i=1:ngroups shock_names{i} = (shock_groups.(shock_ind{i}).label); end zz = zeros(endo_nbr,ngroups+2,gend); @@ -205,9 +206,9 @@ if options_.plot_shock_decomp.use_shock_groups shock_groups.(['group' int2str(ngroups+1)]).label = 'Others'; shock_groups.(['group' int2str(ngroups+1)]).shocks = cellstr(M_.exo_names(find(~ismember([1:M_.exo_nbr],kcum)),:))'; M_.shock_groups.(options_.plot_shock_decomp.use_shock_groups)=shock_groups; - if any(any(zothers)), + 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; @@ -221,7 +222,7 @@ MAP = distinguishable_colors(size(z,2)-1,'w',func); 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), +if isempty(options_.plot_shock_decomp.colormap) options_.plot_shock_decomp.colormap = MAP; end @@ -229,7 +230,7 @@ switch type case '' % default - case 'qoq' + case 'qoq' case 'yoy' z=z(:,:,1:end-3)+z(:,:,2:end-2)+z(:,:,3:end-1)+z(:,:,4:end); @@ -239,15 +240,15 @@ switch type initial_date = dates('1Q4'); end steady_state = 4*steady_state; - + case 'aoa' - if isempty(initial_date), + 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, + if initial_date.time(2)==1 t0=1; initial_date1=initial_date0; else @@ -255,27 +256,27 @@ switch type initial_date1=initial_date0+1; end end - if isstruct(q2a) + if isstruct(q2a) if realtime_ == 0 - if ~isfield(q2a,'var_type'), % private trap for aoa calls + if ~isfield(q2a,'var_type') % private trap for aoa calls q2a.var_type=1; end - if ~isfield(q2a,'islog'), % private trap for aoa calls + if ~isfield(q2a,'islog') % private trap for aoa calls q2a.islog=0; end - if ~isfield(q2a,'GYTREND0'), % private trap for aoa calls + if ~isfield(q2a,'GYTREND0') % private trap for aoa calls q2a.GYTREND0=0; end - if ~isfield(q2a,'aux'), % private trap for aoa calls + if ~isfield(q2a,'aux') % private trap for aoa calls q2a.aux=0; end - if ~isfield(q2a,'cumfix'), % private trap for aoa calls + if ~isfield(q2a,'cumfix') % private trap for aoa calls q2a.cumfix=1; end - if ~isfield(q2a,'plot'), % private trap for aoa calls + 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'; @@ -300,15 +301,15 @@ switch type 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') @@ -340,7 +341,7 @@ z = z(:,:,a:b); options_.plot_shock_decomp.fig_name=fig_name; options_.plot_shock_decomp.orig_varlist = varlist; -if detail_plot, +if detail_plot graph_decomp_detail(z,shock_names,M_.endo_names,i_var,my_initial_date,M_,options_) else graph_decomp(z,shock_names,M_.endo_names,i_var,my_initial_date,M_,options_); diff --git a/matlab/pltorg.m b/matlab/pltorg.m index 7f100e4b2..e7f680772 100644 --- a/matlab/pltorg.m +++ b/matlab/pltorg.m @@ -1,6 +1,6 @@ function [nbplt,nr,nc,lr,lc,nstar] = pltorg(number) -% Copyright (C) 2004-2008 Dynare Team +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % @@ -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 d5502d29b..695b641d8 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 @@ -24,7 +24,7 @@ function pm3(n1,n2,ifil,B,tit1,tit2,tit3,tit_tex,names1,names2,name3,DirectoryNa % See also the comment in posterior_sampler.m funtion. -% Copyright (C) 2007-2016 Dynare Team +% Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. % @@ -60,10 +60,10 @@ else end end if options_.TeX - if isempty(tit_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; @@ -321,13 +321,13 @@ if ~options_.nograph && ~options_.no_graph.posterior if ~isoctave % Commenting for testing! - if isnumeric(options_.parallel) || ceil(size(varlist,1)/MaxNumberOfPlotsPerFigure)<4, + 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), + for indPC=1:length(options_.parallel) isRemoteOctave = isRemoteOctave + (findstr(options_.parallel(indPC).MatlabOctavePath, 'octave')); end if isRemoteOctave @@ -342,7 +342,7 @@ if ~options_.nograph && ~options_.no_graph.posterior 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 @@ -355,13 +355,12 @@ if ~options_.nograph && ~options_.no_graph.posterior fprintf(fidTeX,' \n'); nvar0=cumsum(nvar0); - i=0; - for j=1:length(nvar0), - + i=0; + for j=1:length(nvar0) NAMES = []; TEXNAMES = []; nvar=nvar0(j); - while i 10^(-6) subplotnum = subplotnum+1; diff --git a/matlab/pm3_core.m b/matlab/pm3_core.m index 2f925e5e3..881c4b423 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 @@ -30,7 +30,7 @@ function myoutput=pm3_core(myinputs,fpar,nvar,whoiam, ThisMatlab) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see . -if nargin<4, +if nargin<4 whoiam=0; end @@ -66,7 +66,7 @@ figunumber = 0; subplotnum = 0; hh = dyn_figure(options_.nodisplay,'Name',[tit1 ' ' int2str(figunumber+1)]); RemoteFlag = 0; -if whoiam, +if whoiam if Parallel(ThisMatlab).Local ==0 RemoteFlag=1; end @@ -100,16 +100,16 @@ for i=fpar:nvar set(gca,'yticklabel',yticklabels_new) end end - - if whoiam, + + 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, + if RemoteFlag==1 OutputFileName = [OutputFileName; {[M_.dname, filesep, 'Output',filesep], [M_.fname '_' name3 '_' deblank(tit3(i,:)) '.*']}]; end subplotnum = 0; @@ -118,17 +118,17 @@ for i=fpar:nvar hh = dyn_figure(options_.nodisplay,'Name',[name3 ' ' int2str(figunumber+1)]); end end - - if whoiam, + + if whoiam % 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, +if whoiam dyn_waitbar_close(h); end myoutput.OutputFileName=OutputFileName; diff --git a/matlab/posterior_analysis.m b/matlab/posterior_analysis.m index faa117c03..fa365b607 100644 --- a/matlab/posterior_analysis.m +++ b/matlab/posterior_analysis.m @@ -1,5 +1,5 @@ -function oo_ = posterior_analysis(type,arg1,arg2,arg3,options_,M_,oo_) -% Copyright (C) 2008-2012 Dynare Team +function oo_ = posterior_analysis(type,arg1,arg2,arg3,options_,M_,oo_) +% Copyright (C) 2008-2017 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 beb1b0a41..915827328 100644 --- a/matlab/posterior_moments.m +++ b/matlab/posterior_moments.m @@ -11,17 +11,17 @@ 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. % -% Copyright (C) 2005-2011 Dynare Team +% Copyright (C) 2005-2017 Dynare Team % % This file is part of Dynare. % @@ -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 be512d140..70f7b5de9 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. @@ -37,7 +37,7 @@ function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_boun % Then the comments write here can be used for all the other pairs of % parallel functions and also for management functions. -% Copyright (C) 2006-2016 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -107,7 +107,7 @@ localVars = struct('TargetFun', TargetFun, ... 'oo_', oo_,... 'varargin',[]); -if strcmp(sampler_options.posterior_sampling_method,'tailored_random_block_metropolis_hastings'); +if strcmp(sampler_options.posterior_sampling_method,'tailored_random_block_metropolis_hastings') localVars.options_.silent_optimizer=1; %locally set optimizer to silent mode if ~isempty(sampler_options.optim_opt) localVars.options_.optim_opt=sampler_options.optim_opt; %locally set options for optimizer @@ -117,31 +117,31 @@ end % User doesn't want to use parallel computing, or wants to compute a % single chain compute sequentially. -if isnumeric(options_.parallel) || (nblck-fblck)==0, +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 NamFileInput(1,:) = {'',[ModelName '_static.m']}; NamFileInput(2,:) = {'',[ModelName '_dynamic.m']}; NamFileInput(3,:) = {'',[M_.fname '_set_auxiliary_variables.m']}; - if options_.steadystate_flag, - if options_.steadystate_flag == 1, + if options_.steadystate_flag + if options_.steadystate_flag == 1 NamFileInput(length(NamFileInput)+1,:)={'',[M_.fname '_steadystate.m']}; else NamFileInput(length(NamFileInput)+1,:)={'',[M_.fname '_steadystate2.m']}; end end - if (options_.load_mh_file~=0) && any(fline>1) , + if (options_.load_mh_file~=0) && any(fline>1) NamFileInput(length(NamFileInput)+1,:)={[M_.dname '/metropolis/'],[ModelName '_mh' int2str(NewFile(1)) '_blck*.mat']}; end % from where to get back results % NamFileOutput(1,:) = {[M_.dname,'/metropolis/'],'*.*'}; [fout, nBlockPerCPU, totCPU] = masterParallel(options_.parallel, fblck, nblck,NamFileInput,'posterior_sampler_core', localVars, globalVars, options_.parallel_info); - for j=1:totCPU, + for j=1:totCPU offset = sum(nBlockPerCPU(1:j-1))+fblck-1; record.LastLogPost(offset+1:sum(nBlockPerCPU(1:j)))=fout(j).record.LastLogPost(offset+1:sum(nBlockPerCPU(1:j))); record.LastParameters(offset+1:sum(nBlockPerCPU(1:j)),:)=fout(j).record.LastParameters(offset+1:sum(nBlockPerCPU(1:j)),:); diff --git a/matlab/posterior_sampler_core.m b/matlab/posterior_sampler_core.m index d88ae742a..b753391b4 100644 --- a/matlab/posterior_sampler_core.m +++ b/matlab/posterior_sampler_core.m @@ -31,12 +31,12 @@ function myoutput = posterior_sampler_core(myinputs,fblck,nblck,whoiam, ThisMatl % % SPECIAL REQUIREMENTS. % None. -% +% % PARALLEL CONTEXT % See the comments in the posterior_sampler.m funtion. -% Copyright (C) 2006-2016 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -53,7 +53,7 @@ function myoutput = posterior_sampler_core(myinputs,fblck,nblck,whoiam, ThisMatl % You should have received a copy of the GNU General Public License % along with Dynare. If not, see . -if nargin<4, +if nargin<4 whoiam=0; end @@ -108,7 +108,7 @@ end % sampler_options.xparam1 = xparam1; -if ~isempty(d), +if ~isempty(d) sampler_options.proposal_covariance_Cholesky_decomposition = d*diag(bayestopt_.jscale); %store information for load_mh_file record.ProposalCovariance=d; @@ -117,7 +117,7 @@ end block_iter=0; -for curr_block = fblck:nblck, +for curr_block = fblck:nblck LastSeeds=[]; block_iter=block_iter+1; try @@ -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; @@ -192,7 +192,7 @@ for curr_block = fblck:nblck, end if (draw_index_current_file == InitSizeArray(curr_block)) || (draw_iter == nruns(curr_block)) % Now I save the simulations, either because the current file is full or the chain is done [LastSeeds.(['file' int2str(NewFile(curr_block))]).Unifor, LastSeeds.(['file' int2str(NewFile(curr_block))]).Normal] = get_dynare_random_generator_state(); - if save_tmp_file, + if save_tmp_file delete([BaseName '_mh_tmp_blck' int2str(curr_block) '.mat']); end save([BaseName '_mh' int2str(NewFile(curr_block)) '_blck' int2str(curr_block) '.mat'],'x2','logpo2','LastSeeds'); diff --git a/matlab/posterior_sampler_initialization.m b/matlab/posterior_sampler_initialization.m index 0292b010d..b8b65e8b8 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 @@ -38,7 +38,7 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa % SPECIAL REQUIREMENTS % None. -% Copyright (C) 2006-2015 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -58,7 +58,7 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa %Initialize outputs ix2 = []; ilogpo2 = []; -ModelName = []; +ModelName = []; MetropolisFolder = []; FirstBlock = []; FirstLine = []; @@ -112,7 +112,7 @@ if ~options_.load_mh_file && ~options_.mh_recover fprintf(fidlog,[' Number of blocks...............: ' int2str(NumberOfBlocks) '\n']); fprintf(fidlog,[' Number of simulations per block: ' int2str(nruns(1)) '\n']); fprintf(fidlog,' \n'); - if isempty(d), + if isempty(d) prior_draw(bayestopt_,options_.prior_trunc); end % Find initial values for the NumberOfBlocks chains... @@ -127,12 +127,12 @@ if ~options_.load_mh_file && ~options_.mh_recover init_iter = 0; trial = 1; while validate == 0 && trial <= 10 - if isempty(d), + if isempty(d) candidate = prior_draw(); 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.') @@ -234,7 +234,7 @@ if ~options_.load_mh_file && ~options_.mh_recover fprintf(fidlog,[' Expected number of files per block.......: ' int2str(AnticipatedNumberOfFiles) '.\n']); fprintf(fidlog,[' Expected number of lines in the last file: ' int2str(AnticipatedNumberOfLinesInTheLastFile) '.\n']); fprintf(fidlog,['\n']); - for j = 1:NumberOfBlocks, + for j = 1:NumberOfBlocks fprintf(fidlog,[' Initial state of the Gaussian random number generator for chain number ',int2str(j),':\n']); for i=1:length(record.InitialSeeds(j).Normal) fprintf(fidlog,[' ' num2str(record.InitialSeeds(j).Normal(i)') '\n']); @@ -243,7 +243,7 @@ if ~options_.load_mh_file && ~options_.mh_recover for i=1:length(record.InitialSeeds(j).Unifor) fprintf(fidlog,[' ' num2str(record.InitialSeeds(j).Unifor(i)') '\n']); end - end, + end fprintf(fidlog,' \n'); fclose(fidlog); elseif options_.load_mh_file && ~options_.mh_recover @@ -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,8 +347,8 @@ 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 + %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); @@ -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 + 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). + % % 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 mh_bounds.lb(indices(blocks==block_iter,1),:) ) && all( proposed_par(:) < mh_bounds.ub(indices(blocks==block_iter,1),:) ) @@ -136,7 +136,7 @@ switch posterior_sampling_method current_draw(indices(blocks==block_iter,1))=proposed_par; last_posterior=logpost; accepted_draws_counter =accepted_draws_counter +1; - else %no updating + else %no updating %do nothing, keep old value end end diff --git a/matlab/print_bytecode_dynamic_model.m b/matlab/print_bytecode_dynamic_model.m index f4e381ed1..af5eb0115 100644 --- a/matlab/print_bytecode_dynamic_model.m +++ b/matlab/print_bytecode_dynamic_model.m @@ -1,17 +1,17 @@ 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 % % SPECIAL REQUIREMENTS % none -% Copyright (C) 2001-2011 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/print_bytecode_static_model.m b/matlab/print_bytecode_static_model.m index bc216c70d..ece12428b 100644 --- a/matlab/print_bytecode_static_model.m +++ b/matlab/print_bytecode_static_model.m @@ -1,17 +1,17 @@ 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 % % SPECIAL REQUIREMENTS % none -% Copyright (C) 2001-2011 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/print_info.m b/matlab/print_info.m index 3185e16bf..76ec1d115 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 @@ -11,7 +11,7 @@ function print_info(info, noprint, DynareOptions) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2005-2013 Dynare Team +% Copyright (C) 2005-2017 Dynare Team % % This file is part of Dynare. % @@ -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 496e3bf86..94d14cb02 100644 --- a/matlab/print_moments_implied_prior.m +++ b/matlab/print_moments_implied_prior.m @@ -1,9 +1,9 @@ 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 +% Copyright (C) 2016-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/print_table_prior.m b/matlab/print_table_prior.m index d84e69a9c..b1f1a13bc 100644 --- a/matlab/print_table_prior.m +++ b/matlab/print_table_prior.m @@ -1,8 +1,8 @@ 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 +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -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); diff --git a/matlab/printline.m b/matlab/printline.m index c60d0906a..29d4ec1c3 100644 --- a/matlab/printline.m +++ b/matlab/printline.m @@ -1,16 +1,16 @@ 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 +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . +% along with Dynare. If not, see . if nargin<3 f = 1; diff --git a/matlab/prior_analysis.m b/matlab/prior_analysis.m index fd79414e5..5820f69c3 100644 --- a/matlab/prior_analysis.m +++ b/matlab/prior_analysis.m @@ -1,5 +1,5 @@ function oo_ = prior_analysis(type,arg1,arg2,arg3,options_,M_,oo_,estim_params_) -% Copyright (C) 2009-2012 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -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 2bf1173ed..56ef1eb32 100644 --- a/matlab/prior_bounds.m +++ b/matlab/prior_bounds.m @@ -40,14 +40,14 @@ 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 -% Copyright (C) 2003-2012 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/prior_draw.m b/matlab/prior_draw.m index 4eb628df9..c97eaeefd 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,8 +25,8 @@ 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-2016 Dynare Team +% +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -108,9 +108,9 @@ 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)'ub(uniform_index)) | (pdraw(uniform_index)'ub(gaussian_index)) | (pdraw(gaussian_index)'ub(gaussian_index)) | (pdraw(gaussian_index)'ub(gamma_index)) | (pdraw(gamma_index)'ub(gamma_index)) | (pdraw(gamma_index)'ub(beta_index)) | (pdraw(beta_index)'ub(beta_index)) | (pdraw(beta_index)'ub(inverse_gamma_1_index)) | (pdraw(inverse_gamma_1_index)'ub(inverse_gamma_1_index)) | (pdraw(inverse_gamma_1_index)'ub(inverse_gamma_2_index)) | (pdraw(inverse_gamma_2_index)'ub(inverse_gamma_2_index)) | (pdraw(inverse_gamma_2_index)'ub(weibull_index)) | (pdraw(weibull_index)'ub(weibull_index)) | (pdraw(weibull_index)' MAX_nsmoo || b == B), + if run_smoother && (irun(1) > MAX_nsmoo || b == B) stock = stock_smooth(:,:,1:irun(1)-1); ifil(1) = ifil(1) + 1; save([DirectoryName '/' M_.fname '_smooth' int2str(ifil(1)) '.mat'],'stock'); stock = stock_update(:,:,1:irun(1)-1); save([DirectoryName '/' M_.fname '_update' int2str(ifil(1)) '.mat'],'stock'); - if RemoteFlag==1, + if RemoteFlag==1 OutputFileName_smooth = [OutputFileName_smooth; {[DirectoryName filesep], [M_.fname '_smooth' int2str(ifil(1)) '.mat']}]; OutputFileName_update = [OutputFileName_update; {[DirectoryName filesep], [M_.fname '_update' int2str(ifil(1)) '.mat']}]; end @@ -363,7 +363,7 @@ for b=fpar:B stock = stock_innov(:,:,1:irun(2)-1); ifil(2) = ifil(2) + 1; save([DirectoryName '/' M_.fname '_inno' int2str(ifil(2)) '.mat'],'stock'); - if RemoteFlag==1, + if RemoteFlag==1 OutputFileName_inno = [OutputFileName_inno; {[DirectoryName filesep], [M_.fname '_inno' int2str(ifil(2)) '.mat']}]; end irun(2) = 1; @@ -373,7 +373,7 @@ for b=fpar:B stock = stock_error(:,:,1:irun(3)-1); ifil(3) = ifil(3) + 1; save([DirectoryName '/' M_.fname '_error' int2str(ifil(3)) '.mat'],'stock'); - if RemoteFlag==1, + if RemoteFlag==1 OutputFileName_error = [OutputFileName_error; {[DirectoryName filesep], [M_.fname '_error' int2str(ifil(3)) '.mat']}]; end irun(3) = 1; @@ -383,7 +383,7 @@ for b=fpar:B stock = stock_filter_step_ahead(:,:,:,1:irun(4)-1); ifil(4) = ifil(4) + 1; save([DirectoryName '/' M_.fname '_filter_step_ahead' int2str(ifil(4)) '.mat'],'stock'); - if RemoteFlag==1, + if RemoteFlag==1 OutputFileName_filter_step_ahead = [OutputFileName_filter_step_ahead; {[DirectoryName filesep], [M_.fname '_filter_step_ahead' int2str(ifil(4)) '.mat']}]; end irun(4) = 1; @@ -395,7 +395,7 @@ for b=fpar:B stock_ys = stock_ys(1:irun(5)-1,:); ifil(5) = ifil(5) + 1; save([DirectoryName '/' M_.fname '_param' int2str(ifil(5)) '.mat'],'stock','stock_logpo','stock_ys'); - if RemoteFlag==1, + if RemoteFlag==1 OutputFileName_param = [OutputFileName_param; {[DirectoryName filesep], [M_.fname '_param' int2str(ifil(5)) '.mat']}]; end irun(5) = 1; @@ -405,7 +405,7 @@ for b=fpar:B stock = stock_forcst_mean(:,:,1:irun(6)-1); ifil(6) = ifil(6) + 1; save([DirectoryName '/' M_.fname '_forc_mean' int2str(ifil(6)) '.mat'],'stock'); - if RemoteFlag==1, + if RemoteFlag==1 OutputFileName_forc_mean = [OutputFileName_forc_mean; {[DirectoryName filesep], [M_.fname '_forc_mean' int2str(ifil(6)) '.mat']}]; end irun(6) = 1; @@ -415,39 +415,39 @@ for b=fpar:B stock = stock_forcst_point(:,:,1:irun(7)-1); ifil(7) = ifil(7) + 1; save([DirectoryName '/' M_.fname '_forc_point' int2str(ifil(7)) '.mat'],'stock'); - if RemoteFlag==1, + if RemoteFlag==1 OutputFileName_forc_point = [OutputFileName_forc_point; {[DirectoryName filesep], [M_.fname '_forc_point' int2str(ifil(7)) '.mat']}]; 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; save([DirectoryName '/' M_.fname '_filter_covar' int2str(ifil(8)) '.mat'],'stock'); - if RemoteFlag==1, + if RemoteFlag==1 OutputFileName_filter_covar = [OutputFileName_filter_covar; {[DirectoryName filesep], [M_.fname '_filter_covar' int2str(ifil(8)) '.mat']}]; 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); ifil(irun_index) = ifil(irun_index) + 1; save([DirectoryName '/' M_.fname '_trend_coeff' int2str(ifil(irun_index)) '.mat'],'stock'); - if RemoteFlag==1, + if RemoteFlag==1 OutputFileName_trend_coeff = [OutputFileName_trend_coeff; {[DirectoryName filesep], [M_.fname '_trend_coeff' int2str(ifil(irun_index)) '.mat']}]; 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); ifil(irun_index) = ifil(irun_index) + 1; save([DirectoryName '/' M_.fname '_smoothed_constant' int2str(ifil(irun_index)) '.mat'],'stock'); - if RemoteFlag==1, + if RemoteFlag==1 OutputFileName_smoothed_constant = [OutputFileName_smoothed_constant; {[DirectoryName filesep], [M_.fname '_smoothed_constant' int2str(ifil(irun_index)) '.mat']}]; end irun(irun_index) = 1; @@ -458,29 +458,29 @@ for b=fpar:B stock = stock_smoothed_trend(:,:,1:irun(irun_index)-1); ifil(irun_index) = ifil(irun_index) + 1; save([DirectoryName '/' M_.fname '_smoothed_trend' int2str(ifil(irun_index)) '.mat'],'stock'); - if RemoteFlag==1, + if RemoteFlag==1 OutputFileName_smoothed_trend = [OutputFileName_smoothed_trend; {[DirectoryName filesep], [M_.fname '_smoothed_trend' int2str(ifil(irun_index)) '.mat']}]; 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); ifil(irun_index) = ifil(irun_index) + 1; save([DirectoryName '/' M_.fname '_forc_point_ME' int2str(ifil(irun_index)) '.mat'],'stock'); - if RemoteFlag==1, + if RemoteFlag==1 OutputFileName_forc_point_ME = [OutputFileName_forc_point_ME; {[DirectoryName filesep], [M_.fname '_forc_point_ME' int2str(ifil(irun_index)) '.mat']}]; 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); ifil(irun_index) = ifil(irun_index) + 1; save([DirectoryName '/' M_.fname '_state_uncert' int2str(ifil(irun_index)) '.mat'],'stock'); - if RemoteFlag==1, + if RemoteFlag==1 OutputFileName_state_uncert = [OutputFileName_state_uncert; {[DirectoryName filesep], [M_.fname '_state_uncert' int2str(ifil(irun_index)) '.mat']}]; end irun(irun_index) = 1; @@ -490,7 +490,7 @@ for b=fpar:B end myoutput.ifil=ifil; -if RemoteFlag==1, +if RemoteFlag==1 myoutput.OutputFileName = [OutputFileName_smooth; OutputFileName_update; OutputFileName_inno; @@ -508,4 +508,3 @@ if RemoteFlag==1, end dyn_waitbar_close(h); - diff --git a/matlab/prior_sampler.m b/matlab/prior_sampler.m index 267563d8e..b49523634 100644 --- a/matlab/prior_sampler.m +++ b/matlab/prior_sampler.m @@ -13,7 +13,7 @@ function results = prior_sampler(drsave,M_,bayestopt_,options_,oo_,estim_params_ % SPECIAL REQUIREMENTS % none -% Copyright (C) 2009-2012 Dynare Team +% Copyright (C) 2009-2016 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/priordens.m b/matlab/priordens.m index f760680cf..b988e7ea1 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,13 +9,13 @@ 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 % -% Copyright (C) 2003-2015 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -89,12 +89,12 @@ 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 end - if nargout == 2, + if nargout == 2 [tmp, dlprior(id1)]=lpdfgbeta(x(id1),p6(id1),p7(id1),p3(id1),p4(id1)); elseif nargout == 3 [tmp, dlprior(id1), d2lprior(id1)]=lpdfgbeta(x(id1),p6(id1),p7(id1),p3(id1),p4(id1)); @@ -104,12 +104,12 @@ 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 end - if nargout == 2, + if nargout == 2 [tmp, dlprior(id2)]=lpdfgam(x(id2)-p3(id2),p6(id2),p7(id2)); elseif nargout == 3 [tmp, dlprior(id2), d2lprior(id2)]=lpdfgam(x(id2)-p3(id2),p6(id2),p7(id2)); @@ -118,7 +118,7 @@ end if tt3 logged_prior_density = logged_prior_density + sum(lpdfnorm(x(id3),p6(id3),p7(id3))) ; - if nargout == 2, + if nargout == 2 [tmp, dlprior(id3)]=lpdfnorm(x(id3),p6(id3),p7(id3)); elseif nargout == 3 [tmp, dlprior(id3), d2lprior(id3)]=lpdfnorm(x(id3),p6(id3),p7(id3)); @@ -128,12 +128,12 @@ 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 end - if nargout == 2, + if nargout == 2 [tmp, dlprior(id4)]=lpdfig1(x(id4)-p3(id4),p6(id4),p7(id4)); elseif nargout == 3 [tmp, dlprior(id4), d2lprior(id4)]=lpdfig1(x(id4)-p3(id4),p6(id4),p7(id4)); @@ -143,13 +143,13 @@ 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 end logged_prior_density = logged_prior_density + sum(log(1./(p4(id5)-p3(id5)))) ; - if nargout >1, + if nargout >1 dlprior(id5)=zeros(length(id5),1); end if nargout == 3 @@ -160,12 +160,12 @@ 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 end - if nargout == 2, + if nargout == 2 [tmp, dlprior(id6)]=lpdfig2(x(id6)-p3(id6),p6(id6),p7(id6)); elseif nargout == 3 [tmp, dlprior(id6), d2lprior(id6)]=lpdfig2(x(id6)-p3(id6),p6(id6),p7(id6)); @@ -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 @@ -187,7 +187,7 @@ if tt8 end end -if nargout==3, +if nargout==3 d2lprior = diag(d2lprior); end diff --git a/matlab/qr2.m b/matlab/qr2.m index 3c84db996..bdd1c0dea 100644 --- a/matlab/qr2.m +++ b/matlab/qr2.m @@ -1,23 +1,23 @@ 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. -% Copyright (C) 2006-2012 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/quadratic_matrix_equation_solver.m b/matlab/quadratic_matrix_equation_solver.m index d96ea0d9d..40342085e 100644 --- a/matlab/quadratic_matrix_equation_solver.m +++ b/matlab/quadratic_matrix_equation_solver.m @@ -47,7 +47,7 @@ function [X,info] = quadratic_matrix_equation_solver(A,B,C,tol,maxit,line_search %! @end deftypefn %@eod: -% Copyright (C) 2012 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/qz/mjdgges.m b/matlab/qz/mjdgges.m index 58e4b6513..12c91d801 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 2c88184f1..ba5206efa 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'. @@ -10,7 +10,7 @@ function [A,B,Q,Z] = qzdiv(stake,A,B,Q,Z) % http://sims.princeton.edu/yftp/gensys/mfiles/qzdiv.m % Copyright (C) 1993-2007 Christopher Sims -% Copyright (C) 2008-2011 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -27,25 +27,25 @@ function [A,B,Q,Z] = qzdiv(stake,A,B,Q,Z) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see . -[n jnk] = size(A); +[n, jnk] = size(A); root = abs([diag(A) diag(B)]); root(:,1) = root(:,1)-(root(:,1)<1.e-13).*(root(:,1)+root(:,2)); root(:,2) = root(:,2)./root(:,1); for i = n:-1:1 m=0; for j=i:-1:1 - if (root(j,2) > stake || root(j,2) < -.1) + 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); + [A, B, Q, Z] = qzswitch(k,A,B,Q,Z); tmp = root(k,2); root(k,2) = root(k+1,2); root(k+1,2) = tmp; end -end +end diff --git a/matlab/ramsey_policy.m b/matlab/ramsey_policy.m index ccc50fb04..2ca9079fe 100644 --- a/matlab/ramsey_policy.m +++ b/matlab/ramsey_policy.m @@ -1,6 +1,6 @@ function info = ramsey_policy(var_list) -% Copyright (C) 2007-2012 Dynare Team +% Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/read_data_.m b/matlab/read_data_.m index 7ad6b4228..d7de0843d 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 @@ -12,7 +12,7 @@ function read_data_() % SPECIAL REQUIREMENT % none -% Copyright (C) 2007-2012 Dynare Team +% Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/read_key_value_string.m b/matlab/read_key_value_string.m index d92fb2698..446afd2f5 100644 --- a/matlab/read_key_value_string.m +++ b/matlab/read_key_value_string.m @@ -4,7 +4,7 @@ function c = read_key_value_string(s) % estimation command) into a cell (first column for the option name ans second column for the % option value). -% Copyright (C) 2011-2016 Dynare Team +% Copyright (C) 2011-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/read_variables.m b/matlab/read_variables.m index a96e8d013..a50501252 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 % @@ -17,7 +17,7 @@ function dyn_data_01=read_variables(file_name_01,var_names_01,dyn_data_01,xls_sh % all local variables have complicated names in order to avoid name % conflicts with possible user variable names -% Copyright (C) 2005-2013 Dynare Team +% Copyright (C) 2005-2017 Dynare Team % % This file is part of Dynare. % @@ -65,7 +65,7 @@ fullname = [basename extension]; if ~exist(fullname) error(['Can''t find datafile: ' fullname ]); -end +end switch (extension) case '.m' diff --git a/matlab/realtime_shock_decomposition.m b/matlab/realtime_shock_decomposition.m index 72b1bde3e..64bf96c6f 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 @@ -22,7 +22,7 @@ function oo_ = realtime_shock_decomposition(M_,oo_,options_,varlist,bayestopt_,e % SPECIAL REQUIREMENTS % none -% Copyright (C) 2009-2016 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -44,7 +44,8 @@ if size(varlist,1) == 0 varlist = M_.endo_names(1:M_.orig_endo_nbr,:); end -[i_var,nvar] = varlist_indices(varlist,M_.endo_names); +[i_var,nvar,index_uniques] = varlist_indices(varlist,M_.endo_names); +varlist=varlist(index_uniques,:); % number of variables endo_nbr = M_.endo_nbr; @@ -68,13 +69,13 @@ if isempty(parameter_set) end presample = max(1,options_.presample); -if isfield(options_.shock_decomp,'presample'), +if isfield(options_.shock_decomp,'presample') presample = max(presample,options_.shock_decomp.presample); end % forecast_=0; forecast_ = options_.shock_decomp.forecast; forecast_params=0; -if forecast_ && isfield(options_.shock_decomp,'forecast_params'), +if forecast_ && isfield(options_.shock_decomp,'forecast_params') forecast_params = options_.shock_decomp.forecast_params; end @@ -95,32 +96,32 @@ options_.plot_priors=0; init=1; nobs = options_.nobs; -if forecast_ && any(forecast_params), +if forecast_ && any(forecast_params) M1=M_; M1.params = forecast_params; [junk1,junk2,junk3,junk4,junk5,junk6,oo1] = dynare_resolve(M1,options_,oo_); clear junk1 junk2 junk3 junk4 junk5 junk6 end -for j=presample+1:nobs, +for j=presample+1:nobs % 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), + + if forecast_ + if any(forecast_params) Af = oo1.dr.ghx; Bf = oo1.dr.ghu; else @@ -136,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_, + 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); @@ -164,30 +165,30 @@ 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(:,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, - + 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 %% %% conditional shock decomp k step ahead - if forecast_ && forecast_ 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); @@ -196,15 +197,15 @@ 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(:,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, + + if init zreal(:,:,1:j) = z(:,:,1:j); else zreal(:,:,j) = z(:,:,gend); @@ -213,7 +214,7 @@ 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); @@ -226,9 +227,9 @@ 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, + for my_forecast_=(forecast_-1):-1:1 oo_.realtime_conditional_shock_decomposition.(['time_' int2str(j-my_forecast_)]) = ... zreal(:,:,j-my_forecast_:j) - ... oo_.realtime_forecast_shock_decomposition.(['time_' int2str(j-my_forecast_)])(:,:,1:my_forecast_+1); @@ -238,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 712a4b597..4d38d9b1b 100644 --- a/matlab/recursive_moments.m +++ b/matlab/recursive_moments.m @@ -1,25 +1,25 @@ 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. -% Copyright (C) 2006-2009 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -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_form_models/local_state_space_iteration_2/local_state_space_iteration_2.m b/matlab/reduced_form_models/local_state_space_iteration_2/local_state_space_iteration_2.m index 0c6a52d07..522456728 100644 --- a/matlab/reduced_form_models/local_state_space_iteration_2/local_state_space_iteration_2.m +++ b/matlab/reduced_form_models/local_state_space_iteration_2/local_state_space_iteration_2.m @@ -58,7 +58,7 @@ function [y,y_] = local_state_space_iteration_2(yhat,epsilon,ghx,ghu,constant,gh %! @end deftypefn %@eod: -% Copyright (C) 2011-2012 Dynare Team +% Copyright (C) 2011-2014 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/reduced_rank_cholesky.m b/matlab/reduced_rank_cholesky.m index f2b6ff74c..fe9edbace 100644 --- a/matlab/reduced_rank_cholesky.m +++ b/matlab/reduced_rank_cholesky.m @@ -36,7 +36,7 @@ function T = reduced_rank_cholesky(X) %! @end deftypefn %@eod: -% Copyright (C) 2009-2011 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -51,7 +51,7 @@ 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 . +% along with Dynare. If not, see . [T,X_is_not_positive_definite] = chol(X); @@ -87,7 +87,7 @@ end %$ catch %$ t(1) = 0; %$ T = all(t); -%$ return; +%$ return %$ end %$ %$ diff --git a/matlab/resid.m b/matlab/resid.m index 71e0f6619..f124409c1 100644 --- a/matlab/resid.m +++ b/matlab/resid.m @@ -2,17 +2,17 @@ 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 -% Copyright (C) 2001-2012 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -58,7 +58,7 @@ 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 diff --git a/matlab/resol.m b/matlab/resol.m index 0fae31a9e..ba3d0e647 100644 --- a/matlab/resol.m +++ b/matlab/resol.m @@ -76,7 +76,7 @@ function [dr,info,M,options,oo] = resol(check_flag,M,options,oo) %! @end deftypefn %@eod: -% Copyright (C) 2001-2016 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -93,7 +93,7 @@ function [dr,info,M,options,oo] = resol(check_flag,M,options,oo) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see . -if isfield(oo,'dr'); +if isfield(oo,'dr') dr = oo.dr; end diff --git a/matlab/rotated_slice_sampler.m b/matlab/rotated_slice_sampler.m index d5e53e384..79f4b267f 100644 --- a/matlab/rotated_slice_sampler.m +++ b/matlab/rotated_slice_sampler.m @@ -4,7 +4,7 @@ function [theta, fxsim, neval] = rotated_slice_sampler(objective_function,theta, % extension of the orthogonal univarite sampler (slice_sampler.m) % copyright M. Ratto (European Commission) % -% objective_function(theta,varargin): -log of any unnormalized pdf +% objective_function(theta,varargin): -log of any unnormalized pdf % with varargin (optional) a vector of auxiliaty parameters % to be passed to f( ). % ---------------------------------------------------------- @@ -24,7 +24,7 @@ function [theta, fxsim, neval] = rotated_slice_sampler(objective_function,theta, % SPECIAL REQUIREMENTS % none -% Copyright (C) 2015 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -45,22 +45,22 @@ theta=theta(:); npar = length(theta); neval = zeros(npar,1); W1=[]; -if isfield(sampler_options,'WR'), +if isfield(sampler_options,'WR') W1 = sampler_options.WR; end -if ~isempty(sampler_options.mode), +if ~isempty(sampler_options.mode) mm = sampler_options.mode; n = length(mm); - for j=1:n, + 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, + for j=1:n + if j~=r jj=jj+1; tmp=mm(j).m-mm(r).m; %tmp=mm(j).m-theta; @@ -73,7 +73,7 @@ if ~isempty(sampler_options.mode), %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, @@ -86,23 +86,23 @@ if ~isempty(sampler_options.mode), % V1(:,j)=V1(:,j)-V1(:,k)'*V1(:,j)*V1(:,k); % end % V1(:,j)=V1(:,j)/norm(V1(:,j)); - % end + % end % for j=1:n, % distance(j)=sqrt(sum((theta-mm(j).m).^2)); % end % [m, im] = min(distance); - % if im==r, + % if im==r, % fxsim=[]; % return, % else % theta1=theta; % end else - V1 = sampler_options.V1; + V1 = sampler_options.V1; end npar=size(V1,2); -for it=1:npar, +for it=1:npar theta0 = theta; neval(it) = 0; xold = 0; @@ -110,18 +110,18 @@ for it=1:npar, % 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; + 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; @@ -133,7 +133,7 @@ for it=1:npar, 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; @@ -141,7 +141,7 @@ for it=1:npar, fxl = -feval(objective_function,theta,varargin{:}); neval(it) = neval(it) + 1; if (fxl <= Z) - break; + break end L = max(XLB,L-W); end @@ -151,7 +151,7 @@ for it=1:npar, fxr = -feval(objective_function,theta,varargin{:}); neval(it) = neval(it) + 1; if (fxr <= Z) - break; + break end R = min(XUB,R+W); end @@ -180,5 +180,4 @@ end % fxsim=[]; % end % end -end - +end \ No newline at end of file diff --git a/matlab/row_header_width.m b/matlab/row_header_width.m index c3132e261..e3a995502 100644 --- a/matlab/row_header_width.m +++ b/matlab/row_header_width.m @@ -1,19 +1,19 @@ 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 % None. -% Copyright (C) 2006-2013 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -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 b77bbdd2f..cc7f30515 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'),:)] ; @@ -143,7 +143,7 @@ function []=create_TeX_loader(fidTeX,options,figpath,caption,label_name,label_ty if nargin<6 scale_factor=1; end -fprintf(fidTeX,' \n'); +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,'\','/')); diff --git a/matlab/sample_autocovariance.m b/matlab/sample_autocovariance.m index 12bd34e86..3ae17e1a0 100644 --- a/matlab/sample_autocovariance.m +++ b/matlab/sample_autocovariance.m @@ -1,19 +1,19 @@ 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 -% Copyright (C) 2003-2008 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/sample_hp_filter.m b/matlab/sample_hp_filter.m index a7b3592cf..381086b3d 100644 --- a/matlab/sample_hp_filter.m +++ b/matlab/sample_hp_filter.m @@ -1,18 +1,18 @@ 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-2011 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/save_params_and_steady_state.m b/matlab/save_params_and_steady_state.m index 0f8dbfe1a..273800fce 100644 --- a/matlab/save_params_and_steady_state.m +++ b/matlab/save_params_and_steady_state.m @@ -12,17 +12,17 @@ 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 % % SPECIAL REQUIREMENTS % none -% Copyright (C) 2008-2009 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/score.m b/matlab/score.m index f9d418bfe..89d4b512b 100644 --- a/matlab/score.m +++ b/matlab/score.m @@ -8,7 +8,7 @@ function [DLIK] = score(T,R,Q,H,P,Y,DT,DYss,DOm,DH,DP,start,mf,kalman_tol,riccat % NOTE: the derivative matrices (DT,DR ...) are 3-dim. arrays with last % dimension equal to the number of structural parameters -% Copyright (C) 2009-2011 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -40,7 +40,7 @@ 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. 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 e4daafc37..2f4fcc28e 100644 --- a/matlab/set_all_parameters.m +++ b/matlab/set_all_parameters.m @@ -33,7 +33,7 @@ function M = set_all_parameters(xparam1,estim_params,M) %! @end deftypefn %@eod: -% Copyright (C) 2003-2016 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -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 760d74fa8..44976a15a 100644 --- a/matlab/set_default_option.m +++ b/matlab/set_default_option.m @@ -1,20 +1,20 @@ 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 -% Copyright (C) 2003-2009 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/set_dynare_random_generator_state.m b/matlab/set_dynare_random_generator_state.m index 209965124..a06fdff5d 100644 --- a/matlab/set_dynare_random_generator_state.m +++ b/matlab/set_dynare_random_generator_state.m @@ -1,12 +1,12 @@ 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-2012 Dynare Team +% +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -34,7 +34,7 @@ if matlab_random_streams% Use new matlab interface. if isequal(s.Type,'legacy') rand('state',state_u); randn('state',state_n); - else + else if ~isequal(state_u,state_n) error(['You are using the new Matlab RandStream mechanism ' ... 'with a single random generator, but the values ' ... diff --git a/matlab/set_dynare_seed.m b/matlab/set_dynare_seed.m index 3a71d7236..65c5e0587 100644 --- a/matlab/set_dynare_seed.m +++ b/matlab/set_dynare_seed.m @@ -1,8 +1,8 @@ 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 +% +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/set_parameters.m b/matlab/set_parameters.m index c183bb3d3..15f4175ed 100644 --- a/matlab/set_parameters.m +++ b/matlab/set_parameters.m @@ -4,17 +4,17 @@ function set_parameters(xparam1) % Sets parameters value (except measurement errors) % This is called for computations such as IRF and forecast % when measurement errors aren't taken into account -% +% % INPUTS % xparam1: vector of parameters to be estimated (initial values) -% +% % OUTPUTS % none -% +% % SPECIAL REQUIREMENTS % none -% Copyright (C) 2003-2013 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -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 bb4924c4c..dc7922916 100644 --- a/matlab/set_prior.m +++ b/matlab/set_prior.m @@ -4,21 +4,21 @@ 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 -% Copyright (C) 2003-2013 Dynare Team +% Copyright (C) 2003-2017 Dynare Team % % This file is part of Dynare. % @@ -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)]; @@ -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/set_state_space.m b/matlab/set_state_space.m index a7d108165..de8108f32 100644 --- a/matlab/set_state_space.m +++ b/matlab/set_state_space.m @@ -34,7 +34,7 @@ function dr=set_state_space(dr,DynareModel,DynareOptions) %! @end deftypefn %@eod: -% Copyright (C) 1996-2013 Dynare Team +% Copyright (C) 1996-2017 Dynare Team % % This file is part of Dynare. % @@ -73,7 +73,7 @@ if DynareOptions.block == 1 order_var = DynareModel.block_structure.variable_reordered; else order_var = [ stat_var(:); pred_var(:); both_var(:); fwrd_var(:)]; -end; +end inv_order_var(order_var) = (1:endo_nbr); % building kmask for z state vector in t+1 diff --git a/matlab/shock_decomposition.m b/matlab/shock_decomposition.m index c63facfe7..1785e8c08 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 @@ -23,7 +23,7 @@ function [oo_,M_] = shock_decomposition(M_,oo_,options_,varlist,bayestopt_,estim % SPECIAL REQUIREMENTS % none -% Copyright (C) 2009-2016 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -45,7 +45,8 @@ if size(varlist,1) == 0 varlist = M_.endo_names(1:M_.orig_endo_nbr,:); end -[i_var,nvar] = varlist_indices(varlist,M_.endo_names); +[i_var,nvar,index_uniques] = varlist_indices(varlist,M_.endo_names); +varlist=varlist(index_uniques,:); % number of variables endo_nbr = M_.endo_nbr; @@ -58,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 ' ... @@ -104,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); diff --git a/matlab/simulated_moment_uncertainty.m b/matlab/simulated_moment_uncertainty.m index 042f9914a..14ca70429 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 @@ -94,17 +94,17 @@ else end -for j=1:replic; +for j=1:replic [ys, oo_] = simult(y0,oo_.dr,M_,options_,oo_);%do simulation oo_=disp_moments(ys,char(options_.varobs),M_,options_,oo_); %get moments dum=[oo_.mean; dyn_vech(oo_.var)]; sd = sqrt(diag(oo_.var)); - for i=1:options_.ar; + for i=1:options_.ar dum=[dum; vec(oo_.autocorr{i}.*(sd*sd'))]; end mm(:,j)=dum(indx); dyn_waitbar(j/replic,h,['Simulated moment uncertainty. Replic ',int2str(j),'/',int2str(replic)]) -end; +end dyn_waitbar_close(h); if logged_steady_state_indicator diff --git a/matlab/simulated_moments_estimation.m b/matlab/simulated_moments_estimation.m index 0946e3117..b01e5e9d3 100644 --- a/matlab/simulated_moments_estimation.m +++ b/matlab/simulated_moments_estimation.m @@ -2,19 +2,19 @@ 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. % % SPECIAL REQUIREMENTS % The user has to provide a file where the moment conditions are defined. -% Copyright (C) 2010-2012 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -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'); @@ -282,7 +282,7 @@ fprintf(fid,[' time_series = extended_path([],' int2str(sample_size) ',1);\n' fprintf(fid,[' data = time_series([' int2str(observed_variables_idx) '],' int2str(burn_in_periods) '+1:' int2str(sample_size) ');\n']); fprintf(fid,[' eval(''tmp = ' moments_file_name '(data);'');\n']); fprintf(fid,[' simulated_moments = simulated_moments + tmp;\n']); -fprintf(fid,['end;\n\n']); +fprintf(fid,['end\n\n']); fprintf(fid,['simulated_moments = simulated_moments/' int2str(number_of_simulations) ';\n']); fprintf(fid,['save(''simulated_moments_slave_' int2str(slave_number) '.dat'',''simulated_moments'',''-ascii'');\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 6113cbb37..381bfaf1b 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. @@ -15,7 +15,7 @@ function y_=simult_(y0,dr,ex_,iorder) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2001-2015 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -77,15 +77,15 @@ else k2 = dr.state_var; else k2 = []; - end; + end order_var = 1:endo_nbr; dr.order_var = order_var; else k2 = dr.kstate(find(dr.kstate(:,2) <= M_.maximum_lag+1),[1 2]); k2 = k2(:,1)+(M_.maximum_lag+1-k2(:,2))*endo_nbr; order_var = dr.order_var; - end; - + end + switch iorder case 1 if isempty(dr.ghu)% For (linearized) deterministic models. @@ -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 96b1f4c44..21f0421e4 100644 --- a/matlab/simultxdet.m +++ b/matlab/simultxdet.m @@ -22,7 +22,7 @@ function [y_,int_width,int_width_ME]=simultxdet(y0,ex,ex_det, iorder,var_list,M_ % The condition size(ex,1)+M_.maximum_lag=size(ex_det,1) must be verified % for consistency. -% Copyright (C) 2008-2016 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -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 diff --git a/matlab/skipline.m b/matlab/skipline.m index 5b311ab93..f148997b8 100644 --- a/matlab/skipline.m +++ b/matlab/skipline.m @@ -1,16 +1,16 @@ 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 % -% Copyright (C) 2013-2014 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . +% along with Dynare. If not, see . if nargin < 2 fid = 1; diff --git a/matlab/slice_sampler.m b/matlab/slice_sampler.m index 1505a5f28..84ee4a6de 100644 --- a/matlab/slice_sampler.m +++ b/matlab/slice_sampler.m @@ -4,7 +4,7 @@ function [theta, fxsim, neval] = slice_sampler(objective_function,theta,thetapri % 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 +% objective_function(theta,varargin): -log of any unnormalized pdf % with varargin (optional) a vector of auxiliaty parameters % to be passed to f( ). % ---------------------------------------------------------- @@ -24,7 +24,7 @@ function [theta, fxsim, neval] = slice_sampler(objective_function,theta,thetapri % SPECIAL REQUIREMENTS % none -% Copyright (C) 2015 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -43,11 +43,11 @@ function [theta, fxsim, neval] = slice_sampler(objective_function,theta,thetapri 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, + if isempty(sampler_options.mode) % jumping + return else nevalR=sum(neval); - end + end end theta=theta(:); @@ -55,18 +55,18 @@ npar = length(theta); W1 = sampler_options.W1; neval = zeros(npar,1); -for it=1:npar, +for it=1:npar neval(it) = 0; - W = W1(it); + 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)) + % 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{:}); @@ -85,7 +85,7 @@ for it=1:npar, fxl = -feval(objective_function,theta,varargin{:}); neval(it) = neval(it) + 1; if (fxl <= Z) - break; + break end L = max(XLB,L-W); end @@ -95,7 +95,7 @@ for it=1:npar, fxr = -feval(objective_function,theta,varargin{:}); neval(it) = neval(it) + 1; if (fxr <= Z) - break; + break end R = min(XUB,R+W); end @@ -115,9 +115,9 @@ for it=1:npar, L = xsim; end end - + end -if sampler_options.rotated && ~isempty(sampler_options.mode), % jumping +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 030cb98d9..fc6358205 100644 --- a/matlab/smm_objective.m +++ b/matlab/smm_objective.m @@ -2,20 +2,20 @@ 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. % % SPECIAL REQUIREMENTS % The user has to provide a file where the moment conditions are defined. -% Copyright (C) 2010-2013 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . +% along with Dynare. If not, see . global M_ options_ oo_ persistent mainStream mainState @@ -67,8 +67,8 @@ end if penalty>0 flag = 0; - r = priorObjectiveValue + penalty; - return; + r = priorObjectiveValue + penalty; + return end save('estimated_parameters.mat','xparams'); @@ -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 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 2ce90c7bc..a579ea67e 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,19 +43,19 @@ 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-2016 Dynare Team +% Copyright (C) 1996-2017 Dynare Team % % This file is part of Dynare. % @@ -387,7 +387,7 @@ for it_=start:incr:finish oo_.deterministic_simulation.block(Block_Num).status = 0;% Convergency failed. oo_.deterministic_simulation.block(Block_Num).error = max_res; oo_.deterministic_simulation.block(Block_Num).iterations = iter; - end; + end info = -Block_Num*10; return end diff --git a/matlab/solve_perfect_foresight_model.m b/matlab/solve_perfect_foresight_model.m index 89d39fac6..cedf3e060 100644 --- a/matlab/solve_perfect_foresight_model.m +++ b/matlab/solve_perfect_foresight_model.m @@ -1,6 +1,6 @@ function [flag,endo_simul,err] = solve_perfect_foresight_model(endo_simul,exo_simul,pfm) -% Copyright (C) 2012 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -34,7 +34,7 @@ end if pfm.use_bytecode [flag, endo_simul]=bytecode(Y, exo_simul, pfm.params); - return; + return end z = Y(find(pfm.lead_lag_incidence')); @@ -72,7 +72,7 @@ for iter = 1:pfm.maxit_ end end % Stop if Newton residuals are zero. - err = max(abs(res)); + err = max(abs(res)); if err < pfm.tolerance stop = 1 ; if pfm.verbose @@ -86,7 +86,7 @@ for iter = 1:pfm.maxit_ endo_simul = reshape(Y,pfm.ny,pfm.periods+2); break end - % Compute the Newton step. + % Compute the Newton step. dy = -A\res; if any(isnan(dy)) nan_flag = 1; diff --git a/matlab/solve_two_boundaries.m b/matlab/solve_two_boundaries.m index 136d3e1ac..4b5904946 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,17 +36,17 @@ 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-2016 Dynare Team +% Copyright (C) 1996-2017 Dynare Team % % This file is part of Dynare. % @@ -92,7 +92,7 @@ while ~(cvg==1 || iter>maxit_) [max_res, max_indx]=max(max(abs(r'))); if ~isreal(r) max_res = (-max_res^2)^0.5; - end; + end if ~isreal(max_res) || isnan(max_res) cvg = 0; elseif(is_linear && iter>0) @@ -123,7 +123,7 @@ while ~(cvg==1 || iter>maxit_) end dx = (g1aa+correcting_factor*speye(periods*Blck_size))\ba- ya; y(1+y_kmin:periods+y_kmin,y_index)=reshape((ya_save+lambda*dx)',length(y_index),periods)'; - continue; + continue else disp('The singularity of the jacobian matrix could not be corrected'); return @@ -178,7 +178,7 @@ while ~(cvg==1 || iter>maxit_) B1_inv = inv(g1a(Elem, Elem)); if (t < periods) S1 = B1_inv * g1a(Elem, Elem_1); - end; + end g1a(Elem, Elem_1) = S1; b(Elem) = B1_inv * b(Elem); g1a(Elem, Elem) = ones(Blck_size, Blck_size); diff --git a/matlab/steady.m b/matlab/steady.m index 5f11f73c8..3e0ec0095 100644 --- a/matlab/steady.m +++ b/matlab/steady.m @@ -1,17 +1,17 @@ function steady() % function steady() % computes and prints the steady state calculations -% +% % INPUTS % none -% +% % OUTPUTS % none % % SPECIAL REQUIREMENTS % none -% Copyright (C) 2001-2012 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -28,7 +28,7 @@ function steady() % You should have received a copy of the GNU General Public License % along with Dynare. If not, see . -global M_ oo_ options_ ys0_ +global M_ oo_ options_ ys0_ test_for_deep_parameters_calibration(M_); @@ -70,7 +70,7 @@ 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 @@ -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 02c7c69ed..46c0e3411 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 @@ -18,7 +18,7 @@ function [steady_state,params,info] = steady_(M_,options_,oo_) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2001-2016 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/step_length_correction.m b/matlab/step_length_correction.m index 5af7dcaee..89710637b 100644 --- a/matlab/step_length_correction.m +++ b/matlab/step_length_correction.m @@ -1,6 +1,6 @@ function c = step_length_correction(x,scale,i) -% Copyright (C) 2013 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/stoch_simul.m b/matlab/stoch_simul.m index 5e7decfff..81f8b886a 100644 --- a/matlab/stoch_simul.m +++ b/matlab/stoch_simul.m @@ -56,7 +56,8 @@ if size(var_list,1) == 0 var_list = M_.endo_names(1:M_.orig_endo_nbr, :); end -[i_var,nvar] = varlist_indices(var_list,M_.endo_names); +[i_var,nvar,index_uniques] = varlist_indices(var_list,M_.endo_names); +var_list=var_list(index_uniques,:); iter_ = max(options_.periods,1); if M_.exo_nbr > 0 @@ -83,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 @@ -200,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); @@ -323,7 +324,7 @@ if options_.irf end hh = dyn_figure(options_.nodisplay,'Name',['Orthogonalized shock to ' tit(i,:) ' figure ' int2str(nbplt) '.']); m = 0; - for plt = 1:number_of_plots_to_draw-(nbplt-1)*nstar; + for plt = 1:number_of_plots_to_draw-(nbplt-1)*nstar m = m+1; subplot(lr,lc,m); plot(1:options_.irf,transpose(irfs((nbplt-1)*nstar+plt,:)),'-k','linewidth',1); diff --git a/matlab/stochastic_solvers.m b/matlab/stochastic_solvers.m index 1da71109d..a51648a43 100644 --- a/matlab/stochastic_solvers.m +++ b/matlab/stochastic_solvers.m @@ -1,35 +1,35 @@ 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-2016 Dynare Team +% Copyright (C) 1996-2017 Dynare Team % % This file is part of Dynare. % @@ -62,7 +62,7 @@ if (options_.aim_solver == 1) && (local_order > 1) 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') @@ -85,7 +85,7 @@ if M_.maximum_endo_lead==0 && M_.exo_det_nbr~=0 error(['var_exo_det not implemented for purely backwards models']) end -if options_.k_order_solver; +if options_.k_order_solver if options_.risky_steadystate [dr,info] = dyn_risky_steadystate_solver(oo_.steady_state,M_,dr, ... options_,oo_); @@ -96,7 +96,7 @@ if options_.k_order_solver; [dr,info] = k_order_pert(dr,M_,options_); options_.order = orig_order; end - return; + return end klen = M_.maximum_lag + M_.maximum_lead + 1; @@ -120,7 +120,7 @@ if local_order == 1 else [junk,jacobia_] = feval([M_.fname '_dynamic'],z(iyr0),exo_simul, ... M_.params, dr.ys, it_); - end; + end elseif local_order == 2 if (options_.bytecode) [chck, junk, loc_dr] = bytecode('dynamic','evaluate', z,exo_simul, ... @@ -130,7 +130,7 @@ elseif local_order == 2 [junk,jacobia_,hessian1] = feval([M_.fname '_dynamic'],z(iyr0),... exo_simul, ... M_.params, dr.ys, it_); - end; + 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), ... @@ -138,7 +138,7 @@ elseif local_order == 2 end [infrow,infcol]=find(isinf(hessian1)); if options_.debug - if ~isempty(infrow) + 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') @@ -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,14 +159,14 @@ 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') + 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 @@ -194,8 +194,8 @@ 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') + 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 @@ -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; @@ -263,7 +263,7 @@ else else % use original Dynare solver [dr,info] = dyn_first_order_solver(jacobia_,M_,dr,options_,task); if info(1) || task - return; + return end end @@ -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)'); @@ -381,4 +381,3 @@ if options_.loglinear end end end - diff --git a/matlab/store_smoother_results.m b/matlab/store_smoother_results.m index d8fcbbd06..5ef6e1509 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,19 +42,19 @@ 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. % -% Copyright (C) 2014-2016 Dynare Team +% Copyright (C) 2014-2017 Dynare Team % % This file is part of Dynare. % @@ -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); @@ -172,8 +172,8 @@ end 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 diff --git a/matlab/subset.m b/matlab/subset.m index 95ad23645..946ebdcc5 100644 --- a/matlab/subset.m +++ b/matlab/subset.m @@ -1,6 +1,6 @@ function jndx = subset() -% Copyright (C) 2006-2011 Dynare Team +% Copyright (C) 2006-2017 Dynare Team % % This file is part of Dynare. % @@ -63,7 +63,7 @@ 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') ) diff --git a/matlab/symmetric_matrix_index.m b/matlab/symmetric_matrix_index.m index 73cf4a50b..60b2afe70 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 @@ -11,7 +11,7 @@ function k = symmetric_matrix_index(i,j,n) % Outputs: % k [scalar] index of variable combination in vech(A) -% Copyright (C) 2007-2015 Dynare Team +% Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/test_for_deep_parameters_calibration.m b/matlab/test_for_deep_parameters_calibration.m index 4dbfca7cd..3cdc831b9 100644 --- a/matlab/test_for_deep_parameters_calibration.m +++ b/matlab/test_for_deep_parameters_calibration.m @@ -3,17 +3,17 @@ 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 -% Copyright (C) 2010-2014 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . +% along with Dynare. If not, see . 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 0f08c18ce..78e6fff4b 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,15 +34,15 @@ 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-2014 Dynare Team +% +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -114,7 +114,7 @@ else trend = 1:M_.endo_nbr; inv_order_var = trend(M_.block_structure.variable_reordered); ghu1(1:length(dr.state_var),:) = ghu(dr.state_var,:); -end; +end b = ghu1*M_.Sigma_e*ghu1'; @@ -122,7 +122,7 @@ if options_.block == 0 ipred = nstatic+(1:nspred)'; else ipred = dr.state_var; -end; +end % state space representation for state variables only [A,B] = kalman_transition_matrix(dr,ipred,1:nx,M_.exo_nbr); % Compute stationary variables (before HP filtering), @@ -134,7 +134,7 @@ if options_.order == 2 || options_.hp_filter == 0 iky = inv_order_var(ivar); else iky = ivar; - end; + end stationary_vars = (1:length(ivar))'; if ~isempty(u) x = abs(ghx*u); @@ -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,22 +227,22 @@ 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)); IE = eye(M_.exo_nbr); for ig = 1:ngrid - if filter_gain(ig)==0, + if filter_gain(ig)==0 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' + 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 - end; + end % Covariance of filtered series imathp_col = real(ifft(mathp_col))*(2*pi); % Inverse Fast Fourier Transformation; middle formula Uhlig (2001), p. 21; Gamma_y{1} = reshape(imathp_col(1,:),nvar,nvar); @@ -269,32 +269,32 @@ else% ==> Theoretical filters. IA = eye(size(A,1)); IE = eye(M_.exo_nbr); for ig = 1:ngrid - if filter_gain(ig)==0, + if filter_gain(ig)==0 f_hp = zeros(length(ivar),length(ivar)); 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 - end; + end imathp_col = real(ifft(mathp_col))*(2*pi); vv = diag(reshape(imathp_col(1,:),nvar,nvar)); for i=1:M_.exo_nbr mathp_col = NaN(ngrid,length(ivar)^2); SSi = cs(:,i)*cs(:,i)'; for ig = 1:ngrid - if filter_gain(ig)==0, + if filter_gain(ig)==0 f_hp = zeros(length(ivar),length(ivar)); 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 - end; + end imathp_col = real(ifft(mathp_col))*(2*pi); Gamma_y{nar+2}(:,i) = abs(diag(reshape(imathp_col(1,:),nvar,nvar)))./vv; end diff --git a/matlab/thet2tau.m b/matlab/thet2tau.m index 54673e542..965934e3d 100644 --- a/matlab/thet2tau.m +++ b/matlab/thet2tau.m @@ -1,7 +1,7 @@ function tau = thet2tau(params, estim_params_, M_, oo_, indx, indexo, flagmoments,mf,nlags,useautocorr,iv) % -% Copyright (C) 2011-2012 Dynare Team +% Copyright (C) 2011-2017 Dynare Team % % This file is part of Dynare. % @@ -20,22 +20,22 @@ function tau = thet2tau(params, estim_params_, M_, oo_, indx, indexo, flagmoment global options_ -if nargin==1, +if nargin==1 indx = [1:M_.param_nbr]; indexo = []; end -if nargin<7, +if nargin<7 flagmoments=0; end -if nargin<10 || isempty(useautocorr), +if nargin<10 || isempty(useautocorr) useautocorr=0; end -if nargin<11 || isempty(iv), +if nargin<11 || isempty(iv) iv=[1:M_.endo_nbr]; end -if length(params)>length(indx), +if length(params)>length(indx) M_ = set_all_parameters(params,estim_params_,M_); else M_.params(indx) = params; @@ -44,7 +44,7 @@ end % M_.Sigma_e(indexo,indexo) = diag(params(1:length(indexo)).^2); % end [A,B,tele,tubbies,M_,options_,oo_] = dynare_resolve(M_,options_,oo_); -if flagmoments==0, +if flagmoments==0 ys=oo_.dr.ys(oo_.dr.order_var); tau = [ys(iv); vec(A(iv,iv)); dyn_vech(B(iv,:)*M_.Sigma_e*B(iv,:)')]; elseif flagmoments==-1 @@ -58,7 +58,7 @@ else GAM = lyapunov_symm(A,B*M_.Sigma_e*B',options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold,[],options_.debug); k = find(abs(GAM) < 1e-12); GAM(k) = 0; - if useautocorr, + if useautocorr sy = sqrt(diag(GAM)); sy = sy*sy'; sy0 = sy-diag(diag(sy))+eye(length(sy)); @@ -69,7 +69,7 @@ else end for ii = 1:nlags dum = A^(ii)*GAM; - if useautocorr, + if useautocorr dum = dum./sy; end tau = [tau;vec(dum(mf,mf))]; diff --git a/matlab/trace_plot.m b/matlab/trace_plot.m index c07e4707b..9fbf38358 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 02acae0c5..13f11bd3d 100644 --- a/matlab/trust_region.m +++ b/matlab/trust_region.m @@ -25,7 +25,7 @@ function [x,check,info] = trust_region(fcn,x0,j1,j2,jacobian_flag,gstep,tolf,tol % none % Copyright (C) 2008-2012 VZLU Prague, a.s. -% Copyright (C) 2014-2016 Dynare Team +% Copyright (C) 2014-2017 Dynare Team % % This file is part of Dynare. % @@ -150,7 +150,7 @@ while (niter < maxiter && ~info) else info = -3; end - break; + break end elseif (abs (1-ratio) <= 0.1) delta = 1.4142*sn; @@ -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 5af782162..6baceb82f 100644 --- a/matlab/uniform_specification.m +++ b/matlab/uniform_specification.m @@ -3,20 +3,20 @@ 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 -% Copyright (C) 2004-2011 Dynare Team +% Copyright (C) 2004-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/update_last_mh_history_file.m b/matlab/update_last_mh_history_file.m index d0c4e9ca5..a0e2d4a96 100644 --- a/matlab/update_last_mh_history_file.m +++ b/matlab/update_last_mh_history_file.m @@ -5,9 +5,9 @@ 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 +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/user_has_matlab_license.m b/matlab/user_has_matlab_license.m index 51d7cf0b6..c8c681283 100644 --- a/matlab/user_has_matlab_license.m +++ b/matlab/user_has_matlab_license.m @@ -11,7 +11,7 @@ function [hasLicense] = user_has_matlab_license(toolbox) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2012 Dynare Team +% Copyright (C) 2012-2017 Dynare Team % % This file is part of Dynare. % @@ -31,7 +31,7 @@ function [hasLicense] = user_has_matlab_license(toolbox) if matlab_ver_less_than('7.12') hasLicense = license('test', toolbox); else - [hasLicense junk] = license('checkout',toolbox); + [hasLicense, junk] = license('checkout',toolbox); end if ~hasLicense return @@ -50,7 +50,7 @@ end hasInstallation=check_toolbox_installation(n); if ~hasInstallation hasLicense=0; - return; + return end end @@ -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 d2b52292d..79d324141 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 -% +% Copyright (C) 2011-2017 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 0b00df4dc..d7e3ed384 100644 --- a/matlab/utilities/dataset/initialize_dataset.m +++ b/matlab/utilities/dataset/initialize_dataset.m @@ -1,7 +1,7 @@ function dataset_ = initialize_dataset(datafile,varobs,first,nobs,logged_data_flag,prefilter,xls) % Initializes a structure describing the dataset. -% Copyright (C) 2011-2013 Dynare Team +% Copyright (C) 2011-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/utilities/dataset/lagged.m b/matlab/utilities/dataset/lagged.m index 87a7c64a4..4f17d7eeb 100644 --- a/matlab/utilities/dataset/lagged.m +++ b/matlab/utilities/dataset/lagged.m @@ -1,16 +1,16 @@ -function xlag = lagged(x, n); +function xlag = lagged(x, n) % xlag = lagged(x, n); % applies n-lags backward shift operator to x -% +% % INPUTS -% x = time series +% 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 @@ -26,7 +26,9 @@ function xlag = lagged(x, n); % You should have received a copy of the GNU General Public License % along with Dynare. If not, see . -if nargin==1, n=1; end +if nargin==1 + n=1; +end x=x(:); -xlag=[NaN(n,1); x(1:end-n)]; +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 e46f7aa76..85d86d841 100644 --- a/matlab/utilities/dataset/makedataset.m +++ b/matlab/utilities/dataset/makedataset.m @@ -23,6 +23,24 @@ function [DynareDataset, DatasetInfo, newdatainterface] = makedataset(DynareOpti % % See also dynare_estimation_init +% 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 . + + if nargin<3 gsa_flag = 0; end @@ -107,7 +125,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 d4894e8e9..121fb2dda 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 -% +% Copyright (C) 2011-2017 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 4a01941bd..c5c776724 100644 --- a/matlab/utilities/dataset/quarterly2annual.m +++ b/matlab/utilities/dataset/quarterly2annual.m @@ -18,16 +18,16 @@ function [ya, yass, gya, gyass] = quarterly2annual(y,yss,GYTREND0,type,islog,aux % 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 +% 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 @@ -43,32 +43,32 @@ function [ya, yass, gya, gyass] = quarterly2annual(y,yss,GYTREND0,type,islog,aux % You should have received a copy of the GNU General Public License % along with Dynare. If not, see . -if nargin ==0, +if nargin ==0 disp('[ya, yass, gya, gyass] = quarterly2annual(y,yss,GYTREND0,type,islog);') return end -if nargin<4 || isempty(type), +if nargin<4 || isempty(type) type=1; end -if nargin<5 || isempty(islog), +if nargin<5 || isempty(islog) islog=0; end -if isstruct(aux), +if isstruct(aux) yaux=aux.y; yauxss=aux.yss; islogaux=aux.islog; GYTREND0aux=aux.GYTREND0; - typeaux=aux.type; + typeaux=aux.type; if islogaux yaux=exp(yaux+yauxss); yauxss=exp(yauxss); yaux=yaux-yauxss; end -elseif type > 4, +elseif type > 4 error('TYPE>4 requires auxiliary variable!') end -if islog == 2, +if islog == 2 % construct loglevel out of growth rate y = cumsum(y); yss=0; @@ -80,28 +80,23 @@ if islog == 1 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 = (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; @@ -110,8 +105,7 @@ switch type [yra, yrass] = quarterly2annual(yaux,yauxss,GYTREND0aux,typeaux,0,0); % deflator yass = ynass/yrass; - ya = (yna+ynass)./(yr+yrass)-yass; - + ya = (yna+ynass)./(yr+yrass)-yass; case 6 % nominal series yn = (y+yss).*(yaux+yauxss) - yss.*yauxss; @@ -120,14 +114,12 @@ switch type [pa, pass] = quarterly2annual(yaux,yauxss,GYTREND0aux,2,0,0); % real series yass = ynass/pass; - ya = (yna+ynass)./(pa+pass)-yass; - + 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 @@ -140,5 +132,4 @@ if islog ya=log(ya+yass); yass=log(yass); ya=ya-yass; -end - +end \ No newline at end of file diff --git a/matlab/utilities/doc/dynInfo.m b/matlab/utilities/doc/dynInfo.m index 952c5bbe1..85c964974 100644 --- a/matlab/utilities/doc/dynInfo.m +++ b/matlab/utilities/doc/dynInfo.m @@ -31,7 +31,7 @@ function dynInfo(fun) %! @end deftypefn %@eod: -% Copyright (C) 2011-2012 Dynare Team +% Copyright (C) 2011-2013 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/utilities/doc/get_internal_doc_block.m b/matlab/utilities/doc/get_internal_doc_block.m index 77e4f6625..96dda6d6f 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 -% +% Copyright (C) 2011-2017 Dynare Team +% % This file is part of Dynare. % % Dynare is free software: you can redistribute it and/or modify @@ -50,7 +50,7 @@ else (~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/clean_current_folder.m b/matlab/utilities/general/clean_current_folder.m index 8375c5607..6c302927e 100644 --- a/matlab/utilities/general/clean_current_folder.m +++ b/matlab/utilities/general/clean_current_folder.m @@ -1,6 +1,6 @@ function clean_current_folder() -% Copyright (C) 2014 Dynare Team +% Copyright (C) 2014-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/utilities/general/compare_vectors.m b/matlab/utilities/general/compare_vectors.m index e0ec681a2..00ea0c11e 100644 --- a/matlab/utilities/general/compare_vectors.m +++ b/matlab/utilities/general/compare_vectors.m @@ -7,13 +7,13 @@ 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 Dynare Team +% Copyright (C) 2013-2017 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 8ac8b7996..d5e9951e4 100644 --- a/matlab/utilities/general/delete_stale_file.m +++ b/matlab/utilities/general/delete_stale_file.m @@ -2,7 +2,7 @@ function delete_stale_file(fname) % function delete_old_files(fname) % Checks for presence of files and deletes them if necessary -% Copyright (C) 2015 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -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 aed9eb4b1..741a2f107 100644 --- a/matlab/utilities/general/demean.m +++ b/matlab/utilities/general/demean.m @@ -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 -% +% Copyright (C) 2011-2017 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/disp_verbose.m b/matlab/utilities/general/disp_verbose.m index 09c09e4d7..6ea4e702e 100644 --- a/matlab/utilities/general/disp_verbose.m +++ b/matlab/utilities/general/disp_verbose.m @@ -1,8 +1,8 @@ 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 +% +% Copyright (C) 2015-2017 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 d4fd7336f..ec682aebb 100644 --- a/matlab/utilities/general/dyn_mex.m +++ b/matlab/utilities/general/dyn_mex.m @@ -1,21 +1,21 @@ 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 +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % 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 37697e723..1e092e0ac 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 @@ -9,8 +9,8 @@ function k = get_all_variables_but_lagged_leaded_exogenous(M) % k: vector of variable indices % -% Copyright (C) 2011-2016 Dynare Team -% +% Copyright (C) 2011-2017 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 6b3f0b416..a199b4b0f 100644 --- a/matlab/utilities/general/indices_lagged_leaded_exogenous_variables.m +++ b/matlab/utilities/general/indices_lagged_leaded_exogenous_variables.m @@ -12,8 +12,8 @@ function [il,l1,ik,k1] = indices_lagged_leaded_exogenous_variables(k,M) % ik: indices of non lagged or leaded variable in vector k % k1: value of non lagged or leaded variable in vector k -% Copyright (C) 2011-2016 Dynare Team -% +% Copyright (C) 2011-2017 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/isaletter.m b/matlab/utilities/general/isaletter.m index 054ced91d..f562a320a 100644 --- a/matlab/utilities/general/isaletter.m +++ b/matlab/utilities/general/isaletter.m @@ -1,7 +1,7 @@ function info = isaletter(str) % Returns 1 if the string str has at least one letter, 0 otherwise. -% Copyright (C) 2013 Dynare Team +% Copyright (C) 2013-2014 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/utilities/general/isconst.m b/matlab/utilities/general/isconst.m index 37ee23532..28001ce4e 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. % @@ -10,7 +10,7 @@ function aa = isconst(y) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2008-2009 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/utilities/general/isdiagonal.m b/matlab/utilities/general/isdiagonal.m index f76e43797..a8c1a4cf8 100644 --- a/matlab/utilities/general/isdiagonal.m +++ b/matlab/utilities/general/isdiagonal.m @@ -1,6 +1,6 @@ function b = isdiagonal(A) % --*-- Unitary tests --*-- -% Copyright (C) 2014 Dynare Team +% Copyright (C) 2014-2017 Dynare Team % % This file is part of Dynare. % @@ -60,5 +60,3 @@ end %$ t = isdiagonal(A); %$ T = all(t); %@eof:5 - - diff --git a/matlab/utilities/general/isint.m b/matlab/utilities/general/isint.m index e80a79cdf..01f403d5d 100644 --- a/matlab/utilities/general/isint.m +++ b/matlab/utilities/general/isint.m @@ -1,21 +1,21 @@ function [l,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 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/utilities/general/ispd.m b/matlab/utilities/general/ispd.m index 7fed2d44c..7ddd73e8a 100644 --- a/matlab/utilities/general/ispd.m +++ b/matlab/utilities/general/ispd.m @@ -24,7 +24,7 @@ function [test, penalty] = ispd(A) %! @end deftypefn %@eod: -% Copyright (C) 2007-2009, 2013 Dynare Team +% Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/utilities/general/isquare.m b/matlab/utilities/general/isquare.m index da47ac62e..693417c35 100644 --- a/matlab/utilities/general/isquare.m +++ b/matlab/utilities/general/isquare.m @@ -22,7 +22,7 @@ function info = isquare(A) %! @end deftypefn %@eod: -% Copyright (C) 2013 Dynare Team +% Copyright (C) 2013-2014 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/utilities/general/log_variable.m b/matlab/utilities/general/log_variable.m index 74a6aa126..98956a77c 100644 --- a/matlab/utilities/general/log_variable.m +++ b/matlab/utilities/general/log_variable.m @@ -12,8 +12,8 @@ function y = log_variable(ivar,x,M) % for lagged/leaded exogenous variables % -% Copyright (C) 2011-2016 Dynare Team -% +% Copyright (C) 2011-2017 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 1c4d003bb..95dda019d 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 -% +% Copyright (C) 2011-2017 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 19eab7a04..5cf6f33fd 100644 --- a/matlab/utilities/general/remove_fractional_xticks.m +++ b/matlab/utilities/general/remove_fractional_xticks.m @@ -2,7 +2,7 @@ function remove_fractional_xticks % function remove_fractional_xticks % removes non-integer xtick-labels -% Copyright (C) 2001-2016 Dynare Team +% Copyright (C) 2001-2017 Dynare Team % % This file is part of Dynare. % @@ -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 . +% along with Dynare. If not, see . 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 3cd4f1c23..a83aee2ff 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,36 +75,29 @@ 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"). -% Pascal Getreuer 2005-2010 -% All rights reserved. +% Copyright (C) 2005-2010 Pascal Getreuer +% Copyright (C) 2017 Dynare Team % -% Redistribution and use in source and binary forms, with or without -% modification, are permitted provided that the following conditions are -% met: +% This file is part of Dynare. % -% * 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 +% 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. % -% 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. +% 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 . %%% Input parsing %%% if nargin < 2, error('Not enough input arguments.'); end @@ -130,7 +123,7 @@ 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)]; + 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); @@ -155,7 +148,7 @@ else varargout = {Image}; end -return; +return function [SrcSpace,DestSpace] = parse(Str) @@ -164,21 +157,21 @@ function [SrcSpace,DestSpace] = parse(Str) 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 end - + SrcSpace = alias(SrcSpace); DestSpace = alias(DestSpace); else @@ -186,7 +179,7 @@ else DestSpace = Conversion; if any(size(Conversion) ~= 3), error('Transformation matrix must be 3x3.'); end end -return; +return function Space = alias(Space) @@ -204,9 +197,9 @@ switch Space case {'hsl','hsi','hls'} Space = 'hsl'; case {'rgb','yuv','yiq','ydbdr','ycbcr','jpegycbcr','xyz','lab','luv','lch'} - return; + return end -return; +return function T = gettransform(Space) @@ -240,14 +233,14 @@ switch Space otherwise error(['Unknown color space, ''',Space,'''.']); end -return; +return function Image = rgb(Image,SrcSpace) % Convert to sRGB from 'SrcSpace' switch SrcSpace case 'rgb' - return; + return case 'hsv' % Convert HSV to sRGB Image = huetorgb((1 - Image(:,:,2)).*Image(:,:,3),Image(:,:,3),Image(:,:,1)); @@ -264,7 +257,7 @@ switch SrcSpace 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] + % 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; @@ -287,16 +280,16 @@ end % Clip to [0,1] Image = min(max(Image,0),1); -return; +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; + return case 'luv' % Convert CIE L*uv to XYZ WhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3)); @@ -324,7 +317,7 @@ switch SrcSpace L = Image(:,:,1); M = Image(:,:,2); S = Image(:,:,3); - Image(:,:,1) = T(1)*L + T(4)*M + T(7)*S; % X + 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 @@ -336,11 +329,11 @@ switch SrcSpace 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(:,:,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; +return function Image = hsv(Image,SrcSpace) @@ -351,14 +344,14 @@ S = (V - min(Image,[],3))./(V + (V == 0)); Image(:,:,1) = rgbtohue(Image); Image(:,:,2) = S; Image(:,:,3) = V; -return; +return function Image = hsl(Image,SrcSpace) -% Convert to HSL +% Convert to HSL switch SrcSpace case 'hsv' - % Convert HSV to HSL + % Convert HSV to HSL MaxVal = Image(:,:,3); MinVal = (1 - Image(:,:,2)).*MaxVal; L = 0.5*(MaxVal + MinVal); @@ -377,7 +370,7 @@ switch SrcSpace Image(:,:,2) = S; Image(:,:,3) = L; end -return; +return function Image = lab(Image,SrcSpace) @@ -386,7 +379,7 @@ WhitePoint = [0.950456,1,1.088754]; switch SrcSpace case 'lab' - return; + return case 'lch' % Convert CIE L*CH to CIE L*ab C = Image(:,:,2); @@ -405,7 +398,7 @@ switch SrcSpace Image(:,:,2) = 500*(fX - fY); % a* Image(:,:,3) = 200*(fY - fZ); % b* end -return; +return function Image = luv(Image,SrcSpace) @@ -423,7 +416,7 @@ L = 116*f(Y) - 16; Image(:,:,1) = L; % L* Image(:,:,2) = 13*L.*(U - WhitePointU); % u* Image(:,:,3) = 13*L.*(V - WhitePointV); % v* -return; +return function Image = lch(Image,SrcSpace) @@ -433,7 +426,7 @@ H = atan2(Image(:,:,3),Image(:,:,2)); H = H*180/pi + 360*(H < 0); Image(:,:,2) = sqrt(Image(:,:,2).^2 + Image(:,:,3).^2); % C Image(:,:,3) = H; % H -return; +return function Image = cat02lms(Image,SrcSpace) @@ -446,7 +439,7 @@ Z = Image(:,:,3); Image(:,:,1) = T(1)*X + T(4)*Y + T(7)*Z; % L Image(:,:,2) = T(2)*X + T(5)*Y + T(8)*Z; % M Image(:,:,3) = T(3)*X + T(6)*Y + T(9)*Z; % S -return; +return function Image = huetorgb(m0,m2,H) @@ -461,7 +454,7 @@ Num = length(m0); j = [2 1 0;1 2 0;0 2 1;0 1 2;1 0 2;2 0 1;2 1 0]*Num; k = floor(H) + 1; Image = reshape([M(j(k,1)+(1:Num).'),M(j(k,2)+(1:Num).'),M(j(k,3)+(1:Num).')],[N,3]); -return; +return function H = rgbtohue(Image) @@ -482,7 +475,7 @@ k = (i == 3); H(k) = 4 + (R(k) - G(k))./Delta(k); H = 60*H + 360*(H < 0); H(Delta == 0) = nan; -return; +return function Rp = gammacorrection(R) @@ -490,7 +483,7 @@ Rp = zeros(size(R)); i = (R <= 0.0031306684425005883); Rp(i) = 12.92*R(i); Rp(~i) = real(1.055*R(~i).^0.416666666666666667 - 0.055); -return; +return function R = invgammacorrection(Rp) @@ -498,18 +491,18 @@ R = zeros(size(Rp)); i = (Rp <= 0.0404482362771076); R(i) = Rp(i)/12.92; R(~i) = real(((Rp(~i) + 0.055)/1.055).^2.4); -return; +return function fY = f(Y) fY = real(Y.^(1/3)); i = (Y < 0.008856); fY(i) = Y(i)*(841/108) + (4/29); -return; +return function Y = invf(fY) Y = fY.^3; i = (Y < 0.008856); Y(i) = (fY(i) - 4/29)*(108/841); -return; +return diff --git a/matlab/utilities/graphics/distinguishable_colors.m b/matlab/utilities/graphics/distinguishable_colors.m index f2c66231d..027ad2cb6 100644 --- a/matlab/utilities/graphics/distinguishable_colors.m +++ b/matlab/utilities/graphics/distinguishable_colors.m @@ -53,32 +53,24 @@ function colors = distinguishable_colors(n_colors,bg,func) % Example using the file exchange's 'colorspace': % func = @(x) colorspace('RGB->Lab',x); % c = distinguishable_colors(25,'w',func); - -% Copyright 2010-2011 by Timothy E. Holy -% All rights reserved. + +% Copyright (C) 2005-2010 2010-2011 by Timothy E. Holy +% Copyright (C) 2017 Dynare Team % -% Redistribution and use in source and binary forms, with or without -% modification, are permitted provided that the following conditions are -% met: +% This file is part of Dynare. % -% * 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 +% 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. % -% 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. - +% 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 . % Parse the inputs if (nargin < 2) @@ -162,9 +154,9 @@ k = find(cspec==c(1)); if isempty(k) error('MATLAB:InvalidColorString','Unknown color string.'); end -if k~=3 || length(c)==1, +if k~=3 || length(c)==1 c = rgbspec(k,:); -elseif length(c)>2, +elseif length(c)>2 if strcmpi(c(1:3),'bla') c = [0 0 0]; elseif strcmpi(c(1:3),'blu') diff --git a/matlab/utilities/tests b/matlab/utilities/tests index c548b2a91..fe65c7727 160000 --- a/matlab/utilities/tests +++ b/matlab/utilities/tests @@ -1 +1 @@ -Subproject commit c548b2a91ebedde0d625fe53f5c9f86b0911c45d +Subproject commit fe65c7727f4d1b91355b62b2cc58f5775c287afd diff --git a/matlab/variance_decomposition_mc_analysis.m b/matlab/variance_decomposition_mc_analysis.m index cfaf71c9a..4621f25d3 100644 --- a/matlab/variance_decomposition_mc_analysis.m +++ b/matlab/variance_decomposition_mc_analysis.m @@ -25,7 +25,7 @@ function oo_ = variance_decomposition_mc_analysis(NumberOfSimulations,type,dname -% Copyright (C) 2008-2013 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % @@ -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 1299e54d5..4347f9af4 100644 --- a/matlab/varlist_indices.m +++ b/matlab/varlist_indices.m @@ -1,10 +1,10 @@ function [i_var,nvar,index_uniques] = varlist_indices(sublist,list) -% function [i_var,nvar] = varlist_indices(sublist,list) +% function [i_var,nvar,index_uniques] = varlist_indices(sublist,list) % returns the indices of a list of endogenous variables % % INPUT % sublist: sublist of variables -% list: list of variables +% list: list of variables % % OUTPUT % i_var: variable indices in M_.endo_names @@ -14,7 +14,7 @@ function [i_var,nvar,index_uniques] = varlist_indices(sublist,list) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2010-2014 Dynare Team +% Copyright (C) 2010-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/ver_greater_than.m b/matlab/ver_greater_than.m index 1fef34bf2..7bd973f45 100644 --- a/matlab/ver_greater_than.m +++ b/matlab/ver_greater_than.m @@ -12,7 +12,7 @@ function tf = ver_greater_than(ver1, ver2) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2015 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -36,27 +36,27 @@ ver2 = strsplit(ver2, {'.', '-'}); maj_ver1 = str2double(ver1{1}); maj_ver2 = str2double(ver2{1}); if maj_ver1 > maj_ver2 - return; + return end min_ver1 = str2double(ver1{2}); min_ver2 = str2double(ver2{2}); if (maj_ver1 == maj_ver2) && (min_ver1 > min_ver2) - return; + return end if (length(ver1) == length(ver2) && length(ver1) == 3) ismaster1 = isnan(str2double(ver1{3})); ismaster2 = isnan(str2double(ver2{3})); if (maj_ver1 == maj_ver2) && (min_ver1 == min_ver2) && (ismaster1 && ~ismaster2) - return; + return end if ~ismaster1 && ~ismaster2 rev_ver1 = str2double(ver1{3}); rev_ver2 = str2double(ver2{3}); if (maj_ver1 == maj_ver2) && (min_ver1 == min_ver2) && (rev_ver1 > rev_ver2) - return; + return end end end diff --git a/matlab/ver_less_than.m b/matlab/ver_less_than.m index e953ed8a2..c71d163be 100644 --- a/matlab/ver_less_than.m +++ b/matlab/ver_less_than.m @@ -12,7 +12,7 @@ function tf = ver_less_than(ver1, ver2) % SPECIAL REQUIREMENTS % none -% Copyright (C) 2015 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -36,27 +36,27 @@ ver2 = strsplit(ver2, {'.', '-'}); maj_ver1 = str2double(ver1{1}); maj_ver2 = str2double(ver2{1}); if maj_ver1 < maj_ver2 - return; + return end min_ver1 = str2double(ver1{2}); min_ver2 = str2double(ver2{2}); if (maj_ver1 == maj_ver2) && (min_ver1 < min_ver2) - return; + return end if (length(ver1) == length(ver2) && length(ver1) == 3) ismaster1 = isnan(str2double(ver1{3})); ismaster2 = isnan(str2double(ver2{3})); if (maj_ver1 == maj_ver2) && (min_ver1 == min_ver2) && (~ismaster1 && ismaster2) - return; + return end if ~ismaster1 && ~ismaster2 rev_ver1 = str2double(ver1{3}); rev_ver2 = str2double(ver2{3}); if (maj_ver1 == maj_ver2) && (min_ver1 == min_ver2) && (rev_ver1 < rev_ver2) - return; + return end end end diff --git a/matlab/vnorm.m b/matlab/vnorm.m index fc9f5850a..5d3cdadd6 100644 --- a/matlab/vnorm.m +++ b/matlab/vnorm.m @@ -35,7 +35,7 @@ function y = vnorm(A,varargin) % vnorm(A,[],inf) % Correct % % -% Copyright (C) 2009-2011 Dynare Team +% Copyright (C) 2009-2017 Dynare Team % % This file is part of Dynare. % @@ -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 3b9f45d63..a7cbaab92 100644 --- a/matlab/warning_config.m +++ b/matlab/warning_config.m @@ -3,14 +3,14 @@ function warning_config() % % INPUTS % none -% +% % OUTPUTS % none -% +% % SPECIAL REQUIREMENTS % none -% Copyright (C) 2008-2015 Dynare Team +% Copyright (C) 2008-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/write_latex_definitions.m b/matlab/write_latex_definitions.m index 144f6242b..e9345ac6a 100644 --- a/matlab/write_latex_definitions.m +++ b/matlab/write_latex_definitions.m @@ -12,7 +12,7 @@ function write_latex_definitions % SPECIAL REQUIREMENTS % none -% Copyright (C) 2013 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/write_latex_parameter_table.m b/matlab/write_latex_parameter_table.m index 5a753c31c..92374d77c 100644 --- a/matlab/write_latex_parameter_table.m +++ b/matlab/write_latex_parameter_table.m @@ -12,7 +12,7 @@ function write_latex_parameter_table % SPECIAL REQUIREMENTS % none -% Copyright (C) 2015 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % @@ -29,7 +29,7 @@ function write_latex_parameter_table % You should have received a copy of the GNU General Public License % along with Dynare. If not, see . -global M_; +global M_ if ~isequal(M_.param_names,M_.param_names_long) Long_names_present=1; @@ -38,7 +38,7 @@ else end fid = fopen([M_.fname '_latex_parameters.tex'], 'w'); fprintf(fid, '\\begin{center}\n'); -if Long_names_present==1; +if Long_names_present==1 fprintf(fid, '\\begin{longtable}{ccc}\n'); else fprintf(fid, '\\begin{longtable}{cc}\n'); @@ -48,7 +48,7 @@ fprintf(fid, ['\\caption{Parameter Values}\\\\%%\n']); fprintf(fid, '\\toprule%%\n'); fprintf(fid, '\\multicolumn{1}{c}{\\textbf{Parameter}} &\n'); fprintf(fid, '\\multicolumn{1}{c}{\\textbf{Value}} '); -if Long_names_present==1; +if Long_names_present==1 fprintf(fid, '&\n \\multicolumn{1}{c}{\\textbf{Description}}\\\\%%\n'); else fprintf(fid, ' \\\\%%\n'); @@ -56,7 +56,7 @@ end fprintf(fid, '\\midrule%%\n'); fprintf(fid, '\\endfirsthead\n'); -if Long_names_present==1; +if Long_names_present==1 fprintf(fid, '\\multicolumn{3}{c}{{\\tablename} \\thetable{} -- Continued}\\\\%%\n'); else fprintf(fid, '\\multicolumn{2}{c}{{\\tablename} \\thetable{} -- Continued}\\\\%%\n'); @@ -64,7 +64,7 @@ end fprintf(fid, '\\midrule%%\n'); fprintf(fid, '\\multicolumn{1}{c}{\\textbf{Parameter}} &\n'); fprintf(fid, '\\multicolumn{1}{c}{\\textbf{Value}} '); -if Long_names_present==1; +if Long_names_present==1 fprintf(fid, '&\n \\multicolumn{1}{c}{\\textbf{Description}}\\\\%%\n'); else fprintf(fid, '\\\\%%\n'); @@ -75,7 +75,7 @@ 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; + if Long_names_present==1 % replace underscores long_names_temp=regexprep(strtrim(long(j,:)), '_', '\\_'); % replace percent diff --git a/matlab/write_latex_prior_table.m b/matlab/write_latex_prior_table.m index db9c8bfbc..2fb738bd7 100644 --- a/matlab/write_latex_prior_table.m +++ b/matlab/write_latex_prior_table.m @@ -11,7 +11,7 @@ function write_latex_prior_table % SPECIAL REQUIREMENTS % none -% Copyright (C) 2015-16 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/write_mh_history_file.m b/matlab/write_mh_history_file.m index 00984c26c..72ce6a22e 100644 --- a/matlab/write_mh_history_file.m +++ b/matlab/write_mh_history_file.m @@ -5,10 +5,10 @@ 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 +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/writecellofchar.m b/matlab/writecellofchar.m index 9ad378cb2..c08f4bb50 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,9 +19,9 @@ function str = writecellofchar(c) % % ans = % -%{'a', '['b'; 'c']', 'd'} +%{'a', '['b'; 'c']', 'd'} -% Copyright (C) 2015 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/writedata.m b/matlab/writedata.m index 112d7f130..c714728fc 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 @@ -10,7 +10,7 @@ function writedata(fname) % SPECIAL REQUIREMENT % none -% Copyright (C) 2007-2014 Dynare Team +% Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. % diff --git a/matlab/writedata_text.m b/matlab/writedata_text.m index 5af543e9c..0fa0f7ac2 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 @@ -10,7 +10,7 @@ function writedata_text(fname) % SPECIAL REQUIREMENT % none -% Copyright (C) 2007-2009 Dynare Team +% Copyright (C) 2007-2017 Dynare Team % % This file is part of Dynare. % @@ -32,7 +32,7 @@ S=[fname '_endo.dat']; fid = fopen(S,'w'); for i = 1:size(M_.endo_names,1) fprintf(fid,'%s ',M_.endo_names(i,:)'); -end; +end fprintf(fid,'\n'); for i = 1:size(oo_.endo_simul,2) fprintf(fid,'%15.7f ',oo_.endo_simul(:,i)); @@ -44,11 +44,10 @@ S=[fname '_exo.dat']; fid = fopen(S,'w'); for i = 1:size(M_.exo_names,1) fprintf(fid,'%s ',M_.exo_names(i,:)); -end; +end fprintf(fid,'\n'); for i = 1:size(oo_.exo_simul,1) fprintf(fid,'%15.7f ',oo_.exo_simul(i,:)); fprintf(fid,'\n'); end -fclose(fid); -return; \ No newline at end of file +fclose(fid); \ No newline at end of file diff --git a/matlab/writematrixofchar.m b/matlab/writematrixofchar.m index aca783955..5f3f26359 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 = @@ -17,7 +17,7 @@ function str = writematrixofchar(m) % % where the returned argument is a string which can be evaluated or printed. -% Copyright (C) 2015 Dynare Team +% Copyright (C) 2015-2017 Dynare Team % % This file is part of Dynare. % diff --git a/mex/build/matlab/configure.ac b/mex/build/matlab/configure.ac index 5bc631690..5fd9aa04d 100644 --- a/mex/build/matlab/configure.ac +++ b/mex/build/matlab/configure.ac @@ -18,7 +18,7 @@ dnl You should have received a copy of the GNU General Public License dnl along with Dynare. If not, see . AC_PREREQ([2.62]) -AC_INIT([dynare], [4.5-unstable]) +AC_INIT([dynare], [4.6-unstable]) AC_CONFIG_SRCDIR([configure.ac]) AM_INIT_AUTOMAKE([-Wall -Wno-portability foreign]) diff --git a/mex/build/octave/configure.ac b/mex/build/octave/configure.ac index fd563e61c..54351c003 100755 --- a/mex/build/octave/configure.ac +++ b/mex/build/octave/configure.ac @@ -18,7 +18,7 @@ dnl You should have received a copy of the GNU General Public License dnl along with Dynare. If not, see . AC_PREREQ([2.62]) -AC_INIT([dynare], [4.5-unstable]) +AC_INIT([dynare], [4.6-unstable]) AC_CONFIG_SRCDIR([configure.ac]) AM_INIT_AUTOMAKE([-Wall -Wno-portability foreign]) diff --git a/mex/sources/block_kalman_filter/block_kalman_filter.cc b/mex/sources/block_kalman_filter/block_kalman_filter.cc index 6ef1087a6..4da025ce7 100644 --- a/mex/sources/block_kalman_filter/block_kalman_filter.cc +++ b/mex/sources/block_kalman_filter/block_kalman_filter.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007-2013 Dynare Team + * Copyright (C) 2007-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/block_kalman_filter/block_kalman_filter.h b/mex/sources/block_kalman_filter/block_kalman_filter.h index 83eac9a44..28cb75396 100644 --- a/mex/sources/block_kalman_filter/block_kalman_filter.h +++ b/mex/sources/block_kalman_filter/block_kalman_filter.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007-2012 Dynare Team + * Copyright (C) 2007-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/bytecode/ErrorHandling.hh b/mex/sources/bytecode/ErrorHandling.hh index f9a745d54..b03599444 100644 --- a/mex/sources/bytecode/ErrorHandling.hh +++ b/mex/sources/bytecode/ErrorHandling.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007-2015 Dynare Team + * Copyright (C) 2007-2017 Dynare Team * * This file is part of Dynare. * @@ -386,7 +386,7 @@ public: string tmp_n(str.length(), ' '); string dollar, pound, tilde; dollar = "$"; - pound = "£"; + pound = "£"; tilde = "~"; for (unsigned int i = 0; i < str.length(); i++) { @@ -1329,7 +1329,7 @@ public: tmp_out << "$"; tmp_out << " / "; if (isinf(r)) - tmp_out << "£"; + tmp_out << "£"; } else tmp_out << " / "; @@ -1492,7 +1492,7 @@ public: if (compute) { if (isnan(r)) - tmp_out << "$ ^ " << "£"; + tmp_out << "$ ^ " << "£"; else tmp_out << " ^ "; } @@ -1534,7 +1534,7 @@ public: if (compute) { if (isnan(r)) - tmp_out << "$ PowerDeriv " << "£"; + tmp_out << "$ PowerDeriv " << "£"; else tmp_out << "PowerDeriv"; } @@ -1608,7 +1608,7 @@ public: if (compute) { if (isnan(r)) - tmp_out << "$log" << "£" << "(" << v1 << ")"; + tmp_out << "$log" << "£" << "(" << v1 << ")"; else tmp_out << "log(" << v1 << ")"; } @@ -1626,7 +1626,7 @@ public: if (compute) { if (isnan(r)) - tmp_out << "$log10" << "£" << "(" << v1 << ")"; + tmp_out << "$log10" << "£" << "(" << v1 << ")"; else tmp_out << "log10(" << v1 << ")"; } diff --git a/mex/sources/bytecode/Evaluate.cc b/mex/sources/bytecode/Evaluate.cc index 20e94ba06..c0860b011 100644 --- a/mex/sources/bytecode/Evaluate.cc +++ b/mex/sources/bytecode/Evaluate.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Dynare Team + * Copyright (C) 2013-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/bytecode/Evaluate.hh b/mex/sources/bytecode/Evaluate.hh index 2ff37e915..bcf62824b 100644 --- a/mex/sources/bytecode/Evaluate.hh +++ b/mex/sources/bytecode/Evaluate.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007-2013 Dynare Team + * Copyright (C) 2007-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/bytecode/Interpreter.cc b/mex/sources/bytecode/Interpreter.cc index a31b5d148..1c36f5a86 100644 --- a/mex/sources/bytecode/Interpreter.cc +++ b/mex/sources/bytecode/Interpreter.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007-2013 Dynare Team + * Copyright (C) 2007-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/bytecode/Interpreter.hh b/mex/sources/bytecode/Interpreter.hh index ab1cda491..d41e0c8cd 100644 --- a/mex/sources/bytecode/Interpreter.hh +++ b/mex/sources/bytecode/Interpreter.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007-2013 Dynare Team + * Copyright (C) 2007-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/bytecode/Mem_Mngr.cc b/mex/sources/bytecode/Mem_Mngr.cc index 78a713688..52a2ab905 100644 --- a/mex/sources/bytecode/Mem_Mngr.cc +++ b/mex/sources/bytecode/Mem_Mngr.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007-2011 Dynare Team + * Copyright (C) 2007-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/bytecode/Mem_Mngr.hh b/mex/sources/bytecode/Mem_Mngr.hh index 3d2140c26..4bde597a0 100644 --- a/mex/sources/bytecode/Mem_Mngr.hh +++ b/mex/sources/bytecode/Mem_Mngr.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007-2010 Dynare Team + * Copyright (C) 2007-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/bytecode/SparseMatrix.cc b/mex/sources/bytecode/SparseMatrix.cc index eb6eefc00..7526bbf4e 100644 --- a/mex/sources/bytecode/SparseMatrix.cc +++ b/mex/sources/bytecode/SparseMatrix.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007-2013 Dynare Team + * Copyright (C) 2007-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/bytecode/SparseMatrix.hh b/mex/sources/bytecode/SparseMatrix.hh index 7d40bdd9c..087853755 100644 --- a/mex/sources/bytecode/SparseMatrix.hh +++ b/mex/sources/bytecode/SparseMatrix.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007-2013 Dynare Team + * Copyright (C) 2007-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/bytecode/bytecode.cc b/mex/sources/bytecode/bytecode.cc index 3e00913b8..80ba1b450 100644 --- a/mex/sources/bytecode/bytecode.cc +++ b/mex/sources/bytecode/bytecode.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007-2013 Dynare Team + * Copyright (C) 2007-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/bytecode/testing/mex_interface.hh b/mex/sources/bytecode/testing/mex_interface.hh index d734c8366..aaee45edf 100644 --- a/mex/sources/bytecode/testing/mex_interface.hh +++ b/mex/sources/bytecode/testing/mex_interface.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007-2011 Dynare Team + * Copyright (C) 2007-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/dynumfpack.h b/mex/sources/dynumfpack.h index d21ed7954..1eb5511d3 100644 --- a/mex/sources/dynumfpack.h +++ b/mex/sources/dynumfpack.h @@ -3,7 +3,7 @@ */ /* - * Copyright (C) 2013 Dynare Team + * Copyright (C) 2013-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/DecisionRules.cc b/mex/sources/estimation/DecisionRules.cc index d8e38960f..41c095925 100644 --- a/mex/sources/estimation/DecisionRules.cc +++ b/mex/sources/estimation/DecisionRules.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2013 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/DecisionRules.hh b/mex/sources/estimation/DecisionRules.hh index 069536e8f..65b965aea 100644 --- a/mex/sources/estimation/DecisionRules.hh +++ b/mex/sources/estimation/DecisionRules.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/DetrendData.cc b/mex/sources/estimation/DetrendData.cc index 7a24c89e5..f9fa1b76d 100644 --- a/mex/sources/estimation/DetrendData.cc +++ b/mex/sources/estimation/DetrendData.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2013 Dynare Team + * Copyright (C) 2009-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/DetrendData.hh b/mex/sources/estimation/DetrendData.hh index ce4d185cc..408b14a11 100644 --- a/mex/sources/estimation/DetrendData.hh +++ b/mex/sources/estimation/DetrendData.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2013 Dynare Team + * Copyright (C) 2009-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/EstimatedParameter.cc b/mex/sources/estimation/EstimatedParameter.cc index a6810ceb1..5fd2bad2b 100644 --- a/mex/sources/estimation/EstimatedParameter.cc +++ b/mex/sources/estimation/EstimatedParameter.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2011 Dynare Team + * Copyright (C) 2009-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/EstimatedParameter.hh b/mex/sources/estimation/EstimatedParameter.hh index 69f2e3be8..52cc26187 100644 --- a/mex/sources/estimation/EstimatedParameter.hh +++ b/mex/sources/estimation/EstimatedParameter.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2011 Dynare Team + * Copyright (C) 2009-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/EstimatedParametersDescription.hh b/mex/sources/estimation/EstimatedParametersDescription.hh index 24a210d1c..2fc2ad8ea 100644 --- a/mex/sources/estimation/EstimatedParametersDescription.hh +++ b/mex/sources/estimation/EstimatedParametersDescription.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2010 Dynare Team + * Copyright (C) 2009-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/EstimationSubsample.cc b/mex/sources/estimation/EstimationSubsample.cc index 51d6c556d..a8dba8039 100644 --- a/mex/sources/estimation/EstimationSubsample.cc +++ b/mex/sources/estimation/EstimationSubsample.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2010 Dynare Team + * Copyright (C) 2009-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/EstimationSubsample.hh b/mex/sources/estimation/EstimationSubsample.hh index b4e6ad459..d8c90723a 100644 --- a/mex/sources/estimation/EstimationSubsample.hh +++ b/mex/sources/estimation/EstimationSubsample.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2011 Dynare Team + * Copyright (C) 2009-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/InitializeKalmanFilter.cc b/mex/sources/estimation/InitializeKalmanFilter.cc index adbd7565d..095032494 100644 --- a/mex/sources/estimation/InitializeKalmanFilter.cc +++ b/mex/sources/estimation/InitializeKalmanFilter.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2013 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/InitializeKalmanFilter.hh b/mex/sources/estimation/InitializeKalmanFilter.hh index 7a49f7ad1..a78b5970e 100644 --- a/mex/sources/estimation/InitializeKalmanFilter.hh +++ b/mex/sources/estimation/InitializeKalmanFilter.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2013 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/KalmanFilter.cc b/mex/sources/estimation/KalmanFilter.cc index a97a7110b..db9628b81 100644 --- a/mex/sources/estimation/KalmanFilter.cc +++ b/mex/sources/estimation/KalmanFilter.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2013 Dynare Team + * Copyright (C) 2009-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/KalmanFilter.hh b/mex/sources/estimation/KalmanFilter.hh index f199ec87b..4de6e156e 100644 --- a/mex/sources/estimation/KalmanFilter.hh +++ b/mex/sources/estimation/KalmanFilter.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2013 Dynare Team + * Copyright (C) 2009-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/LogLikelihoodMain.cc b/mex/sources/estimation/LogLikelihoodMain.cc index 42ebd789b..e775dbc3b 100644 --- a/mex/sources/estimation/LogLikelihoodMain.cc +++ b/mex/sources/estimation/LogLikelihoodMain.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2013 Dynare Team + * Copyright (C) 2009-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/LogLikelihoodMain.hh b/mex/sources/estimation/LogLikelihoodMain.hh index e18c84cb2..33863f336 100644 --- a/mex/sources/estimation/LogLikelihoodMain.hh +++ b/mex/sources/estimation/LogLikelihoodMain.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2013 Dynare Team + * Copyright (C) 2009-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/LogLikelihoodSubSample.cc b/mex/sources/estimation/LogLikelihoodSubSample.cc index 7d53b67fb..6c647c1f8 100644 --- a/mex/sources/estimation/LogLikelihoodSubSample.cc +++ b/mex/sources/estimation/LogLikelihoodSubSample.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2013 Dynare Team + * Copyright (C) 2009-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/LogLikelihoodSubSample.hh b/mex/sources/estimation/LogLikelihoodSubSample.hh index e87071ffa..e9f0dbe9a 100644 --- a/mex/sources/estimation/LogLikelihoodSubSample.hh +++ b/mex/sources/estimation/LogLikelihoodSubSample.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2013 Dynare Team + * Copyright (C) 2009-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/LogPosteriorDensity.cc b/mex/sources/estimation/LogPosteriorDensity.cc index b7b94dbbd..c87e6dee7 100644 --- a/mex/sources/estimation/LogPosteriorDensity.cc +++ b/mex/sources/estimation/LogPosteriorDensity.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2013 Dynare Team + * Copyright (C) 2009-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/LogPosteriorDensity.hh b/mex/sources/estimation/LogPosteriorDensity.hh index c8088bcb7..425eb625a 100644 --- a/mex/sources/estimation/LogPosteriorDensity.hh +++ b/mex/sources/estimation/LogPosteriorDensity.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2013 Dynare Team + * Copyright (C) 2009-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/LogPriorDensity.hh b/mex/sources/estimation/LogPriorDensity.hh index b1f424810..c7c57a6bd 100644 --- a/mex/sources/estimation/LogPriorDensity.hh +++ b/mex/sources/estimation/LogPriorDensity.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2012 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/ModelSolution.cc b/mex/sources/estimation/ModelSolution.cc index 3a8478dd8..abeb02124 100644 --- a/mex/sources/estimation/ModelSolution.cc +++ b/mex/sources/estimation/ModelSolution.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2013 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/ModelSolution.hh b/mex/sources/estimation/ModelSolution.hh index 88f312056..8bdc4a66a 100644 --- a/mex/sources/estimation/ModelSolution.hh +++ b/mex/sources/estimation/ModelSolution.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2013 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/Prior.hh b/mex/sources/estimation/Prior.hh index c3d0ce3e1..f550e2b75 100644 --- a/mex/sources/estimation/Prior.hh +++ b/mex/sources/estimation/Prior.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2011 Dynare Team + * Copyright (C) 2009-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/Proposal.cc b/mex/sources/estimation/Proposal.cc index f632ab2c4..8bf5933d4 100644 --- a/mex/sources/estimation/Proposal.cc +++ b/mex/sources/estimation/Proposal.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2010 Dynare Team + * Copyright (C) 2009-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/Proposal.hh b/mex/sources/estimation/Proposal.hh index 7d1386cc8..4beb1c9dd 100644 --- a/mex/sources/estimation/Proposal.hh +++ b/mex/sources/estimation/Proposal.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2011 Dynare Team + * Copyright (C) 2009-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/RandomWalkMetropolisHastings.hh b/mex/sources/estimation/RandomWalkMetropolisHastings.hh index 0a28dbb4e..c09b2c9df 100644 --- a/mex/sources/estimation/RandomWalkMetropolisHastings.hh +++ b/mex/sources/estimation/RandomWalkMetropolisHastings.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2013 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/SteadyStateSolver.cc b/mex/sources/estimation/SteadyStateSolver.cc index 03361cda2..a0bb7cbe0 100644 --- a/mex/sources/estimation/SteadyStateSolver.cc +++ b/mex/sources/estimation/SteadyStateSolver.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Dynare Team + * Copyright (C) 2013-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/SteadyStateSolver.hh b/mex/sources/estimation/SteadyStateSolver.hh index 846543c7d..726d8594b 100644 --- a/mex/sources/estimation/SteadyStateSolver.hh +++ b/mex/sources/estimation/SteadyStateSolver.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Dynare Team + * Copyright (C) 2013-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/libmat/DiscLyapFast.hh b/mex/sources/estimation/libmat/DiscLyapFast.hh index 1acef6dad..b85d73728 100644 --- a/mex/sources/estimation/libmat/DiscLyapFast.hh +++ b/mex/sources/estimation/libmat/DiscLyapFast.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2013 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc b/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc index ca6fde75a..47fc2816e 100644 --- a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc +++ b/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2011 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.hh b/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.hh index 3d2898f84..e6d939604 100644 --- a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.hh +++ b/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/libmat/LUSolver.hh b/mex/sources/estimation/libmat/LUSolver.hh index 1c0af58c1..16ab45dad 100644 --- a/mex/sources/estimation/libmat/LUSolver.hh +++ b/mex/sources/estimation/libmat/LUSolver.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/libmat/Matrix.hh b/mex/sources/estimation/libmat/Matrix.hh index 774811f5d..b17e5b3ce 100644 --- a/mex/sources/estimation/libmat/Matrix.hh +++ b/mex/sources/estimation/libmat/Matrix.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2012 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/libmat/QRDecomposition.hh b/mex/sources/estimation/libmat/QRDecomposition.hh index 0d1f900dc..d77c2baaf 100644 --- a/mex/sources/estimation/libmat/QRDecomposition.hh +++ b/mex/sources/estimation/libmat/QRDecomposition.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2011 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/libmat/Vector.hh b/mex/sources/estimation/libmat/Vector.hh index 5deaa4deb..f4c71c404 100644 --- a/mex/sources/estimation/libmat/Vector.hh +++ b/mex/sources/estimation/libmat/Vector.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2011 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/logMHMCMCposterior.cc b/mex/sources/estimation/logMHMCMCposterior.cc index ee9dd2f64..6551701d8 100644 --- a/mex/sources/estimation/logMHMCMCposterior.cc +++ b/mex/sources/estimation/logMHMCMCposterior.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2013 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/logposterior.cc b/mex/sources/estimation/logposterior.cc index 319d5e517..95e4e3cbe 100644 --- a/mex/sources/estimation/logposterior.cc +++ b/mex/sources/estimation/logposterior.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2013 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/tests/testInitKalman.cc b/mex/sources/estimation/tests/testInitKalman.cc index 21bd12954..28139ccdb 100644 --- a/mex/sources/estimation/tests/testInitKalman.cc +++ b/mex/sources/estimation/tests/testInitKalman.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2013 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/tests/testKalman.cc b/mex/sources/estimation/tests/testKalman.cc index 29e85c600..f75f3459e 100644 --- a/mex/sources/estimation/tests/testKalman.cc +++ b/mex/sources/estimation/tests/testKalman.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2013 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/utils/dynamic_dll.cc b/mex/sources/estimation/utils/dynamic_dll.cc index c4eeecc68..e9d126d9e 100644 --- a/mex/sources/estimation/utils/dynamic_dll.cc +++ b/mex/sources/estimation/utils/dynamic_dll.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2013 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/utils/dynamic_dll.hh b/mex/sources/estimation/utils/dynamic_dll.hh index ce346d08a..5e19472ee 100644 --- a/mex/sources/estimation/utils/dynamic_dll.hh +++ b/mex/sources/estimation/utils/dynamic_dll.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2013 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/utils/static_dll.hh b/mex/sources/estimation/utils/static_dll.hh index 3ca5febc3..36b28a9f2 100644 --- a/mex/sources/estimation/utils/static_dll.hh +++ b/mex/sources/estimation/utils/static_dll.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2013 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/estimation/utils/ts_exception.h b/mex/sources/estimation/utils/ts_exception.h index ba0bfb324..c3d3ea3c7 100644 --- a/mex/sources/estimation/utils/ts_exception.h +++ b/mex/sources/estimation/utils/ts_exception.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2011 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/k_order_perturbation/dynamic_dll.hh b/mex/sources/k_order_perturbation/dynamic_dll.hh index 922f1d12d..15b4acfe9 100644 --- a/mex/sources/k_order_perturbation/dynamic_dll.hh +++ b/mex/sources/k_order_perturbation/dynamic_dll.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2008-2012 Dynare Team + * Copyright (C) 2008-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/k_order_perturbation/dynamic_m.hh b/mex/sources/k_order_perturbation/dynamic_m.hh index 746acdedc..260d07ef8 100644 --- a/mex/sources/k_order_perturbation/dynamic_m.hh +++ b/mex/sources/k_order_perturbation/dynamic_m.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2011 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/k_order_perturbation/k_ord_dynare.cc b/mex/sources/k_order_perturbation/k_ord_dynare.cc index 5a5e7a1cc..7602b550d 100644 --- a/mex/sources/k_order_perturbation/k_ord_dynare.cc +++ b/mex/sources/k_order_perturbation/k_ord_dynare.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2008-2014 Dynare Team + * Copyright (C) 2008-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/k_order_perturbation/k_ord_dynare.hh b/mex/sources/k_order_perturbation/k_ord_dynare.hh index f0644acbb..b5d942f6b 100644 --- a/mex/sources/k_order_perturbation/k_ord_dynare.hh +++ b/mex/sources/k_order_perturbation/k_ord_dynare.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2008-2012 Dynare Team + * Copyright (C) 2008-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/k_order_perturbation/k_order_perturbation.cc b/mex/sources/k_order_perturbation/k_order_perturbation.cc index 4be824595..1159b810b 100644 --- a/mex/sources/k_order_perturbation/k_order_perturbation.cc +++ b/mex/sources/k_order_perturbation/k_order_perturbation.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2008-2014 Dynare Team + * Copyright (C) 2008-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/kronecker/sparse_hessian_times_B_kronecker_C.cc b/mex/sources/kronecker/sparse_hessian_times_B_kronecker_C.cc index be71632d6..492a18ff6 100644 --- a/mex/sources/kronecker/sparse_hessian_times_B_kronecker_C.cc +++ b/mex/sources/kronecker/sparse_hessian_times_B_kronecker_C.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007-2011 Dynare Team + * Copyright (C) 2007-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/linsolve/linsolve.cc b/mex/sources/linsolve/linsolve.cc index daec3999f..c8e55eecb 100644 --- a/mex/sources/linsolve/linsolve.cc +++ b/mex/sources/linsolve/linsolve.cc @@ -10,7 +10,7 @@ */ /* - * Copyright (C) 2012-2013 Dynare Team + * Copyright (C) 2012-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/local_state_space_iterations/local_state_space_iteration_2.cc b/mex/sources/local_state_space_iterations/local_state_space_iteration_2.cc index 19cc5739e..3b45d193a 100644 --- a/mex/sources/local_state_space_iterations/local_state_space_iteration_2.cc +++ b/mex/sources/local_state_space_iterations/local_state_space_iteration_2.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2013 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/mjdgges/mjdgges.c b/mex/sources/mjdgges/mjdgges.c index c73165d35..5086dc8d4 100644 --- a/mex/sources/mjdgges/mjdgges.c +++ b/mex/sources/mjdgges/mjdgges.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006-2016 Dynare Team + * Copyright (C) 2006-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/ms-sbvar/mex_top_level.cc b/mex/sources/ms-sbvar/mex_top_level.cc index 4ca78b408..9d982f327 100644 --- a/mex/sources/ms-sbvar/mex_top_level.cc +++ b/mex/sources/ms-sbvar/mex_top_level.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2011 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/ms-sbvar/mex_write_to_matlab.c b/mex/sources/ms-sbvar/mex_write_to_matlab.c index 8f7a5c580..1d14ffe3e 100644 --- a/mex/sources/ms-sbvar/mex_write_to_matlab.c +++ b/mex/sources/ms-sbvar/mex_write_to_matlab.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Dynare Team + * Copyright (C) 2011-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/ms-sbvar/modify_for_mex.h b/mex/sources/ms-sbvar/modify_for_mex.h index 0dae81f70..0689df90f 100644 --- a/mex/sources/ms-sbvar/modify_for_mex.h +++ b/mex/sources/ms-sbvar/modify_for_mex.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2011 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/qzcomplex/qzcomplex.cc b/mex/sources/qzcomplex/qzcomplex.cc index 92cf7f7ae..74773fcdc 100644 --- a/mex/sources/qzcomplex/qzcomplex.cc +++ b/mex/sources/qzcomplex/qzcomplex.cc @@ -6,7 +6,7 @@ */ /* - * Copyright (C) 2010-2016 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/mex/sources/sobol/gaussian.hh b/mex/sources/sobol/gaussian.hh index 8692814f4..6dd00ca22 100644 --- a/mex/sources/sobol/gaussian.hh +++ b/mex/sources/sobol/gaussian.hh @@ -2,7 +2,7 @@ ** ** Pseudo code of the algorithm is given at http://home.online.no/~pjacklam/notes/invnorm ** -** Copyright (C) 2010-2016 Dynare Team +** Copyright (C) 2010-2017 Dynare Team ** ** This file is part of Dynare. ** diff --git a/mex/sources/sobol/initialize_v_array.hh b/mex/sources/sobol/initialize_v_array.hh index c276701f4..ad172d7a5 100644 --- a/mex/sources/sobol/initialize_v_array.hh +++ b/mex/sources/sobol/initialize_v_array.hh @@ -7,7 +7,7 @@ initialize_v_array(int dim_max, int log_max, T **v) ** Original files downloaded from http://people.sc.fsu.edu/~burkardt/cpp_src/sobol/ (version 17-Feb-2009 09:46) ** ** Copyright (C) 2009 John Burkardt -** Copyright (C) 2010-2011 Dynare Team +** Copyright (C) 2010-2017 Dynare Team ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License as published by @@ -21,8 +21,6 @@ initialize_v_array(int dim_max, int log_max, T **v) ** ** You should have received a copy of the GNU Lesser General Public License ** along with this program. If not, see . -** -** AUTHOR(S): stephane DOT adjemian AT univ DASH lemans DOT fr */ { #include "initialize_v_array.inc" diff --git a/mex/sources/sobol/qmc_sequence.cc b/mex/sources/sobol/qmc_sequence.cc index 6b60d1614..e99d80594 100644 --- a/mex/sources/sobol/qmc_sequence.cc +++ b/mex/sources/sobol/qmc_sequence.cc @@ -1,7 +1,7 @@ /* ** Computes Quasi Monte-Carlo sequence. ** -** Copyright (C) 2010-2012 Dynare Team +** Copyright (C) 2010-2017 Dynare Team ** ** This file is part of Dynare (can be used outside Dynare). ** @@ -17,8 +17,6 @@ ** ** You should have received a copy of the GNU General Public License ** along with Dynare. If not, see . -** -** AUTHOR(S): stephane DOT adjemian AT univ DASH lemans DOT fr **/ #include diff --git a/mex/sources/sobol/sobol.hh b/mex/sources/sobol/sobol.hh index 37c589412..8926daca9 100644 --- a/mex/sources/sobol/sobol.hh +++ b/mex/sources/sobol/sobol.hh @@ -3,7 +3,7 @@ ** Original files downloaded from http://people.sc.fsu.edu/~burkardt/cpp_src/sobol/ (version 17-Feb-2009 09:46) ** ** Copyright (C) 2009 John Burkardt -** Copyright (C) 2010-2011 Dynare Team +** Copyright (C) 2010-2017 Dynare Team ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License as published by @@ -17,8 +17,6 @@ ** ** You should have received a copy of the GNU Lesser General Public License ** along with this program. If not, see . -** -** AUTHOR(S): stephane DOT adjemian AT univ DASH lemans DOT fr */ #include diff --git a/preprocessor/ConfigFile.cc b/preprocessor/ConfigFile.cc index 36a1faa7d..64d899e13 100644 --- a/preprocessor/ConfigFile.cc +++ b/preprocessor/ConfigFile.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2016 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/preprocessor/ConfigFile.hh b/preprocessor/ConfigFile.hh index e054922f7..e3d9143eb 100644 --- a/preprocessor/ConfigFile.hh +++ b/preprocessor/ConfigFile.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2016 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/preprocessor/DataTree.hh b/preprocessor/DataTree.hh index 72b12ddbe..486b57441 100644 --- a/preprocessor/DataTree.hh +++ b/preprocessor/DataTree.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2016 Dynare Team + * Copyright (C) 2003-2017 Dynare Team * * This file is part of Dynare. * diff --git a/preprocessor/DynareMain.cc b/preprocessor/DynareMain.cc index 51fa77672..887cf2818 100644 --- a/preprocessor/DynareMain.cc +++ b/preprocessor/DynareMain.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2016 Dynare Team + * Copyright (C) 2003-2017 Dynare Team * * This file is part of Dynare. * diff --git a/preprocessor/ExtendedPreprocessorTypes.hh b/preprocessor/ExtendedPreprocessorTypes.hh index 4c6869a38..bf57a19f5 100644 --- a/preprocessor/ExtendedPreprocessorTypes.hh +++ b/preprocessor/ExtendedPreprocessorTypes.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2015 Dynare Team + * Copyright (C) 2014-2017 Dynare Team * * This file is part of Dynare. * diff --git a/preprocessor/ExternalFunctionsTable.cc b/preprocessor/ExternalFunctionsTable.cc index 8554d8304..eb4ab00cb 100644 --- a/preprocessor/ExternalFunctionsTable.cc +++ b/preprocessor/ExternalFunctionsTable.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2011 Dynare Team + * Copyright (C) 2010-2015 Dynare Team * * This file is part of Dynare. * diff --git a/preprocessor/ExternalFunctionsTable.hh b/preprocessor/ExternalFunctionsTable.hh index aa4b02cdf..42d18391e 100644 --- a/preprocessor/ExternalFunctionsTable.hh +++ b/preprocessor/ExternalFunctionsTable.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2011 Dynare Team + * Copyright (C) 2010-2015 Dynare Team * * This file is part of Dynare. * diff --git a/preprocessor/MinimumFeedbackSet.cc b/preprocessor/MinimumFeedbackSet.cc index a84a994ab..d91391c58 100644 --- a/preprocessor/MinimumFeedbackSet.cc +++ b/preprocessor/MinimumFeedbackSet.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2012 Dynare Team + * Copyright (C) 2009-2017 Dynare Team * * This file is part of Dynare. * diff --git a/preprocessor/NumericalInitialization.cc b/preprocessor/NumericalInitialization.cc index aa7a25021..7d9439764 100644 --- a/preprocessor/NumericalInitialization.cc +++ b/preprocessor/NumericalInitialization.cc @@ -213,12 +213,12 @@ InitValStatement::writeOutput(ostream &output, const string &basename, bool mini void InitValStatement::writeOutputPostInit(ostream &output) const { - output << "if M_.exo_nbr > 0;" << endl - << "\too_.exo_simul = [ones(M_.maximum_lag,1)*oo_.exo_steady_state'];" << endl - <<"end;" << endl - << "if M_.exo_det_nbr > 0;" << endl - << "\too_.exo_det_simul = [ones(M_.maximum_lag,1)*oo_.exo_det_steady_state'];" << endl - <<"end;" << endl; + output << "if M_.exo_nbr > 0" << endl + << "\too_.exo_simul = ones(M_.maximum_lag,1)*oo_.exo_steady_state';" << endl + <<"end" << endl + << "if M_.exo_det_nbr > 0" << endl + << "\too_.exo_det_simul = ones(M_.maximum_lag,1)*oo_.exo_det_steady_state';" << endl + <<"end" << endl; } EndValStatement::EndValStatement(const init_values_t &init_values_arg, diff --git a/preprocessor/Shocks.cc b/preprocessor/Shocks.cc index 0aa7fdfa6..6f95a7a9a 100644 --- a/preprocessor/Shocks.cc +++ b/preprocessor/Shocks.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2016 Dynare Team + * Copyright (C) 2003-2017 Dynare Team * * This file is part of Dynare. * diff --git a/preprocessor/Shocks.hh b/preprocessor/Shocks.hh index 1c7abb913..0710e6630 100644 --- a/preprocessor/Shocks.hh +++ b/preprocessor/Shocks.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2016 Dynare Team + * Copyright (C) 2003-2017 Dynare Team * * This file is part of Dynare. * diff --git a/preprocessor/SteadyStateModel.cc b/preprocessor/SteadyStateModel.cc index 5fc9dc1de..0a6e1536d 100644 --- a/preprocessor/SteadyStateModel.cc +++ b/preprocessor/SteadyStateModel.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2016 Dynare Team + * Copyright (C) 2010-2017 Dynare Team * * This file is part of Dynare. * diff --git a/preprocessor/SymbolTable.cc b/preprocessor/SymbolTable.cc index 01a85ae26..fe96c9088 100644 --- a/preprocessor/SymbolTable.cc +++ b/preprocessor/SymbolTable.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2016 Dynare Team + * Copyright (C) 2003-2017 Dynare Team * * This file is part of Dynare. * diff --git a/preprocessor/SymbolTable.hh b/preprocessor/SymbolTable.hh index d0e178ecc..8a67d6bdb 100644 --- a/preprocessor/SymbolTable.hh +++ b/preprocessor/SymbolTable.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2016 Dynare Team + * Copyright (C) 2003-2017 Dynare Team * * This file is part of Dynare. * diff --git a/preprocessor/WarningConsolidation.cc b/preprocessor/WarningConsolidation.cc index f026dea8f..f1c24f4ad 100644 --- a/preprocessor/WarningConsolidation.cc +++ b/preprocessor/WarningConsolidation.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2013 Dynare Team + * Copyright (C) 2012-2017 Dynare Team * * This file is part of Dynare. * diff --git a/preprocessor/WarningConsolidation.hh b/preprocessor/WarningConsolidation.hh index 582af0f43..ece47995e 100644 --- a/preprocessor/WarningConsolidation.hh +++ b/preprocessor/WarningConsolidation.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2013 Dynare Team + * Copyright (C) 2012-2017 Dynare Team * * This file is part of Dynare. * diff --git a/preprocessor/macro/MacroDriver.cc b/preprocessor/macro/MacroDriver.cc index c5193cc6b..71d53b9cb 100644 --- a/preprocessor/macro/MacroDriver.cc +++ b/preprocessor/macro/MacroDriver.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2008-2015 Dynare Team + * Copyright (C) 2008-2017 Dynare Team * * This file is part of Dynare. * diff --git a/preprocessor/macro/MacroDriver.hh b/preprocessor/macro/MacroDriver.hh index 7b828b028..773a99dcf 100644 --- a/preprocessor/macro/MacroDriver.hh +++ b/preprocessor/macro/MacroDriver.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2008-2015 Dynare Team + * Copyright (C) 2008-2017 Dynare Team * * This file is part of Dynare. * diff --git a/preprocessor/macro/MacroValue.cc b/preprocessor/macro/MacroValue.cc index 3dfab3233..b20beb5db 100644 --- a/preprocessor/macro/MacroValue.cc +++ b/preprocessor/macro/MacroValue.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2008-2013 Dynare Team + * Copyright (C) 2008-2014 Dynare Team * * This file is part of Dynare. * diff --git a/preprocessor/macro/MacroValue.hh b/preprocessor/macro/MacroValue.hh index 64f0cdef7..1097841d9 100644 --- a/preprocessor/macro/MacroValue.hh +++ b/preprocessor/macro/MacroValue.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2008-2016 Dynare Team + * Copyright (C) 2008-2017 Dynare Team * * This file is part of Dynare. * diff --git a/scripts/fix-copyright-years b/scripts/fix-copyright-years index 86eceb7bd..d6f883e27 100755 --- a/scripts/fix-copyright-years +++ b/scripts/fix-copyright-years @@ -14,7 +14,7 @@ # Note that the script does not understand some unusual copyright notices: it # will display a message in that case. -LAST_UPDATE_COMMIT=61485ab809d9a33484abf6136f05abd84da2be1b +LAST_UPDATE_COMMIT=1bf81c9f5a79757c23356f16fe015ae4f10bebde if [ -z "$1" ]; then echo "Give a filename in argument" diff --git a/scripts/indent-c++.el b/scripts/indent-c++.el index 17ab26ba5..ffbfaf68d 100644 --- a/scripts/indent-c++.el +++ b/scripts/indent-c++.el @@ -1,5 +1,6 @@ (c++-mode) (setq indent-tabs-mode nil) (indent-region (point-min) (point-max)) -(set-buffer-file-coding-system 'unix) +(set-buffer-file-coding-system 'utf-8-unix) +(delete-trailing-whitespace) (save-buffer) diff --git a/scripts/indent-matlab.el b/scripts/indent-matlab.el index 76861b258..a0ef3ae76 100644 --- a/scripts/indent-matlab.el +++ b/scripts/indent-matlab.el @@ -3,5 +3,6 @@ (setq matlab-indent-function-body nil) (untabify (point-min) (point-max)) (indent-region (point-min) (point-max)) -(set-buffer-file-coding-system 'unix) +(set-buffer-file-coding-system 'utf-8-unix) +(delete-trailing-whitespace) (save-buffer) diff --git a/tests/reporting/AnnualTable.m b/tests/reporting/AnnualTable.m index fb78267f2..304cc3fe9 100644 --- a/tests/reporting/AnnualTable.m +++ b/tests/reporting/AnnualTable.m @@ -1,5 +1,5 @@ function rep = AnnualTable(rep, db_a, dc_a, seriesRootName, arange) -% Copyright (C) 2013 Dynare Team +% Copyright (C) 2013-2014 Dynare Team % % This file is part of Dynare. % diff --git a/tests/reporting/CountryGraphPage.m b/tests/reporting/CountryGraphPage.m index d67bb28a1..c3b03d188 100644 --- a/tests/reporting/CountryGraphPage.m +++ b/tests/reporting/CountryGraphPage.m @@ -1,5 +1,5 @@ function rep = CountryGraphPage(rep, countryAbbr, db_q, dc_q, prange, srange) -% Copyright (C) 2013 Dynare Team +% Copyright (C) 2013-2014 Dynare Team % % This file is part of Dynare. % diff --git a/tests/reporting/CountryTablePage.m b/tests/reporting/CountryTablePage.m index 309d69c9c..bf0087587 100644 --- a/tests/reporting/CountryTablePage.m +++ b/tests/reporting/CountryTablePage.m @@ -1,5 +1,5 @@ function rep = CountryTablePage(rep, countryAbbr, countryName, db_q, dc_q, db_a, dc_a, trange, vline_after) -% Copyright (C) 2013-2014 Dynare Team +% Copyright (C) 2013-2016 Dynare Team % % This file is part of Dynare. % diff --git a/tests/reporting/runDynareReport.m b/tests/reporting/runDynareReport.m index ba67cec76..f358a5fcc 100644 --- a/tests/reporting/runDynareReport.m +++ b/tests/reporting/runDynareReport.m @@ -1,5 +1,5 @@ function runDynareReport(dc_a, dc_q, db_a, db_q) -% Copyright (C) 2013-2014 Dynare Team +% Copyright (C) 2013-2015 Dynare Team % % This file is part of Dynare. % diff --git a/tests/run_all_unitary_tests.m b/tests/run_all_unitary_tests.m index 7200f40b3..e01aa2950 100644 --- a/tests/run_all_unitary_tests.m +++ b/tests/run_all_unitary_tests.m @@ -1,4 +1,4 @@ -% Copyright (C) 2013-2016 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % diff --git a/tests/run_block_byte_tests_matlab.m b/tests/run_block_byte_tests_matlab.m index 3675c0da7..8d6d14974 100644 --- a/tests/run_block_byte_tests_matlab.m +++ b/tests/run_block_byte_tests_matlab.m @@ -1,4 +1,4 @@ -% Copyright (C) 2011-2013 Dynare Team +% Copyright (C) 2011-2017 Dynare Team % % This file is part of Dynare. % diff --git a/tests/run_block_byte_tests_octave.m b/tests/run_block_byte_tests_octave.m index d930e8028..23e615995 100644 --- a/tests/run_block_byte_tests_octave.m +++ b/tests/run_block_byte_tests_octave.m @@ -1,4 +1,4 @@ -## Copyright (C) 2009-2013 Dynare Team +## Copyright (C) 2009-2017 Dynare Team ## ## This file is part of Dynare. ## diff --git a/tests/run_reporting_test_matlab.m b/tests/run_reporting_test_matlab.m index bd8a738d4..c716aa414 100644 --- a/tests/run_reporting_test_matlab.m +++ b/tests/run_reporting_test_matlab.m @@ -1,4 +1,4 @@ -% Copyright (C) 2013-2016 Dynare Team +% Copyright (C) 2013-2017 Dynare Team % % This file is part of Dynare. % diff --git a/tests/run_reporting_test_octave.m b/tests/run_reporting_test_octave.m index d47fb64a6..abcee07a3 100644 --- a/tests/run_reporting_test_octave.m +++ b/tests/run_reporting_test_octave.m @@ -1,4 +1,4 @@ -## Copyright (C) 2013-2016 Dynare Team +## Copyright (C) 2013-2017 Dynare Team ## ## This file is part of Dynare. ## diff --git a/tests/run_test_matlab.m b/tests/run_test_matlab.m index c7735dc16..c1922d86e 100644 --- a/tests/run_test_matlab.m +++ b/tests/run_test_matlab.m @@ -1,4 +1,4 @@ -% Copyright (C) 2011-2012 Dynare Team +% Copyright (C) 2011-2017 Dynare Team % % This file is part of Dynare. % diff --git a/tests/run_test_octave.m b/tests/run_test_octave.m index 12ff117ad..7a9ce68f4 100644 --- a/tests/run_test_octave.m +++ b/tests/run_test_octave.m @@ -1,4 +1,4 @@ -## Copyright (C) 2009-2016 Dynare Team +## Copyright (C) 2009-2017 Dynare Team ## ## This file is part of Dynare. ## diff --git a/tests/stochastic-backward-models/solow_cd_with_steadystate.mod b/tests/stochastic-backward-models/solow_cd_with_steadystate.mod index 90dfb7400..500cc137c 100644 --- a/tests/stochastic-backward-models/solow_cd_with_steadystate.mod +++ b/tests/stochastic-backward-models/solow_cd_with_steadystate.mod @@ -53,15 +53,15 @@ T = 5*floor(log(precision)/log(max(rho_x, rho_n))); oo_ = simul_backward_model(M_.endo_histval, T, options_, M_, oo_, zeros(T+1,2)); if abs(oo_.endo_simul(1,end)-LongRunEfficiency)>1e-10 - error('Wrong long run level!') + error('Wrong long run level!') end if abs(oo_.endo_simul(3,end)-LongRunPopulation)>1e-10 - error('Wrong long run level!') + error('Wrong long run level!') end IntensiveCapitalStock = oo_.endo_simul(6,1:end)./(oo_.endo_simul(1,1:end).*oo_.endo_simul(3,1:end)); -if abs(IntensiveCapitalStock-LongRunIntensiveCapitalStock)>1e-6 - error('Wrong long run level!') +if abs(IntensiveCapitalStock(end)-LongRunIntensiveCapitalStock>1e-10) + error('Wrong long run level!') end diff --git a/windows/dynare.nsi b/windows/dynare.nsi index 51d31ef26..60b575149 100644 --- a/windows/dynare.nsi +++ b/windows/dynare.nsi @@ -54,7 +54,7 @@ Section "Dynare core (preprocessor and M-files)" SectionIn RO !insertmacro DETERMINE_CONTEXT SetOutPath $INSTDIR - File README.txt ..\NEWS mexopts-win32.bat mexopts-win64.bat ..\license.txt + File README.txt ..\NEWS mexopts-win32.bat mexopts-win64.bat ..\license.txt ..\VERSION SetOutPath $INSTDIR\matlab File /r ..\matlab\*.m