%get_dist.m 
%Evaluate the distance between the impulse responses implied by the SVAR and MXN models. This program is auxiliary to the program probe.m, which 
%use a Metropolis-Hastings Sampling method to estimate the parameters [PHIM PHIX PHIN PSSI] in the MXN model with tot and interest-rate spread shocks developed in the paper ``How Important Are Terms of Trade Shocks?,'' by Stephanie Schmitt-Grohé and Martín Uribe, forthcoming in the International Economic Review, 2017. The algorithm minimizes  the distance between the empirical and theoretical impulse responses (IRs) targeted  in the estimation.    The IRs  targeted are those associated with a terms-of-trade shock and the country spread shock  in the SVAR model with both shocks  studied in the aforementioned paper and the variables included are the trade balance, output, consumption,   investment and the real exchange rate. The output of probe.m is stored in the file probe.mat. The 38x4 matrix MXPAR contains the estimates of the 4 parameter values [PHIM  PHIX  PHIN  PSSI]  for each of the 38 countries in the panel. The 38x1 vector MXLL contains the minimum distance attained.  
%© Martín Uribe  October 2016.


function [dist,exitflag] = get_distance(x,P)
%parameters passed on
RHO = P{1}; 
STD = P{2};
IRtarget = P{3};
IRstd = P{4};
IRstarget = P{5};
IRsstd = P{6};

RHO_TOTTOT = RHO(1,1); %parameter of AR(1) coeff of (totms) process 
RHO_TOTS = RHO(1,2); %parameter of AR(1) coeff of (totms) process 
RHO_STOT = RHO(2,1); %parameter of AR(1) coeff of (totms) process 
RHO_SS = RHO(2,2); %parameter of AR(1) coeff of (totms) process 

STD_TOTTOT = STD(1,1); %parameter of AR(1) coeff of (totms) process 
STD_TOTS = STD(1,2); %parameter of AR(1) coeff of (totms) process 
STD_STOT = STD(2,1); %parameter of AR(1) coeff of (totms) process 
STD_SS = STD(2,2); %parameter of AR(1) coeff of (totms) process 

PHIM = x(1);
PHIX = x(2);
PHINT = x(3);
PSSI = x(4);

%AQUI COMIENZA
externallyset_parameters = 1;

mxns_ss
mxns_num_eval %this .m script was created by running mxns.m 
%in z:\uribe\tot\ier\mfiles\mxn_with_spread

if max(abs(nf(:)))>1e-5
    error('nf is not zero')
end

%The linearized equilibrium system is of the form
%y_t=gx x_t
%x_t+1 = hx x_t + ETASHOCK epsilon_t+1

[gx, hx, exitflag] = gx_hx(nfy, nfx, nfyp, nfxp);

nrer = nptau;

x0 = zeros(nstate,1);
x0(ntot) = 1;
x0(ns) = STD_STOT/STD_TOTTOT;

x0s = zeros(nstate,1);
x0s(ns) = 1;

T = size(IRtarget,1);
[~,IR] = ir(gx([ntby noutput_constant_prices nc_constant_prices nivv_constant_prices nrer],:),hx,x0,T);

[~,IRs] = ir(gx([ntby noutput_constant_prices nc_constant_prices nivv_constant_prices nrer],:),hx,x0s,T);

dist = -sum(abs( (IR(:)-IRtarget(:))./IRstd(:))) - sum(abs((IRs(:)-IRstarget(:))./IRsstd(:) ));