Adding Mex Functionality to work with new MS-SBVAR Code, includes Forecasting,IRF,Variance Decomposition, Plotting and new global settings

time-shift
Jacob Smith 2011-04-25 14:45:12 -04:00 committed by Houtan Bastani
parent ea103ecb84
commit da43f3d0f5
17 changed files with 2755 additions and 489 deletions

View File

@ -255,66 +255,70 @@ options_.initial_date.subperiod = 0;
% discretionary policy
options_.discretionary_policy = 0;
% SWZ SBVAR
%% SWZ SBVAR
options_.ms.filtered_probabilities = 1;
options_.ms.real_time_smoothed_probabilities = 0;
options_.ms.freq = 1;
options_.ms.initial_subperiod = 1;
options_.ms.final_subperiod=4;
options_.ms.log_var = [ ];
options_.ms.forecast = 1;
options_.ms.nlags = 1;
options_.ms.restriction_fname = 0;
options_.ms.cross_restrictions = 0;
options_.ms.contemp_reduced_form = 0;
options_.ms.real_pseudo_forecast = 0;
options_.ms.bayesian_prior = 1;
options_.ms.dummy_obs = 0;
options_.ms.ncsk = 0;
options_.ms.nstd = 6;
options_.ms.ninv = 1000;
options_.ms.indxparr = 1;
options_.ms.indxovr = 0;
options_.ms.aband = 1;
options_.ms.indxap = 1;
options_.ms.apband = 1;
options_.ms.indximf = 1;
options_.ms.imfband = 1;
options_.ms.indxfore = 0;
options_.ms.foreband = 0;
options_.ms.indxgforhat = 1;
options_.ms.indxgimfhat = 1;
options_.ms.indxestima = 1;
options_.ms.indxgdls = 1;
options_.ms.cms =0;
options_.ms.ncms = 0;
options_.ms.eq_cms = 1;
options_.ms.cnum = 0;
options_.ms.banact = 1;
options_.ms.nstates = 2;
options_.ms.indxscalesstates = 0;
options_.ms.alpha = 1.0;
options_.ms.beta = 1.0;
options_.ms.gsig2_lmd = 50^2;
options_.ms.gsig2_lmdm = 50^2;
options_.ms.q_diag = 0.85;
options_.ms.flat_prior = 0;
options_.ms.create_initialization_file = 1;
options_.ms.estimate_msmodel = 1;
options_.ms.compute_mdd = 1;
options_.ms.compute_probabilities = 1;
options_.ms.print_draws = 1;
options_.ms.n_draws=1000;
options_.ms.thinning_factor=1;
options_.ms.proposal_draws = 100000;
options_.ms.lower_cholesky = 0;
options_.ms.upper_cholesky = 0;
options_.ms.Qi = [];
options_.ms.Ri = [];
options_.ms.draws_nbr_burn_in_1 = 30000;
options_.ms.draws_nbr_burn_in_2 = 10000;
options_.ms.draws_nbr_mean_var_estimate = 200000;
options_.ms.draws_nbr_modified_harmonic_mean = 1000000;
options_.ms.create_initialization_file = 1;
options_.ms.compute_mdd = 1;
options_.ms.compute_probabilities = 1;
options_.ms.coefficients_prior_hyperparameters = [1.0 1.0 0.1 1.2 1.0 1.0];
options_.ms.irf = 0;
options_.ms.bayesian_irf = 0;
options_.ms.forecast = 0;
options_.ms.variance_decomposition = 0;
options_.ms.thinning_factor = 1;
options_.ms.dirichlet_scale = [1.0 1.5 2.0];
options_.ms.vlistlog = [];
options_.ms.shock_draws = 10000;
options_.ms.shocks_per_parameter = 10;
options_.ms.percentiles = [.16 .5 .84];
options_.ms.mode_compute = 1;
options_.ms.mode_file = 0;
options_.ms.estimate.random = 5;
options_.ms.estimate.random_max = 20;
options_.ms.estimate.random_tol_obj = 0.1;
options_.ms.estimate.random_tol_parms = 0.1;
options_.ms.estimate.cb = 1e-3;
options_.ms.estimate.ce = 1e-6;
options_.ms.estimate.ci = 0.1;
options_.ms.estimate.ib = 50;
options_.ms.estimate.ii = 2.0;
options_.ms.estimate.mb = 100;
options_.ms.load_mh_file = 0;
options_.ms.mh_replic = 20000;
options_.ms.thinning_factor = 10;
options_.ms.drop = 2000;
options_.ms.adapative_mh_draws = 30000;
options_.ms.mdd_proposal_type = [3 0.1 0.9];
options_.ms.mdd_use_mean_center = 0;
options_.ms.mdd_proposal_draws = 100000;
options_.ms.filtered_probabilities = 0;
options_.ms.real_time_smoothed_probabilities = 0;
options_.ms.irf_shocks_per_parameter = options_.ms.shocks_per_parameter;
options_.ms.irf_shock_draws = options_.ms.shock_draws;
options_.ms.irf_thinning_factor = 1;
options_.ms.irf_filtered = 0;
options_.ms.forecast_shocks_per_parameter = options_.ms.shocks_per_parameter;
options_.ms.forecast_shock_draws = options_.ms.shock_draws;
options_.ms.forecast_thinning_factor = 1;
options_.ms.forecast_data_obs = 0;
options_.ms.vd_shocks_per_parameter = options_.ms.shocks_per_parameter;
options_.ms.vd_shock_draws = options_.ms.shock_draws;
options_.ms.vd_thinning_factor = 1;
options_.ms.vd_filtered = 0;
% Shock decomposition
options_.parameter_set = [];

View File

@ -35,17 +35,6 @@ elseif ~isempty(options.ms.Qi) && ~isempty(options.ms.Ri)
end
if ms_flag == 1
% changing some option names to match MS code
options.ms.firstMetrop = options.ms.draws_nbr_burn_in_1;
options.ms.secondMetrop = options.ms.draws_nbr_burn_in_2;
options.ms.ndrawsmv = options.ms.draws_nbr_mean_var_estimate;
options.ms.ndrawsmhm = options.ms.draws_nbr_modified_harmonic_mean;
options.ms.tfmhm = options.ms.thinning_factor;
options.ms.svd = options.ms.dirichlet_scale;
% are these options necessary ?
options.ms.opt1 = 1;
options.ms.opt2 = 1;
options.ms.opt3 = 1;
% temporary fix
options.ms.markov_file = 'markov_file';
sz_prd(M,options);

View File

@ -15,7 +15,7 @@ function ms_write_markov_file(fname,M,options)
fprintf(fh,'//== Number Observations ==//\n');
fprintf(fh,'0\n\n');
fprintf(fh,'//== Number Independent State Variables ==//\n');
fprintf(fh,'//== Number independent state variables ==//\n');
fprintf(fh,'%d\n\n',n_chains);
for i_chain = 1:n_chains

View File

@ -0,0 +1,142 @@
function plot_ms_forecast(forecast,title_)
% function [] = plot_ms_forecast(forecast,names)
% plots the forecast from the output from a ms-sbvar
%
% INPUTS
% forecast should be in the form (percentile x horizon x nvar ), if banded otherwise
% ( horizon x nvar )
%
% title: optional super title
%
% Copyright (C) 2011 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ oo_ options_
nc = 2;
nr = 2;
nvars = M_.endo_nbr;
endo_names = M_.endo_names;
fname = M_.fname;
var_list = endo_names(1:M_.orig_endo_nbr,:);
i_var = [];
for i = 1:size(var_list)
tmp = strmatch(var_list(i,:),endo_names,'exact');
if isempty(tmp)
error([var_list(i,:) ' isn''t and endogenous variable'])
end
i_var = [i_var; tmp];
end
nvar = length(i_var);
dims = size(forecast);
if nargin < 2
title_ = '';
end
if (length(dims) == 2)
% Point Forecast (horizon x nvars )
horizon = dims(1);
num_percentiles = 1;
elseif (length(dims) == 3)
% Banded Forecast
horizon = dims(2);
num_percentiles = dims(1);
else
error('The impulse response matrix passed to be plotted does not appear to be the correct size');
end
if ~exist(fname, 'dir')
mkdir('.',fname);
end
if ~exist([fname '/graphs'])
mkdir(fname,'graphs');
end
n_fig = 1;
if num_percentiles == 1
plot_point_forecast(forecast,nvars,endo_names);
else
plot_banded_forecast(forecast,nvars,endo_names,num_percentiles);
end
function plot_point_forecast(forecast,nvars,names)
fig = figure('Name','Forecast (I)');
m = 1;
for j=1:nvars
if m > nr*nc
%eval(['print -deps ' fname '/graphs/forcst' int2str(n_fig) '.eps;'])
n_fig =n_fig+1;
eval(['figure(''Name'',''Forecast (' int2str(n_fig) ')'');']);
m = 1;
end
subplot(nr,nc,m);
vn = deblank(names(i_var(j),:));
plot(forecast(:,j))
title(vn,'Interpreter','none');
%suptitle(title_);
grid on;
m = m+1;
end
if m > 1
%eval(['print -deps ' fname '/graphs/forcst' int2str(n_fig) '.eps;'])
end
end
function plot_banded_forecast(forecast,nvars,names,num_percentiles)
fig = figure('Name',[title_ ' (1)']);
%suptitle(title_);
m = 1;
for j=1:nvars
if m > nr*nc
suptitle(title_);
%eval(['print -deps ' fname '/graphs/forcst' int2str(n_fig) '.eps;'])
n_fig =n_fig+1;
eval(['figure(''Name'',''' title_ ' (' int2str(n_fig) ')'');']);
m = 1;
end
subplot(nr,nc,m);
vn = deblank(names(i_var(j),:));
for k=1:num_percentiles
if ceil(num_percentiles/2) == k
plot(forecast(k,:,j),'LineWidth',1.5)
else
plot(forecast(k,:,j),'LineWidth',1.1)
end
if k==1
hold on;
end
end
title(vn,'Interpreter','none');
hold off
grid on;
m = m+1;
end
if m > 1
%eval(['print -deps ' fname '/graphs/forcst' int2str(n_fig) '.eps;'])
end
end
end

View File

@ -0,0 +1,131 @@
function plot_ms_irf(irf,names,title_)
% function [] = plot_ms_irf(irf,names)
% plots the impulse responses from the output from a ms-sbvar
%
% INPUTS
% irf should be in the form (percentile x horizon x (nvar x nvar)), if banded otherwise
% ( horizon x (nvar x nvar) )
%
% names: character list of the names of the variables
%
% title: optional super title
%
% The element in position (k,i+j*nvars) of ir is the response of the ith
% variable to the jth shock at horizon k. Horizon 0 is the contemporaneous
% response.
% Copyright (C) 2011 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ oo_ options_
nc = 2;
nr = 2;
nvars = M_.endo_nbr;
endo_names = M_.endo_names;
fname = M_.fname;
var_list = endo_names(1:M_.orig_endo_nbr,:);
i_var = [];
for i = 1:size(var_list)
tmp = strmatch(var_list(i,:),endo_names,'exact');
if isempty(tmp)
error([var_list(i,:) ' isn''t and endogenous variable'])
end
i_var = [i_var; tmp];
end
nvar = length(i_var);
dims = size(irf);
if nargin < 3
title_ = '';
end
if (length(dims) == 2)
% Point IRF (horizon x (nvarsxnvars) )
horizon = dims(1);
num_percentiles = 1;
elseif (length(dims) == 3)
% Banded IRF
horizon = dims(2);
num_percentiles = dims(1);
else
error('The impulse response matrix passed to be plotted does not appear to be the correct size');
end
if size(names,1) ~= nvars
error('The names passed are not the same length as the number of variables')
end
if ~exist(fname, 'dir')
mkdir('.',fname);
end
if ~exist([fname '/graphs'])
mkdir(fname,'graphs');
end
if num_percentiles == 1
% loop through the shocks
for s=1:nvars
shock = zeros(horizon,nvars);
for i=1:nvars
shock(:,i) = irf(:,((i-1) + ((s-1)*nvars)+1));
end
plot_point_irf_for_shock(shock,nvars,names,names(s,:));
end
else
for s=1:nvars
shock = zeros(horizon,nvars,num_percentiles);
for n=1:num_percentiles
for i=1:nvars
shock(:,i,n) = irf(n,:,((i-1) + ((s-1)*nvars)+1));
end
end
plot_banded_irf_for_shock(shock,nvars,names,names(s,:));
end
end
function [fig] = plot_point_irf_for_shock(irf,nvars,names,shock_name)
fig = figure('Name',title_);
for k=1:nvars
subplot(ceil(sqrt(nvars)), ceil(sqrt(nvars)),k);
plot(irf(:,k))
title([names(k,:) ' shock from ' shock_name]);
end
%suptitle(title_);
end
function [fig] = plot_banded_irf_for_shock(irf,nvars, names, shock_name)
fig = figure('Name',title_);
npercentiles = size(irf,3);
for ii=1:nvars
subplot(ceil(sqrt(nvars)), ceil(sqrt(nvars)),ii);
for nn=1:npercentiles
plot(irf(:,ii,nn))
hold on
end
hold off
title([names(ii,:) ' shock from ' shock_name]);
end
%suptitle(title_);
end
end

View File

@ -0,0 +1,68 @@
function plot_ms_probabilities(computed_probabilities)
% function plot_ms_probabilities(computed_probabilities)
% Plots the regime probablities for each graph
%
% INPUTS
% computed_probabilities: Txnstates
%
% OUTPUTS
% none
%
% SPECIAL REQUIREMENTS
% none
% Copyright (C) 2011 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ oo_ options_
[T,num_grand_regimes] = size(computed_probabilities);
num_chains = length(options_.ms.ms_chain);
for i=1:num_chains
chains(i).num_regimes = length(options_.ms.ms_chain(i).state);
chains(i).probabilities = zeros([T,chains(i).num_regimes]);
end
for t=1:T
chains = iterate_chain(computed_probabilities(t,:), t, chains, 1, num_chains);
end
for i=1:num_chains
figure
plot(chains(i).probabilities,'LineWidth', 1.2);
ltxt = {};
for j=1:chains(i).num_regimes
ltxt{j} = ['Regime ' num2str(j)];
end
legend(ltxt{:});
title(['Chain ' num2str(i)]);
ylim([0 1.0]);
end
end
function [chains] = iterate_chain(probs, t, chains, chain, num_chains)
offset_length = length(probs)/chains(chain).num_regimes;
for i=1:chains(chain).num_regimes
p = probs( (i-1)*offset_length+1 : i*offset_length );
chains(chain).probabilities(t, i) = chains(chain).probabilities(t, i) + sum( p );
if chain < num_chains
chains = iterate_chain(p, t, chains, chain+1, num_chains);
end
end
end

View File

@ -0,0 +1,148 @@
function plot_ms_variance_decomposition(vd, title_, varargin)
% plot the variance decomposition of shocks
%
% Inputs
% shocks: matrix of the individual shocks Tx(KxK)with J=number of shocks
%
% Optional Inputs
% 'data': the actual data, TxK with K=number of data series
% 'steady': the steady state value, TxK
% 'shock_names': to specify the names of the shocks
% 'series_names': to specify the names of the different series
% 'dates': pass a date vector to use, otherwise will just index on 1:T
% 'colors': Jx3 list of the rgb colors to use for each shock
%
% Example:
% plot_historic_decomposition(shocks,'VD','shock_names',shock_names,'series_names',series_names)
% Copyright (C) 2011 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <http://www.gnu.org/licenses/>.
global M_ oo_ options_
nvars = M_.endo_nbr;
endo_names = M_.endo_names;
dims = size(vd);
if length(dims) == 3
[T,K,J] = dims;
shocks = vd;
else
T = dims(1);
K = nvars;
J = nvars;
temp_vd = zeros(T,K,J);
for i=1:nvars
for j=1:nvars
temp_vd(:,i,j) = vd(:,((j-1) + ((i-1)*nvars)+1));
end
end
shocks = temp_vd;
end
for i=1:nvars
shock_names{i} = endo_names(i,:);
series_names{i} = endo_names(i,:);
end
if nargin < 2
title_ = '';
end
x = [1:T]; plot_dates = 0;
data = 0;
steady = 0;
colors = [ .1 .1 .75
.8 0 0
1 .7 .25
1 1 0
.5 1 .5
.7 .7 .1
.5 .6 .2
.1 .5 .1];
% overide the defaults with optional inputs
for i=1:length(varargin)
if strcmpi(varargin{i},'data')
data = varargin{i+1};
elseif strcmpi(varargin{i},'steady')
steady = varargin{i+1};
elseif strcmpi(varargin{i},'shock_names')
shock_names = varargin{i+1};
elseif strcmpi(varargin{i},'series_names')
series_names = varargin{i+1};
elseif strcmpi(varargin{i}, 'dates')
x = varargin{i+1}; plot_dates = 1;
elseif strcmpi(varargin{i},'colors')
colors = varargin{i+1};
end
end
% add an extra period to the time series
x(T+1) = x(T) + (x(T) - x(T-1));
figure('Name',title_)
for k=1:K
% Go through each series
subplot(K,1,k);
sshocks = shocks(:,k,:);
hold on
% plot the stacked shocks
for t=1:T
% step through each time period
pos_position = 0; neg_position = 0;
xt = [x(t) x(t) x(t+1) x(t+1)];
for j=1:J
% stack each shock
st = sshocks(t,1,j);
if st < 0
yi = st+neg_position;
y = [neg_position yi yi neg_position];
neg_position = yi;
else
yi = st+pos_position;
y = [pos_position yi yi pos_position];
pos_position = yi;
end
fill(xt,y,colors(j,:));
XY(t,j,:) = y;
end
end
if data
plot(x(2:end)',data(:,k),'k','LineWidth',2.5);
end
if steady
plot(x(2:end)',steady(:,k), '--k','LineWidth',2.25);
end
if k==K
lh = legend(shock_names,'Location','BestOutside','Orientation','horizontal');
end
hold off
if plot_dates
datetick 'x';
end
xlim([min(x),max(x)])
ylim([0 , 1])
grid on
title(series_names{k});
%suptitle(title_);
end
end

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
noinst_PROGRAMS = ms_sbvar_create_init_file ms_sbvar_command_line
noinst_PROGRAMS = ms_sbvar_create_init_file ms_sbvar_command_line mex_ms_convert_free_parameters mex_ms_irf mex_ms_forecast mex_ms_variance_decomposition
DWSWITCHDIR = $(top_srcdir)/../../../ms-sbvar/switch_dw
DWUTILITIESDIR = $(top_srcdir)/../../../ms-sbvar/utilities_dw
@ -57,8 +57,91 @@ nodist_ms_sbvar_command_line_SOURCES = \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_probabilities.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_mdd.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_forecast.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_impulse_responses.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_variance_decomposition.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_impulse_responses.c \
$(DWSWITCHDIR)/state_space/sbvar/dw_csminwel.c \
$(DWUTILS) \
$(MSMEXSRC)
nodist_mex_ms_convert_free_parameters_SOURCES = \
$(DWSWITCHDIR)/switching/dw_switch.c \
$(DWSWITCHDIR)/switching/dw_switchio.c \
$(DWSWITCHDIR)/switching/dw_dirichlet_restrictions.c \
$(DWSWITCHDIR)/switching/dw_metropolis_theta.c \
$(DWSWITCHDIR)/state_space/sbvar/VARbase.c \
$(DWSWITCHDIR)/state_space/sbvar/VARio.c \
$(DWSWITCHDIR)/state_space/sbvar/VARio_matlab.c \
$(MSMEXSRCDIR)/mex_ms_convert_free_parameters.cc \
$(MSMEXSRCDIR)/mex_ms_sbvar.cc \
$(MSMEXSRCDIR)/modify_for_mex.cc \
$(DWUTILS)
nodist_mex_ms_irf_SOURCES = \
$(DWSWITCHDIR)/switching/dw_switch.c \
$(DWSWITCHDIR)/switching/dw_switchio.c \
$(DWSWITCHDIR)/switching/dw_dirichlet_restrictions.c \
$(DWSWITCHDIR)/switching/dw_metropolis_theta.c \
$(DWSWITCHDIR)/switching/dw_switch_opt.c \
$(DWSWITCHDIR)/switching/dw_mdd_switch.c \
$(DWSWITCHDIR)/state_space/sbvar/VARbase.c \
$(DWSWITCHDIR)/state_space/sbvar/VARio.c \
$(DWSWITCHDIR)/state_space/sbvar/dw_sbvar_command_line.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_estimate.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_simulate.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_probabilities.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_mdd.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_forecast.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_variance_decomposition.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_impulse_responses.c \
$(DWSWITCHDIR)/state_space/sbvar/dw_csminwel.c \
$(MSMEXSRCDIR)/mex_ms_sbvar.cc \
$(MSMEXSRCDIR)/modify_for_mex.cc \
$(MSMEXSRCDIR)/mex_ms_irf.cc \
$(DWUTILS)
nodist_mex_ms_forecast_SOURCES = \
$(DWSWITCHDIR)/switching/dw_switch.c \
$(DWSWITCHDIR)/switching/dw_switchio.c \
$(DWSWITCHDIR)/switching/dw_dirichlet_restrictions.c \
$(DWSWITCHDIR)/switching/dw_metropolis_theta.c \
$(DWSWITCHDIR)/switching/dw_switch_opt.c \
$(DWSWITCHDIR)/switching/dw_mdd_switch.c \
$(DWSWITCHDIR)/state_space/sbvar/VARbase.c \
$(DWSWITCHDIR)/state_space/sbvar/VARio.c \
$(DWSWITCHDIR)/state_space/sbvar/dw_sbvar_command_line.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_estimate.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_simulate.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_probabilities.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_mdd.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_forecast.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_variance_decomposition.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_impulse_responses.c \
$(DWSWITCHDIR)/state_space/sbvar/dw_csminwel.c \
$(MSMEXSRCDIR)/mex_ms_sbvar.cc \
$(MSMEXSRCDIR)/modify_for_mex.cc \
$(MSMEXSRCDIR)/mex_ms_forecast.cc \
$(DWUTILS)
nodist_mex_ms_variance_decomposition_SOURCES = \
$(DWSWITCHDIR)/switching/dw_switch.c \
$(DWSWITCHDIR)/switching/dw_switchio.c \
$(DWSWITCHDIR)/switching/dw_dirichlet_restrictions.c \
$(DWSWITCHDIR)/switching/dw_metropolis_theta.c \
$(DWSWITCHDIR)/switching/dw_switch_opt.c \
$(DWSWITCHDIR)/switching/dw_mdd_switch.c \
$(DWSWITCHDIR)/state_space/sbvar/VARbase.c \
$(DWSWITCHDIR)/state_space/sbvar/VARio.c \
$(DWSWITCHDIR)/state_space/sbvar/dw_sbvar_command_line.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_estimate.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_simulate.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_probabilities.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_mdd.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_forecast.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_variance_decomposition.c \
$(DWSWITCHDIR)/state_space/sbvar/sbvar_impulse_responses.c \
$(DWSWITCHDIR)/state_space/sbvar/dw_csminwel.c \
$(MSMEXSRCDIR)/mex_ms_sbvar.cc \
$(MSMEXSRCDIR)/modify_for_mex.cc \
$(MSMEXSRCDIR)/mex_ms_variance_decomposition.cc \
$(DWUTILS)

View File

@ -0,0 +1,122 @@
/*
* Copyright (C) 2011 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE)
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "mex_ms_sbvar.h"
extern "C" {
#include "modify_for_mex.h"
#include "switch.h"
#include "switchio.h"
#include "VARio.h"
}
void
mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
using namespace std;
char *input_buf;
double *free_parameters;
int nvars, npre, nstates, nfree;
double *aplus = NULL, *a0 = NULL, *zeta = NULL, *q = NULL;
mxArray *Q = NULL;
TStateModel *model;
SbvarOption *options = NULL;
/* input must be a string */
if (mxIsChar(prhs[0]) != 1)
DYN_MEX_FUNC_ERR_MSG_TXT("First argument has to be a string to the init_filename.");
if (!mxIsDouble(prhs[1]))
DYN_MEX_FUNC_ERR_MSG_TXT("Second argument is a vector of free parameters");
if (nlhs < 3)
DYN_MEX_FUNC_ERR_MSG_TXT("You must specify at least three output arguments [A0,Aplus,Zeta]");
// copy the string data from prhs[0] into a C string input_ buf. */
input_buf = mxArrayToString(prhs[0]);
if (input_buf == NULL)
DYN_MEX_FUNC_ERR_MSG_TXT("Could not convert input to string.");
// second element should be vector of free parameters */
free_parameters = mxGetPr(prhs[1]);
// copy the string data from prhs[0] into a C string input_ buf. */
input_buf = mxArrayToString(prhs[0]);
if (input_buf == NULL)
DYN_MEX_FUNC_ERR_MSG_TXT("Could not convert input to string.");
model = initialize_model_and_options(input_buf, &options, nrhs, prhs, &nstates, &nvars, &npre, &nfree);
if (model == NULL || options == NULL)
DYN_MEX_FUNC_ERR_MSG_TXT("There was a problem initializing the model, can not continue");
// Check the size of the parameters that were passed in
size_t npars_passed = mxGetN(prhs[1]) > mxGetM(prhs[1]) ? mxGetN(prhs[1]) : mxGetM(prhs[1]);
// If it is 2 longer than the number of free parameters assume that the first two numbers should be ignored (log posterior, log likelihood)
if (nfree + 2 == (int) npars_passed)
free_parameters = free_parameters + 2;
else if (nfree != (int) npars_passed && nfree + 2 != (int) npars_passed)
{
printf("\n\nThe model requires a free paramter vector of length %d, you passed one of length %d\n\n",
(int) nfree, (int) npars_passed);
DYN_MEX_FUNC_ERR_MSG_TXT("The Free Parameter Array is the wrong size for this model\n");
}
// Ao (nstates x nvars x nvars)
mwSize dims[3] = {nstates, nvars, nvars};
plhs[0] = mxCreateNumericArray(3, dims, mxDOUBLE_CLASS, mxREAL);
a0 = mxGetPr(plhs[0]);
// Zeta (nstates x nvars x nvars)
plhs[2] = mxCreateNumericArray(3, dims, mxDOUBLE_CLASS, mxREAL);
zeta = mxGetPr(plhs[2]);
// Aplus (nstates x (nlags*nvars +nconstant) x nvars)
dims[1] = npre;
plhs[1] = mxCreateNumericArray(3, dims, mxDOUBLE_CLASS, mxREAL);
aplus = mxGetPr(plhs[1]);
// Grand Transition Matrix
Q = mxCreateDoubleMatrix(nstates, nstates, mxREAL);
q = mxGetPr(Q);
// get the matrices
int ret = convert_free_parameters_to_VAR(model, free_parameters, a0, aplus, zeta, q);
if (ret > 0)
{
char *error_msg;
sprintf(error_msg = (char *) mxMalloc(255*sizeof(char)), "There was a problem converting the free parameters for the given model and inputs\nError Code: %d", ret);
DYN_MEX_FUNC_ERR_MSG_TXT(error_msg);
}
// if they have passed 4 arguments then pass back Q
if (nlhs > 3)
plhs[3] = Q;
mxFree(model);
}
#endif

View File

@ -0,0 +1,194 @@
/*
* Copyright (C) 2011 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE)
#include "dynmex.h"
#include "mex_ms_sbvar.h"
#include <iostream>
extern "C" {
#include "modify_for_mex.h"
#include "switch.h"
#include "switchio.h"
#include "VARio.h"
#include "dw_histogram.h"
#include "sbvar_forecast.h"
}
void
mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
using namespace std;
char *input_buf;
double *out_buf;
int i, j, k, s, nfree, nstates, nvars, npre, T;
TStateModel *model;
SbvarOption *options = (SbvarOption *) NULL;
T_VAR_Parameters *p = (T_VAR_Parameters *) NULL;
TMatrixHistogram *histogram = (TMatrixHistogram *) NULL;
TMatrix forecast;
int type = F_FREE;
// Check the left hand and right hand side arguments to make sure they conform
if (mxIsChar(prhs[0]) != 1)
DYN_MEX_FUNC_ERR_MSG_TXT("First argument has to be a string to the init_filename.");
if (nlhs != 1)
DYN_MEX_FUNC_ERR_MSG_TXT("You must specify one output argument");
// copy the string data from prhs[0] into a C string input_ buf. */
input_buf = mxArrayToString(prhs[0]);
if (input_buf == NULL)
DYN_MEX_FUNC_ERR_MSG_TXT("Could not convert input to string.");
model = initialize_model_and_options(input_buf, &options, nrhs, prhs, &nstates, &nvars, &npre, &nfree);
if (model == NULL || options == NULL)
DYN_MEX_FUNC_ERR_MSG_TXT("There was a problem initializing the model, can not continue");
p = (T_VAR_Parameters *) (model->theta);
T = p->nobs;
// Check to make sure that there is a simulation file present if we are
// using parameter uncertainty
if (options->parameter_uncertainty && options->simulation_file == NULL)
DYN_MEX_FUNC_ERR_MSG_TXT("Paramter Uncertainty Was Specified but the simulation file was not found, please specify the simulation file to use with: 'simulation_file',<filename>");
if (!options->parameter_uncertainty)
options->simulation_file = (FILE *) NULL;
// Allocate the output matrix
if (options->regimes)
if (options->num_percentiles > 1)
{
// regimes x percentile x horizon x nvar
mwSize dims[4] = {nstates, options->num_percentiles, options->horizon, nvars};
plhs[0] = mxCreateNumericArray(4, dims, mxDOUBLE_CLASS, mxREAL);
out_buf = mxGetPr(plhs[0]);
}
else
{
// regimes x horizon x (nvar*nvar)
mwSize dims[3] = {nstates, options->horizon, nvars};
plhs[0] = mxCreateNumericArray(3, dims, mxDOUBLE_CLASS, mxREAL);
out_buf = mxGetPr(plhs[0]);
}
else
if (options->num_percentiles > 1)
{
// percentile x horizon x (nvar*nvar)
mwSize dims[3] = {options->num_percentiles, options->horizon, nvars};
plhs[0] = mxCreateNumericArray(3, dims, mxDOUBLE_CLASS, mxREAL);
out_buf = mxGetPr(plhs[0]);
}
else
{
// horizon x (nvar*nvar)
mwSize dims[2] = {options->horizon, nvars};
plhs[0] = mxCreateNumericArray(2, dims, mxDOUBLE_CLASS, mxREAL);
out_buf = mxGetPr(plhs[0]);
}
// hard coding dates for now to be off
int dates = 0;
try
{
if (options->regimes)
for (s = 0; s < nstates; s++)
{
printf("Constructing percentiles for forecast - regime %d\n", s);
if (histogram = forecast_percentile_regime(options->shocks, options->simulation_file, options->thin, s, T, options->horizon, model, type))
{
for (k = 0; k < options->num_percentiles; k++)
if (forecast = ForecastHistogramToPercentile((TMatrix) NULL, options->number_observations, options->horizon, T, options->percentiles[k], histogram, model, dates))
{
// the case where we are only dealing with one percentile so we can reduce dimensionality of output argument
if (options->num_percentiles == 1)
for (i = 0; i < options->horizon; i++)
for (j = 0; j < nvars; j++)
out_buf[(s) + ((i) + (j)*options->horizon)*nstates] = ElementM(forecast, i, j);
else
for (i = 0; i < options->horizon; i++)
for (j = 0; j < nvars; j++)
out_buf[(s) + ((k) + ((i) + (j)*options->horizon)*options->num_percentiles)*nstates] = ElementM(forecast, i, j);
mxFree(forecast);
}
mxFree(histogram);
}
}
else if (options->regime >= 0)
{
s = options->regime;
printf("Constructing percentiles for forecast - regime %d\n", s);
if (histogram = forecast_percentile_regime(options->shocks, options->simulation_file, options->thin, s, T, options->horizon, model, type))
{
for (k = 0; k < options->num_percentiles; k++)
if (forecast = ForecastHistogramToPercentile((TMatrix) NULL, options->number_observations, options->horizon, T, options->percentiles[k], histogram, model, dates))
{
// the case where we are only dealing with one percentile so we can reduce dimensionality of output argument
if (options->num_percentiles == 1)
for (i = 0; i < options->horizon; i++)
for (j = 0; j < nvars; j++)
out_buf[(i) + (j)*options->horizon] = ElementM(forecast, i, j);
else
for (i = 0; i < options->horizon; i++)
for (j = 0; j < nvars; j++)
out_buf[(k) + ((i) + (j)*options->horizon)*options->num_percentiles] = ElementM(forecast, i, j);
mxFree(forecast);
}
mxFree(histogram);
}
}
else
{
printf("Constructing percentiles for forecasts - %d draws of shocks/regimes per posterior value\n", options->shocks);
if (histogram = forecast_percentile(options->shocks, options->simulation_file, options->thin, T, options->horizon, model, type))
{
for (k = 0; k < options->num_percentiles; k++)
if (forecast = ForecastHistogramToPercentile((TMatrix) NULL, options->number_observations, options->horizon, T, options->percentiles[k], histogram, model, dates))
{
// the case where we are only dealing with one percentile so we can reduce dimensionality of output argument
if (options->num_percentiles == 1)
for (i = 0; i < options->horizon; i++)
for (j = 0; j < nvars; j++)
out_buf[(i) + (j)*options->horizon] = ElementM(forecast, i, j);
else
for (i = 0; i < options->horizon; i++)
for (j = 0; j < nvars; j++)
out_buf[(k) + ((i) + (j)*options->horizon)*options->num_percentiles] = ElementM(forecast, i, j);
mxFree(forecast);
}
}
mxFree(histogram);
}
}
catch (const char *s)
{
DYN_MEX_FUNC_ERR_MSG_TXT("Exception Thrown in Forecast: \n");
}
mxFree(p);
mxFree(model);
}
#endif

View File

@ -0,0 +1,194 @@
/*
* Copyright (C) 2011 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE)
#include "dynmex.h"
#include "mex_ms_sbvar.h"
extern "C" {
#include "modify_for_mex.h"
#include "switch.h"
#include "switchio.h"
#include "VARio.h"
#include "dw_rand.h"
#include "dw_histogram.h"
#include "sbvar_impulse_responses.h"
}
void
mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
char *input_buf;
double *out_buf;
int i, j, k, s, nfree, nstates, nvars, npre;
TStateModel *model;
SbvarOption *options = (SbvarOption *) NULL;
T_VAR_Parameters *p = (T_VAR_Parameters *) NULL;
TMatrixHistogram *histogram = (TMatrixHistogram *) NULL;
TMatrix ir;
int type = F_FREE, ergodic = 1;
// Check the left hand and right hand side arguments to make sure they conform
if (mxIsChar(prhs[0]) != 1)
DYN_MEX_FUNC_ERR_MSG_TXT("First argument has to be a string to the init_filename.");
if (nlhs != 1)
DYN_MEX_FUNC_ERR_MSG_TXT("You must specify one output argument");
// copy the string data from prhs[0] into a C string input_ buf. */
input_buf = mxArrayToString(prhs[0]);
if (input_buf == NULL)
DYN_MEX_FUNC_ERR_MSG_TXT("Could not convert input to string.");
model = initialize_model_and_options(input_buf, &options, nrhs, prhs, &nstates, &nvars, &npre, &nfree);
if (model == NULL || options == NULL)
DYN_MEX_FUNC_ERR_MSG_TXT("There was a problem initializing the model, can not continue");
p = (T_VAR_Parameters *) (model->theta);
// Check to make sure that there is a simulation file present if we are
// using parameter uncertainty
if (options->parameter_uncertainty && options->simulation_file == NULL)
DYN_MEX_FUNC_ERR_MSG_TXT("Paramter Uncertainty Was Specified but the simulation file was not found, please specify the simulation file to use with: 'simulation_file',<filename>");
if (!options->parameter_uncertainty)
options->simulation_file = (FILE *) NULL;
// Allocate the output matrix
if (options->regimes)
if (options->num_percentiles > 1)
{
// regimes x percentile x horizon x (nvar*nvar)
mwSize dims[4] = {nstates, options->num_percentiles, options->horizon, (nvars*nvars)};
plhs[0] = mxCreateNumericArray(4, dims, mxDOUBLE_CLASS, mxREAL);
out_buf = mxGetPr(plhs[0]);
}
else
{
// regimes x horizon x (nvar*nvar)
mwSize dims[3] = {nstates, options->horizon, (nvars*nvars)};
plhs[0] = mxCreateNumericArray(3, dims, mxDOUBLE_CLASS, mxREAL);
out_buf = mxGetPr(plhs[0]);
}
else
if (options->num_percentiles > 1)
{
// percentile x horizon x (nvar*nvar)
mwSize dims[3] = {options->num_percentiles, options->horizon, (nvars*nvars)};
plhs[0] = mxCreateNumericArray(3, dims, mxDOUBLE_CLASS, mxREAL);
out_buf = mxGetPr(plhs[0]);
}
else
{
// horizon x (nvar*nvar)
mwSize dims[2] = {options->horizon, (nvars*nvars)};
plhs[0] = mxCreateNumericArray(2, dims, mxDOUBLE_CLASS, mxREAL);
out_buf = mxGetPr(plhs[0]);
}
// Use filter probabilities?
if (options->filtered_probabilities)
ergodic = 0;
try
{
if (options->regimes)
for (s = 0; s < nstates; s++)
{
printf("Constructing percentiles for impulse responses - regime %d\n", s);
if (histogram = impulse_response_percentile_regime(options->simulation_file, options->thin, s, options->horizon, model, type))
{
for (k = 0; k < options->num_percentiles; k++)
if (ir = IRHistogramToPercentile((TMatrix) NULL, options->horizon, options->percentiles[k], histogram, model))
{
// the case where we are only dealing with one percentile so we can reduce dimensionality of output argument
if (options->num_percentiles == 1)
for (i = 0; i < options->horizon; i++)
for (j = 0; j < (nvars*nvars); j++)
out_buf[(s) + ((i) + (j)*options->horizon)*nstates] = ElementM(ir, i, j);
else
for (i = 0; i < options->horizon; i++)
for (j = 0; j < (nvars*nvars); j++)
out_buf[(s) + ((k) + ((i) + (j)*options->horizon)*options->num_percentiles)*nstates] = ElementM(ir, i, j);
mxFree(ir);
}
}
mxFree(histogram);
}
else if (options->regime >= 0)
{
s = options->regime;
printf("Constructing percentiles for impulse responses - regime %d\n", s);
if (histogram = impulse_response_percentile_regime(options->simulation_file, options->thin, options->regime, options->horizon, model, type))
{
for (k = 0; k < options->num_percentiles; k++)
if (ir = IRHistogramToPercentile((TMatrix) NULL, options->horizon, options->percentiles[k], histogram, model))
{
// the case where we are only dealing with one percentile so we can reduce dimensionality of output argument
if (options->num_percentiles == 1)
for (i = 0; i < options->horizon; i++)
for (j = 0; j < (nvars*nvars); j++)
out_buf[(i) + (j)*options->horizon] = ElementM(ir, i, j);
else
for (i = 0; i < options->horizon; i++)
for (j = 0; j < (nvars*nvars); j++)
out_buf[(k) + ((i) + (j)*options->horizon)*options->num_percentiles] = ElementM(ir, i, j);
mxFree(ir);
}
}
mxFree(histogram);
}
else
{
printf(ergodic ? "Constructing percentiles for ergodic impulse responses - %d draws of regimes per posterior value\n"
: "Constructing percentiles for filtered impulse responses - %d draws of regimes per posterior value\n", options->shocks);
if (histogram = impulse_response_percentile_ergodic(options->shocks, options->simulation_file, options->thin, ergodic, options->horizon, model, type))
{
for (k = 0; k < options->num_percentiles; k++)
if (ir = IRHistogramToPercentile((TMatrix) NULL, options->horizon, options->percentiles[k], histogram, model))
{
// the case where we are only dealing with one percentile so we can reduce dimensionality of output argument
if (options->num_percentiles == 1)
for (i = 0; i < options->horizon; i++)
for (j = 0; j < (nvars*nvars); j++)
out_buf[(i) + (j)*options->horizon] = ElementM(ir, i, j);
else
for (i = 0; i < options->horizon; i++)
for (j = 0; j < (nvars*nvars); j++)
out_buf[(k) + ((i) + (j)*options->horizon)*options->num_percentiles] = ElementM(ir, i, j);
mxFree(ir);
}
}
mxFree(histogram);
}
}
catch (const char *s)
{
DYN_MEX_FUNC_ERR_MSG_TXT("Exception Thrown in IRF: \n");
}
mxFree(model);
mxFree(p);
}
#endif

View File

@ -0,0 +1,653 @@
/*
* Copyright (C) 2011 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE)
#include "dynmex.h"
#include "mex_ms_sbvar.h"
#include <iostream>
#include <fstream>
extern "C" {
#include "modify_for_mex.h"
#include "switch.h"
#include "switchio.h"
#include "VARio.h"
#include "dw_rand.h"
}
using namespace std;
int
file_exist(char *filename)
{
int ret = 0;
char ch;
ifstream fin;
fin.open(filename, ios_base::in);
if (fin.is_open() && fin.get(ch))
ret = 1;
fin.close();
return ret;
}
char *
CreateFilenameFromTag(const char *fmt, const char *tag, const char *dir)
{
char *filename;
if (!tag)
tag = "";
if (!dir)
dir = "";
sprintf(filename = (char *) mxMalloc(strlen(dir) + strlen(fmt) + strlen(tag) - 3), fmt, dir, tag);
return filename;
}
/*
* initialize_ms_model
* - initiliazes a TstateModel given the filename or tagname of initialization file
*/
TStateModel *
initialize_ms_model(char *name)
{
TStateModel *model = (TStateModel *) NULL;
char *filename = (char *) NULL, *est_filename = (char *) NULL, *init_filename = (char *) NULL;
est_filename = CreateFilenameFromTag("%sest_final_%s.out", name, "");
init_filename = CreateFilenameFromTag("%sinit_%s.dat", name, "");
if (file_exist(name))
filename = name;
else if (file_exist(est_filename))
filename = est_filename;
else if (file_exist(init_filename))
filename = init_filename;
else
{
printf("Can not open initialization or estimation file!\n");
return (TStateModel *) NULL;
}
try
{
if (!(model = Read_VAR_Specification((FILE *) NULL, filename)))
{
mxFree(filename);
printf("Can not initialize model with given name!\n");
return (TStateModel *) NULL;
}
if (est_filename != NULL)
{
if (!strstr(est_filename, filename))
{
printf("Initializing with empty parameters %s\n", filename);
// If no estimation file is around then just initialize the sizes
double *theta = (double *) mxMalloc(sizeof(double)*NumberFreeParametersTheta(model));
double *q = (double *) mxMalloc(sizeof(double)*NumberFreeParametersQ(model));
ConvertFreeParametersToQ(model, q);
ConvertFreeParametersToTheta(model, theta);
}
}
}
catch (const char *s)
{
printf("Error Initializing TStateModel: %s\n", s);
model = (TStateModel *) NULL;
}
mxFree(filename);
return model;
}
int
get_var_dimensions(TStateModel *model, int *nstates, int *nvars, int *npre, int *nfree)
{
if (model)
{
try
{
*nfree = NumberFreeParametersTheta(model)+NumberFreeParametersQ(model);
T_VAR_Parameters *p = (T_VAR_Parameters *) (model->theta);
*nstates = model->sv->nstates;
*nvars = p->nvars;
*npre = p->npre;
return 0;
}
catch (const char *s)
{
printf("Error Getting VAR Dimensions");
return 1;
}
}
else
{
printf("The model passed was null!\n");
return 1;
}
}
int
set_parameters_in_VAR(TStateModel *model, double *free_parameters)
{
int nfree;
try
{
nfree = NumberFreeParametersTheta(model)+NumberFreeParametersQ(model);
ConvertFreeParametersToQ(model, free_parameters+NumberFreeParametersTheta(model));
ConvertFreeParametersToTheta(model, free_parameters);
ComputeTransitionMatrix(0, model);
}
catch (const char *s)
{
return 1;
}
return 0;
}
int
convert_free_parameters_to_VAR(TStateModel *model, double *free_parameters, double *A0, double *Aplus, double *Zeta, double *Q)
{
int nstates = 0, nvars = 0, npre = 0;
int i = 0, j = 0, s = 0;
if (model == NULL)
{
printf("The model passed was null in Convert Free Parameters!\n");
return 1;
}
if (set_parameters_in_VAR(model, free_parameters) > 0)
{
printf("Could not set Parameters in model when converting parameters to var\n");
return 2;
}
try
{
T_VAR_Parameters *p = (T_VAR_Parameters *) (model->theta);
nstates = model->sv->nstates;
nvars = p->nvars;
npre = p->npre;
TMatrix a = NULL, aplus = NULL;
a = CreateMatrix(p->nvars, p->nvars);
aplus = CreateMatrix(p->npre, p->nvars);
// Is this is a good idea in matlab?
if (A0 == NULL)
A0 = new double [nstates*nvars*nvars];
//A0 = malloc(sizeof(double)*(nstates*nvars*nvars));
if (Aplus == NULL)
Aplus = new double [nstates*npre*nvars];
//Aplus = malloc(sizeof(double)*(nstates*npre*nvars));
if (Zeta == NULL)
Zeta = new double [nstates*nvars*nvars];
//Zeta = malloc(sizeof(double)*(nstates*nvars*nvars));
if (Q == NULL)
Q = new double [nstates*nstates];
//Q = malloc(sizeof(double)*(nstates*nstates));
for (s = 0; s < nstates; s++)
{
MakeA0(a, s, p);
for (i = 0; i < nvars; i++)
{
for (j = 0; j < nvars; j++)
A0[(s)+((i+j*nvars)*nstates)] = ElementM(a, i, j);
}
MakeAplus(aplus, s, p);
for (i = 0; i < npre; i++)
{
for (j = 0; j < nvars; j++)
Aplus[(s)+((i+j*npre)*nstates)] = ElementM(aplus, i, j);
}
MakeZeta(a, s, p);
for (i = 0; i < nvars; i++)
{
for (j = 0; j < nvars; j++)
Zeta[(s)+((i+j*nvars)*nstates)] = ElementM(a, i, j);
}
}
// Grand Transition Matrix
for (i = 0; i < nstates; i++)
for (j = 0; j < nstates; j++)
Q[i + j*nstates] = ElementM(model->sv->Q, i, j);
FreeMatrix(a);
FreeMatrix(aplus);
}
catch (const char *s)
{
printf("Exception: convert_free_parameters\n");
return 3;
}
return 0;
}
/*
Additional command line parameters
'horizon', <integer>
If this argument exists, then the forecast horizon is given by the passed
integer. The default value is 12.
'filtered'
Uses filtered probabilities at the end of the sample as initial conditions
for regime probabilities. The default behavior is to us the erogdic
distribution for the initial conditions. This flag only applies if neither
-regimes nor -regime is specified.
'error_bands'
Output error bands. (default = off - only median is computed)
'percentiles' n p_1 p_2 ... p_n
Percentiles to compute. The first parameter after percentiles must be the
number of percentiles and the following values are the actual percentiles.
default = 3 0.16 0.50 0.84 if error_bands flag is set
= 1 0.50 otherwise
'parameter_uncertainty'
Apply parameter uncertainty when computing error bands or median. When set,
will default shocks = 1
'shocks' or 'shocks_per_parameter', <integer>
Number of regime paths to draw for each parameter draw. The default value
is 1 if parameter_uncertainty is set and 10,000 otherwise.
'thin'
Thinning factor. Only 1/thin of the draws in posterior draws file are
used. The default value is 1.
'regimes'
Produces forecasts as if each regime were permanent. (default = off)
'regime' <integer>
Produces forecasts as if regime were permanent. Regime numbers are zero
based. (default = off)
'simulation_file', <string>
name of the file containing the model's simulated free values
'number_observations', <integer>
If this argument exists, then the number of data points included in the
output is given by the passed integer int the forecast output. The default value is 0.
'free_parameters' <vector>:
Vector of free paramters to initialize the model with.
'median':
Shortcut for setting 'percentiles',[0.5]
'mean':
Compute the mean, instead of percentiles
'seed':
Set the Seed for random number generation, default=0 (random)
*/
SbvarOption *
initialize_sbvar_options(char *file_tag)
{
SbvarOption *options = new SbvarOption;
options->shocks = 10000;
options->thin = 1;
options->horizon = 20;
options->number_observations = 0;
options->regime = -1;
options->regimes = false;
options->parameter_uncertainty = false;
options->num_percentiles = 3;
options->percentiles = new double[3];
options->percentiles[0] = 0.16;
options->percentiles[1] = 0.5;
options->percentiles[2] = 0.84;
options->filtered_probabilities = false;
options->num_parameters = -1;
options->free_parameters = (double *) NULL;
options->mean = false;
options->seed = 0;
if (file_tag != NULL)
{
options->simulation_filename = (char *) CreateFilenameFromTag("%ssimulation_%s.out", file_tag, "");
if (file_exist(options->simulation_filename))
options->simulation_file = fopen(options->simulation_filename, "r");
}
else
{
options->simulation_filename = (char *) NULL;
options->simulation_file = (FILE *) NULL;
}
return options;
}
int
set_options(SbvarOption *options, int nrhs, const mxArray *prhs[])
{
if (options == NULL)
options = initialize_sbvar_options((char *) NULL);
int i, buf_len, buf_len2;
char *input_buf = NULL;
double *temp_buf;
bool shocks_passed = false;
/* deal with optional arguments */
for (i = 0; i < nrhs; i++)
{
if (mxIsChar(prhs[i]) == 1)
{
buf_len = mxGetN(prhs[i])*sizeof(mxChar)+1;
input_buf = (char *) mxMalloc(buf_len);
mxGetString(prhs[i], input_buf, buf_len);
if (strstr(input_buf, "horizon"))
{
if (nrhs >= i+1 && mxIsNumeric(prhs[i+1]))
{
temp_buf = (double *) mxGetData(prhs[i+1]);
options->horizon = (int) temp_buf[0];
}
else
{
printf("The you must pass an integer after specifying the 'horizon' option");
return 1;
}
}
else if (strstr(input_buf, "error_bands"))
{
mxFree(options->percentiles);
options->num_percentiles = 3;
options->percentiles = new double[3];
options->percentiles[0] = 0.16;
options->percentiles[1] = 0.5;
options->percentiles[2] = 0.84;
// Check if the specified to turn off error bands
if (nrhs > i+1)
if (mxIsNumeric(prhs[i+1]))
{
temp_buf = (double *) mxGetData(prhs[i+1]);
if (temp_buf[0] == 0)
{
options->num_percentiles = 1;
options->percentiles = new double[1];
options->percentiles[0] = 0.50;
}
}
}
else if (strstr(input_buf, "median"))
{
mxFree(options->percentiles);
options->num_percentiles = 1;
options->percentiles = new double[1];
options->percentiles[0] = 0.5;
}
else if (strstr(input_buf, "percentiles"))
{
if (nrhs >= i+1)
{
options->num_percentiles = mxGetN(prhs[i+1]) > mxGetM(prhs[i+1]) ? mxGetN(prhs[i+1]) : mxGetM(prhs[i+1]);
options->percentiles = mxGetPr(prhs[i+1]);
}
else
{
printf("You must pass a vector after the 'percentiles' argument with the percentiles that you want to have computed, ex 'percentiles',[.16 .5 .84]");
return 1;
}
}
else if (strstr(input_buf, "parameter_uncertainty"))
{
options->parameter_uncertainty = true;
if (shocks_passed == false)
options->shocks = 1;
}
else if (strstr(input_buf, "shocks") || strstr(input_buf, "shocks_per_parameter"))
{
if (nrhs >= i+1 && mxIsNumeric(prhs[i+1]))
{
temp_buf = (double *) mxGetData(prhs[i+1]);
options->shocks = (int) temp_buf[0];
shocks_passed = true;
}
else
{
printf("You must pass an integer after specifying the 'shocks' option");
return 1;
}
}
else if (strstr(input_buf, "thin"))
{
if (nrhs >= i+1 && mxIsNumeric(prhs[i+1]))
{
temp_buf = (double *) mxGetData(prhs[i+1]);
options->thin = (int) temp_buf[0];
}
else
{
printf("You must pass an integer after specifying the 'thin' option");
return 1;
}
}
else if (strstr(input_buf, "simulation_file"))
{
buf_len2 = mxGetN(prhs[i+1])*sizeof(mxChar)+1;
char *posterior_filename = (char *) mxMalloc(buf_len2);
mxGetString(prhs[i+1], posterior_filename, buf_len2);
strcpy(options->simulation_filename, posterior_filename);
if (!(options->simulation_file = fopen(posterior_filename, "rt")))
{
printf("The posterior simulation file does not exist");
return 1;
}
}
else if (strstr(input_buf, "regimes"))
{
options->regimes = true;
}
else if (strstr(input_buf, "regime"))
{
if (nrhs >= i+1 && mxIsNumeric(prhs[i+1]))
{
temp_buf = (double *) mxGetData(prhs[i+1]);
options->regime = (int) temp_buf[0];
}
else
{
printf("You must pass an integer after specifying the 'regime' option, or alternatively you can specify 'regimes'");
return 1;
}
}
else if (strstr(input_buf, "number_observations"))
{
if (nrhs >= i+1 && mxIsNumeric(prhs[i+1]))
{
temp_buf = (double *) mxGetData(prhs[i+1]);
options->number_observations = (int) temp_buf[0];
}
else
{
printf("You must pass an integer after specifying the 'regime' option, or alternatively you can specify 'regimes'");
return 1;
}
}
else if (strstr(input_buf, "free_parameters"))
{
if (nrhs >= i+1 && mxIsNumeric(prhs[i+1]))
{
options->num_parameters = mxGetM(prhs[i+1]);
options->free_parameters = mxGetPr(prhs[i+1]);
}
else
{
printf("You must pass a vector of free parameters after specifying 'free_parameters'");
return 1;
}
}
else if (strstr(input_buf, "mean"))
{
options->mean = true;
options->num_percentiles = 0;
options->percentiles = (double *) NULL;
}
else if (strstr(input_buf, "seed"))
{
if (nrhs >= i+1 && mxIsNumeric(prhs[i+1]))
{
temp_buf = (double *) mxGetData(prhs[i+1]);
options->seed = (long) temp_buf[0];
}
else
{
printf("You must pass an integer after specifying the 'seed' option");
return 1;
}
}
}
} // End Optional Arguments
return 0;
}
int
print_sbvar_options(SbvarOption *options)
{
using namespace std;
int i;
if (options == NULL)
return 1;
cout << "SBVAR OPTIONS" << endl;
cout << "Number of Shocks: " << options->shocks << endl;
cout << "Thinning Factor: " << options->thin << endl;
cout << "Horizon: " << options->horizon << endl;
cout << "Number of Observations to Show: " << options->number_observations << endl;
cout << "Regime: " << options->regime << endl;
cout << "Regimes: " << options->regimes << endl;
cout << "Number Free parameters: " << options->num_parameters << endl;
cout << "Parameter Uncertainty: " << options->parameter_uncertainty << endl;
cout << "Mean: " << options->mean << endl;
cout << "Number Percentiles: " << options->num_percentiles << endl;
cout << "Percentiles: ";
for (i = 0; i < options->num_percentiles; i++)
cout << options->percentiles[i] << " ";
cout << endl;
cout << "Filtered Probabilities: " << options->filtered_probabilities << endl;
cout << "Simulation Filename: " << options->simulation_filename << endl;
cout << "Random Number Seed: " << options->seed << endl;
return 0;
}
TStateModel *
initialize_model_and_options(char *name, SbvarOption **options, int nrhs, const mxArray *prhs[], int *nstates, int *nvars, int *npre, int *nfree)
{
using namespace std;
TStateModel *model = (TStateModel *) NULL;
int ret;
SbvarOption *opt;
// Initialize the StateSpace Model with the initialization file
model = initialize_ms_model(name);
if (model == NULL)
{
cout << "Could not initialize State Space Switching model with the given tag." << endl;
return (TStateModel *) NULL;
}
if (get_var_dimensions(model, nstates, nvars, npre, nfree) > 0)
{
cout << "Problems Determining the size of the Initialized model." << endl;
return (TStateModel *) NULL;
}
// Process the rest of the options
opt = initialize_sbvar_options(name);
if (set_options(opt, nrhs, prhs) > 0)
{
cout << "There was a problem with the options passed." << endl;
return (TStateModel *) NULL;
}
// Set seed value
try
{
dw_initialize_generator(opt->seed);
}
catch (const char *s)
{
cout << "Exception: " << s << endl;
cout << "Exception thrown initializing Random Seed." << endl;
return (TStateModel *) NULL;
}
// If free parameters have been passed, then set them in the model
if (opt->num_parameters > 0)
{
if (opt->num_parameters == *nfree + 2)
{
opt->free_parameters = opt->free_parameters+2;
opt->num_parameters = opt->num_parameters - 2;
}
if (opt->num_parameters != *nfree)
{
cout << "The Free Parameter vector passed is the wrong size for the given model" << endl;
return (TStateModel *) NULL;
}
// Set the paramters as the current 'theta'
if (set_parameters_in_VAR(model, opt->free_parameters) > 0)
{
cout << "Problem with the free parameters that were passed being set in MS-SBVAR Model." << endl;
return (TStateModel *) NULL;
}
}
*options = opt;
return model;
}
#endif

View File

@ -0,0 +1,73 @@
/*
* Copyright (C) 2011 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _MEXMSSBVAR_H_
#define _MEXMSSBVAR_H_
#if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE)
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern "C" {
#include "modify_for_mex.h"
#include "switch.h"
#include "switchio.h"
#include "VARio.h"
}
typedef struct sbvar_options_t {
int shocks;
int thin;
int horizon;
int number_observations;
int regime;
bool regimes;
bool parameter_uncertainty;
int num_percentiles;
double *percentiles;
bool filtered_probabilities;
char *simulation_filename;
int num_parameters;
double *free_parameters;
FILE *simulation_file;
bool mean;
long seed;
} SbvarOption;
#define printf mexPrintf
int file_exist(char *filename);
char* CreateFilenameFromTag(const char *fmt,const char *tag,const char *dir);
SbvarOption * initialize_sbvar_options(char *file_tag);
int set_options(SbvarOption *options, int nrhs, const mxArray *prhs[]);
int print_sbvar_options(SbvarOption *options);
TStateModel * initialize_ms_model(char *filename);
int get_var_dimensions(TStateModel *model, int *nstates, int *nvars, int *npre, int *nfree);
int set_parameters_in_VAR(TStateModel *model, double *free_parameters);
int convert_free_parameters_to_VAR(TStateModel *model, double *free_parameters, double *A0, double *Aplus, double *Zeta, double *Q );
TStateModel * initialize_model_and_options(char *name,SbvarOption **options, int nrhs, const mxArray *prhs[], int *nstates, int *nvars, int *npre, int *nfree);
#endif
#endif

View File

@ -0,0 +1,248 @@
/*
* Copyright (C) 2011 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE)
#include "dynmex.h"
#include "mex_ms_sbvar.h"
extern "C" {
#include "switch.h"
#include "switchio.h"
#include "VARio.h"
#include "dw_rand.h"
#include "dw_histogram.h"
#include "sbvar_variance_decomposition.h"
}
void
mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
char *input_buf;
double *out_buf;
int i, j, k, s, nfree, nstates, nvars, npre;
TStateModel *model;
SbvarOption *options = (SbvarOption *) NULL;
T_VAR_Parameters *p = (T_VAR_Parameters *) NULL;
TMatrixHistogram *histogram = (TMatrixHistogram *) NULL;
TMatrix tvd;
int type = F_FREE, ergodic = 1;
/* Check the left hand and right hand side arguments to make sure they conform */
if (mxIsChar(prhs[0]) != 1)
DYN_MEX_FUNC_ERR_MSG_TXT("First argument has to be a string to the init_filename.");
if (nlhs != 1)
DYN_MEX_FUNC_ERR_MSG_TXT("You must specify one output argument");
// copy the string data from prhs[0] into a C string input_ buf. */
input_buf = mxArrayToString(prhs[0]);
if (input_buf == NULL)
DYN_MEX_FUNC_ERR_MSG_TXT("Could not convert input to string.");
model = initialize_model_and_options(input_buf, &options, nrhs, prhs, &nstates, &nvars, &npre, &nfree);
if (model == NULL || options == NULL)
DYN_MEX_FUNC_ERR_MSG_TXT("There was a problem initializing the model, can not continue");
p = (T_VAR_Parameters *) (model->theta);
/* Check to make sure that there is a simulation file present if we are
* using parameter uncertainty
*/
if (options->parameter_uncertainty && options->simulation_file == NULL)
DYN_MEX_FUNC_ERR_MSG_TXT("Paramter Uncertainty Was Specified but the simulation file was not found, please specify the simulation file to use with: 'simulation_file',<filename>");
if (!options->parameter_uncertainty)
options->simulation_file = (FILE *) NULL;
/* Allocate the output matrix */
if (options->regimes)
if (options->num_percentiles > 1)
{
/* regimes x percentile x horizon x (nvar*nvar) */
mwSize dims[4] = {nstates, options->num_percentiles, options->horizon, (nvars*nvars)};
plhs[0] = mxCreateNumericArray(4, dims, mxDOUBLE_CLASS, mxREAL);
out_buf = mxGetPr(plhs[0]);
}
else
{
/* regimes x horizon x (nvar*nvar) */
mwSize dims[3] = {nstates, options->horizon, (nvars*nvars)};
plhs[0] = mxCreateNumericArray(3, dims, mxDOUBLE_CLASS, mxREAL);
out_buf = mxGetPr(plhs[0]);
}
else
if (options->num_percentiles > 1)
{
/* percentile x horizon x (nvar*nvar) */
mwSize dims[3] = {options->num_percentiles, options->horizon, (nvars*nvars)};
plhs[0] = mxCreateNumericArray(3, dims, mxDOUBLE_CLASS, mxREAL);
out_buf = mxGetPr(plhs[0]);
}
else
{
/* horizon x (nvar*nvar) */
mwSize dims[2] = {options->horizon, (nvars*nvars)};
plhs[0] = mxCreateNumericArray(2, dims, mxDOUBLE_CLASS, mxREAL);
out_buf = mxGetPr(plhs[0]);
}
/* Use filter probabilities? */
if (options->filtered_probabilities)
ergodic = 0;
try
{
if (options->regimes)
{
for (s = 0; s < nstates; s++)
{
printf("Constructing variance decomposition - regime %d\n", s);
if (options->mean)
{
if (tvd = variance_decomposition_mean_regime(options->simulation_file, options->thin, s, options->horizon, model, type))
{
NormalizeVarianceDecomposition(tvd, p);
ReorderVarianceDecomposition(tvd, p);
for (i = 0; i < options->horizon; i++)
for (j = 0; j < (nvars*nvars); j++)
out_buf[(s) + ((i) + (j)*options->horizon)*nstates] = ElementM(tvd, i, j);
}
mxFree(tvd);
}
else
{
if (histogram = variance_decomposition_percentiles_regime(options->simulation_file, options->thin, s, options->horizon, model, type))
{
tvd = CreateMatrix(options->horizon, nvars*nvars);
for (k = 0; k < options->num_percentiles; k++)
{
MatrixPercentile(tvd, options->percentiles[k], histogram);
ReorderVarianceDecomposition(tvd, p);
if (options->num_percentiles == 1)
for (i = 0; i < options->horizon; i++)
for (j = 0; j < (nvars*nvars); j++)
out_buf[(s) + ((i) + (j)*options->horizon)*nstates] = ElementM(tvd, i, j);
else
for (i = 0; i < options->horizon; i++)
for (j = 0; j < (nvars*nvars); j++)
out_buf[(s) + ((k) + ((i) + (j)*options->horizon)*options->num_percentiles)*nstates] = ElementM(tvd, i, j);
}
mxFree(tvd);
}
mxFree(histogram);
}
}
}
else if (options->regime >= 0)
{
s = options->regime;
printf("Constructing variance decomposition - regime %d\n", s);
if (options->mean)
{
if (tvd = variance_decomposition_mean_regime(options->simulation_file, options->thin, s, options->horizon, model, type))
{
NormalizeVarianceDecomposition(tvd, p);
ReorderVarianceDecomposition(tvd, p);
for (i = 0; i < options->horizon; i++)
for (j = 0; j < (nvars*nvars); j++)
out_buf[(s) + ((i) + (j)*options->horizon)*nstates] = ElementM(tvd, i, j);
}
mxFree(tvd);
}
else
{
if (histogram = variance_decomposition_percentiles_regime(options->simulation_file, options->thin, s, options->horizon, model, type))
{
tvd = CreateMatrix(options->horizon, nvars*nvars);
for (k = 0; k < options->num_percentiles; k++)
{
MatrixPercentile(tvd, options->percentiles[k], histogram);
ReorderVarianceDecomposition(tvd, p);
if (options->num_percentiles == 1)
for (i = 0; i < options->horizon; i++)
for (j = 0; j < (nvars*nvars); j++)
out_buf[(i) + (j)*options->horizon] = ElementM(tvd, i, j);
else
for (i = 0; i < options->horizon; i++)
for (j = 0; j < (nvars*nvars); j++)
out_buf[(k) + ((i) + (j)*options->horizon)*options->num_percentiles] = ElementM(tvd, i, j);
}
mxFree(tvd);
}
mxFree(histogram);
}
}
else
{
printf("Constructing variance decomposition - %d draws of regimes per posterior value\n", options->shocks);
if (options->mean)
{
if (tvd = variance_decomposition_mean(options->shocks, options->simulation_file, options->thin, ergodic, options->horizon, model, type))
{
NormalizeVarianceDecomposition(tvd, p);
ReorderVarianceDecomposition(tvd, p);
for (i = 0; i < options->horizon; i++)
for (j = 0; j < (nvars*nvars); j++)
out_buf[(i) + (j)*options->horizon] = ElementM(tvd, i, j);
}
mxFree(tvd);
}
else
{
if (histogram = variance_decomposition_percentiles(options->shocks, options->simulation_file, options->thin, ergodic, options->horizon, model, type))
{
tvd = CreateMatrix(options->horizon, nvars*nvars);
for (k = 0; k < options->num_percentiles; k++)
{
MatrixPercentile(tvd, options->percentiles[k], histogram);
ReorderVarianceDecomposition(tvd, p);
if (options->num_percentiles == 1)
for (i = 0; i < options->horizon; i++)
for (j = 0; j < (nvars*nvars); j++)
out_buf[(i) + (j)*options->horizon] = ElementM(tvd, i, j);
else
for (i = 0; i < options->horizon; i++)
for (j = 0; j < (nvars*nvars); j++)
out_buf[(k) + ((i) + (j)*options->horizon)*options->num_percentiles] = ElementM(tvd, i, j);
}
mxFree(tvd);
}
mxFree(histogram);
}
}
}
catch (const char *s)
{
DYN_MEX_FUNC_ERR_MSG_TXT("Exception Thrown in Variance Decomposition: \n");
}
mxFree(p);
mxFree(model);
}
#endif

View File

@ -26,7 +26,6 @@
int main(int nargs, char **args);
/* MATLAB interface */
void
mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])

View File

@ -35,8 +35,8 @@
void msExit(int status);
extern int constant_seed;
/* Write Matlab Output */
mxArray *globalMatlabStruct;
/* Write Matlab Output
mxArray *globalMatlabStruct;*/
void mex_write_to_matlab_matfile(double *, int, int, const char *, const char *);
void mex_write_to_matlab_global_struct(double *, int, int, const char *);
mxArray *getMxArray(double *, int, int);