diff --git a/105/paper.pdf b/105/paper.pdf new file mode 100644 index 0000000000000000000000000000000000000000..e401f61fdb3c887196fb8391a1b8b2edc720870e --- /dev/null +++ b/105/paper.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f400ea5e7ad9695850fedeb786911509bc15785d2f93f9c5077b3a67df043325 +size 881387 diff --git a/105/replication_package/Financial balance sheets non consolidated SNA 2008/CentralBank_gov_bonds.csv b/105/replication_package/Financial balance sheets non consolidated SNA 2008/CentralBank_gov_bonds.csv new file mode 100644 index 0000000000000000000000000000000000000000..e8ae17c0fd12e611629efc582c69b5e3452cf4f7 --- /dev/null +++ b/105/replication_package/Financial balance sheets non consolidated SNA 2008/CentralBank_gov_bonds.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:847836042b8c20655ccefa8b019995882e1407948b594372a66b0056aadea271 +size 502130 diff --git a/105/replication_package/Financial balance sheets non consolidated SNA 2008/CentralBank_liabilities.csv b/105/replication_package/Financial balance sheets non consolidated SNA 2008/CentralBank_liabilities.csv new file mode 100644 index 0000000000000000000000000000000000000000..3631d5eff6aa7bccc389612eae25049109296fa2 --- /dev/null +++ b/105/replication_package/Financial balance sheets non consolidated SNA 2008/CentralBank_liabilities.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e64747220749fe3eae333298ff678591438ae19a9f08a1aa651c306bc9158853 +size 1153426 diff --git a/105/replication_package/Financial balance sheets non consolidated SNA 2008/Financial_Asset_Details.csv b/105/replication_package/Financial balance sheets non consolidated SNA 2008/Financial_Asset_Details.csv new file mode 100644 index 0000000000000000000000000000000000000000..d35969c349cca49ed4dbf41ccd6ee54473f17c13 --- /dev/null +++ b/105/replication_package/Financial balance sheets non consolidated SNA 2008/Financial_Asset_Details.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:447da03cd373c357bdca599308266247fbe3a3115951d965cb6679dcce8a2df5 +size 1092238 diff --git a/105/replication_package/Financial balance sheets non consolidated SNA 2008/Financial_Safe_Liabilities.csv b/105/replication_package/Financial balance sheets non consolidated SNA 2008/Financial_Safe_Liabilities.csv new file mode 100644 index 0000000000000000000000000000000000000000..22a9a163f482ba0d8c2f4133be94415e7bd6ae4d --- /dev/null +++ b/105/replication_package/Financial balance sheets non consolidated SNA 2008/Financial_Safe_Liabilities.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8df4d6cfbfc9415b11754089a1e9a6278d0da1dbeb76ab85e09e8ddfda1572ac +size 1996412 diff --git a/105/replication_package/Financial balance sheets non consolidated SNA 2008/Government_Safe_Liabilities.csv b/105/replication_package/Financial balance sheets non consolidated SNA 2008/Government_Safe_Liabilities.csv new file mode 100644 index 0000000000000000000000000000000000000000..5453acb268ea1dc5018729939317a237e3bd5d70 --- /dev/null +++ b/105/replication_package/Financial balance sheets non consolidated SNA 2008/Government_Safe_Liabilities.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f230d212c89375d7252466681a17d53e570673cd976d3e36dfc755d65ff4c431 +size 1268435 diff --git a/105/replication_package/Financial balance sheets non consolidated SNA 2008/Total liabilities.csv b/105/replication_package/Financial balance sheets non consolidated SNA 2008/Total liabilities.csv new file mode 100644 index 0000000000000000000000000000000000000000..efda2e45f0e49301d3ca4552d7b7b6781413bc96 --- /dev/null +++ b/105/replication_package/Financial balance sheets non consolidated SNA 2008/Total liabilities.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea484dee1a87689447c1987f5b337acc86f23a02197c833105c8aa49ffe96393 +size 6614345 diff --git a/105/replication_package/GDP/GDP_current_prices.csv b/105/replication_package/GDP/GDP_current_prices.csv new file mode 100644 index 0000000000000000000000000000000000000000..541f2a9315aecd4906e18c1e6fdc4ee3768ef343 --- /dev/null +++ b/105/replication_package/GDP/GDP_current_prices.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cea81d95092d1b07bfa92d0b08aa4c802192558d27c10848f3fc24b9cc9ae6d1 +size 803870 diff --git a/105/replication_package/GENERAL_IES/Parameters.m b/105/replication_package/GENERAL_IES/Parameters.m new file mode 100644 index 0000000000000000000000000000000000000000..2401d108ca2adf43131d06491d8a9e75c30875e9 --- /dev/null +++ b/105/replication_package/GENERAL_IES/Parameters.m @@ -0,0 +1,22 @@ +period_length = 0.25; + +P = 1 - exp(-.04*period_length); % disaster probability + +B = -log(1 - .32); % disaster size + +meanB = B; + +G = 0.025*period_length; % drift of log output + +RHO = 0.04*period_length; % time preference rate + +NU = 0.02*period_length; % replacement rate + +MU = 0.05; % popoulation share of agent 1 + +ALPHA = 1/3; % capital share in output + +TAU = 0; % bond duration - short-term bonds + +GAMMA1 = 1.000001; % start with unit risk aversion +GAMMA2 = GAMMA1; diff --git a/105/replication_package/GENERAL_IES/Table_6_theta_half.m b/105/replication_package/GENERAL_IES/Table_6_theta_half.m new file mode 100644 index 0000000000000000000000000000000000000000..3eac695ce6bbfbff332d4b5030303c01082946f6 --- /dev/null +++ b/105/replication_package/GENERAL_IES/Table_6_theta_half.m @@ -0,0 +1,100 @@ +% THETA = 0.5 + +load('model') +addpath('files') + +Parameters; +THETA = 0.9999; % start with THETA close to 1, for which we have a good initial guess + +% make the vector of parameters +params = eval(symparams); + +% distribution of hatyp +nodes = exp([G,G-B]); % hatyp +weights = [1-P,P]; % corresponding probabilities + +T = 2000/period_length; % simulate 2000 years + +% disaster shock +rng('default') +disaster = double(rand(1,T+1)testF && solve==1 + t + [coeffs,model] = tpsolve(coeffs,xt,model,params,c0,nodes,weights,tolX,tolF,maxiter,OPTIONS); % solve + + % evaluate the new solution + [R,g,nPhi] = residual(coeffs,xt,params,c0,nodes,weights); + end + + newxt = nPhi(:,1); % assume no realized disasters + + if t>burn+10 % after 10 periods start checking for convergence + if max(abs(newxt-xt))<1e-7 + [coeffs] = tpsolve(coeffs,xt,model,params,c0,nodes,weights,tolX,tolF,maxiter,OPTIONS); + [R,g,nPhi] = residual(coeffs,xt,params,c0,nodes,weights); + + newxt = nPhi(:,1); + if max(abs(newxt-xt))<1e-7 + stop = 1; + state0 = xt; % solution point + coeffs0 = coeffs; + end + end + end + xt = newxt; +end + diff --git a/105/replication_package/GENERAL_IES/define_model.m b/105/replication_package/GENERAL_IES/define_model.m new file mode 100644 index 0000000000000000000000000000000000000000..373d5a4c67adf5015676a60f6da144740a905e3d --- /dev/null +++ b/105/replication_package/GENERAL_IES/define_model.m @@ -0,0 +1,152 @@ +%------------------------------------------------------------------------- +% The model: Safe Assets - the case of general IES (THETA not equal 1) +% +% This file defines the model (see Appendix for the full derivation). +% Bonds are perfectly safe short-term assets. +% +% Variables are denoted by small letters and +% parameters by capital letters. Future values are denoted by suffix p. +%------------------------------------------------------------------------- + +clear,clc + +%% Symbolic variables + +syms RHO GAMMA1 GAMMA2 NU MU THETA real +syms f1 f2 f1p f2p x1 x2 x1p x2p real +syms logq logqp tilp tilpp real +syms state1 state1p state2 state2p hatyp k1 tilb1 real +syms tila1 tila2 invtila1 invtila2 invtilp rbp rep c1 c2 c1p c2p q qp real +syms invc1 invc1p invc2 invc2p invf1 invf2 r1p r2p u1p_power u2p_power u1p u2p logf1 logf1p logf2 logf2p real +syms term1p term2p invr1p invr2p real + +%% Parameters + +symparams = [RHO,GAMMA1,GAMMA2,NU,MU,THETA]; + +%% State variables + +state = [state1,state2]; % current period +statep = [state1p,state2p]; % future period + +%% Control variables + +control = [f1,f2,x1,x2,logq,tilp]; % current period +controlp = [f1p,f2p,x1p,x2p,logqp,tilpp]; % future period + +%% shocks + +shocks = hatyp; + +%% auxiliary variables + +logc1p = log(c1p); +logc2p = log(c2p); + +invf1_ = 1/f1; +invf2_ = 1/f2; + +logf1p_ = log(f1p); +logf2p_ = log(f2p); + +invr1p_ = 1/r1p; +invr2p_ = 1/r2p; + +q_ = exp(logq); +qp_ = exp(logqp); + +invtila1_ = 1/tila1; +invtila2_ = 1/tila2; + +rep_ = (1 + tilpp)/tilp*hatyp; % return on equity +rbp_ = 1/q; % return on bond + +%% MODEL CONDITIONS + +invc1_ = 1 + 1/RHO*f1^(1 - THETA); + +c1_ = 1/invc1; + +invc1p_ = 1 + 1/RHO*f1p^(1 - THETA); + +c1p_ = 1/invc1p; + +invc2_ = 1 + 1/RHO*f2^(1-THETA); + +c2_ = 1/invc2; + +invc2p_ = 1 + 1/RHO*f2p^(1 - THETA); + +c2p_ = 1/invc2p; + +tila1_ = (1 + tilp)*state1 + state2; + +tila2_ = tilp + 1 - tila1; + +k1_ = x1*(1 - c1)*tila1/tilp; + +eq0 = -(1 - k1) + x2*(1 - c2)*tila2/tilp; + +tilb1_ = (1 - x1)*(1 - c1)*tila1; + +eq1 = tilb1*invtila2 + (1 - x2)*(1 - c2); + +r1p_ = x1*rep + (1 - x1)*rbp; + +r2p_ = x2*rep + (1 - x2)*rbp; + +term1p_ = ((invc1 - 1)*r1p*invf1)^(1 - GAMMA1)*((1 - NU*(1 - MU))*u1p^(1 - GAMMA1)... + + NU*(1 - MU)*u2p^(1 - GAMMA1)); + +term2p_ = ((invc2 - 1)*r2p*invf2)^(1 - GAMMA2)*((1 - NU*MU)*u2p^(1 - GAMMA2)... + + NU*MU*u1p^(1 - GAMMA2)); + +eq2 = -1 + term1p; + +eq3 = -1 + term2p; + +u1p_power_ = RHO/(1 + RHO)*c1p^(1 - THETA) + 1/(1 + RHO)*c1p^(1 - THETA)*f1p^(1 - THETA); + +u2p_power_ = RHO/(1 + RHO)*c2p^(1 - THETA) + 1/(1 + RHO)*c2p^(1 - THETA)*f2p^(1 - THETA); + +u1p_ = u1p_power^(1/(1 - THETA)); + +u2p_ = u2p_power^(1/(1 - THETA)); + +eq4 = (rep - rbp)*term1p*invr1p; + +eq5 = (rep - rbp)*term2p*invr2p; + +%% Function f (Ef = 0 imposes model conditions) + +f_fun = [eq0;eq1;eq2;eq3;eq4;eq5]; + +%% law of motion of state variables + +Phi_fun = [k1 - NU*(k1 - MU); % law of motion of state1p + (1 - NU)*tilb1/(hatyp*q)]; % law of motion of state2p + +%% collect auxiliary variables and functions + +allvars=who; +auxfuns=[]; +auxvars=[]; +for i=1:length(allvars) + if strcmp(allvars{i}(end),'_') + eval(['tempfun=' allvars{i} ';']) + eval(['tempvar=' allvars{i}(1:end-1) ';']) + auxfuns=[auxfuns;tempfun]; + auxvars=[auxvars;tempvar]; + end +end + +%% Approximation order (<=4) + +order = 4; + +%% Preprocess model and save + +model = prepare_tp(f_fun,Phi_fun,controlp,control,statep,state,shocks,symparams,order,auxfuns,auxvars); + +save('model') + diff --git a/105/replication_package/GENERAL_IES/make_Table_6_part_1.m b/105/replication_package/GENERAL_IES/make_Table_6_part_1.m new file mode 100644 index 0000000000000000000000000000000000000000..cc7e22aa1220500f4d7f486f4afc69a0b3dc752e --- /dev/null +++ b/105/replication_package/GENERAL_IES/make_Table_6_part_1.m @@ -0,0 +1,44 @@ +Table_6_theta_half; +Table_6_theta_two; + +%% Display Table 6 (part 1) +clc +homefolder = pwd; +cd .. + +diary on + +disp('********** Table 6 **********') + +load([homefolder '\Table_6_theta_half']) + +Table_6 = [round(Table(:,[1,2,4,5]),3),Table_vol,round(Table_labor(:,[3,4,5]),3),round(Table_labor(:,[6]),2)]; + +disp('THETA = 0.5') +disp(Table_6(3,:)) + +load([homefolder '\Table_6_theta_two']) + +Table_6 = [round(Table(:,[1,2,4,5]),3),Table_vol,round(Table_labor(:,[3,4,5]),3),round(Table_labor(:,[6]),2)]; + +disp('THETA = 2') +disp(Table_6(3,:)) + +%% Accuracy Measures +disp('Appendix Table 2: Accuracy Measures for Table 6') + +load([homefolder '\Table_6_theta_half']) +Accuarcy = [round(Table(:,1),3),round(log10(Table(:,end-1:end)),1)]; + +disp('THETA = 0.5') +disp(Accuarcy(3,2:end)) + +load([homefolder '\Table_6_theta_two']) +Accuarcy = [round(Table(:,1),3),round(log10(Table(:,end-1:end)),1)]; + +disp('THETA = 2') +disp(Accuarcy(3,2:end)) + +diary off + +cd(homefolder) \ No newline at end of file diff --git a/105/replication_package/GENERAL_IES/simulate_with_disasters.m b/105/replication_package/GENERAL_IES/simulate_with_disasters.m new file mode 100644 index 0000000000000000000000000000000000000000..f424aa4e4f620e4434e7f1622854becd925284a0 --- /dev/null +++ b/105/replication_package/GENERAL_IES/simulate_with_disasters.m @@ -0,0 +1,19 @@ +% Simulate with disasters +y_results = zeros(model.n_y,T+1); +x_results = zeros(model.n_x,T+1); +R_results = zeros(model.n_f,T+1); + +x_results(:,1) = state0; + +for t = 1:T +t + xt = x_results(:,t); + + [R,g,nPhi] = residual(coeffs,xt,params,c0,nodes,weights); + + % store results + R_results(:,t) = R; + y_results(:,t) = g; + + x_results(:,t+1) = nPhi(:,disaster(t+1)); +end \ No newline at end of file diff --git a/105/replication_package/GENERAL_IES/solve_and_simulate.m b/105/replication_package/GENERAL_IES/solve_and_simulate.m new file mode 100644 index 0000000000000000000000000000000000000000..c70927c73a0c797bd5b4684b38fc5e079a8ce3f3 --- /dev/null +++ b/105/replication_package/GENERAL_IES/solve_and_simulate.m @@ -0,0 +1,84 @@ +% This file performs the following: +% 1. Solve the model by Taylor projection at the initial state. +% 2. Simulate the model without realized disasters. + +%% make initial guess for a deterministic version of the model + +% in a deterministic economy, the following variables are constant: + +x1 = 1; % agents invests only in equity +x2 = 1; +tilp = 1/RHO; % price/earning ratio +hatyp = exp(G-meanB*P); % average growth +haty = hatyp; +rep = (1+tilp)/tilp*hatyp; % asset return +logq = log(1/rep); % price of bond +c1 = RHO/(1+RHO); % consumption/wealth ratio +c2 = c1; +logu1 = (RHO*log(c1)+log(1-c1)+log(rep))/RHO; +u1 = exp(logu1); +logu2 = (RHO*log(c2)+log(1-c2)+log(rep))/RHO; +u2 = exp(logu2); +f1 = (rep*u1); +f2 = (rep*u2); + +k1 = MU; + +tila1 = k1*(1+tilp); + +state0 = [k1;0]; +c0 = state0; + +derivs0 = [f1;f2;x1;x2;logq;tilp]; + +derivs1 = zeros(model.n_f,model.n_x); +derivs2 = zeros(model.n_f,model.n_x^2); +derivs3 = zeros(model.n_f,model.n_x^3); +derivs4 = zeros(model.n_f,model.n_x^4); + +if order==1 + [ initial_guess ] = derivs2coeffs( model,derivs0,derivs1 ); +elseif order==2 + [ initial_guess ] = derivs2coeffs( model,derivs0,derivs1,derivs2); +elseif order==3 + [ initial_guess ] = derivs2coeffs( model,derivs0,derivs1,derivs2,derivs3 ); +elseif order==4 + [ initial_guess ] = derivs2coeffs( model,derivs0,derivs1,derivs2,derivs3,derivs4 ); +end + +%% solve the model + +[coeffs,model] = tpsolve(initial_guess,state0,model,params,c0,nodes,weights,tolX,tolF,maxiter,OPTIONS); + +%% simulate the model + +solve = 1; +stop = 0; +t = 0; +xt = state0; +while stop==0 + t = t+1; + % evaluate the previous solution at the new point xt + [R,g,nPhi] = residual(coeffs,xt,params,c0,nodes,weights); + + % if residuals are too large solve again + if norm(R(:))>testF && solve==1 + t + [coeffs] = tpsolve(coeffs,xt,model,params,c0,nodes,weights,tolX,tolF,maxiter,OPTIONS); % solve + + % evaluate the new solution + [R,g,nPhi] = residual(coeffs,xt,params,c0,nodes,weights); + end + + newxt = nPhi(:,disaster(t+1)); % new state + + if t>=10 % after 10 periods start checking for convergence + if max(abs(newxt-xt))<1e-7 + stop = 1; + state0 = xt; + coeffs0 = coeffs; + end + end + xt = newxt; +end + diff --git a/105/replication_package/GENERAL_IES/summarize_results.m b/105/replication_package/GENERAL_IES/summarize_results.m new file mode 100644 index 0000000000000000000000000000000000000000..7c0bffe0c0beff6fcf10fb1a36a303f6b44ac52a --- /dev/null +++ b/105/replication_package/GENERAL_IES/summarize_results.m @@ -0,0 +1,61 @@ + +normal = logical(disaster==1); % normal periods +d = logical(disaster>1); % disaster periods + +state1 = x_results(1,1:T); +state2 = x_results(2,1:T); + +f1 = y_results(1,1:T); +x1 = y_results(3,1:T); +logq = y_results(5,1:T); +tilp=y_results(6,1:T); + +invc1 = 1 + 1/RHO*f1.^(1 - THETA); +c1 = 1./invc1; + +q = exp(logq); + +tila1 = (1 + tilp).*state1(1:T) + state2(1:T); + +k1 = x1.*(1 - c1).*tila1./tilp; +tilb1 = (1 - x1).*(1 - c1).*tila1; + + +W1_share = k1 - NU*(k1 - MU) + (1 - NU)*tilb1./tilp; % wealth share after type changes +equity = k1 - NU*(k1 - MU); + +debt_to_assets = -(1 - NU)*tilb1./tilp; % debt ratio (after type changes) +debt_to_GDP = -(1 - NU)*tilb1*period_length; + +haty = nodes(1,double(disaster(1:T))); + +% compute means by iterated expectations + +roe = ((1 + tilp(2:T))./tilp(1:T-1).*haty(2:T)); % this is actual return from t to t+1. +mean_roe = 1/period_length*log((1-P)*mean(roe(normal(2:T)))+P*mean(roe(d(2:T)))); % mean return + +period_mean_roe = (1-P)*mean(roe(normal(2:T)))+P*mean(roe(d(2:T))); +period_var_roe = (1-P)*mean((roe(normal(2:T)) - period_mean_roe).^2)+P*mean((roe(d(2:T)) - period_mean_roe).^2); +vol_roe = sqrt(period_var_roe/period_length); + +rb = log(1./q(1:T-1))/period_length; % this is log return on bonds +mean_rb = (1-P)*mean(rb(normal(1:T-1)))+P*mean(rb(d(1:T-1))); + +Rb = 1./q(2:T-1); +period_mean_rb = (1-P)*mean(Rb(normal(2:T-1)))+P*mean(Rb(d(2:T-1))); +period_var_rb = (1-P)*mean((Rb(normal(2:T-1)) - period_mean_rb).^2)+P*mean((Rb(d(2:T-1)) - period_mean_rb).^2); +vol_rb = sqrt(period_var_rb/period_length); + +mean_equity = (1-P)*mean(equity(normal(1:T))) + P*mean(equity(d(1:T))); +mean_debt_to_assets = (1-P)*mean(debt_to_assets(normal(1:T))) + P*mean(debt_to_assets(d(1:T))); +mean_debt_to_GDP = (1-P)*mean(debt_to_GDP(normal(1:T))) + P*mean(debt_to_GDP(d(1:T))); +mean_W1_share = (1-P)*mean(W1_share(normal(1:T))) + P*mean(W1_share(d(1:T))); + +% mean_W1_share_excluding_labor = mean_W1_share*(1+L) - MU*L; +% mean_debt_to_assets_excluding_labor = mean_debt_to_assets*(1+L); +% mean_debt_to_GDP_including_labor = mean_debt_to_GDP/(1+L); +% mean_equity_excluding_labor = mean_equity*(1+L) - MU*L; + +mean_equity_excluding_labor = mean_equity/ALPHA - MU*(1 - ALPHA)/ALPHA; +mean_debt_to_assets_excluding_labor = mean_debt_to_assets/ALPHA; +mean_W1_share_excluding_labor = mean_equity_excluding_labor - mean_debt_to_assets_excluding_labor; \ No newline at end of file diff --git a/105/replication_package/Make_OECD_data.do b/105/replication_package/Make_OECD_data.do new file mode 100644 index 0000000000000000000000000000000000000000..dc3c083f493c9b3b22fb78f12fe1353baafc677c --- /dev/null +++ b/105/replication_package/Make_OECD_data.do @@ -0,0 +1,684 @@ +clear + +*set matsize 3000 +set matsize 800 +clear mata +set mem 500m +set more off +set logtype text +capture log close +*set linesize 255 + +// IMPORTANT!!! change working directory to the folder of this file + +* cd "folder name" + +// GDP current prices +clear + +local folder="GDP" + +insheet using "`folder'\GDP_current_prices.csv", n c case + +des + +tab PowerCode /* all number in millions */ +tab Measure /* two types of measures - current price and ppp */ +tab Transaction + +keep if Measure=="Current prices" + +keep Country Year Value + +rename Value GDP + +rename Country country +rename Year year + + +label var GDP "GDP current prices, Million of national currency" + +save GDP, replace + + +// Step 1: make dataset.dta + +clear + +local folder="Financial balance sheets non consolidated SNA 2008" + +* Total liabilities - all sectors + +insheet using "`folder'\Total liabilities.csv", n c case + +des + +tab PowerCode /* all number in millions */ +tab Measure /* two types of measures - national currency and USD */ +tab Transaction + +keep if Measure=="National currency, current prices" + +keep Country Sector Time Value + +rename Time Year +rename Value totliab + +gen Sec="" + +replace Sec="Total" if Sector=="Total economy" +replace Sec="World" if Sector=="Rest of the world" +replace Sec="Households" if Sector=="Households and NPISH" +replace Sec="Financials" if Sector=="Financial corporations" +replace Sec="nonFinancials" if Sector=="Non-financial corporations" +replace Sec="Gov" if Sector=="General Government" + +keep if Sec~="" + +keep Country Year Sec totliab + +rename Country country +rename Year year +rename Sec sector +rename totliab totliab_ + +reshape wide totliab_, i(country year) j(sector) string + +label var totliab_Total "Tota Liabilities - Total Economy" +label var totliab_World "Tota Liabilities - Rest of the World" +label var totliab_Households "Tota Liabilities - Households and NPISH" +label var totliab_Financials "Tota Liabilities - Financial corporations" +label var totliab_nonFinancials "Tota Liabilities - Non-financial corporations" + +save total_liabilities, replace + + +//* Financial Corporations - safe liabilities +clear + +insheet using "`folder'\Financial_Safe_Liabilities.csv", n c case + +des + +tab PowerCode /* all number in millions */ +tab Measure /* two types of measures - national currency and USD */ +tab Transaction +tab Sector /* only financial corporations */ + +keep if Measure=="National currency, current prices" & Sector=="Financial corporations" + +keep Country Time Transaction Value + +gen tran="" + +replace tran="dep" if Transaction=="Currency and deposits" +replace tran="secur" if Transaction=="Debt securities" +replace tran="loan" if Transaction=="Loans" +replace tran="mmf" if Transaction=="Money market fund shares /units" +replace tran="trade" if Transaction=="Trade credits and advances" + +drop if tran=="" + +keep Country Time tran Value +rename Country country +rename Time year +rename Value fin_ + +reshape wide fin_, i(country year) j(tran) string + +label var fin_dep "Currency and deposits - Financial corporations" +label var fin_secur "Debt securities - Financial corporations" +label var fin_loan "Loans - Financial corporations" +label var fin_mmf "Money market fund shares /units - Financial corporations" +label var fin_trade "Trade credits and advances - Financial corporations" + + +save financials_safe_items, replace + + +//* General Government - safe liabilities + +clear + +insheet using "`folder'\Government_Safe_Liabilities.csv", n c case + +des + +tab PowerCode /* all number in millions */ +tab Measure /* two types of measures - national currency and USD */ +tab Transaction +tab Sector /* only general government */ + +keep if Measure=="National currency, current prices" & Sector=="General Government" + +keep Country Time Transaction Value + +gen tran="" + +replace tran="dep" if Transaction=="Currency and deposits" +replace tran="secur" if Transaction=="Debt securities" +replace tran="loan" if Transaction=="Loans" +replace tran="mmf" if Transaction=="Money market fund shares /units" +replace tran="trade" if Transaction=="Trade credits and advances" + +drop if tran=="" + +keep Country Time tran Value +rename Country country +rename Time year +rename Value gov_ + +reshape wide gov_, i(country year) j(tran) string + + +label var gov_dep "Currency and deposits - General Government" +label var gov_secur "Debt securities - General Government" +label var gov_loan "Loans - General Government" +label var gov_mmf "Money market fund shares /units - General Government" +label var gov_trade "Trade credits and advances - General Government" + +save government_safe_items, replace + +//* Central bank holdings of bonds (assume most of these holdings are government bonds) + +clear + +insheet using "`folder'\CentralBank_gov_bonds.csv", n c case + +des + +tab PowerCode /* all number in millions */ +tab Measure /* two types of measures - national currency and USD */ +tab Transaction +tab Sector /* only general government */ + +keep if Measure=="National currency, current prices" & Sector=="Central Bank" + +keep Country Time Transaction Value + +gen tran="" + +replace tran="lbond" if Transaction=="Long-term debt securities" +replace tran="sbond" if Transaction=="Short-term debt securities" + + +drop if tran=="" + +keep Country Time tran Value +rename Country country +rename Time year +rename Value cb_ + +reshape wide cb_, i(country year) j(tran) string + +save central_bank_bonds, replace + +//* Central bank - safe and total liabilities + +clear + +insheet using "`folder'\CentralBank_liabilities.csv", n c case + +des + +tab PowerCode /* all number in millions */ +tab Measure /* two types of measures - national currency and USD */ +tab Transaction +tab Sector /* only Central Bank */ + +keep if Measure=="National currency, current prices" & Sector=="Central Bank" + +keep Country Time Transaction Value + +gen tran="" + +replace tran="dep" if Transaction=="Currency and deposits" +replace tran="secur" if Transaction=="Debt securities" +replace tran="loan" if Transaction=="Loans" +replace tran="mmf" if Transaction=="Money market fund shares /units" +replace tran="trade" if Transaction=="Trade credits and advances" +replace tran="totliab_Total" if Transaction=="Financial liabilities" + +drop if tran=="" + +keep Country Time tran Value +rename Country country +rename Time year +rename Value cb_ + +reshape wide cb_, i(country year) j(tran) string + + +label var cb_dep "Currency and deposits - Central Bank" +label var cb_secur "Debt securities - Central Bank" +label var cb_loan "Loans - Central Bank" +label var cb_mmf "Money market fund shares /units - Central Bank" +label var cb_trade "Trade credits and advances - Central Bank" +label var cb_totliab_Total "Financial liabilities - Central Bank" + +save cb_safe_items, replace + +clear + +use total_liabilities, replace + +joinby country year using financials_safe_items, unmatched(both) +cap drop _merge + +joinby country year using government_safe_items, unmatched(both) +cap drop _merge + +joinby country year using central_bank_bonds, unmatched(both) +cap drop _merge + +joinby country year using GDP, unmatched(master) +cap drop _merge + +joinby country year using cb_safe_items, unmatched(master) +cap drop _merge + +* replace missing values with zeros +foreach var of varlist fin_* gov_* cb_* { +replace `var'=0 if `var'==. +} + +label var cb_lbond "Long-term debt securities held by the central bank" +label var cb_sbond "Short-term debt securities held by the central bank" + + +encode country, gen(countrys) + +drop country +rename countrys country + +tsset country year + +save dataset, replace + +//* Compute variables in USD +* Total liabilities - all sectors + +clear + +insheet using "`folder'\Total liabilities.csv", n c case + +des + +tab PowerCode /* all number in millions */ +tab Measure /* two types of measures - national currency and USD */ +tab Transaction + + +*keep if Measure=="National currency, current prices" +keep if Measure=="US $, current prices, current exchange rates, end of period" + +keep Country Sector Time Value + +rename Time Year +rename Value totliab + +gen Sec="" + +replace Sec="Total" if Sector=="Total economy" +replace Sec="World" if Sector=="Rest of the world" +replace Sec="Households" if Sector=="Households and NPISH" +replace Sec="Financials" if Sector=="Financial corporations" +replace Sec="nonFinancials" if Sector=="Non-financial corporations" +replace Sec="Gov" if Sector=="General Government" + +keep if Sec~="" + +keep Country Year Sec totliab + +rename Country country +rename Year year +rename Sec sector +rename totliab totliab_ + +reshape wide totliab_, i(country year) j(sector) string + +label var totliab_Total "Tota Liabilities - Total Economy" +label var totliab_World "Tota Liabilities - Rest of the World" +label var totliab_Households "Tota Liabilities - Households and NPISH" +label var totliab_Financials "Tota Liabilities - Financial corporations" +label var totliab_nonFinancials "Tota Liabilities - Non-financial corporations" + +save total_liabilitiesUSD, replace + +*/ + +//* Financial Corporations - safe liabilities +clear + +insheet using "`folder'\Financial_Safe_Liabilities.csv", n c case + +des + +tab PowerCode /* all number in millions */ +tab Measure /* two types of measures - national currency and USD */ +tab Transaction +tab Sector /* only financial corporations */ + +*keep if Measure=="National currency, current prices" & Sector=="Financial corporations" +keep if Measure=="US $, current prices, current exchange rates, end of period" + +keep Country Time Transaction Value + +gen tran="" + +replace tran="dep" if Transaction=="Currency and deposits" +replace tran="secur" if Transaction=="Debt securities" +replace tran="loan" if Transaction=="Loans" +replace tran="mmf" if Transaction=="Money market fund shares /units" +replace tran="trade" if Transaction=="Trade credits and advances" + +drop if tran=="" + +keep Country Time tran Value +rename Country country +rename Time year +rename Value fin_ + +reshape wide fin_, i(country year) j(tran) string + +label var fin_dep "Currency and deposits - Financial corporations" +label var fin_secur "Debt securities - Financial corporations" +label var fin_loan "Loans - Financial corporations" +label var fin_mmf "Money market fund shares /units - Financial corporations" +label var fin_trade "Trade credits and advances - Financial corporations" + + +save financials_safe_itemsUSD, replace + +//* General Government - safe liabilities + +clear + +insheet using "`folder'\Government_Safe_Liabilities.csv", n c case + +des + +tab PowerCode /* all number in millions */ +tab Measure /* two types of measures - national currency and USD */ +tab Transaction +tab Sector /* only general government */ + +*keep if Measure=="National currency, current prices" & Sector=="General Government" +keep if Measure=="US $, current prices, current exchange rates, end of period" + +keep Country Time Transaction Value + +gen tran="" + +replace tran="dep" if Transaction=="Currency and deposits" +replace tran="secur" if Transaction=="Debt securities" +replace tran="loan" if Transaction=="Loans" +replace tran="mmf" if Transaction=="Money market fund shares /units" +replace tran="trade" if Transaction=="Trade credits and advances" + +drop if tran=="" + +keep Country Time tran Value +rename Country country +rename Time year +rename Value gov_ + +reshape wide gov_, i(country year) j(tran) string + + +label var gov_dep "Currency and deposits - General Government" +label var gov_secur "Debt securities - General Government" +label var gov_loan "Loans - General Government" +label var gov_mmf "Money market fund shares /units - General Government" +label var gov_trade "Trade credits and advances - General Government" + +save government_safe_itemsUSD, replace + + +//* Central bank holdings of bonds (assume most of these holdings are government bonds) + +clear + +insheet using "`folder'\CentralBank_gov_bonds.csv", n c case + +des + +tab PowerCode /* all number in millions */ +tab Measure /* two types of measures - national currency and USD */ +tab Transaction +tab Sector /* only general government */ + +*keep if Measure=="National currency, current prices" & Sector=="Central Bank" +keep if Measure=="US $, current prices, current exchange rates, end of period" + +keep Country Time Transaction Value + +gen tran="" + +replace tran="lbond" if Transaction=="Long-term debt securities" +replace tran="sbond" if Transaction=="Short-term debt securities" + + +drop if tran=="" + +keep Country Time tran Value +rename Country country +rename Time year +rename Value cb_ + +reshape wide cb_, i(country year) j(tran) string + +save central_bank_bondsUSD, replace + + +//* Central bank - safe and total liabilities + +clear + +insheet using "`folder'\CentralBank_liabilities.csv", n c case + +des + +tab PowerCode /* all number in millions */ +tab Measure /* two types of measures - national currency and USD */ +tab Transaction +tab Sector /* only Central Bank */ + +*keep if Measure=="National currency, current prices" & Sector=="Central Bank" +keep if Measure=="US $, current prices, current exchange rates, end of period" + +keep Country Time Transaction Value + +gen tran="" + +replace tran="dep" if Transaction=="Currency and deposits" +replace tran="secur" if Transaction=="Debt securities" +replace tran="loan" if Transaction=="Loans" +replace tran="mmf" if Transaction=="Money market fund shares /units" +replace tran="trade" if Transaction=="Trade credits and advances" +replace tran="totliab_Total" if Transaction=="Financial liabilities" + +drop if tran=="" + +keep Country Time tran Value +rename Country country +rename Time year +rename Value cb_ + +reshape wide cb_, i(country year) j(tran) string + + +label var cb_dep "Currency and deposits - Central Bank" +label var cb_secur "Debt securities - Central Bank" +label var cb_loan "Loans - Central Bank" +label var cb_mmf "Money market fund shares /units - Central Bank" +label var cb_trade "Trade credits and advances - Central Bank" +label var cb_totliab_Total "Financial liabilities - Central Bank" + +save cb_safe_itemsUSD, replace + +*** + +clear + +use total_liabilitiesUSD, replace + +joinby country year using financials_safe_itemsUSD, unmatched(both) +cap drop _merge + +joinby country year using government_safe_itemsUSD, unmatched(both) +cap drop _merge + +joinby country year using central_bank_bondsUSD, unmatched(both) +cap drop _merge + +joinby country year using cb_safe_itemsUSD, unmatched(both) +cap drop _merge + + +* replace missing values with zeros +foreach var of varlist fin_* gov_* cb_* { +replace `var'=0 if `var'==. +} + +label var cb_lbond "Long-term debt securities held by the central bank" +label var cb_sbond "Short-term debt securities held by the central bank" + + +encode country, gen(countrys) + +drop country +rename countrys country + +tsset country year + +save datasetUSD, replace + +*** do USD aggregates + +use datasetUSD, clear + + +gen fin_safeUSD=fin_dep+fin_loan+fin_mmf+fin_secur // remove trade credit and advances - it's a small part of financial debt and seems unrelated +gen cb_safeUSD=cb_dep+cb_loan+cb_mmf+cb_secur // remove trade credit and advances - it's a small part of financial debt and seems unrelated + + +gen gov_safeUSD=gov_dep+gov_loan+gov_mmf+gov_secur // remove trade credit and advnaces + + +rename totliab_Total totliab_TotalUSD + +keep country year fin_safeUSD gov_safeUSD cb_safeUSD totliab_TotalUSD + +sort country year +tsset country year + + +save safeUSD, replace + +// Make world table + +use safeUSD, clear + +gen tempvar=fin_safeUSD+gov_safeUSD+totliab_TotalUSD + +bysort country: egen minyear=min(year) if tempvar<. +bysort country: egen maxyear=max(year) if tempvar<. + +keep if minyear<=1995 +keep if year>=1995 + +keep if maxyear>=2017 +keep if year<=2017 + +sort country year +tsset country year // panel is balanced + + +if r(balanced)!="strongly balanced" { +di "WARNING!!!! panel is not balanced" + } + +preserve + +keep if year==2017 + +keep country + +gen OECD=1 + +save OECD, replace + +restore + + +decode country, g(country_name) + +bysort year: egen fin_safeWorld=total(fin_safeUSD) +bysort year: egen gov_safeWorld=total(gov_safeUSD) +bysort year: egen new_totalWorld=total(totliab_TotalUSD) + +bysort year: egen cb_safeWorld=total(cb_safeUSD) + +gen fin_shareWorld=fin_safeWorld/new_totalWorld +gen gov_shareWorld=gov_safeWorld/new_totalWorld +gen shareWorld=fin_shareWorld+gov_shareWorld + +gen cb_shareWorld=cb_safeWorld/new_totalWorld + +bysort year: egen fin_safeNonUS=total(fin_safeUSD) if country_name!="United States" +bysort year: egen gov_safeNonUS=total(gov_safeUSD) if country_name!="United States" +bysort year: egen new_totalNonUS=total(totliab_TotalUSD) if country_name!="United States" + +bysort year: egen cb_safeNonUS=total(cb_safeUSD) if country_name!="United States" + +gen fin_shareNonUS=fin_safeNonUS/new_totalNonUS +gen gov_shareNonUS=gov_safeNonUS/new_totalNonUS +gen shareNonUS=fin_shareNonUS+gov_shareNonUS + +gen cb_shareNonUS=cb_safeNonUS/new_totalNonUS + +sort country year + +keep if country==country[1] + +keep fin_shareWorld gov_shareWorld shareWorld cb_shareWorld fin_shareNonUS gov_shareNonUS shareNonUS cb_shareNonUS year + + +keep year fin_shareWorld gov_shareWorld shareWorld cb_shareWorld fin_shareNonUS gov_shareNonUS shareNonUS cb_shareNonUS + +save World, replace + + +// Make final dataset + +use dataset // non-consolidated data + +joinby country year using safeUSD, unmatched(both) +cap drop _merge + +joinby year using World, unmatched(both) +cap drop _merge + +joinby country using OECD, unmatched(both) +cap drop _merge + +cap drop fin_safe +cap drop cb_safe + +label var gov_safeUSD "government safe liabilities in USD" +label var fin_shareWorld "financial liabilities (as share of total assets) for the whole world" +label var gov_shareWorld "government liabilities (as share of total assets) for the whole world" +label var cb_shareWorld "central bank liabilities (as share of total assets) for the whole world" +label var shareWorld "safe liabilities (as share of total assets) for the whole world" + +label var fin_shareNonUS "financial liabilities (as share of total assets) for non-US sample" +label var gov_shareNonUS "government liabilities (as share of total assets) for non-US sample" +label var cb_shareNonUS "central bank liabilities (as share of total assets) for non-US sample" +label var shareNonUS "safe liabilities (as share of total assets) for non-US sample" + +label var totliab_Gov "Tota Liabilities - Government" +label var OECD "dummy for OECD countries" + +save OECD_data, replace + diff --git a/105/replication_package/ReadMe.pdf b/105/replication_package/ReadMe.pdf new file mode 100644 index 0000000000000000000000000000000000000000..411b0922f234db6171b506074f386e907428468d --- /dev/null +++ b/105/replication_package/ReadMe.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9068400c5ca91682b0dd81943ea676402c4cd3e4a0083709b46a65c0d502af1f +size 42724 diff --git a/105/replication_package/Replicate_Empirical_Results.do b/105/replication_package/Replicate_Empirical_Results.do new file mode 100644 index 0000000000000000000000000000000000000000..81c488972425daffbe7dc7554239d7a4ec88ee72 --- /dev/null +++ b/105/replication_package/Replicate_Empirical_Results.do @@ -0,0 +1,16 @@ +************************************************************************************************************* +* Replicate Tables 1-4 and Figures 1-2 of "Safe Assets" by Barro, Fernandez-Villaverde, Levintal and Mollerus +************************************************************************************************************* + +clear all + +clear mata +set mem 500m +set maxvar 32767 +set more off +set linesize 255 +cap log close + +do make_Tables_1_to_3_Figures_1_and_2 + +do make_Table_4 diff --git a/105/replication_package/Replicate_Simulation_Results.m b/105/replication_package/Replicate_Simulation_Results.m new file mode 100644 index 0000000000000000000000000000000000000000..c04034d0d1a34e97bfe690cf2281e925ab3a1a9e --- /dev/null +++ b/105/replication_package/Replicate_Simulation_Results.m @@ -0,0 +1,40 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Replicate Tables 5-7 and Figure 3 of "Safe Assets" by Barro, Fernandez-Villaverde, Levintal and Mollerus +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +clear + +%% open diary file + +FID = fopen('Tables_5_to_7.txt','w'); +fclose(FID); + +diary Tables_5_to_7.txt +diary off + +%% add folders to search path +homefolder = pwd; + +addpath(genpath([homefolder '\solution_methods'])); + +%% define models + +run('UNIT_IES\define_model'); % THETA = 1 +run('GENERAL_IES\define_model'); % THETA ~= 1 +run('Variable_Disaster_Size\define_model'); % THETA = 1, variable disaster size, defaultable long-term bonds + + +%% replicate Table 5 +run('UNIT_IES\make_Table_5.m') + +%% replicate Table 6 +run('GENERAL_IES\make_Table_6_part_1.m') +run('UNIT_IES\make_Table_6_part_2.m') + +%% replicate Table 7 +run('Variable_Disaster_Size\make_Table_7.m') + +%% replicate Figure 3 +run('UNIT_IES\Disaster_IRF.m') + + diff --git a/105/replication_package/UNIT_IES/Disaster_IRF.m b/105/replication_package/UNIT_IES/Disaster_IRF.m new file mode 100644 index 0000000000000000000000000000000000000000..6098efaee7047147b85c2a9c4242df58d5b1e477 --- /dev/null +++ b/105/replication_package/UNIT_IES/Disaster_IRF.m @@ -0,0 +1,46 @@ +% Disaster Impulse response function + +clear,clc,close all +addpath('files') + +load('benchmark') + +state0 = mean(tila1); +mean_W1_share0 = mean_W1_share; + +T = 10/period_length + 1; + +disaster = ones(1,T+1); +disaster(2) = 2; + +simulate_with_disasters; +summarize_results; + +W1_share = [mean_W1_share0;W1_share(:)]; + +% adjust for human capital +equity = equity/ALPHA - MU*(1 - ALPHA)/ALPHA; +debt_to_assets = debt_to_assets/ALPHA; +W1_share = W1_share/ALPHA - (1 - ALPHA)/ALPHA*MU; + +set(0, 'defaultFigurePaperPosition', [0 0 20 21.5]*30); +h = figure('color', [1 1 1], 'PaperType', 'A4'); + +subplot(2,2,1); +plot(W1_share); +title('W1/W') + +subplot(2,2,2) +plot(rb); +title('rf') + +subplot(2,2,3) +plot(equity); +title('K1') + +subplot(2,2,4) +plot(debt_to_assets); +title('B1/assets') + +cd .. +saveas(h,'Figure_3','jpg') \ No newline at end of file diff --git a/105/replication_package/UNIT_IES/Parameters.m b/105/replication_package/UNIT_IES/Parameters.m new file mode 100644 index 0000000000000000000000000000000000000000..2401d108ca2adf43131d06491d8a9e75c30875e9 --- /dev/null +++ b/105/replication_package/UNIT_IES/Parameters.m @@ -0,0 +1,22 @@ +period_length = 0.25; + +P = 1 - exp(-.04*period_length); % disaster probability + +B = -log(1 - .32); % disaster size + +meanB = B; + +G = 0.025*period_length; % drift of log output + +RHO = 0.04*period_length; % time preference rate + +NU = 0.02*period_length; % replacement rate + +MU = 0.05; % popoulation share of agent 1 + +ALPHA = 1/3; % capital share in output + +TAU = 0; % bond duration - short-term bonds + +GAMMA1 = 1.000001; % start with unit risk aversion +GAMMA2 = GAMMA1; diff --git a/105/replication_package/UNIT_IES/Table_6_MU.m b/105/replication_package/UNIT_IES/Table_6_MU.m new file mode 100644 index 0000000000000000000000000000000000000000..fc572545cc9978208a737f280b088ce72c38785d --- /dev/null +++ b/105/replication_package/UNIT_IES/Table_6_MU.m @@ -0,0 +1,94 @@ +% MU = 0.1 + +load('model') +addpath('files') + +Parameters; +MU = 0.1; % popoulation share of agent 1 + +% make the vector of parameters +params = eval(symparams); + +% distribution of hatyp +nodes = exp([G,G-B]); % hatyp +weights = [1-P,P]; % corresponding probabilities + +T = 2000/period_length; % simulate 2000 years + +% disaster shock +rng('default') +disaster = double(rand(1,T+1)testF && solve==1 + t + [coeffs,model] = tpsolve(coeffs,xt,model,params,c0,nodes,weights,tolX,tolF,maxiter,OPTIONS); % solve + + % evaluate the new solution + [R,g,nPhi] = residual(coeffs,xt,params,c0,nodes,weights); + end + + newxt = nPhi(:,1); % assume no realized disasters + + if t>burn+10 % after 10 periods start checking for convergence + if max(abs(newxt-xt))<1e-7 + [coeffs] = tpsolve(coeffs,xt,model,params,c0,nodes,weights,tolX,tolF,maxiter,OPTIONS); + [R,g,nPhi] = residual(coeffs,xt,params,c0,nodes,weights); + + newxt = nPhi(:,1); + if max(abs(newxt-xt))<1e-7 + stop = 1; + state0 = xt; % solution point + coeffs0 = coeffs; + end + end + end + xt = newxt; +end + diff --git a/105/replication_package/UNIT_IES/define_model.m b/105/replication_package/UNIT_IES/define_model.m new file mode 100644 index 0000000000000000000000000000000000000000..b454c9702d9ba6e773d1b66c362d7a9cafd7df3d --- /dev/null +++ b/105/replication_package/UNIT_IES/define_model.m @@ -0,0 +1,139 @@ +%------------------------------------------------------------------------- +% The model: Safe Assets - the case of unit IES (THETA = 1) +% +% This file defines the baseline model (see Appendix for the full derivation). +% Bonds are short term perfectly safe. +% +% Variables are denoted by small letters and +% parameters by capital letters. Future values are denoted by suffix p. +%------------------------------------------------------------------------- + +clear,clc + +%% Symbolic variables + +syms RHO GAMMA1 GAMMA2 NU MU TAU real +syms f1 f2 f1p f2p x1 x2 x1p x2p real +syms logq logqp tilp tilpp real +syms state1 state1p state2 state2p hatyp deltap k1 tilb1 real +syms tila1 tila1p tila2 invtila1 invtila2 invtilp rbp rep c1 c2 c1p c2p q qp real +syms invc1 invc1p invc2 invc2p invf1 invf2 r1p r2p logu1p logu2p u1p u2p logf1 logf1p logf2 logf2p real +syms term1p term2p invr1p invr2p real + +%% Parameters + +symparams = [RHO,GAMMA1,GAMMA2,NU,MU]; + +%% State variables + +state = [tila1]; % current period +statep = [tila1p]; % future period + +%% Control variables + +control = [f1,f2,x1,x2,logq]; % current period +controlp = [f1p,f2p,x1p,x2p,logqp]; % future period + +%% shocks + +shocks = [hatyp]; + +%% auxiliary variables + +tilp = 1/RHO; % price-dividend ratio for unit IES +tilpp = tilp; % next period + +c1 = RHO/(1 + RHO); % consumption/wealth ratio of agent 1 for unit IES +c1p = c1; % next period + +c2 = c1; % consumption/wealth ratio of agent 2 for unit IES +c2p = c2; % next period + +logc1p = log(c1p); +logc2p = log(c2p); + +invf1_ = 1/f1; +invf2_ = 1/f2; + +logf1p_ = log(f1p); +logf2p_ = log(f2p); + +invr1p_ = 1/r1p; +invr2p_ = 1/r2p; + +q_ = exp(logq); +qp_ = exp(logqp); + +invtila1_ = 1/tila1; +invtila2_ = 1/tila2; + +rep_ = (1 + tilpp)/tilp*hatyp; % return on equity +rbp_ = 1/q; % return on bond + +u1p_ = exp(logu1p); +u2p_ = exp(logu2p); + +%% MODEL CONDITIONS + +tila2_ = tilp + 1 - tila1; + +k1_ = x1*(1 - c1)*tila1/tilp; + +tilb1_ = (1 - x1)*(1 - c1)*tila1; + +eq1 = tilb1*invtila2 + (1 - x2)*(1 - c2); + +r1p_ = x1*rep + (1 - x1)*rbp; + +r2p_ = x2*rep + (1 - x2)*rbp; + +term1p_ = r1p^(1 - GAMMA1)*((1 - NU*(1 - MU))*u1p^(1 - GAMMA1)... + + NU*(1 - MU)*u2p^(1 - GAMMA1))*invf1^(1 - GAMMA1); + +term2p_ = r2p^(1 - GAMMA2)*((1 - NU*MU)*u2p^(1 - GAMMA2)... + +NU*MU*u1p^(1 - GAMMA2))*invf2^(1 - GAMMA2); + +eq2 = -1 + term1p; % define f1 = (E(r1p*u1p)^(1-GAMMA1))^(1/(1-GAMMA1)) + +eq3 = -1 + term2p; % define f2 similarly + +logu1p_ = RHO/(1 + RHO)*logc1p + 1/(1 + RHO)*log(1 - c1p) + 1/(1 + RHO)*logf1p; + +logu2p_ = RHO/(1 + RHO)*logc2p + 1/(1 + RHO)*log(1 - c2p) + 1/(1 + RHO)*logf2p; + +eq4 = (rep - rbp)*term1p*invr1p; + +eq5 = (rep - rbp)*term2p*invr2p; + +%% Function f (Ef = 0 imposes model conditions) + +f_fun = [eq1;eq2;eq3;eq4;eq5]; + +%% law of motion of state variables + +Phi_fun = (1 + tilp)*(k1 - NU*(k1 - MU)) + (1 - NU)*tilb1/(hatyp*q); % law of motion of tila1 + +%% collect auxiliary variables and functions + +allvars=who; +auxfuns=[]; +auxvars=[]; +for i=1:length(allvars) + if strcmp(allvars{i}(end),'_') + eval(['tempfun=' allvars{i} ';']) + eval(['tempvar=' allvars{i}(1:end-1) ';']) + auxfuns=[auxfuns;tempfun]; + auxvars=[auxvars;tempvar]; + end +end + +%% Approximation order (<=4) + +order = 4; + +%% Preprocess model and save + +model = prepare_tp(f_fun,Phi_fun,controlp,control,statep,state,shocks,symparams,order,auxfuns,auxvars); + +save('model') + diff --git a/105/replication_package/UNIT_IES/make_Table_5.m b/105/replication_package/UNIT_IES/make_Table_5.m new file mode 100644 index 0000000000000000000000000000000000000000..cf43b050b59082c9593cc3d582954a673ef236b6 --- /dev/null +++ b/105/replication_package/UNIT_IES/make_Table_5.m @@ -0,0 +1,210 @@ +% Table 5 + +clear,clc + +load('model') +addpath('files') + +Parameters; + +% make the vector of parameters +params = eval(symparams); + +% distribution of hatyp +nodes = exp([G,G-B]); % hatyp +weights = [1-P,P]; % corresponding probabilities + +T = 2000/period_length; % simulate 2000 years + +% disaster shock +rng('default') +disaster = double(rand(1,T+1)testF && solve==1 + t + [coeffs] = tpsolve(coeffs,xt,model,params,c0,nodes,weights,tolX,tolF,maxiter,OPTIONS); % solve + + % evaluate the new solution + [R,g,nPhi] = residual(coeffs,xt,params,c0,nodes,weights); + end + + newxt = nPhi(:,disaster(t+1)); % new state + + if t>=10 % after 10 periods start checking for convergence + if max(abs(newxt-xt))<1e-7 + stop = 1; + state0 = xt; + coeffs0 = coeffs; + end + end + xt = newxt; +end + diff --git a/105/replication_package/UNIT_IES/summarize_results.m b/105/replication_package/UNIT_IES/summarize_results.m new file mode 100644 index 0000000000000000000000000000000000000000..eb8cdabc39a920fa151d0c10b1b5fea33b5eaa4a --- /dev/null +++ b/105/replication_package/UNIT_IES/summarize_results.m @@ -0,0 +1,56 @@ + +normal = logical(disaster==1); % normal periods +d = logical(disaster>1); % disaster periods + +tila1 = x_results(1,1:T); + +x1 = y_results(3,1:T); +logq = y_results(5,1:T); + +c1 = RHO/(1+RHO); +tilp = 1/RHO; +tilp = repmat(tilp,1,T); +q = exp(logq); + +k1 = x1.*(1 - c1).*tila1./tilp; +tilb1 = (1 - x1).*(1 - c1).*tila1; + + +W1_share = k1 - NU*(k1 - MU) + (1 - NU)*tilb1./tilp; % wealth share after type changes +equity = k1 - NU*(k1 - MU); + +debt_to_assets = -(1 - NU)*tilb1./tilp; % debt ratio (after type changes) +debt_to_GDP = -(1 - NU)*tilb1*period_length; + +haty = nodes(1,double(disaster(1:T))); + +% compute means by iterated expectations + +roe = ((1 + tilp(2:T))./tilp(1:T-1).*haty(2:T)); % this is actual return from t to t+1. +mean_roe = 1/period_length*log((1-P)*mean(roe(normal(2:T)))+P*mean(roe(d(2:T)))); % mean return + +period_mean_roe = (1-P)*mean(roe(normal(2:T)))+P*mean(roe(d(2:T))); +period_var_roe = (1-P)*mean((roe(normal(2:T)) - period_mean_roe).^2)+P*mean((roe(d(2:T)) - period_mean_roe).^2); +vol_roe = sqrt(period_var_roe/period_length); + +rb = log(1./q(1:T-1))/period_length; % this is log return on bonds +mean_rb = (1-P)*mean(rb(normal(1:T-1)))+P*mean(rb(d(1:T-1))); + +Rb = 1./q(2:T-1); +period_mean_rb = (1-P)*mean(Rb(normal(2:T-1)))+P*mean(Rb(d(2:T-1))); +period_var_rb = (1-P)*mean((Rb(normal(2:T-1)) - period_mean_rb).^2)+P*mean((Rb(d(2:T-1)) - period_mean_rb).^2); +vol_rb = sqrt(period_var_rb/period_length); + +mean_equity = (1-P)*mean(equity(normal(1:T))) + P*mean(equity(d(1:T))); +mean_debt_to_assets = (1-P)*mean(debt_to_assets(normal(1:T))) + P*mean(debt_to_assets(d(1:T))); +mean_debt_to_GDP = (1-P)*mean(debt_to_GDP(normal(1:T))) + P*mean(debt_to_GDP(d(1:T))); +mean_W1_share = (1-P)*mean(W1_share(normal(1:T))) + P*mean(W1_share(d(1:T))); + +% mean_W1_share_excluding_labor = mean_W1_share*(1+L) - MU*L; +% mean_debt_to_assets_excluding_labor = mean_debt_to_assets*(1+L); +% mean_debt_to_GDP_including_labor = mean_debt_to_GDP/(1+L); +% mean_equity_excluding_labor = mean_equity*(1+L) - MU*L; + +mean_equity_excluding_labor = mean_equity/ALPHA - MU*(1 - ALPHA)/ALPHA; +mean_debt_to_assets_excluding_labor = mean_debt_to_assets/ALPHA; +mean_W1_share_excluding_labor = mean_equity_excluding_labor - mean_debt_to_assets_excluding_labor; \ No newline at end of file diff --git a/105/replication_package/User Guide.pdf b/105/replication_package/User Guide.pdf new file mode 100644 index 0000000000000000000000000000000000000000..472c53d6556de6364aee7049056746e176869cb9 --- /dev/null +++ b/105/replication_package/User Guide.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ae3ea65d6ead2e1e273aabe94a8a1f913ec926e7b77f7f75784b25d6db4748f +size 161394 diff --git a/105/replication_package/Variable_Disaster_Size/Parameters.m b/105/replication_package/Variable_Disaster_Size/Parameters.m new file mode 100644 index 0000000000000000000000000000000000000000..a6fe9ac05166cc4ddbc618313b5bdcccdc4e2f83 --- /dev/null +++ b/105/replication_package/Variable_Disaster_Size/Parameters.m @@ -0,0 +1,46 @@ +period_length = 0.25; + +P = 1 - exp(-.04*period_length); % disaster probability + +% variable disaster size +B = -log(1 - [0.1384074; + 0.2375926; + 0.335; + 0.4331111; + 0.5516667; + 0.653]); + +% distribution of disaster size +probB = [0.6; + 0.2; + 0.088888889; + 0.066666667; + 0.022222222; + 0.022222222]; + + +meanB = B(:)'*probB; + +Size = 1 - exp(-B(:)'); +meanSize = Size*probB; +sdSize = sqrt((Size - meanSize).^2*probB(:)); + +G = 0.021*period_length; % drift of log output + +RHO = 0.04*period_length; % time preference rate + +NU = 0.02*period_length; % replacement rate + +MU = 0.05; % popoulation share of agent 1 + +ALPHA = 1/3; % capital share in output + +TAU = 0; % bond duration - start with short-term bonds + +GAMMA1 = 1.000001; % start with unit risk aversion +GAMMA2 = GAMMA1; + +delta_prob = 0.4; % default probability +delta_size = 0; % default size + + diff --git a/105/replication_package/Variable_Disaster_Size/correct_params.m b/105/replication_package/Variable_Disaster_Size/correct_params.m new file mode 100644 index 0000000000000000000000000000000000000000..f3a4df1c176c5a6163e633593681f37f0fae6039 --- /dev/null +++ b/105/replication_package/Variable_Disaster_Size/correct_params.m @@ -0,0 +1,45 @@ +% This file changes the parameters gradually from their initival value to +% the target value + +solve = 1; +stop = 0; +t = 0; + +xt = state0; +params0 = params; +while stop==0 + t = t + 1; + + if t<=burn + factor = t/burn; + params = (1 - factor)*params0 + factor*newparams; + end + [R,g,nPhi] = residual(coeffs,xt,params,c0,nodes,weights); + + % if residuals are too large solve again + if norm(R(:))>testF && solve==1 + t + [coeffs,model] = tpsolve(coeffs,xt,model,params,c0,nodes,weights,tolX,tolF,maxiter,OPTIONS); % solve + + % evaluate the new solution + [R,g,nPhi] = residual(coeffs,xt,params,c0,nodes,weights); + end + + newxt = nPhi(:,1); % assume no realized disasters + + if t>burn+10 % after 10 periods start checking for convergence + if max(abs(newxt-xt))<1e-7 + [coeffs] = tpsolve(coeffs,xt,model,params,c0,nodes,weights,tolX,tolF,maxiter,OPTIONS); + [R,g,nPhi] = residual(coeffs,xt,params,c0,nodes,weights); + + newxt = nPhi(:,1); + if max(abs(newxt-xt))<1e-7 + stop = 1; + state0 = xt; % solution point + coeffs0 = coeffs; + end + end + end + xt = newxt; +end + diff --git a/105/replication_package/Variable_Disaster_Size/define_model.m b/105/replication_package/Variable_Disaster_Size/define_model.m new file mode 100644 index 0000000000000000000000000000000000000000..ccc424df9ddbff9ebfc0f7ba5d09b32140fd5334 --- /dev/null +++ b/105/replication_package/Variable_Disaster_Size/define_model.m @@ -0,0 +1,142 @@ +%------------------------------------------------------------------------- +% The model: Safe Assets - the case of unit IES (THETA = 1) +% Bonds are long term and subject to a default shock deltap +% +% This file defines the model (see Appendix for the full derivation). +% +% Variables are denoted by small letters and +% parameters by capital letters. Future values are denoted by suffix p. +%------------------------------------------------------------------------- + +clear,clc + +%% Symbolic variables + +syms RHO GAMMA1 GAMMA2 NU MU TAU real +syms f1 f2 f1p f2p x1 x2 x1p x2p real +syms logq logqp tilp tilpp real +syms state1 state1p state2 state2p hatyp deltap k1 tilb1 real +syms tila1 tila2 invtila1 invtila2 invtilp rbp rep c1 c2 c1p c2p q qp real +syms invc1 invc1p invc2 invc2p invf1 invf2 r1p r2p logu1p logu2p u1p u2p logf1 logf1p logf2 logf2p real +syms term1p term2p invr1p invr2p real + +%% Parameters + +symparams = [RHO,GAMMA1,GAMMA2,NU,MU,TAU]; + +%% State variables + +state = [state1,state2]; % current period +statep = [state1p,state2p]; % future period + +%% Control variables + +control = [f1,f2,x1,x2,logq]; % current period +controlp = [f1p,f2p,x1p,x2p,logqp]; % future period + +%% shocks + +shocks = [hatyp,deltap]; + +%% auxiliary variables + +tilp = 1/RHO; % price-dividend ratio for unit IES +tilpp = tilp; % next period + +c1 = RHO/(1 + RHO); % consumption/wealth ratio of agent 1 for unit IES +c1p = c1; % next period + +c2 = c1; % consumption/wealth ratio of agent 2 for unit IES +c2p = c2; % next period + +logc1p = log(c1p); +logc2p = log(c2p); + +invf1_ = 1/f1; +invf2_ = 1/f2; + +logf1p_ = log(f1p); +logf2p_ = log(f2p); + +invr1p_ = 1/r1p; +invr2p_ = 1/r2p; + +q_ = exp(logq); +qp_ = exp(logqp); + +invtila1_ = 1/tila1; +invtila2_ = 1/tila2; + +rep_ = (1 + tilpp)/tilp*hatyp; % return on equity +rbp_ = (1 + TAU*qp)/q*(1 - deltap); % return on bond + +u1p_ = exp(logu1p); +u2p_ = exp(logu2p); + +%% MODEL CONDITIONS + +tila1_ = (1 + tilp)*state1 + state2*(1 + TAU*q); + +tila2_ = tilp + 1 - tila1; + +k1_ = x1*(1 - c1)*tila1/tilp; + +tilb1_ = (1 - x1)*(1 - c1)*tila1; + +eq1 = tilb1*invtila2 + (1 - x2)*(1 - c2); + +r1p_ = x1*rep + (1 - x1)*rbp; + +r2p_ = x2*rep + (1 - x2)*rbp; + +term1p_ = r1p^(1 - GAMMA1)*((1 - NU*(1 - MU))*u1p^(1 - GAMMA1)... + + NU*(1 - MU)*u2p^(1 - GAMMA1))*invf1^(1 - GAMMA1); + +term2p_ = r2p^(1 - GAMMA2)*((1 - NU*MU)*u2p^(1 - GAMMA2)... + +NU*MU*u1p^(1 - GAMMA2))*invf2^(1 - GAMMA2); + +eq2 = -1 + term1p; % define f1 = (E(r1p*u1p)^(1-GAMMA1))^(1/(1-GAMMA1)) + +eq3 = -1 + term2p; % define f2 similarly + +logu1p_ = RHO/(1 + RHO)*logc1p + 1/(1 + RHO)*log(1 - c1p) + 1/(1 + RHO)*logf1p; + +logu2p_ = RHO/(1 + RHO)*logc2p + 1/(1 + RHO)*log(1 - c2p) + 1/(1 + RHO)*logf2p; + +eq4 = (rep - rbp)*term1p*invr1p; + +eq5 = (rep - rbp)*term2p*invr2p; + +%% Function f (Ef = 0 imposes model conditions) + +f_fun = [eq1;eq2;eq3;eq4;eq5]; + +%% law of motion of state variables + +Phi_fun = [k1 - NU*(k1 - MU); % law of motion of state1p + (1 - NU)*tilb1*(1 - deltap)/(hatyp*q)]; % law of motion of state2p + +%% collect auxiliary variables and functions + +allvars=who; +auxfuns=[]; +auxvars=[]; +for i=1:length(allvars) + if strcmp(allvars{i}(end),'_') + eval(['tempfun=' allvars{i} ';']) + eval(['tempvar=' allvars{i}(1:end-1) ';']) + auxfuns=[auxfuns;tempfun]; + auxvars=[auxvars;tempvar]; + end +end + +%% Approximation order (<=4) + +order = 4; + +%% Preprocess model and save + +model = prepare_tp(f_fun,Phi_fun,controlp,control,statep,state,shocks,symparams,order,auxfuns,auxvars); + +save('model') + diff --git a/105/replication_package/Variable_Disaster_Size/make_Table_7.m b/105/replication_package/Variable_Disaster_Size/make_Table_7.m new file mode 100644 index 0000000000000000000000000000000000000000..8dd2c43038bb03b365c36016686f87dfe4db1c91 --- /dev/null +++ b/105/replication_package/Variable_Disaster_Size/make_Table_7.m @@ -0,0 +1,200 @@ +% Variable disaster size, long-term bonds, default probability + +clear,clc + +load('model') +addpath('files') + +Parameters; + +% make the vector of parameters +params = eval(symparams); + +% distribution of hatyp and deltap +nodes = [exp([G,kron(G-B(:)',ones(1,2))]); + 0,kron(ones(1,numel(B)),[0,delta_size])];% realizations + +weights = [1-P,P*kron(probB(:)',[1-delta_prob,delta_prob])]; % corresponding probabilities + +rng('default') + +T = 1e5; + +N_disasters = ceil(T*P); +ptr = 1 + round(cumsum([0;probB(:)])*N_disasters); +disaster_state = zeros(1,N_disasters); +for i = 1:numel(probB) + disaster_state(ptr(i):ptr(i+1)-1) = i; +end +randorder = rand(1,N_disasters); +[~,I] = sort(randorder); +disaster_state = disaster_state(I); + +% disaster shock (normal = 1, disaster>1) + +disaster = zeros(1,T+1); +disaster(randperm(T,N_disasters)) = 1; + +default = double(rand(1,T+1)testF && solve==1 + t + [coeffs] = tpsolve(coeffs,xt,model,params,c0,nodes,weights,tolX,tolF,maxiter,OPTIONS); % solve + + % evaluate the new solution + [R,g,nPhi] = residual(coeffs,xt,params,c0,nodes,weights); + end + + newxt = nPhi(:,disaster(t+1)); % new state + + if t>=10 % after 10 periods start checking for convergence + if max(abs(newxt-xt))<1e-7 + stop = 1; + state0 = xt; + coeffs0 = coeffs; + end + end + xt = newxt; +end + diff --git a/105/replication_package/Variable_Disaster_Size/summarize_results.m b/105/replication_package/Variable_Disaster_Size/summarize_results.m new file mode 100644 index 0000000000000000000000000000000000000000..a1f296f3b25e1ce0a965895568c0c05b92b2c022 --- /dev/null +++ b/105/replication_package/Variable_Disaster_Size/summarize_results.m @@ -0,0 +1,55 @@ + +normal = logical(disaster==1); % normal periods +d = logical(disaster>1); % disaster periods + +state1 = x_results(1,1:T); +state2 = x_results(2,1:T); + +x1 = y_results(3,1:T); +logq = y_results(5,1:T); + +c1 = RHO/(1+RHO); +tilp = 1/RHO; +tilp = repmat(tilp,1,T); +q = exp(logq); + +tila1 = (1 + tilp).*state1 + state2.*(1 + TAU*q); + +k1 = x1.*(1 - c1).*tila1./tilp; +tilb1 = (1 - x1).*(1 - c1).*tila1; + + +W1_share = k1 - NU*(k1 - MU) + (1 - NU)*tilb1./tilp; % wealth share after type changes +equity = k1 - NU*(k1 - MU); + +debt_to_assets = -(1 - NU)*tilb1./tilp; % debt ratio (after type changes) +debt_to_GDP = -(1 - NU)*tilb1*period_length; + +haty = nodes(1,double(disaster(1:T))); +delta = nodes(2,double(disaster(1:T))); + +% compute means by iterated expectations + +roe = ((1 + tilp(2:T))./tilp(1:T-1).*haty(2:T)); % this is actual return from t to t+1. +mean_roe = 1/period_length*log((1-P)*mean(roe(normal(2:T)))+P*mean(roe(d(2:T)))); % mean return + +period_mean_roe = (1-P)*mean(roe(normal(2:T)))+P*mean(roe(d(2:T))); +period_var_roe = (1-P)*mean((roe(normal(2:T)) - period_mean_roe).^2)+P*mean((roe(d(2:T)) - period_mean_roe).^2); +vol_roe = sqrt(period_var_roe/period_length); + +rb = log((1 + TAU*q(2:T))./q(1:T-1)).*(1 - delta(2:T))/period_length; % this is log return on bonds +mean_rb = (1-P)*mean(rb(normal(1:T-1)))+P*mean(rb(d(1:T-1))); + +Rb = (1 + TAU*q(3:T))./q(2:T-1).*(1 - delta(3:T)); +period_mean_rb = (1-P)*mean(Rb(normal(2:T-1)))+P*mean(Rb(d(2:T-1))); +period_var_rb = (1-P)*mean((Rb(normal(2:T-1)) - period_mean_rb).^2)+P*mean((Rb(d(2:T-1)) - period_mean_rb).^2); +vol_rb = sqrt(period_var_rb/period_length); + +mean_equity = (1-P)*mean(equity(normal(1:T))) + P*mean(equity(d(1:T))); +mean_debt_to_assets = (1-P)*mean(debt_to_assets(normal(1:T))) + P*mean(debt_to_assets(d(1:T))); +mean_debt_to_GDP = (1-P)*mean(debt_to_GDP(normal(1:T))) + P*mean(debt_to_GDP(d(1:T))); +mean_W1_share = (1-P)*mean(W1_share(normal(1:T))) + P*mean(W1_share(d(1:T))); + +mean_equity_excluding_labor = mean_equity/ALPHA - MU*(1 - ALPHA)/ALPHA; +mean_debt_to_assets_excluding_labor = mean_debt_to_assets/ALPHA; +mean_W1_share_excluding_labor = mean_equity_excluding_labor - mean_debt_to_assets_excluding_labor; \ No newline at end of file diff --git a/105/replication_package/examples/rbc/prepare_model.m b/105/replication_package/examples/rbc/prepare_model.m new file mode 100644 index 0000000000000000000000000000000000000000..4528eff1b0ca8cf36151739d330c21d922c7ba81 --- /dev/null +++ b/105/replication_package/examples/rbc/prepare_model.m @@ -0,0 +1,69 @@ +%------------------------------------------------------------------ +% This script shows how to solve the RBC model by Taylor projection +%------------------------------------------------------------------ + +clear,clc + +%----------------------------------------- +% Define symbolic variables and parameters +%----------------------------------------- + +syms k kp c cp z zp epsp real +syms BETA GAMMA ALPHA RHO DELTA SIGMA real + +%------------------------------------------------- +% Function f (Euler condition) in a unit-free form +%------------------------------------------------- + +f_fun=BETA*(c/cp)^GAMMA*(ALPHA*exp(zp)*kp^(ALPHA-1)+1-DELTA)-1; + +%------------------------------------------------------- +% Function Phi (law of motion of capital and technology) +%------------------------------------------------------- + +Phi_fun=[exp(z)*k^ALPHA+(1-DELTA)*k-c; + RHO*z+SIGMA*epsp]; + +%-------------------------- +% Vector of state variables +%-------------------------- + +x=[k,z]; % current period +xp=[kp,zp]; % future period + +%---------------------------- +% Vector of control variables +%---------------------------- + +y=[c]; % current period +yp=[cp]; % future period + +%----------------- +% Vector of shocks +%----------------- + +shocks=[epsp]; + +%--------------------- +% Vector of parameters +%--------------------- + +symparams=[BETA,GAMMA,ALPHA,RHO,DELTA,SIGMA]; + +%-------------------- +% Approximation order +%-------------------- + +order=4; % fourth order is the maximum possible + +%---------------- +% Call prepare_tp +%---------------- + +model=prepare_tp(f_fun,Phi_fun,yp,y,xp,x,shocks,symparams,order); + +%----------- +% Save model +%----------- + +save('model') % you will need this later diff --git a/105/replication_package/examples/rbc/prepare_model_auxiliary_functions.m b/105/replication_package/examples/rbc/prepare_model_auxiliary_functions.m new file mode 100644 index 0000000000000000000000000000000000000000..4b595a5f24c2b66b6bcf319edaaa876f16956d0c --- /dev/null +++ b/105/replication_package/examples/rbc/prepare_model_auxiliary_functions.m @@ -0,0 +1,127 @@ +%---------------------------------------------- +% RBC model with auxiliary functions +%---------------------------------------------- + +clear,clc + +%----------------------------------------- +% Define symbolic variables and parameters +%----------------------------------------- + +syms k kp c cp z zp epsp real +syms BETA GAMMA ALPHA RHO DELTA SIGMA real + +%------------------------------- +% Define the auxiliary functions +%------------------------------- + +% Logs of consumption and capital. +syms logc logcp logk logkp real +logc_=log(c); +logcp_=log(cp); +logk_=log(k); +logkp_=log(kp); + +% Log and level of future mpk. +syms mpkp logmpkp real +logmpkp_=log(ALPHA)+zp+(ALPHA-1)*logkp; +mpkp_=exp(logmpkp); + +% Log and level of stochastic discount factor. +syms mp logmp real +logmp_=log(BETA)+GAMMA*(logc-logcp); +mp_=exp(logmp); + +% Log and level of output. +syms logoutput output real +logoutput_=z+ALPHA*logk; +output_=exp(logoutput); + +%----------------------------- +% Function f (Euler condition) +%----------------------------- +f_fun=mp*(mpkp+1-DELTA)-1; + +%------------------------------------------------------- +% Function Phi (law of motion of capital and technology) +%------------------------------------------------------- + +Phi_fun=[output+(1-DELTA)*k-c; + RHO*z+SIGMA*epsp]; + +%-------------------------- +% Vector of state variables +%-------------------------- +x=[k,z]; % current period +xp=[kp,zp]; % future period + +%---------------------------- +% Vector of control variables +%---------------------------- +y=[c]; % current period +yp=[cp]; % future period + +%----------------- +% Vector of shocks +%----------------- +shocks=[epsp]; + +%--------------------- +% Vector of parameters +%--------------------- +symparams=[BETA,GAMMA,ALPHA,RHO,DELTA,SIGMA]; + +%----------------------------------------------------------- +% Vectors of auxiliary functions and corresponding variables +%----------------------------------------------------------- + +% you can do it manually: + +% auxfuns=[logc_;logcp_;logk_;logkp_;logmp_;logmpkp_;logoutput_;mp_;mpkp_;output_]; +% auxvars=[logc;logcp;logk;logkp;logmp;logmpkp;logoutput;mp;mpkp;output]; + + +% or automatically by the following code (the names of the +% auxiliary functions must be the same as the auxiliary variables with an +% underscore suffix): + +allvars=who; +auxfuns=[]; +auxvars=[]; +for i=1:length(allvars) + if strcmp(allvars{i}(end),'_') + eval(['tempfun=' allvars{i} ';']) + eval(['tempvar=' allvars{i}(1:end-1) ';']) + auxfuns=[auxfuns(:);tempfun(:)]; + auxvars=[auxvars(:);tempvar(:)]; + end +end + +% Note that f is a function of the model variables and the auxiliary +% variables. To get f as a function of the model variables only, use the +% function subsf: + +f_noaux = subsf( f_fun,auxvars,auxfuns ); + +% Compare f with f_noaux + +f_fun,f_noaux + +% Display the auxiliary equations: + +[auxvars,auxfuns] + +%-------------------- +% Approximation order +%-------------------- +order=4; % fourth order is the maximum possible + +%---------------- +% Call prepare_tp +%---------------- +model=prepare_tp(f_fun,Phi_fun,yp,y,xp,x,shocks,symparams,order,auxfuns,auxvars); + +%----------- +% Save model +%----------- +save('model') % you will need this later diff --git a/105/replication_package/examples/rbc/solve_continuation.m b/105/replication_package/examples/rbc/solve_continuation.m new file mode 100644 index 0000000000000000000000000000000000000000..f4c7203e7703a38122e61f854627061430252224 --- /dev/null +++ b/105/replication_package/examples/rbc/solve_continuation.m @@ -0,0 +1,102 @@ +%-------------------------------------------- +% Solve the RBC model by continuation method +%-------------------------------------------- + +clear,clc + +%--------------------------------------------------------- +% Add folder 'files' to the search path and load the model +%--------------------------------------------------------- +addpath('files'); +load('model') + +%---------------------------------------------------------------------------- +% Provide nodes and weights for the quadrature that approximates expectations +%---------------------------------------------------------------------------- +n_e=1; % number of shocks. +[n_nodes,nodes,weights] = Monomials_2(n_e,eye(n_e)); % this quadrature function was written by Judd, Maliar, Maliar and Valero (2014). +nodes=nodes'; % transpose to n_e-by-n_nodes + +%---------------------------------------------------- +% Choose parameter values with a closed-form solution +%---------------------------------------------------- +BETA=.96; GAMMA=1; ALPHA=.3; RHO=.8; DELTA=1; SIGMA=.02; +params=eval(symparams); + +%----------------------------------------------------------------------- +% The closed-form solution for the case GAMMA=1, DELTA=1 for consumption +%----------------------------------------------------------------------- + +g=(1-ALPHA*BETA)*exp(z)*k^ALPHA; + +%--------------------------------------------------------- +% Use the closed-form solution to produce an initial guess +%--------------------------------------------------------- + +% differentiate the closed-form solution up to fourth order +gx=jacobian(g,x); +gxx=jacobian(gx(:),x); +gxxx=jacobian(gxx(:),x); +gxxxx=jacobian(gxxx(:),x); + +% choose some arbitrary state - I use the steady state of the model of +% interest (with DELTA=.1) + +k0=((1/BETA-1+.1)/ALPHA)^(1/(ALPHA-1)); +z0=0; + +x0=[k0;z0]; + +% compute g(x) and its derivatives at x0 + +g0=double(subs(g,x(:),x0)); +gx0=double(subs(gx,x(:),x0)); +gxx0=double(subs(gxx,x(:),x0)); +gxxx0=double(subs(gxxx,x(:),x0)); +gxxxx0=double(subs(gxxxx,x(:),x0)); + +% transform the derivatives into a vector of coefficients + +[ initial_guess ] = derivs2coeffs(model,g0,gx0,gxx0,gxxx0,gxxxx0); + +% this is for order=4. for lower orders include only the relevant +% derivatives, e.g. derivs2coeffs(model,g0,gx0,gxx0) is for second order. + +% define the center of the initial guess (this is the point at which we computed +% the derivatives) + +c0=x0; + +% now we have the initial guess, and we can proceed to solve the model by +% continuation + +%------------------------------------------------------------------------------- +% solve by Taylor projection and change the parameters gradually to the +% required level +%------------------------------------------------------------------------------- +tolX=1e-6; +tolF=1e-6; +maxiter=10; + +[coeffs,model]=tpsolve(initial_guess,x0,model,params,c0,nodes,weights,tolX,tolF,maxiter); + +% Now change the parameters GAMMA and DELTA gradually to their required levels: + +GAMMA_original=GAMMA; +GAMMA_target=2; + +DELTA_original=DELTA; +DELTA_target=.1; + +for h=0:.1:1 % this is the homotopy parameter + GAMMA=(1-h)*GAMMA_original+h*GAMMA_target; + DELTA=(1-h)*DELTA_original+h*DELTA_target; + + disp(['GAMMA=' num2str(GAMMA) ' DELTA=' num2str(DELTA)]) + + params(2)=GAMMA; + params(5)=DELTA; + [coeffs,model]=tpsolve(coeffs,x0,model,params,c0,nodes,weights,tolX,tolF,maxiter); + +end + diff --git a/105/replication_package/examples/rbc/solve_model.m b/105/replication_package/examples/rbc/solve_model.m new file mode 100644 index 0000000000000000000000000000000000000000..f0e4139ed386a775b98a908d71ac61b6b79a88b8 --- /dev/null +++ b/105/replication_package/examples/rbc/solve_model.m @@ -0,0 +1,160 @@ +clear,clc + +%--------------------------------------------------------- +% Add folder 'files' to the search path and load the model +%--------------------------------------------------------- +addpath('files'); +load('model') + +%---------------------------------------------------------------------------- +% Provide nodes and weights for the quadrature that approximates expectations +%---------------------------------------------------------------------------- +n_e=1; % number of shocks. +[n_nodes,nodes,weights] = Monomials_2(n_e,eye(n_e)); % this quadrature function was written by Judd, Maliar, Maliar and Valero (2014). +nodes=nodes'; % transpose to n_e-by-n_nodes + +%---------------------------------- +% Make a vector of parameter values +%---------------------------------- +BETA=.96; GAMMA=2; ALPHA=.3; RHO=.8; DELTA=.1; SIGMA=.02; +params=eval(symparams); + +%---------------------------------------------------------------------- +% Prepare an initial guess - in this case I use a perturbation solution +%---------------------------------------------------------------------- + +% Steady state values + +kss=((1/BETA-1+DELTA)/ALPHA)^(1/(ALPHA-1)); +zss=0; +css=kss^ALPHA-DELTA*kss; + +nxss=[kss;zss]; +nyss=css; + +% Cross moments of the shocks + +M=get_moments(nodes,weights,model.order(2)); + +% Compute the perturbation solution (keep the 4 outputs): + +[derivs,stoch_pert,nonstoch_pert,model]=get_pert(model,params,M,nxss,nyss); + +% Explanation of outputs: +% derivs=structure with the perturbation solution as explained in Levintal +% (2017): "Fifth-Order Perturbation Solution to DSGE Models". +% stoch_pert=the perturbation solution in the form of unique polynomial coefficients. +% nonstoch_pert=same as stoch_pert but without correction for the model volatility (i.e. this is a perturbation solution of a deterministic version of the model) + +%------------------------------------- +% Solve the model by Taylor projection +%------------------------------------- + +x0=nxss; % the approximation point (here we use the steady state, but it could be any arbitrary state) +c0=nxss; % the center of the initial guess + +% tolerance parameters for the Newton solver +tolX=1e-6; +tolF=1e-6; +maxiter=10; + +% model.jacobian='exact'; % this is the default +% model.jacobian='approximate'; % for large models try the approximate jacobian. + +initial_guess=stoch_pert; +[coeffs,model]=tpsolve(initial_guess,x0,model,params,c0,nodes,weights,tolX,tolF,maxiter); + +%------------------------------------------------------------------ +% Compute the residual function and the model variables at point x0 +%------------------------------------------------------------------ + +[R_fun0,g_fun0,Phi_fun0,auxvars0]=residual(coeffs,x0,params,c0,nodes,weights); + +% R_fun0 is the residual function at x0. +% g_fun0 is the control variables at x0, namely, g(x0). +% Phi_fun0 is the function Phi at x0 and each future node, namely, Phi(x0,g(x0),epsp), for each node of the quadrature. +% auxvars0 is the auxiliary functions at x0 and each future node. + +% compute the function g(x) at x0 +y0=evalg(x0,coeffs,c0); + +% compute the function Phi(x,y,epsp) at x0, y0 and epsp0 +epsp0=.02; +xp0=evalPhi(x0,y0,epsp0,params); + +%--------------------------------- +% simulate the model for T periods +%--------------------------------- +T=100; +shocks=randn(1,T+1); % draw shocks + +% preallocate +x_simul=zeros(model.n_x,T+1); +y_simul=zeros(model.n_y,T); +R_simul=zeros(model.n_y,T); + +x_simul(:,1)=x0; + +% option=1; % compute only simulated variables +option=2; % compute model residuals + +for t=1:T + xt=x_simul(:,t); + epsp=shocks(t+1); + + % Option 1 - compute only the simulated variables + if option==1 + yt=evalg(xt,coeffs,c0); + + y_simul(:,t)=yt; + x_simul(:,t+1)=evalPhi(xt,yt,epsp,params); + else + % Option 2 - compute also model residuals + [Rt,yt]=residual(coeffs,xt,params,c0,nodes,weights); + + y_simul(:,t)=yt; + x_simul(:,t+1)=evalPhi(xt,yt,epsp,params); + R_simul(:,t)=Rt; + end +end + +%------------------------------------------- +% Solve the model again at a different state +%------------------------------------------- +% This is useful when the long run domain of the model is far from the +% initial state, so we need to approximate the solution at the long run state +% (e.g. the risky steady state or the mean of the ergodic distribution) +% rather than the steady state. + +x1=x0*1.1; % take some arbitrary state +[coeffs1,model]=tpsolve(coeffs,x1,model,params,c0,nodes,weights,tolX,tolF,maxiter); % solve at x1 + +%----------------------- +% Use a different solver +%----------------------- + +% The function tpsolve uses the Newton method for up to maxiter iterations. If it fails, it +% switches automatically to fsolve for another maxiter iterations. You can +% control the parameters of the second solver by optimoptions. The +% supported solvers are fsolve and lsqnonlin. + +% For example, do one Newton iteration and switch to lsqnonlin: + +x2=x1*1.1; +maxiter=1; % one Newton iteration +OPTIONS = optimoptions('lsqnonlin','TolX',tolX,'TolF',tolF,'MaxIter',10,'Display','iter-detailed'); % 10 more iterations by lsqnonlin + +[coeffs2,model]=tpsolve(coeffs,x2,model,params,c0,nodes,weights,tolX,tolF,maxiter,OPTIONS); + + +% or switch to fsolve: + +maxiter=1; % one Newton iteration +OPTIONS = optimoptions('fsolve','TolX',tolX,'TolF',tolF,'MaxIter',10,'Display','iter-detailed'); % 10 more iterations by fsolve + +[coeffs3,model]=tpsolve(coeffs,x2,model,params,c0,nodes,weights,tolX,tolF,maxiter,OPTIONS); + + + + + diff --git a/105/replication_package/examples/rbc_EZ/prepare_model.m b/105/replication_package/examples/rbc_EZ/prepare_model.m new file mode 100644 index 0000000000000000000000000000000000000000..304c5eafddf3d65bce7e016499ab231474d99eef --- /dev/null +++ b/105/replication_package/examples/rbc_EZ/prepare_model.m @@ -0,0 +1,88 @@ +%------------------------------------------------------------------ +% RBC model with Epstein-Zin preferences +%------------------------------------------------------------------ + +clear,clc + +%----------------------------------------- +% Define symbolic variables and parameters +%----------------------------------------- + +syms logk logkp logc logcp z zp logxi logxip logq logqp epsp real +syms BETA GAMMA PSI ALPHA RHO DELTA SIGMA real + + +%---------------------- +% Substituted variables +%---------------------- + +c=exp(logc); cp=exp(logcp); + +k=exp(logk); kp=exp(logkp); + +xi=exp(logxi); xip=exp(logxip); + +q=exp(logq); + +Vpowerp=(1-BETA)*cp^(1-PSI)+BETA*xip^(1-PSI); % this is Vp^(1-PSI) + +logVp=1/(1-PSI)*log( Vpowerp ); + +Vp=exp(logVp); + +logmp=log(BETA)+PSI*(logc-logcp)+(PSI-GAMMA)*(logVp-logxi); + +mp=exp(logmp); + +%----------------------- +% Equilibrium conditions +%----------------------- +f1=mp*(ALPHA*exp(zp)*kp^(ALPHA-1)+1-DELTA)-1; +f2=xi^(GAMMA-1)*Vp^(1-GAMMA)-1; +f3=mp/q-1; + +f_fun=[f1;f2;f3]; + +%------------------------------------------------------- +% Function Phi (law of motion of log capital and technology) +%------------------------------------------------------- + +Phi_fun=[log(exp(z)*k^ALPHA+(1-DELTA)*k-c); + RHO*z+SIGMA*epsp]; + +%-------------------------- +% Vector of state variables +%-------------------------- +x=[logk,z]; % current period +xp=[logkp,zp]; % future period + +%---------------------------- +% Vector of control variables +%---------------------------- +y=[logc,logxi,logq]; % current period +yp=[logcp,logxip,logqp]; % future period + +%----------------- +% Vector of shocks +%----------------- +shocks=[epsp]; + +%--------------------- +% Vector of parameters +%--------------------- +symparams=[BETA,GAMMA,PSI,ALPHA,RHO,DELTA,SIGMA]; + +%-------------------- +% Approximation order +%-------------------- +order=3; % fourth order is the maximum possible + +%---------------- +% Call prepare_tp +%---------------- +model=prepare_tp(f_fun,Phi_fun,yp,y,xp,x,shocks,symparams,order); + +%----------- +% Save model +%----------- +save('model') % you will need this later diff --git a/105/replication_package/examples/rbc_EZ/prepare_model_auxiliary_functions.m b/105/replication_package/examples/rbc_EZ/prepare_model_auxiliary_functions.m new file mode 100644 index 0000000000000000000000000000000000000000..59f127fed7187de7e8614246d682b7815fe28549 --- /dev/null +++ b/105/replication_package/examples/rbc_EZ/prepare_model_auxiliary_functions.m @@ -0,0 +1,106 @@ +%------------------------------------------------------------------ +% RBC model with Epstein-Zin preferences +%------------------------------------------------------------------ + +clear,clc + +%----------------------------------------- +% Define symbolic variables and parameters +%----------------------------------------- + +syms logk logkp logc logcp z zp logxi logxip logq logqp epsp real +syms BETA GAMMA PSI ALPHA RHO DELTA SIGMA real + + +%----------------------------------------------------- +% Substituted variables defined by auxiliary functions +%----------------------------------------------------- + +syms c cp k kp xi xip q Vpowerp logVp Vp logmp mp real + +c_=exp(logc); cp_=exp(logcp); + +k_=exp(logk); kp_=exp(logkp); + +xi_=exp(logxi); xip_=exp(logxip); + +q_=exp(logq); + +Vpowerp_=(1-BETA)*cp^(1-PSI)+BETA*xip^(1-PSI); % this is Vp^(1-PSI) + +logVp_=1/(1-PSI)*log( Vpowerp ); + +Vp_=exp(logVp); + +logmp_=log(BETA)+PSI*(logc-logcp)+(PSI-GAMMA)*(logVp-logxi); + +mp_=exp(logmp); + +%----------------------- +% Equilibrium conditions +%----------------------- +f1=mp*(ALPHA*exp(zp)*kp^(ALPHA-1)+1-DELTA)-1; +f2=xi^(GAMMA-1)*Vp^(1-GAMMA)-1; +f3=mp/q-1; + +f_fun=[f1;f2;f3]; + +%------------------------------------------------------- +% Function Phi (law of motion of log capital and technology) +%------------------------------------------------------- + +Phi_fun=[log(exp(z)*k^ALPHA+(1-DELTA)*k-c); + RHO*z+SIGMA*epsp]; + +%-------------------------- +% Vector of state variables +%-------------------------- +x=[logk,z]; % current period +xp=[logkp,zp]; % future period + +%---------------------------- +% Vector of control variables +%---------------------------- +y=[logc,logxi,logq]; % current period +yp=[logcp,logxip,logqp]; % future period + +%----------------- +% Vector of shocks +%----------------- +shocks=[epsp]; + +%--------------------- +% Vector of parameters +%--------------------- +symparams=[BETA,GAMMA,PSI,ALPHA,RHO,DELTA,SIGMA]; + +%------------------------------------------ +% Collect auxiliary functions and variables +%------------------------------------------ + +allvars=who; +auxfuns=[]; +auxvars=[]; +for i=1:length(allvars) + if strcmp(allvars{i}(end),'_') + eval(['tempfun=' allvars{i} ';']) + eval(['tempvar=' allvars{i}(1:end-1) ';']) + auxfuns=[auxfuns(:);tempfun(:)]; + auxvars=[auxvars(:);tempvar(:)]; + end +end + +%-------------------- +% Approximation order +%-------------------- +order=4; % fourth order is the maximum possible + +%---------------- +% Call prepare_tp +%---------------- +model=prepare_tp(f_fun,Phi_fun,yp,y,xp,x,shocks,symparams,order,auxfuns,auxvars); + +%----------- +% Save model +%----------- +save('model') % you will need this later diff --git a/105/replication_package/examples/rbc_EZ/solve_model.m b/105/replication_package/examples/rbc_EZ/solve_model.m new file mode 100644 index 0000000000000000000000000000000000000000..7fb77ea16892b0353e82ec2e91ce281984046943 --- /dev/null +++ b/105/replication_package/examples/rbc_EZ/solve_model.m @@ -0,0 +1,104 @@ +clear,clc + +%--------------------------------------------------------- +% Add folder 'files' to the search path and load the model +%--------------------------------------------------------- +addpath('files'); +load('model') + +%---------------------------------------------------------------------------- +% Provide nodes and weights for the quadrature that approximates expectations +%---------------------------------------------------------------------------- +n_e=length(shocks); % number of shocks. +[n_nodes,nodes,weights] = Monomials_2(n_e,eye(n_e)); % this quadrature function was written by Judd, Maliar, Maliar and Valero (2014). +nodes=nodes'; % transpose to n_e-by-n_nodes + +%---------------------------------- +% Make a vector of parameter values +%---------------------------------- +BETA=.96; GAMMA=2; PSI=1.5; ALPHA=.3; RHO=.8; DELTA=.1; SIGMA=.08; +params=eval(symparams); + +%---------------------------------------------------------------------- +% Prepare an initial guess - in this case I use a perturbation solution +%---------------------------------------------------------------------- + +% Steady state values + +kss=((1/BETA-1+DELTA)/ALPHA)^(1/(ALPHA-1)); +zss=0; +css=kss^ALPHA-DELTA*kss; +vss=css; +xiss=vss; +qss=BETA; + +nxss=[log(kss);zss]; +nyss=[log(css);log(xiss);log(qss)]; + +% Cross moments of the shocks + +M=get_moments(nodes,weights,model.order(2)); + +% Compute the perturbation solution (keep the 4 outputs): + +[derivs,stoch_pert,nonstoch_pert,model]=get_pert(model,params,M,nxss,nyss); + +% Explanation of outputs: +% derivs=structure with the perturbation solution as explained in Levintal +% (2017): "Fifth-Order Perturbation Solution to DSGE Models". +% stoch_pert=the perturbation solution in the form of unique polynomial coefficients. +% nonstoch_pert=same as stoch_pert but without correction for the model volatility (i.e. this is a perturbation solution of a deterministic version of the model) + +%------------------------------------- +% Solve the model by Taylor projection +%------------------------------------- + +x0=nxss; % the approximation point (here we use the steady state, but it could be any arbitrary state) +c0=nxss; % the center of the initial guess + +% tolerance parameters for the Newton solver +tolX=1e-6; +tolF=1e-6; +maxiter=10; + +% model.jacobian='exact'; % this is the default +% model.jacobian='approximate'; % for large models try the approximate jacobian. + +initial_guess=stoch_pert; +[coeffs,model]=tpsolve(initial_guess,x0,model,params,c0,nodes,weights,tolX,tolF,maxiter); + +%------------------------------------------------------------------ +% Compute the residual function and the model variables at point x0 +%------------------------------------------------------------------ + +[R_fun0,g_fun0,Phi_fun0,auxvars0]=residual(coeffs,x0,params,c0,nodes,weights); + +%------------------------ +% Check the interest rate +%------------------------ + +logq=g_fun0(3); +Rf=exp(-logq)-1 + +%---------------------------------------------------------------------------- +% Increase risk aversion (gradually) and see how the interest rate falls +%---------------------------------------------------------------------------- + +GAMMAvec=2:4:82; + +Rfvec=zeros(size(GAMMAvec)); + +i=0; +for GAMMA=GAMMAvec + i=i+1; + params(2)=GAMMA; + [coeffs,model]=tpsolve(coeffs,x0,model,params,c0,nodes,weights,tolX,tolF,maxiter); + [R_fun0,g_fun0,Phi_fun0,auxvars0]=residual(coeffs,x0,params,c0,nodes,weights); + logq=g_fun0(3); + Rfvec(i)=exp(-logq)-1; +end + + +plot(GAMMAvec,Rfvec) +xlabel('Risk aversion (GAMMA)') +ylabel('Risk-free interest rate (Rf)') \ No newline at end of file diff --git a/105/replication_package/examples/rbc_MS_parameters/prepare_model.m b/105/replication_package/examples/rbc_MS_parameters/prepare_model.m new file mode 100644 index 0000000000000000000000000000000000000000..88e3c30acb93c0961d4bb1d1d100697c91d2d739 --- /dev/null +++ b/105/replication_package/examples/rbc_MS_parameters/prepare_model.m @@ -0,0 +1,75 @@ +%------------------------------------------- +% RBC model with Markov-switching parameters +%------------------------------------------- +% The parameters that depend on the regime are the discount +% factor and the depreciation rate. +% There are 2 regimes. + +clear,clc + +%----------------------------------------- +% Define symbolic variables and parameters +%----------------------------------------- + +syms k kp c cp z zp epsp real +syms BETA BETAp GAMMA ALPHA RHO DELTA DELTAp SIGMA real + +%----------------------------- +% Function f (Euler condition) +%----------------------------- +f_fun=BETA*(c/cp)^GAMMA*(ALPHA*exp(zp)*kp^(ALPHA-1)+1-DELTAp)-1; % note the use of future depreciation rate DELTAp + +%------------------------------------------------------- +% Function Phi (law of motion of capital and technology) +%------------------------------------------------------- + +Phi_fun=[exp(z)*k^ALPHA+(1-DELTA)*k-c; % here we use the current depreciation rate DELTA + RHO*z+SIGMA*epsp]; + +%-------------------------- +% Vector of state variables +%-------------------------- +x=[k,z]; % current period +xp=[kp,zp]; % future period + +%---------------------------- +% Vector of control variables +%---------------------------- +y=[c]; % current period +yp=[cp]; % future period + +%----------------- +% Vector of shocks +%----------------- +shocks=[epsp]; + +%--------------------------- +% Vector of fixed parameters +%--------------------------- +symparams=[GAMMA,ALPHA,RHO,SIGMA]; + +%-------------------------------------- +% Vector of Markov-switching parameters +%-------------------------------------- +chi=[BETA,DELTA]; % current period +chip=[BETAp,DELTAp]; % next period + +%-------------------- +% Approximation order +%-------------------- +order=4; % fourth order is the maximum possible + +%------------------ +% number of regimes +%------------------ +n_regimes=2; + +%---------------- +% Call prepare_tp +%---------------- +model=prepare_tp(f_fun,Phi_fun,yp,y,xp,x,shocks,chip,chi,symparams,order,n_regimes); + +% % if you use auxiliary functions and variables, use the following syntax: +% model=prepare_tp(f_fun,Phi_fun,yp,y,xp,x,shocks,chip,chi,symparams,order,n_regimes,auxfuns,auxvars); + +save('model') % you will need this later diff --git a/105/replication_package/examples/rbc_MS_parameters/solve_model.m b/105/replication_package/examples/rbc_MS_parameters/solve_model.m new file mode 100644 index 0000000000000000000000000000000000000000..c0fdd1eb899dcbea2dec15d7e86efb0513885c19 --- /dev/null +++ b/105/replication_package/examples/rbc_MS_parameters/solve_model.m @@ -0,0 +1,191 @@ +clear,clc + +%--------------------------------------------------------- +% Add folder 'files' to the search path and load the model +%--------------------------------------------------------- +addpath('files'); +load('model') + +%---------------------------------------------------------------------------- +% Provide nodes and weights for the quadrature that approximates expectations +%---------------------------------------------------------------------------- +n_e=1; % number of shocks. +[n_nodes,nodes,weights] = Monomials_2(n_e,eye(n_e)); % this quadrature function was written by Judd, Maliar, Maliar and Valero (2014). +nodes=nodes'; % transpose to n_e-by-n_nodes + +%-------------------------------------------- +% parameter values (for the fixed parameters) +%-------------------------------------------- +GAMMA=2; ALPHA=.3; RHO=.8; SIGMA=.02; +params=eval(symparams); + +%-------------------------------------------------------------------- +% Start with a perturbation solution for the case of fixed parameters +%-------------------------------------------------------------------- +BETA=.96; DELTA=.1; +% Steady state values +kss=((1/BETA-1+DELTA)/ALPHA)^(1/(ALPHA-1)); +zss=0; +css=kss^ALPHA-DELTA*kss; + +nxss=[kss;zss]; +nyss=css; + +pert_order=model.order(2); + +M=get_moments(nodes,weights,pert_order); + +% Get a perturbation solution for the case of fixed parameters. You need to +% provide the fixed value of the ms parameters (the variable chi_fixed) + +chi_fixed=eval(chi); + +[derivs,stoch_pert,nonstoch_pert,model]=get_pert(model,params,M,nxss,nyss,chi_fixed); + +%--------------------------------------- +% Proceed to Markov-switching parameters +%--------------------------------------- + +% The values of the parameters in each regime (there are 2 regimes) +msparams=[BETA-.02,BETA+.02;% BETA varies across regimes + DELTA-.05,DELTA+.05]; % DELTA varies across regimes + +transition=[.9,.1; + .8,.2]; + +initial_guess=stoch_pert; % the initial guess has n_regimes columns (one for each regime). + +x0=nxss; % evaluate the system at the steady state +c0=nxss; % the center of the initial guess is the steady state. + +tolX=1e-6; +tolF=1e-6; +maxiter=10; +[coeffs,model]=tpsolve(initial_guess,x0,model,params,msparams,transition,c0,nodes,weights,tolX,tolF,maxiter); + + +% compute the model residuals + +[R_funMS,g_funMS,Phi_funMS,aux_funMS]=residual(coeffs,x0,params,msparams,transition,c0,nodes,weights); + +% R_funMS is a n_y-by-n_regimes matrix of the model residuals. +% g_funMS is a n_y-by-n_regimes matrix of the endogenous control variables for each current regime. +% Phi_funMS is a n_x-by-n_nodes-by-n_regimes-by-n_regimes array of next period state variables for each future node and current and future regimes. +% aux_funMS is a similar array of the auxiliary functions (for each future +% node and current/future regimes) + +% To compute the model residuals only for a specific regime, add the +% required regime as the last argument + +specific_regime=1; + +[R_specific,g_specific,Phi_specific,auxvars_specific]=residual(coeffs,x0,params,msparams,transition,c0,nodes,weights,specific_regime); + +% Compute the function g given the state x0 and the regime specific_regime +g_fun=evalg(x0,specific_regime,coeffs,c0); + +% Compute the function Phi given the state x0, the control y0, the current +% and future regimes and the future shock epsp +y0=g_fun; +current_regime=1; +future_regime=2; +epsp=0; +Phi_fun=evalPhi(x0,y0,epsp,future_regime,current_regime,params,msparams); + + +%--------------------------------- +% simulate the model for T periods +%--------------------------------- + +T=10000; +shocks=randn(1,T+1); +rshock=rand(1,T+1); % to determine the regime + +x_simul=zeros(model.n_x,T+1); +regime_simul=zeros(1,T+1); +y_simul=zeros(model.n_y,T); +R_simul=zeros(model.n_y,T); + +coeffs=reshape(coeffs,[],model.n_regimes); + +x_simul(:,1)=x0; +regime_simul(1)=1; + +% option=1; % compute only simulated variables +option=2; % compute model residuals + +for t=1:T + + xt=x_simul(:,t); % current state + regimet=regime_simul(t); % current regime + + epsp=shocks(t+1); % future shock + % future regime + regimet_next=1+model.n_regimes-sum(double(logical((rshock(t+1)-cumsum(transition(regimet,:)))<0))); + + % Option 1 - compute only the simulated variables + if option==1 + yt=evalg(xt,regimet,coeffs,c0); + + y_simul(:,t)=yt; + x_simul(:,t+1)=evalPhi(xt,yt,epsp,regimet_next,regimet,params,msparams); + regime_simul(t+1)=regimet_next; + else + % Option 2 - compute also model residuals + [Rt,yt]=residual(coeffs,xt,params,msparams,transition,c0,nodes,weights,regimet); + + y_simul(:,t)=yt; + x_simul(:,t+1)=evalPhi(xt,yt,epsp,regimet_next,regimet,params,msparams); + regime_simul(t+1)=regimet_next; + R_simul(:,t)=Rt; + end +end + +% Note that the simulated capital level is considerably different than the +% initial approximation point that we used. To improve accuracy, we can solve the +% model at the mean of the ergodic distribution. + +meank=mean(x_simul(1,:)); + +ergodic_x0=[meank;0]; % solve at the mean of the ergodic distribution + +[coeffs,model]=tpsolve(coeffs,ergodic_x0,model,params,msparams,transition,c0,nodes,weights,tolX,tolF,maxiter); + +% simulate again and store residuals in R_simul2 + +x_simul(:,1)=ergodic_x0; +regime_simul(1)=1; +R_simul2=R_simul; +for t=1:T + xt=x_simul(:,t); + regimet=regime_simul(t); + + epsp=shocks(t+1); + % future regime + regimet_next=1+model.n_regimes-sum(double(logical((rshock(t+1)-cumsum(transition(regimet,:)))<0))); + + % Option 1 - compute only the simulated variables + if option==1 + yt=evalg(xt,regimet,coeffs,c0); + + y_simul(:,t)=yt; + x_simul(:,t+1)=evalPhi(xt,yt,epsp,regimet_next,regimet,params,msparams); + regime_simul(t+1)=regimet_next; + else + % Option 2 - compute also model residuals + [Rt,yt]=residual(coeffs,xt,params,msparams,transition,c0,nodes,weights,regimet); + + y_simul(:,t)=yt; + x_simul(:,t+1)=evalPhi(xt,yt,epsp,regimet_next,regimet,params,msparams); + regime_simul(t+1)=regimet_next; + R_simul2(:,t)=Rt; + end +end + +% compare mean errors for the two simulations + +mean(abs(R_simul)) + +mean(abs(R_simul2)) + +% the second simulation is more accurate \ No newline at end of file diff --git a/105/replication_package/examples/rbc_disasters/prepare_model.m b/105/replication_package/examples/rbc_disasters/prepare_model.m new file mode 100644 index 0000000000000000000000000000000000000000..ba104b0cba365c4723a6d8e065f5010332851529 --- /dev/null +++ b/105/replication_package/examples/rbc_disasters/prepare_model.m @@ -0,0 +1,111 @@ +%---------------------------------------- +% RBC with Markov shocks (rare disasters) +%---------------------------------------- + +clear,clc + +%----------------------------------------- +% Define symbolic variables and parameters +%----------------------------------------- + +syms logc logcp logk logkp z zp epsp d dp real +syms BETA GAMMA ALPHA RHO DELTA SIGMA PHI real + +%--------------------------- +% Define auxiliary functions +%--------------------------- + +syms k kp c cp loga a logap real +c_=exp(logc); +cp_=exp(logcp); +k_=exp(logk); +kp_=exp(logkp); + +loga_=z-PHI*d; % log technology in current period +a_=exp(loga); + +logap_=zp-PHI*dp; % log technology in next period + +% Log and level of future mpk. +syms mpkp logmpkp real +logmpkp_=log(ALPHA)+logap+(ALPHA-1)*logkp; +mpkp_=exp(logmpkp); + +% Log and level of stochastic discount factor. +syms mp logmp real +logmp_=log(BETA)+GAMMA*(logc-logcp); +mp_=exp(logmp); + +%----------------------------- +% Function f (Euler condition) +%----------------------------- +f_fun=mp*(mpkp+1-DELTA)-1; + +%---------------------------------------------------------- +% Function Phi (law of motion of log capital and technology) +%---------------------------------------------------------- + +Phi_fun=[log(a*k^ALPHA+(1-DELTA)*k-c); + RHO*z+SIGMA*epsp]; + +%-------------------------- +% Vector of state variables +%-------------------------- +x=[logk,z]; % current period +xp=[logkp,zp]; % future period + +%---------------------------- +% Vector of control variables +%---------------------------- +y=[logc]; % current period +yp=[logcp]; % future period + +%--------------------- +% Vector of iid shocks +%--------------------- +shocks=[epsp]; + +%------------------------ +% Vector of Markov shocks +%------------------------ + +markov_shocks=d; % current period +markov_shocksp=dp; % future period + +n_states=2; % number of Markov states + +%--------------------- +% Vector of parameters +%--------------------- +symparams=[BETA,GAMMA,ALPHA,RHO,DELTA,SIGMA,PHI]; + +%----------------------------------------------------------- +% Vectors of auxiliary functions and corresponding variables +%----------------------------------------------------------- + +allvars=who; +auxfuns=[]; +auxvars=[]; +for i=1:length(allvars) + if strcmp(allvars{i}(end),'_') + eval(['tempfun=' allvars{i} ';']) + eval(['tempvar=' allvars{i}(1:end-1) ';']) + auxfuns=[auxfuns(:);tempfun(:)]; + auxvars=[auxvars(:);tempvar(:)]; + end +end + +%-------------------- +% Approximation order +%-------------------- +order=3; % fourth order is the maximum possible + +%---------------- +% Call prepare_tp +%---------------- +model=prepare_tp(f_fun,Phi_fun,yp,y,xp,x,shocks,markov_shocksp,markov_shocks,symparams,order,n_states,auxfuns,auxvars); + +%----------- +% Save model +%----------- +save('model') % you will need this later diff --git a/105/replication_package/examples/rbc_disasters/solve_model.m b/105/replication_package/examples/rbc_disasters/solve_model.m new file mode 100644 index 0000000000000000000000000000000000000000..4dc81507cbff2e03cfdc41a9d68e3972cc61f8c5 --- /dev/null +++ b/105/replication_package/examples/rbc_disasters/solve_model.m @@ -0,0 +1,127 @@ +clear,clc + +%--------------------------------------------------------- +% Add folder 'files' to the search path and load the model +%--------------------------------------------------------- +addpath('files'); +load('model') + +%---------------------------------------------------------------------------- +% Provide nodes and weights for the quadrature that approximates expectations +%---------------------------------------------------------------------------- +n_e=model.n_e; % number of shocks. +[n_nodes,nodes,weights] = Monomials_2(n_e,eye(n_e)); % this quadrature function was written by Judd, Maliar, Maliar and Valero (2014). +nodes=nodes'; % transpose to n_e-by-n_nodes + +%---------------------------------- +% Make a vector of parameter values +%---------------------------------- +BETA=.96; GAMMA=2; ALPHA=.3; RHO=.8; DELTA=.1; SIGMA=.02; PHI=0.1; +params=eval(symparams); + +%------------------ +% transition matrix +%------------------ + +transition=[.95,.05; + .5,.5]; + +%-------------------------------------------------------------------------- +% Prepare an initial guess - perturbation solution of RBC without disasters +%-------------------------------------------------------------------------- + +fixed_markov_values=0; % start with a fixed value for the disaster shock (disaster shock is 0 in all states) + +% Steady state values + +kss=((1/BETA-1+DELTA)/ALPHA)^(1/(ALPHA-1)); +zss=0; +css=kss^ALPHA-DELTA*kss; + +nxss=[log(kss);zss]; +nyss=log(css); + +% Cross moments of the shocks + +M=get_moments(nodes,weights,model.order(2)); + +% Compute the perturbation solution + +[derivs,stoch_pert,nonstoch_pert,model]=get_pert(model,params,M,nxss,nyss,fixed_markov_values); + +% the variables stoch_pert and nonstoch_pert have two columns, corresponding to the two Markov states. + +%------------------------------------- +% Taylor projection with Markov shocks +%------------------------------------- + +markov_values=[0,1]; % now the values of the Markov shock depend on the Markov state + +x0=nxss; % the approximation point +c0=nxss; % the center of the initial guess + +% tolerance parameters for the Newton solver +tolX=1e-6; +tolF=1e-6; +maxiter=10; + +% model.jacobian='exact'; % this is the default +% model.jacobian='approximate'; % for large models try the approximate jacobian. + +initial_guess=stoch_pert; +[coeffs,model]=tpsolve(initial_guess,x0,model,params,markov_values,transition,c0,nodes,weights,tolX,tolF,maxiter); + +%------------------------------------------------------------------------------------- +% Compute the residual function and the model variables at point x0 for Markov state s +%------------------------------------------------------------------------------------- + +s=1; % Markov state 1 +[R_fun1,g_fun1,Phi_fun1,auxvars1]=residual(coeffs,x0,params,markov_values,transition,c0,nodes,weights,s); +c1=exp(g_fun1); % consumption in normal state +inv1=exp(Phi_fun1(1,1))-exp(x0(1))*(1-DELTA); + + +s=2; % Markov state 2 +[R_fun2,g_fun2,Phi_fun2,auxvars2]=residual(coeffs,x0,params,markov_values,transition,c0,nodes,weights,s); +c2=exp(g_fun2); % consumption in normal state +inv2=exp(Phi_fun2(1,1))-exp(x0(1))*(1-DELTA); + +c2/c1-1 % fall in consumption is smaller than fall in output +inv2/inv1-1 % fall in investment is larger than fall in output + + +%------------------- +% Simulate the model +%------------------- + +T=1000; +shocks=randn(1,T+1); % draw shocks + +% simulate a Markov chain from the transition matrix +ushock=rand(1,T+1); % draw shocks from a uniform distribution to determine the Markov state +Markov_state=zeros(1,T+1); +Markov_state(1)=1; % start at state 1 +for t=2:T+1 + Markov_state(t)=1+(ushock(t)>transition(Markov_state(t-1),1)); % state in period t, given the state in t-1 +end + +% preallocate +x_simul=zeros(model.n_x,T+1); +y_simul=zeros(model.n_y,T); +R_simul=zeros(model.n_y,T); + +x_simul(:,1)=x0; + +for t=1:T + xt=x_simul(:,t); + st=Markov_state(t); + + [Rt,yt]=residual(coeffs,xt,params,markov_values,transition,c0,nodes,weights,st); + + epsp=shocks(t+1); % future iid shock + stp=Markov_state(t+1); % future Markov shock + + y_simul(:,t)=yt; + x_simul(:,t+1)=evalPhi(xt,yt,epsp,stp,st,params,markov_values); + R_simul(:,t)=Rt; +end diff --git a/105/replication_package/make_Table_4.do b/105/replication_package/make_Table_4.do new file mode 100644 index 0000000000000000000000000000000000000000..b98af0ed730ee07dd4c3e52a70835a519001d743 --- /dev/null +++ b/105/replication_package/make_Table_4.do @@ -0,0 +1,87 @@ +****************************************************************************************** +* Replicate Table 4 of "Safe Assets" by Barro, Fernandez-Villaverde, Levintal and Mollerus +****************************************************************************************** + +clear all + +clear mata +set mem 500m +set maxvar 32767 +set more off +cap log close + +clear +use rscfp2019 // can be downloaded from https://www.federalreserve.gov/econres/files/scfp2019s.zip + +gen stockfund = stmutf +gen stocks_indirect = equity - stocks - stockfund /* the variable equity is generated by SCF to measure all stock holdings, including indirect holdings of stocks. */ +gen realestate_net = houses - mrthel + oresre - resdbt +nnresre +gen otherphysical = vehic + othnfin +gen allequity = equity + bus + +* percentiles + +_pctile networth [aweight = wgt], p(50,75,90,95,99) + +local p50 = r(r1) +local p75 = r(r2) +local p90 = r(r3) +local p95 = r(r4) +local p99 = r(r5) + +gen pctile = 0 + +replace pctile = 1 if networth<=`p50' +replace pctile = 2 if networth>`p50' & networth<=`p75' +replace pctile = 3 if networth>`p75' & networth<=`p90' +replace pctile = 4 if networth>`p90' & networth<=`p95' +replace pctile = 5 if networth>`p95' & networth<=`p99' +replace pctile = 6 if networth>`p99' + +foreach var in "networth" "allequity" "stocks" "stockfund" "bus" "stocks_indirect" "realestate_net" "othnfin" "vehic" { + di "`var'" + + gen sum_`var' = 0 + gen share_`var' = 0 + gen port_`var' = 0 + + foreach x in 1 2 3 4 5 6 { + sum `var' [aweight = wgt] if pctile==`x' + replace sum_`var' = r(sum) if _n==`x' + } + + * total population + sum `var' [aweight = wgt] + replace sum_`var' = r(sum) if _n==7 + + * bottom 90 + sum `var' [aweight = wgt] if pctile<=3 + replace sum_`var' = r(sum) if _n==8 + + * p90-p95 + sum `var' [aweight = wgt] if pctile==4 + replace sum_`var' = r(sum) if _n==9 + + * top 5 + sum `var' [aweight = wgt] if pctile>=5 + replace sum_`var' = r(sum) if _n==10 + + * top 1 + sum `var' [aweight = wgt] if pctile==6 + replace sum_`var' = r(sum) if _n==11 + + * share in total population + replace share_`var' = sum_`var'/sum_`var'[7] + + } + +keep share* +keep if _n<=11 + +quietly log using Tables_1_to_4.smcl, append + +* Table 4 (transposed) + +list share_networth share_allequity share_stocks share_stockfund share_bus share_stocks_indirect share_realestate_net share_othnfin share_vehic if _n>=8, clean noobs + +log close diff --git a/105/replication_package/make_Tables_1_to_3_Figures_1_and_2.do b/105/replication_package/make_Tables_1_to_3_Figures_1_and_2.do new file mode 100644 index 0000000000000000000000000000000000000000..21cac499024309273da1f7652826473cfb84ce1c --- /dev/null +++ b/105/replication_package/make_Tables_1_to_3_Figures_1_and_2.do @@ -0,0 +1,217 @@ +************************************************************************************************************* +* Replicate Tables 1-3 and Figures 1-2 of "Safe Assets" by Barro, Fernandez-Villaverde, Levintal and Mollerus +************************************************************************************************************* + +clear + +graph drop _all +set matsize 800 +clear mata +set mem 500m +set more off + +run Make_OECD_data + +use OECD_data // this file is generated by Make_OECD_data.do + + +**** +gen fin_safe=fin_dep+fin_loan+fin_mmf+fin_secur +gen cb_safe=cb_dep+cb_loan+cb_mmf+cb_secur +gen gov_safe=gov_dep+gov_loan+gov_mmf+gov_secur + +gen gov_secur_safe=gov_secur/gov_safe +gen gov_loan_safe=gov_loan/gov_safe +gen gov_dep_safe=gov_dep/gov_safe +gen gov_mmf_safe=gov_mmf/gov_safe + +gen new_total=totliab_Households+totliab_nonFinancials+totliab_Financials+totliab_Gov +replace new_total=totliab_Total + +gen fin_share=fin_safe/new_total +gen gov_share=gov_safe/new_total +gen cb_share=cb_safe/new_total + +gen finexcb_share=fin_share-cb_share +gen govcb_share=gov_share+cb_share + +gen dep_share=fin_dep/new_total + +gen share=fin_share+gov_share + +gen asset_gdp=new_total/GDP + +decode country, g(country_name) + +drop if country_name=="Luxembourg" +drop if country_name=="Russia" +drop if country_name=="New Zealand" +drop if country_name=="Colombia" + +log using Tables_1_to_4, replace s + +*** Table 1 + + +list country_name share gov_share cb_share finexcb_share asset_gdp if year==2015, clean noobs + +* means + +sum share gov_share cb_share finexcb_share asset_gdp if year==2015 + +quietly log off + + +bysort year: egen worldassets=sum(totliab_TotalUSD) +gen assetweight=totliab_TotalUSD/worldassets + +quietly log on + +*asset weighted means + +sum share gov_share cb_share finexcb_share asset_gdp if year==2015 [iweight = assetweight] + +quietly log off + +* subsample of countries with bond return data + +gen subsample = 0 + +foreach x in "Belgium" "Canada" "Denmark" "Finland" "France" "Germany" "Italy" "Japan" "Netherlands" "Norway" /* +*/ "Portugal" "Spain" "Sweden" "Switzerland" "United Kingdom" "United States" { + replace subsample = 1 if country_name=="`x'" + } + +quietly log on + +* subsample of 16 countries with bond return data + +sum share gov_share cb_share finexcb_share asset_gdp if year==2015 & subsample==1 [iweight = assetweight] + +quietly log off + +*** Table 2 +gen gov_bonds_safe=gov_secur/gov_safe +gen gov_deposits_safe=(gov_dep+gov_loan)/gov_safe + +gen cb_bonds_safe=cb_secur/cb_safe +gen cb_deposits_safe=(cb_dep+cb_loan)/cb_safe + +gen fin_bonds_safe=fin_secur/fin_safe +gen fin_deposits_safe=(fin_dep+fin_loan)/fin_safe +gen fin_mmf_safe = fin_mmf/fin_safe + +gen finexcb_safe = fin_safe - cb_safe + +gen finexcb_bonds_safe = (fin_secur-cb_secur)/finexcb_safe +gen finexcb_deposits_safe = (fin_loan+fin_dep-cb_loan-cb_dep)/finexcb_safe +gen finexcb_mmfunds_safe = (fin_mmf-cb_mmf)/finexcb_safe + +sort country year + +quietly log on + +* Table 2 + +list country gov_bonds_safe gov_deposits_safe cb_bonds_safe cb_deposits_safe finexcb_bonds_safe finexcb_deposits_safe finexcb_mmfunds_safe if year==2015, clean noobs + +quietly log off + +*** Table 3 + +gen finexcb_shareNonUS=fin_shareNonUS-cb_shareNonUS +gen finexcb_shareWorld=fin_shareWorld-cb_shareWorld +gen govcb_shareNonUS=gov_shareNonUS+cb_shareNonUS +gen govcb_shareWorld=gov_shareWorld+cb_shareWorld + +quietly log on + +* Table 3 + +* US +reg finexcb_share govcb_share if country_name=="United States" +sum year if e(sample) + +* Non-US + +reg finexcb_shareNonUS govcb_shareNonUS if country_name=="United States" +sum year if e(sample) + +* All OECD + +reg finexcb_shareWorld govcb_shareWorld if country_name=="United States" +sum year if e(sample) + +* OECD - balanced panel with fixed effects +xtreg finexcb_share govcb_share if OECD==1 & year<=2017 & year>=1995, fe +sum year if e(sample) + +* OECD - unbalanced panel with fixed effects +xtreg finexcb_share govcb_share if OECD==1, fe +sum year if e(sample) + +quietly log close + +*** Figure 1 - safe asset share for US and non-US + +label var share "safe asset share (US)" +label var gov_share "gov share (US)" + +label var cb_share "central bank share (US)" + +label var shareNonUS "safe asset share (non US)" + +label var gov_shareNonUS "gov share (non US)" +label var cb_shareNonUS "central bank share (non US)" + +label var shareWorld "safe asset share (All)" +label var gov_shareWorld "gov share (All)" +label var cb_shareWorld "central bank share (All)" + +label var share "U.S." +label var shareNonUS "Other OECD countries" +label var shareWorld "All OECD countries" + +*twoway (line share shareNonUS year ) if country_name=="United States", ylabel(0 .1 .2 .3 .4 .5) xlabel(1950 1960 1970 1980 1990 2000 2010 2018) name(Figure1) +twoway (line share year, lcolor(black)) (line shareNonUS year, lcolor(black) lpattern(dash)) if country_name=="United States", ylabel(0 .1 .2 .3 .4 .5) xlabel(1950 1960 1970 1980 1990 2000 2010 2018) name(Figure1) + +graph export "Figure1.emf", as(emf) replace name(Figure1) + + +*** Figure 2.a - public and private safe assets - US + +label var gov_share "Gov (US)" +label var gov_shareNonUS "Gov (non US)" +label var gov_shareWorld "Gov (All)" + +label var cb_share "CB (US)" +label var cb_shareNonUS "CB (non US)" +label var cb_shareWorld "CB (All)" + +label var finexcb_share "Financial (US)" +label var finexcb_shareNonUS "Financial (non US)" +label var finexcb_shareWorld "Financial (All)" + +gen public_share = gov_share + cb_share +label var public_share "Public safe assets" +gen private_share = finexcb_share +label var private_share "Private safe assets" + +gen public_shareNonUS = gov_shareNonUS + cb_shareNonUS +label var public_shareNonUS "Public safe assets" +gen private_shareNonUS = finexcb_shareNonUS +label var private_shareNonUS "Private safe assets" + +label var share "Total safe assets" +label var shareNonUS "Total safe assets" +twoway (line share year, lcolor(black) ) (line private_share year, lcolor(black) lpattern(dash) ) (line public_share year, lcolor(black) lpattern(dot) lwidth(thick) ) if country_name=="United States" , ylabel(0 .1 .2 .3 .4 .5) xlabel(1950 1960 1970 1980 1990 2000 2010 2018) title("A. U.S. - Public, Private and Total Safe Assets") subtitle("(as shares of Total Assets)") name(Figure2a) + +graph export "Figure2a.emf", as(emf) replace name(Figure2a) + +*** Figure 2.b - public and private safe assets - non-US + +twoway (line shareNonUS year, lcolor(black) ) (line private_shareNonUS year, lcolor(black) lpattern(dash) ) (line public_shareNonUS year, lcolor(black) lpattern(dot) lwidth(thick) ) if country_name=="United States" && year>=1995, ylabel(0 .1 .2 .3 .4 .5) xlabel(1995 2000 2005 2010 2015) title("B. Non-U.S. Countries - Public, Private and Total Safe Assets") subtitle("(as shares of Total Assets)") name(Figure2b) + +graph export "Figure2b.emf", as(emf) replace name(Figure2b) + +graph drop _all diff --git a/105/replication_package/scfp2019excel.zip b/105/replication_package/scfp2019excel.zip new file mode 100644 index 0000000000000000000000000000000000000000..1883a1fcbacf0b109f19388b156bf233e6dc5d80 --- /dev/null +++ b/105/replication_package/scfp2019excel.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:87766da9024f7b6742d277c955234cf6bee439248fbc5f689c81d91880fd1b05 +size 2635565 diff --git a/105/replication_package/scfp2019s.zip b/105/replication_package/scfp2019s.zip new file mode 100644 index 0000000000000000000000000000000000000000..4ab6f1d8d164d9f394267ff23774f790c0b27ad9 --- /dev/null +++ b/105/replication_package/scfp2019s.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e4a2ffd493eeb6388766b5f828edf9409d900168d91677c5bd25e4648007baa0 +size 3437486 diff --git a/105/replication_package/solution_methods/Perturbation/AU_fifth_order.m b/105/replication_package/solution_methods/Perturbation/AU_fifth_order.m new file mode 100644 index 0000000000000000000000000000000000000000..b8f9a62489b9a3d9c4cd3f2263b21d2b1b6cf0b6 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/AU_fifth_order.m @@ -0,0 +1,69 @@ +% +% � Copyright, Oren Levintal, June 13, 2016. + +fvvvvvEvx5U5; + +A=result; + + +fvvvvEvx3_vxx; + + +derivs=[1,4]; +perms1=[1,2,4,3;1,4,2,3]; +perms2=[1;1]; +Matrix=kron(kron(hx,Ezeta2),Ix); +tempresult= permutekron2(derivs,4,perms1,perms2,n_v,n_x,n_f,Matrix,fv,Vxxxx1); + +perms1=[]; +perms2=[]; +Matrix=kron(Ezeta3,Ix); +tempresult=tempresult+permutekron2(derivs,4,perms1,perms2,n_v,n_x,n_f,Matrix,fv,Vxxxx1); + +result=result+tempresult*(kron(Ix3,hxx)); +clear tempresult Matrix + +A=A+result*(OMEGA_x.OMEGA5*fullU5); + + +fvvvEvx2_vxxx; + + +derivs=[1,3]; +struct=[0,0,1]; +perms1=[]; +perms2=[]; +Matrix=kron(Ezeta2,Ix); + +tempresult= permutekron2(derivs,3,perms1,perms2,n_v,n_x,n_f,Matrix,fv,Vxxx1); + +result=result+tempresult*kron(Ix2,hxxx); +clear tempresult Matrix + +A=A+result*OMEGA_x.OMEGA6; + + +fvvvEvx_vxx2; + + +A=A+result*OMEGA_x.OMEGA7; + + +fvvEvx_vxxxx; + + +A=A+result*OMEGA_x.OMEGA8; + + +fvvEvxx_vxxxU5; + +A=A+result*OMEGA_x.OMEGA9; + +clear result + +A=reshape(A,n_f,n_x^5); + +A=A+fyp*reshape(chain5(gx,gxx,gxxx,gxxxx,[],hx,hxx,hxxx,hxxxx,[],OMEGA_x.OMEGA5,OMEGA_x.OMEGA6,OMEGA_x.OMEGA7,... + OMEGA_x.OMEGA8,OMEGA_x.OMEGA9),n_y,n_x^5); + +clear result \ No newline at end of file diff --git a/105/replication_package/solution_methods/Perturbation/A_fifth_order.m b/105/replication_package/solution_methods/Perturbation/A_fifth_order.m new file mode 100644 index 0000000000000000000000000000000000000000..8391bcde5ba908fecc3727c5e9b42d86c62c0c3e --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/A_fifth_order.m @@ -0,0 +1,69 @@ +% +% � Copyright, Oren Levintal, June 13, 2016. + +fvvvvvEvx5; + +A=result; + + +fvvvvEvx3_vxx; + + +derivs=[1,4]; +perms1=[1,2,4,3;1,4,2,3]; +perms2=[1;1]; +Matrix=kron(kron(hx,Ezeta2),Ix); +tempresult= permutekron2(derivs,4,perms1,perms2,n_v,n_x,n_f,Matrix,fv,Vxxxx1); + +perms1=[]; +perms2=[]; +Matrix=kron(Ezeta3,Ix); +tempresult=tempresult+permutekron2(derivs,4,perms1,perms2,n_v,n_x,n_f,Matrix,fv,Vxxxx1); + +result=result+tempresult*kron(Ix3,hxx); +clear tempresult Matrix + +A=A+result*OMEGA_x.OMEGA5; + + +fvvvEvx2_vxxx; + + +derivs=[1,3]; +struct=[0,0,1]; +perms1=[]; +perms2=[]; +Matrix=kron(Ezeta2,Ix); + +tempresult= permutekron2(derivs,3,perms1,perms2,n_v,n_x,n_f,Matrix,fv,Vxxx1); + +result=result+tempresult*kron(Ix2,hxxx); +clear tempresult Matrix + +A=A+result*OMEGA_x.OMEGA6; + + +fvvvEvx_vxx2; + + +A=A+result*OMEGA_x.OMEGA7; + + +fvvEvx_vxxxx; + + +A=A+result*OMEGA_x.OMEGA8; + + +fvvEvxx_vxxx; + +A=A+result*OMEGA_x.OMEGA9; + +clear result + +A=reshape(A,n_f,n_x^5); + +A=A+fyp*reshape(chain5(gx,gxx,gxxx,gxxxx,[],hx,hxx,hxxx,hxxxx,[],OMEGA_x.OMEGA5,OMEGA_x.OMEGA6,OMEGA_x.OMEGA7,... + OMEGA_x.OMEGA8,OMEGA_x.OMEGA9),n_y,n_x^5); + +clear result \ No newline at end of file diff --git a/105/replication_package/solution_methods/Perturbation/A_fourth_order.m b/105/replication_package/solution_methods/Perturbation/A_fourth_order.m new file mode 100644 index 0000000000000000000000000000000000000000..48eef3b6d5a3b52d9e264f8c78ee4cdda8bbe928 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/A_fourth_order.m @@ -0,0 +1,24 @@ +% +% � Copyright, Oren Levintal, June 13, 2016. + +fvvvvEvx4; +A=result; + + +fvvvEvx2_vxx; + +result=result+fv*Vxxx1*kron(Ezeta2,hxx); + +A=A+result*OMEGA_x.OMEGA2; + +fvvEvx_vxxx; + +A=A+result*OMEGA_x.OMEGA3; +saveA=A; + +fvvEvxx2; + +A=A+result*OMEGA_x.OMEGA4; + +A=A+fyp*chain4(gx,gxx,gxxx,[],hx,hxx,hxxx,[],OMEGA_x.OMEGA2,OMEGA_x.OMEGA3,OMEGA_x.OMEGA4); + diff --git a/105/replication_package/solution_methods/Perturbation/A_third_order.m b/105/replication_package/solution_methods/Perturbation/A_third_order.m new file mode 100644 index 0000000000000000000000000000000000000000..00ae4e4fccd5fd2114484088d6330471190a244a --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/A_third_order.m @@ -0,0 +1,11 @@ +% +% � Copyright, Oren Levintal, June 13, 2016. + +fvvvEvx3; +A=result; + +fvvEvx_vxx; + +A=A+(result+fyp*innerkron(n_y,n_x,gxx,hx,hxx))*OMEGA_x.OMEGA1; + + diff --git a/105/replication_package/solution_methods/Perturbation/AkronkC.m b/105/replication_package/solution_methods/Perturbation/AkronkC.m new file mode 100644 index 0000000000000000000000000000000000000000..b59b33299ba17091e76bba70487d6273d086bfc5 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/AkronkC.m @@ -0,0 +1,16 @@ +function R=AkronkC(A,C,k) +%Perform R=A*kron(C,...,C), where C is multiplied k times by the Kronecker operator. +% +% � Copyright, Oren Levintal, June 13, 2016. + +n=size(A,1); +m=size(C,1); +for j=1:k + A=reshape(A,numel(A)/m,m); + A=(A*C)'; +end + +R=reshape(A,numel(A)/n,n)'; + + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/Perturbation/LICENSE.txt b/105/replication_package/solution_methods/Perturbation/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..1f4c9cef9508120c4a8d47df9505e92a2d3ac0cd --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/LICENSE.txt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb9263af0dd9125a9f518d09c39d28dd177728acc9ac56a0f3c7fdb2594c00d0 +size 1019 diff --git a/105/replication_package/solution_methods/Perturbation/Treshape.m b/105/replication_package/solution_methods/Perturbation/Treshape.m new file mode 100644 index 0000000000000000000000000000000000000000..e82e4b69fee14aed7b6ace7079620c10f1664401 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/Treshape.m @@ -0,0 +1,15 @@ +function [ rmat ] = Treshape( mat,m,n ) +%Treshape(A,m,n) transposes matrix A and then reshapes it into m,n +%dimensions. +% +% � Copyright, Oren Levintal, June 13, 2016. + +[j0,i0,s]=find(mat); +[n0,m0]=size(mat); + +ind=(j0-1)*m0+i0; +[i1,j1]=ind2sub([m,n],ind); +rmat=sparse(i1,j1,s,m,n); + +end + diff --git a/105/replication_package/solution_methods/Perturbation/WBU_fifth_order.m b/105/replication_package/solution_methods/Perturbation/WBU_fifth_order.m new file mode 100644 index 0000000000000000000000000000000000000000..67ed1e8e7cefe23511199738c119f4d26def5610 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/WBU_fifth_order.m @@ -0,0 +1,29 @@ +% +% � Copyright, Oren Levintal, June 13, 2016. + + + +temp1=(reshape(W5, unique*n_x^3,n_x^2)*kron_hx_hx); +temp1=reshape(temp1,unique,n_x^5); +temp2=kron(hx,kron_hx_hx)*reshape(U5,n_x^3,n_x^2*unique); +temp2=reshape(temp2,n_x^5,unique); +W5BU5=temp1*temp2; + +order=5; +Matrix=hx3_Ezeta2; +perms1=[1,3,2,4,5;1,3,4,2,5;1,3,4,5,2;3,1,2,4,5;3,1,4,2,5;3,1,4,5,2;3,4,1,2,5;3,4,1,5,2;3,4,5,1,2]; +tempresult = permutekronB2(order,perms1,n_x,Matrix,W5 ); + +Matrix=hx2_Ezeta3; +perms1=[1,2,4,3,5;1,2,4,5,3;1,4,2,3,5;1,4,2,5,3;1,4,5,2,3;4,1,2,3,5;4,1,2,5,3;4,1,5,2,3;4,5,1,2,3]; +tempresult = tempresult+permutekronB2(order,perms1,n_x,Matrix,W5 ); + +Matrix=hx_Ezeta4; +perms1=[1,2,3,5,4;1,2,5,3,4;1,5,2,3,4;5,1,2,3,4]; +tempresult = tempresult+permutekronB2(order,perms1,n_x,Matrix,W5); + +tempresult = tempresult+W5*Ezeta5; + +W5BU5=W5BU5+tempresult*U5; + +clear tempresult \ No newline at end of file diff --git a/105/replication_package/solution_methods/Perturbation/WBU_fourth_order.m b/105/replication_package/solution_methods/Perturbation/WBU_fourth_order.m new file mode 100644 index 0000000000000000000000000000000000000000..3f28e7e8a6fcd73b07a5c226b38d59ea59e5a411 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/WBU_fourth_order.m @@ -0,0 +1,21 @@ +% +% � Copyright, Oren Levintal, June 13, 2016. + +temp1=reshape(W4, unique*n_x^2,n_x^2)*kron_hx_hx; +temp1=reshape(temp1,unique,n_x^4); +temp2=kron_hx_hx*reshape(U4,n_x^2,n_x^2*unique); +temp2=reshape(temp2,n_x^4,unique); +W4BU4=temp1*temp2; + + +Matrix=hx2_Ezeta2; +perms1=[1,3,2,4;1,3,4,2;3,1,2,4;3,1,4,2;3,4,1,2]; +tempresult = permutekronB2(4,perms1,n_x,Matrix,W4); + +Matrix=hx_Ezeta3; +perms1=[1,2,4,3;1,4,2,3;4,1,2,3]; +tempresult = tempresult+permutekronB2(4,perms1,n_x,Matrix,W4 ); + +tempresult=tempresult+W4*Ezeta4; + +W4BU4=W4BU4+tempresult*U4; diff --git a/105/replication_package/solution_methods/Perturbation/WBU_third_order.m b/105/replication_package/solution_methods/Perturbation/WBU_third_order.m new file mode 100644 index 0000000000000000000000000000000000000000..2928dc285304283a5faed4d882b4aec4aa7aa796 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/WBU_third_order.m @@ -0,0 +1,17 @@ +% +% � Copyright, Oren Levintal, June 13, 2016. + +% W3(hx^3)U3 +W3BU3=reshape([reshape(reshape([reshape(W3, unique*n_x^2,n_x)*hx]',n_x*unique*n_x,n_x)*hx,n_x,unique*n_x^2)]',unique,n_x^3)... + *reshape(hx*reshape(U3, n_x,n_x^2*unique),n_x^3,unique); + +% W3*E(P(kron(hx,zeta,zeta)))+W3*E(kron(zeta,zeta,zeta)) +Matrix=kron(hx,Ezeta2); +perms1=[1,3,2;3,1,2]; +tempresult = permutekronB2(3,perms1,n_x,Matrix,W3); + +tempresult=tempresult+W3*Ezeta3; + +% final result +W3BU3=W3BU3+tempresult*U3; + diff --git a/105/replication_package/solution_methods/Perturbation/bigprod.m b/105/replication_package/solution_methods/Perturbation/bigprod.m new file mode 100644 index 0000000000000000000000000000000000000000..4a6266bea2984c071f951d2711348e5168682704 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/bigprod.m @@ -0,0 +1,30 @@ +function result=bigprod(bigmat,smallmat) +% +% � Copyright, Oren Levintal, June 13, 2016. + +try + result=bigmat*smallmat; +catch + m=size(bigmat,1); + n=size(smallmat,2); + if nnz(bigmat)==0 || nnz(smallmat)==0 + result=sparse(m,n); + else + [i,j,s]=find(bigmat); + clear bigmat + + temp=repmat(s,1,n).*smallmat(j,:); clear j s smallmat + [sorti,indI] = sort(i,1); clear i + Di=[(abs(diff(sorti))~=0);1]; + cumtemp=cumsum(temp(indI,:)); clear temp indI + sumtemp=cumtemp(Di==1,:); clear cumtemp + sumtemp=[sumtemp(1,:);diff(sumtemp)]; + Di=[1;Di(1:end-1)]; + newi=repmat(sorti(Di==1),n,1); + newj=repmat(1:n,length(sorti(Di==1)),1); clear sorti Di + newj=newj(:); + result=sparse(newi,newj,sumtemp(:),m,n); + end +end + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/Perturbation/chain2.m b/105/replication_package/solution_methods/Perturbation/chain2.m new file mode 100644 index 0000000000000000000000000000000000000000..b07b22a9dd71de937dd356dcfdd17a4a5e4e8149 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/chain2.m @@ -0,0 +1,31 @@ +function [ fxx ] = chain2(fv,fvv,vx,vxx) +%chain2 calculates a 3-dimensional array of second derivatives of the composite +%function f(v(x)) with respect to x, using the second order multivariate chain +%rule derived in Levintal, Oren, "Fifth Order Perturbation Solutions +%to DSGE Models". +% +% Input arguments: +% fv is the Jacobian matrix of f(v) wrt v. +% fvv is an array of the second derivatives of f wrt v. +% vx is the Jacobian matrix of v(x) wrt x. +% vxx is an array of the second derivatives of v wrt x. +% +% All arguments, except fv and vx, can be reshaped in any form by the +% reshape.m function. fv and vx must be in matrix form, where the rows of +% fv correspond to the rows of f(v), and the row of vx correspond to the +% rows of v(x). +% +% � Copyright, Oren Levintal, June 13, 2016. + + +[n_f,n_v]=size(fv); +n_x=size(vx,2); + +term1=innerkron(n_f,n_v,fvv,vx,vx); +term2=fv*reshape(vxx,n_v,n_x^2); + +fxx=term1+term2; + + +end + diff --git a/105/replication_package/solution_methods/Perturbation/chain3.m b/105/replication_package/solution_methods/Perturbation/chain3.m new file mode 100644 index 0000000000000000000000000000000000000000..befdea5fb6c8da9a0ba1601d15cd9197d88ef3e1 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/chain3.m @@ -0,0 +1,65 @@ +function [ fxxx ] = chain3(fv,fvv,fvvv,vx,vxx,vxxx,varargin) +%chain3 calculates the matrix of third derivatives of the composite +%function f(v(x)) with respect to x, using the third order multivariate chain +%rule derived in Levintal, Oren, "Fifth Order Perturbation Solution +%to DSGE Models", July 6, 2014. +% +% Input arguments: +% fv is the Jacobian matrix of f(v) wrt v. +% fvv is an array of the second derivatives of f wrt v. +% fvvv is an array of the third derivatives of f wrt v. +% vx is the Jacobian matrix of v(x) wrt x. +% vxx is an array of the second derivatives of v wrt x. +% vxxx is an array of the third derivatives of v wrt x. +% +% All arguments, except fv and vx, can be reshaped in any form by the +% reshape.m function. fv and vx must be in matrix form, where the rows of +% fv correspond to the rows of f(v), and the row of vx correspond to the +% rows of v(x). +% +% [ fxxx ] = chain3(fv,fvv,fvvv,vx,vxx,vxxx,OMEGA1) uses the user-defined +% OMEGA1 matrix. +% +% � Copyright, Oren Levintal, June 13, 2016. + + +[n_f,n_v]=size(fv); +n_x=size(vx,2); + +if isempty(varargin)==0 + OMEGA1=varargin{1}; +end + +% fvvv(vx^3) + +if isempty(fvvv) + term1=sparse(1,1); +else + term1=innerkron(n_f,n_v,fvvv,vx,vx,vx); +end + +% fvv(vx*vxx) + +term2=innerkron(n_f,n_v,fvv,vx,vxx); + +if isempty(varargin) + term2=reshape(full(term2),n_f,n_x,n_x,n_x); + term2_OMEGA1=ipermute(term2,[1,3,4,2])+ipermute(term2,[1,2,4,3])+ipermute(term2,[1,2,3,4]); + term2_OMEGA1=reshape(term2_OMEGA1,n_f,n_x^3); +else + term2_OMEGA1=term2*OMEGA1; +end + +% fv(vxxx) + +if isempty(vxxx) + term3=sparse(1,1); +else + term3=innerkron(n_f,n_v,fv,vxxx); +end + +fxxx=term1+term2_OMEGA1+term3; + + +end + diff --git a/105/replication_package/solution_methods/Perturbation/chain4.m b/105/replication_package/solution_methods/Perturbation/chain4.m new file mode 100644 index 0000000000000000000000000000000000000000..26c5dac93227c34e08bc77580629bc78d1ee3c75 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/chain4.m @@ -0,0 +1,87 @@ +function [ fxxxx ] = chain4(fv,fvv,fvvv,fvvvv,vx,vxx,vxxx,vxxxx,varargin) +%chain4 calculates a 5-dimensional array of fourth derivatives of the composite +%function f(v(x)) with respect to x, using the fourth order multivariate chain +%rule derived in Levintal, Oren, "Fifth Order Perturbation Solution +%to DSGE Models". +% +% Input arguments: +% fv is the Jacobian matrix of f(v) wrt v. +% fvv is an array of the second derivatives of f wrt v. +% fvvv is an array of the third derivatives of f wrt v. +% fvvvv is an array of the fourth derivatives of f wrt v. +% vx is the Jacobian matrix of v(x) wrt x. +% vxx is an array of the second derivatives of v wrt x. +% vxxx is an array of the third derivatives of v wrt x. +% vxxxx is an array of the fourth derivatives of v wrt x. +% +% All arguments, except fv and vx, can be reshaped in any form by the +% reshape.m function. fv and vx must be in matrix form, where the rows of +% fv correspond to the rows of f(v), and the row of vx correspond to the +% rows of v(x). +% +% � Copyright, Oren Levintal, June 13, 2016. + + + +[n_f,n_v]=size(fv); +n_x=size(vx,2); + +if isempty(varargin)==0 + OMEGA2=varargin{1}; + OMEGA3=varargin{2}; + OMEGA4=varargin{3}; +end + +if isempty(fvvvv) + term1=sparse(1,1); +else + term1=innerkron(n_f,n_v,fvvvv,vx,vx,vx,vx); +end + +% fvvv(vx^2*vxx) + +term2=innerkron(n_f,n_v,fvvv,vx,vx,vxx); + +if isempty(varargin) + term2=reshape(full(term2),n_f,n_x,n_x,n_x,n_x); + term2_OMEGA2=ipermute(term2,[1,4,5,3,2])+ipermute(term2,[1,3,5,4,2])+ipermute(term2,[1,2,5,4,3])... + +ipermute(term2,[1,3,4,5,2])+ipermute(term2,[1,2,4,5,3])+ipermute(term2,[1,2,3,5,4]); + term2_OMEGA2=reshape(term2_OMEGA2,n_f,n_x^4); +else + term2_OMEGA2=term2*OMEGA2; +end + +% fvv(vx*vxxx) + +term3=innerkron(n_f,n_v,fvv,vx,vxxx); + +if isempty(varargin) + term3=reshape(full(term3),n_f,n_x,n_x,n_x,n_x); + term3_OMEGA3=ipermute(term3,[1,3,4,5,2])+ipermute(term3,[1,2,4,5,3])+ipermute(term3,[1,2,3,5,4])+ipermute(term3,[1,2,3,4,5]); + term3_OMEGA3=reshape(term3_OMEGA3,n_f,n_x^4); +else + term3_OMEGA3=term3*OMEGA3; +end + +% fvv(vxx^2) + +term4=innerkron(n_f,n_v,fvv,vxx,vxx); + +if isempty(varargin) + term4=reshape(full(term4),n_f,n_x,n_x,n_x,n_x); + term4_OMEGA4=ipermute(term4,[1,3,4,2,5])+ipermute(term4,[1,2,4,3,5])+ipermute(term4,[1,2,3,4,5]); + term4_OMEGA4=reshape(term4_OMEGA4,n_f,n_x^4); +else + term4_OMEGA4=term4*OMEGA4; +end + +if isempty(vxxxx) + term5=sparse(1,1); +else + term5=innerkron(n_f,n_v,fv,vxxxx); +end + +fxxxx=term1+term2_OMEGA2+term3_OMEGA3+term4_OMEGA4+term5; + +end + diff --git a/105/replication_package/solution_methods/Perturbation/chain5.m b/105/replication_package/solution_methods/Perturbation/chain5.m new file mode 100644 index 0000000000000000000000000000000000000000..c1d20265987d3f46f2d276320f72c8d07d4d7571 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/chain5.m @@ -0,0 +1,133 @@ +function [ fxxxxx ] = chain5(fv,fvv,fvvv,fvvvv,fvvvvv,vx,vxx,vxxx,vxxxx,vxxxxx,varargin) +%chain5 calculates a 6-dimensional array of fifth derivatives of the composite +%function f(v(x)) with respect to x, using the fifth order multivariate chain +%rule derived in Levintal, Oren, "Fifth Order Perturbation Solution +%to DSGE Models". +% +% Input arguments: +% fv is the Jacobian matrix of f(v) wrt v. +% fvv is an array of the second derivatives of f wrt v. +% fvvv is an array of the third derivatives of f wrt v. +% fvvvv is an array of the fourth derivatives of f wrt v. +% fvvvvv is an array of the fifth derivatives of f wrt v. +% vx is the Jacobian matrix of v(x) wrt x. +% vxx is an array of the second derivatives of v wrt x. +% vxxx is an array of the third derivatives of v wrt x. +% vxxxx is an array of the fourth derivatives of v wrt x. +% vxxxxx is an array of the fifth derivatives of v wrt x. +% +% All arguments, except fv and vx, can be reshaped in any form by the +% reshape.m function. fv and vx must be in matrix form, where the rows of +% fv correspond to the rows of f(v), and the rows of vx correspond to the +% rows of v(x). +% +% � Copyright, Oren Levintal, June 13, 2016. + + +[n_f,n_v]=size(fv); +n_x=size(vx,2); + +if isempty(varargin)==0 + OMEGA5=varargin{1}; + OMEGA6=varargin{2}; + OMEGA7=varargin{3}; + OMEGA8=varargin{4}; + OMEGA9=varargin{5}; +end + +% fvvvvv(vx^5) + +if isempty(fvvvvv) + term1=sparse(1,1); +else + term1=innerkron(n_f,n_v,fvvvvv,vx,vx,vx,vx,vx); +end + +% fvvvv(vx^3*vxx) + +term2=innerkron(n_f,n_v,fvvvv,vx,vx,vx,vxx); + +if isempty(varargin) + term2=reshape(full(term2),n_f,n_x,n_x,n_x,n_x,n_x); + term2_OMEGA5=ipermute(term2,[1,5,6,4,3,2])+ipermute(term2,[1,4,6,5,3,2])+ipermute(term2,[1,3,6,5,4,2])+ipermute(term2,[1,2,6,5,4,3])... + +ipermute(term2,[1,4,5,6,3,2])+ipermute(term2,[1,3,5,6,4,2])... + +ipermute(term2,[1,2,5,6,4,3])+ipermute(term2,[1,3,4,6,5,2])+ipermute(term2,[1,2,4,6,5,3])+ipermute(term2,[1,2,3,6,5,4]); + term2_OMEGA5=reshape(term2_OMEGA5,n_f,n_x^5); +else + term2_OMEGA5=term2*OMEGA5; + clear term2 OMEGA5 +end + +% fvvv(vx^2*vxxx) + +term3=innerkron(n_f,n_v,fvvv,vx,vx,vxxx); + +if isempty(varargin) + term3=reshape(full(term3),n_f,n_x,n_x,n_x,n_x,n_x); + term3_OMEGA6=ipermute(term3,[1,4,5,6,3,2])+ipermute(term3,[1,3,5,6,4,2])+ipermute(term3,[1,2,5,6,4,3])+ipermute(term3,[1,3,4,6,5,2])... + +ipermute(term3,[1,2,4,6,5,3])+ipermute(term3,[1,2,3,6,5,4])+ipermute(term3,[1,3,4,5,6,2])... + +ipermute(term3,[1,2,4,5,6,3])+ipermute(term3,[1,2,3,5,6,4])+ipermute(term3,[1,2,3,4,6,5]); + term3_OMEGA6=reshape(term3_OMEGA6,n_f,n_x^5); +else + term3_OMEGA6=term3*OMEGA6; + clear term3 OMEGA6 +end + +% fvvv(vx*vxx^2) + +term4=innerkron(n_f,n_v,fvvv,vx,vxx,vxx); + +if isempty(varargin) + term4=reshape(full(term4),n_f,n_x,n_x,n_x,n_x,n_x); + term4_OMEGA7=ipermute(term4,[1,4,5,3,6,2])+ipermute(term4,[1,3,5,4,6,2])+ipermute(term4,[1,2,5,4,6,3])... + +ipermute(term4,[1,3,4,5,6,2])+ipermute(term4,[1,2,4,5,6,3])+ipermute(term4,[1,2,3,5,6,4])... + +ipermute(term4,[1,4,5,2,6,3])+ipermute(term4,[1,3,5,2,6,4])+ipermute(term4,[1,2,5,3,6,4])... + +ipermute(term4,[1,3,4,2,6,5])+ipermute(term4,[1,2,4,3,6,5])+ipermute(term4,[1,2,3,4,6,5])... + +ipermute(term4,[1,3,4,2,5,6])+ipermute(term4,[1,2,4,3,5,6])+ipermute(term4,[1,2,3,4,5,6]); + term4_OMEGA7=reshape(term4_OMEGA7,n_f,n_x^5); +else + term4_OMEGA7=term4*OMEGA7; + clear term4 OMEGA7 +end + +% fvv(vx*vxxxx) + +term5=innerkron(n_f,n_v,fvv,vx,vxxxx); + +if isempty(varargin) + term5=reshape(full(term5),n_f,n_x,n_x,n_x,n_x,n_x); + term5_OMEGA8=ipermute(term5,[1,3,4,5,6,2])+ipermute(term5,[1,2,4,5,6,3])+ipermute(term5,[1,2,3,5,6,4])... + +ipermute(term5,[1,2,3,4,6,5])+ipermute(term5,[1,2,3,4,5,6]); + term5_OMEGA8=reshape(term5_OMEGA8,n_f,n_x^5); +else + term5_OMEGA8=term5*OMEGA8; + clear term5 OMEGA8 +end + +% fvv(vxx*vxxx) + +term6=innerkron(n_f,n_v,fvv,vxx,vxxx); + +if isempty(varargin) + term6=reshape(full(term6),n_f,n_x,n_x,n_x,n_x,n_x); + term6_OMEGA9=ipermute(term6,[1,3,4,5,2,6])+ipermute(term6,[1,2,4,5,3,6])+ipermute(term6,[1,2,3,5,4,6])+ipermute(term6,[1,2,3,4,5,6])... + +ipermute(term6,[1,3,4,6,2,5])+ipermute(term6,[1,2,4,6,3,5])+ipermute(term6,[1,2,3,6,4,5])... + +ipermute(term6,[1,2,5,6,3,4])+ipermute(term6,[1,3,5,6,2,4])+ipermute(term6,[1,4,5,6,2,3]); + term6_OMEGA9=reshape(term6_OMEGA9,n_f,n_x^5); +else + term6_OMEGA9=term6*OMEGA9; + clear term6 OMEGA9 +end + +% fv(vxxxxx) + +if isempty(vxxxxx) + lastterm=sparse(1,1); +else + lastterm=innerkron(n_f,n_v,fv,vxxxxx); +end + +fxxxxx=term1+term2_OMEGA5+term3_OMEGA6+term4_OMEGA7+term5_OMEGA8+term6_OMEGA9+lastterm; + +end + diff --git a/105/replication_package/solution_methods/Perturbation/compderivs.m b/105/replication_package/solution_methods/Perturbation/compderivs.m new file mode 100644 index 0000000000000000000000000000000000000000..613e38923961e3efebcc302ea1d43e609c316339 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/compderivs.m @@ -0,0 +1,157 @@ +function [derivs,uncomp]=compderivs(f,x,order) + +% [derivs,uncomp,U,W]=compderivs(f,x,order) differentiates f with respect to x +% serveral times (given by order). The differentiation is done in +% a compressed manner, by exploiting sparsity and symmetry of mixed derivatives. +% The function returns two cell arrays. The first output contains the +% nonzero unique derivatives up to the order defined by the user. The +% second array contains matrices that uncompress the nonzero unique derivatives +% into the full arrays of derivatives. U and W are compress/uncompress +% matrices to unique elements. +% +% For details on the compressed differentiation routine see: +% Levintal, Oren, "Fifth Order Perturbation Solution to DSGE Models". +% +% Input arguments: +% f - a symbolic scalar. +% x - a symbolic vector. +% order - the maximum order of derivatives. For example, order=3 returns +% the first, second and third derivatives. +% +% Output arguments: +% derivs - a cell array of the nonzero unique derivatives. For example, +% derivs{1} is a symbolic vector of the nonzero first derivatives, derivs{2} is a +% symbolic vector of the nonzero unique second derivatives and so on. +% uncomp - a cell array of sparse matrices that are used to uncompress the +% compressed derivatives. For example, the full array of second order +% derivatives is obtained by uncomp{2}*derivs{2}. +% +% Example: f=x1^3*x2^4, and x=[x1,x2], both are symbolic variables. +% [derivs,uncomp]=compderivs(f,x,3) returns the first, second and third +% compressed derivatives. The full array of third derivatives is obtained +% by uncomp{3}*derivs{3}. This array can be reshaped into a 2-by-2-by-2 +% array by the reshape function. +% The i,j,l element of this array is the third derivative of f +% w.r.t xi, xj and xl. +% +% +% � Copyright, Oren Levintal, June 13, 2016. + + +n_x=length(x); +derivs=cell(order,1); +uncomp=cell(order,1); + +if n_x==1 + tempderiv=f; + for k=1:order + tempderiv=jacobian(tempderiv,x); + derivs{k}=tempderiv; + if logical(tempderiv==0) + uncomp{k}=sparse(0); + else + uncomp{k}=sparse(1); + end + end +else + tempderiv=jacobian(f,x); + tempderiv=tempderiv(:); + + nnztempderiv=1-logical(tempderiv==0); + tempind=find(nnztempderiv); + countdf=sparse(tempind,ones(length(tempind),1),ones(length(tempind),1),numel(tempderiv),1); % counts nonzero derivatives. + N1=sparse(tempind,1:sum(countdf),ones(1,sum(countdf)),n_x,sum(countdf)); + uncomp{1}=N1; + derivs{1}=tempderiv(countdf==1); + + for k=2:order + tempderiv=jacobian(derivs{k-1}, x); + + nnztempderiv=1-logical(tempderiv==0); + [i,j]=find(nnztempderiv); + + countdf_short=sparse(i,j,ones(length(i),1),size(tempderiv,1),size(tempderiv,2)); + countdf=uncomp{k-1}*countdf_short; + countdf=countdf(:); + if nnz(countdf)>0 + [U,W]=create_UW(n_x,k,countdf); + N=sparse(find(countdf),1:sum(countdf),ones(1,sum(countdf)),n_x^k,sum(countdf)); + tempmat=[U'*(N'*kron(speye(n_x),uncomp{k-1}))]; + [i,j]=find(tempmat'); + tempderiv=tempderiv(i); + [colM,rowM]=find(N); + [rowW,colW]=find(W); + tempuncomp=sparse(size(N,1),size(W,1)); + tempeye=speye(size(W,1)); + tempuncomp(colM,:)=tempeye(rowW,:); + else + tempderiv=sym(0); + tempuncomp=sparse(n_x^k,1); + end + derivs{k}=tempderiv; + uncomp{k}=tempuncomp; + end +end + +end + +function [U,W]=create_UW(n,k,varargin) +% [U,W]=create_UW(n,k) creates two sparse matrices, U and W, that compress and +% uncompress a symmetric array A with k dimensions and n^k elements. +% A(:)'*U is a row vector that contains the unique elements of A, +% and A(:)'=(A(:)'*U)*W. +% [U,W]=create_UW(n,k,N) creates matrices U and W of a sparse symmetric +% array A with k dimensions and n^k elements. N is a vector of size n^k, +% where N(j)=1 if A(j)~=0 and zero otherwise. If B is a row +% vector with the nonzero elements of the row vector A(:)', then B*U +% is a row vector of the unique nonzero elements of A, and B=(B*U)*W. +% +% This code can be used freely for non commercial purposes, provided that +% it is not altered. +% +% (c) Oren Levintal, December 20, 2013 + +if isempty(varargin) +% nonzero=ones(n^k,1); + I=[1:n^k]; +else + nonzero=varargin{1}; + I=find(nonzero); +end + +if isempty(I) + error('The symmetric array is all zero') +end + +I=I(:); +% nonzero(nonzero~=0)=1; nonzero=nonzero(:); +sizeM='n'; +subind='I1'; +for i=2:k + sizeM=[sizeM ' n']; + subind=[subind ',I' num2str(i) ]; +end + +eval(['[' subind ']=ind2sub([' sizeM '],I);']); % I is a linear index of all nonzero elements. +eval(['M=[' subind '];']); + +M=sort(M,2); % sort columns +[M,I]=sortrows(M); % sort rows +if size(M,1)==1 + DM=1; +else + DM=[1;(sum(abs(diff(M)),2)~=0)]; +end +group=cumsum(DM); +minI=accumarray(group,I,[],@min); +newi=minI(group); + +unique=newi(DM>0); % index of unique nonzero elements + +n_unique=length(unique); + +U= sparse(unique,[1:n_unique]',ones(n_unique,1),length(I),n_unique); + +W= sparse(group,I,ones(length(I),1),n_unique,length(I)); + +end diff --git a/105/replication_package/solution_methods/Perturbation/create_OMEGA.m b/105/replication_package/solution_methods/Perturbation/create_OMEGA.m new file mode 100644 index 0000000000000000000000000000000000000000..5d52e9f9310d08448e201238c59af2041fccb56c --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/create_OMEGA.m @@ -0,0 +1,53 @@ +function [ OMEGA ] = create_OMEGA( n_x,varargin ) +%The function creates sparse matrices OMEGA1,..,OMEGA9, that are used for +%the high-order multivariate chain rules described in Levintal, Oren, +%"Fifth Order Perturbation Solution to DSGE Models", 2014. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if length(varargin)==1 + order=varargin{1}; % do only specified order +else + order=0; % do orders 3,4,5 +end + +if order==3 || order==0 + ind=[1:n_x^3]; + M=reshape(ind,1,n_x,n_x,n_x); + Ix=speye(n_x^3); + OMEGA.OMEGA1=Ix(:,ipermute(M,[1,3,4,2]))+Ix(:,ipermute(M,[1,2,4,3]))+Ix(:,ipermute(M,[1,2,3,4])); +end + +if order==4 || order==0 + ind=[1:n_x^4]; + M=reshape(ind,1,n_x,n_x,n_x,n_x); + Ix=speye(n_x^4); + OMEGA.OMEGA2=Ix(:,ipermute(M,[1,4,5,3,2]))+Ix(:,ipermute(M,[1,3,5,4,2]))+Ix(:,ipermute(M,[1,2,5,4,3]))... + +Ix(:,ipermute(M,[1,3,4,5,2]))+Ix(:,ipermute(M,[1,2,4,5,3]))+Ix(:,ipermute(M,[1,2,3,5,4])); + OMEGA.OMEGA3=Ix(:,ipermute(M,[1,3,4,5,2]))+Ix(:,ipermute(M,[1,2,4,5,3]))+Ix(:,ipermute(M,[1,2,3,5,4]))+Ix(:,ipermute(M,[1,2,3,4,5])); + OMEGA.OMEGA4=Ix(:,ipermute(M,[1,3,4,2,5]))+Ix(:,ipermute(M,[1,2,4,3,5]))+Ix(:,ipermute(M,[1,2,3,4,5])); +end + +if order==5 || order==0 + ind=[1:n_x^5]; + M=reshape(ind,1,n_x,n_x,n_x,n_x,n_x); + Ix=speye(n_x^5); + OMEGA.OMEGA5=Ix(:,ipermute(M,[1,5,6,4,3,2]))+Ix(:,ipermute(M,[1,4,6,5,3,2]))+Ix(:,ipermute(M,[1,3,6,5,4,2]))+Ix(:,ipermute(M,[1,2,6,5,4,3]))... + +Ix(:,ipermute(M,[1,4,5,6,3,2]))+Ix(:,ipermute(M,[1,3,5,6,4,2]))... + +Ix(:,ipermute(M,[1,2,5,6,4,3]))+Ix(:,ipermute(M,[1,3,4,6,5,2]))+Ix(:,ipermute(M,[1,2,4,6,5,3]))+Ix(:,ipermute(M,[1,2,3,6,5,4])); + OMEGA.OMEGA6=Ix(:,ipermute(M,[1,4,5,6,3,2]))+Ix(:,ipermute(M,[1,3,5,6,4,2]))+Ix(:,ipermute(M,[1,2,5,6,4,3]))+Ix(:,ipermute(M,[1,3,4,6,5,2]))... + +Ix(:,ipermute(M,[1,2,4,6,5,3]))+Ix(:,ipermute(M,[1,2,3,6,5,4]))+Ix(:,ipermute(M,[1,3,4,5,6,2]))... + +Ix(:,ipermute(M,[1,2,4,5,6,3]))+Ix(:,ipermute(M,[1,2,3,5,6,4]))+Ix(:,ipermute(M,[1,2,3,4,6,5])); + OMEGA.OMEGA7=Ix(:,ipermute(M,[1,4,5,3,6,2]))+Ix(:,ipermute(M,[1,3,5,4,6,2]))+Ix(:,ipermute(M,[1,2,5,4,6,3]))... + +Ix(:,ipermute(M,[1,3,4,5,6,2]))+Ix(:,ipermute(M,[1,2,4,5,6,3]))+Ix(:,ipermute(M,[1,2,3,5,6,4]))... + +Ix(:,ipermute(M,[1,4,5,2,6,3]))+Ix(:,ipermute(M,[1,3,5,2,6,4]))+Ix(:,ipermute(M,[1,2,5,3,6,4]))... + +Ix(:,ipermute(M,[1,3,4,2,6,5]))+Ix(:,ipermute(M,[1,2,4,3,6,5]))+Ix(:,ipermute(M,[1,2,3,4,6,5]))... + +Ix(:,ipermute(M,[1,3,4,2,5,6]))+Ix(:,ipermute(M,[1,2,4,3,5,6]))+Ix(:,ipermute(M,[1,2,3,4,5,6])); + OMEGA.OMEGA8=Ix(:,ipermute(M,[1,3,4,5,6,2]))+Ix(:,ipermute(M,[1,2,4,5,6,3]))+Ix(:,ipermute(M,[1,2,3,5,6,4]))+Ix(:,ipermute(M,[1,2,3,4,6,5]))+Ix(:,ipermute(M,[1,2,3,4,5,6])); + OMEGA.OMEGA9=Ix(:,ipermute(M,[1,3,4,5,2,6]))+Ix(:,ipermute(M,[1,2,4,5,3,6]))+Ix(:,ipermute(M,[1,2,3,5,4,6]))+Ix(:,ipermute(M,[1,2,3,4,5,6]))... + +Ix(:,ipermute(M,[1,3,4,6,2,5]))+Ix(:,ipermute(M,[1,2,4,6,3,5]))+Ix(:,ipermute(M,[1,2,3,6,4,5]))... + +Ix(:,ipermute(M,[1,2,5,6,3,4]))+Ix(:,ipermute(M,[1,3,5,6,2,4]))+Ix(:,ipermute(M,[1,4,5,6,2,3])); +end + +end + diff --git a/105/replication_package/solution_methods/Perturbation/create_OMEGA_x.m b/105/replication_package/solution_methods/Perturbation/create_OMEGA_x.m new file mode 100644 index 0000000000000000000000000000000000000000..0fece30f88267e470d628ab239037de8984bd881 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/create_OMEGA_x.m @@ -0,0 +1,23 @@ +% +% � Copyright, Oren Levintal, June 13, 2016. + +OMEGA_x=[]; +if approx>=3 + tempOMEGA = create_OMEGA( n_x,3 ); + OMEGA_x.OMEGA1=tempOMEGA.OMEGA1; +end + +if approx>=4 + tempOMEGA = create_OMEGA( n_x,4 ); + OMEGA_x.OMEGA2=tempOMEGA.OMEGA2; + OMEGA_x.OMEGA3=tempOMEGA.OMEGA3; + OMEGA_x.OMEGA4=tempOMEGA.OMEGA4; +end +if approx>=5 + tempOMEGA = create_OMEGA( n_x,5 ); + OMEGA_x.OMEGA5=tempOMEGA.OMEGA5; + OMEGA_x.OMEGA6=tempOMEGA.OMEGA6; + OMEGA_x.OMEGA7=tempOMEGA.OMEGA7; + OMEGA_x.OMEGA8=tempOMEGA.OMEGA8; + OMEGA_x.OMEGA9=tempOMEGA.OMEGA9; +end diff --git a/105/replication_package/solution_methods/Perturbation/create_UW.m b/105/replication_package/solution_methods/Perturbation/create_UW.m new file mode 100644 index 0000000000000000000000000000000000000000..0560026cde9504572ee1e2a37619c85cea3f2563 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/create_UW.m @@ -0,0 +1,59 @@ +function [U,W]=create_UW(n,k,varargin) +% [U,W]=create_UW(n,k) creates two sparse matrices, U and W, that compress and +% uncompress a symmetric array A with k dimensions and n^k elements. +% A(:)'*U is a row vector that contains the unique elements of A, +% and A(:)'=(A(:)'*U)*W. +% [U,W]=create_UW(n,k,N) creates matrices U and W of a sparse symmetric +% array A with k dimensions and n^k elements. N is a vector of size n^k, +% where N(j)=1 if A(j)~=0 and zero otherwise. If B is a row +% vector with the nonzero elements of the row vector A(:)', then B*U +% is a row vector of the unique nonzero elements of A, and B=(B*U)*W. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if isempty(varargin) +% nonzero=ones(n^k,1); + I=[1:n^k]; +else + nonzero=varargin{1}; + I=find(nonzero); +end + +if isempty(I) + error('The symmetric array is all zero') +end + +I=I(:); +% nonzero(nonzero~=0)=1; nonzero=nonzero(:); +sizeM='n'; +subind='I1'; +for i=2:k + sizeM=[sizeM ' n']; + subind=[subind ',I' num2str(i) ]; +end + +eval(['[' subind ']=ind2sub([' sizeM '],I);']); % I is a linear index of all nonzero elements. +eval(['M=[' subind '];']); + +M=sort(M,2); % sort columns +[M,I]=sortrows(M); % sort rows +if size(M,1)==1 + DM=1; +else + DM=[1;(sum(abs(diff(M)),2)~=0)]; +end +group=cumsum(DM); +minI=accumarray(group,I,[],@min); +newi=minI(group); + +unique=newi(DM>0); % index of unique nonzero elements + +n_unique=length(unique); + +U= sparse(unique,[1:n_unique]',ones(n_unique,1),length(I),n_unique); + +W= sparse(group,I,ones(length(I),1),n_unique,length(I)); + +end + + diff --git a/105/replication_package/solution_methods/Perturbation/create_compression_matrices_nonzero.m b/105/replication_package/solution_methods/Perturbation/create_compression_matrices_nonzero.m new file mode 100644 index 0000000000000000000000000000000000000000..3ec5214e462b7a390937ac65b4b287e26d008541 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/create_compression_matrices_nonzero.m @@ -0,0 +1,75 @@ +% +% � Copyright, Oren Levintal, June 13, 2016. + +if approx>=2 + k=2; + nonzero=reshape(ones(1,n_x^k),n_x,n_x); + nonzero(end,1:end-1)=0; + nonzero(1:end-1,end)=0; + [U2,W2]=create_UW(n_x,k,nonzero(:)); + nnz=find(nonzero); + N2=sparse(nnz,1:length(nnz),ones(1,length(nnz)),n_x^k,length(nnz)); + U2=N2*U2; + W2=W2*N2'; +end + +if approx>=3 + k=3; + nonzero=reshape(ones(1,n_x^k),n_x,n_x,n_x); + nonzero(end,1:end-1,1:end-1)=0; + nonzero(1:end-1,end,1:end-1)=0; + nonzero(1:end-1,1:end-1,end)=0; + [U3,W3]=create_UW(n_x,k,nonzero(:)); + nnz=find(nonzero); + N3=sparse(nnz,1:length(nnz),ones(1,length(nnz)),n_x^k,length(nnz)); + U3=N3*U3; + W3=W3*N3'; +end + +if approx>=4 + k=4; + nonzero=reshape(ones(1,n_x^k),n_x,n_x,n_x,n_x); + nonzero(end,1:end-1,1:end-1,1:end-1)=0; + nonzero(1:end-1,end,1:end-1,1:end-1)=0; + nonzero(1:end-1,1:end-1,end,1:end-1)=0; + nonzero(1:end-1,1:end-1,1:end-1,end)=0; + [U4,W4]=create_UW(n_x,k,nonzero(:)); + nnz=find(nonzero); + N4=sparse(nnz,1:length(nnz),ones(1,length(nnz)),n_x^k,length(nnz)); + U4=N4*U4; + W4=W4*N4'; +end + +if approx>=5 + k=5; + nonzero=reshape(ones(1,n_x^k),n_x,n_x,n_x,n_x,n_x); + nonzero(end,1:end-1,1:end-1,1:end-1,1:end-1)=0; + nonzero(1:end-1,end,1:end-1,1:end-1,1:end-1)=0; + nonzero(1:end-1,1:end-1,end,1:end-1,1:end-1)=0; + nonzero(1:end-1,1:end-1,1:end-1,end,1:end-1)=0; + nonzero(1:end-1,1:end-1,1:end-1,1:end-1,end)=0; + [U5,W5]=create_UW(n_x,k,nonzero(:)); + nnz=find(nonzero); + N5=sparse(nnz,1:length(nnz),ones(1,length(nnz)),n_x^k,length(nnz)); + U5=N5*U5; + W5=W5*N5'; +end + +if approx==1 + UW=struct([]); +elseif approx==2 + UW.U2=U2; UW.W2=W2; +elseif approx==3 + UW.U2=U2; UW.W2=W2; + UW.U3=U3; UW.W3=W3; +elseif approx==4 + UW.U2=U2; UW.W2=W2; + UW.U3=U3; UW.W3=W3; + UW.U4=U4; UW.W4=W4; +elseif approx==5 + UW.U2=U2; UW.W2=W2; + UW.U3=U3; UW.W3=W3; + UW.U4=U4; UW.W4=W4; + UW.U5=U5; UW.W5=W5; +end + diff --git a/105/replication_package/solution_methods/Perturbation/differentiate_dsge.m b/105/replication_package/solution_methods/Perturbation/differentiate_dsge.m new file mode 100644 index 0000000000000000000000000000000000000000..599057320ec16aad796a1874cb1f3d2658407143 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/differentiate_dsge.m @@ -0,0 +1,77 @@ +function model=differentiate_dsge(f,yp,y,xp,x,symparams,approx,Phi) +%differentiate_dsge(f,yp,y,xp,x,symparams,approx,Phi,ufun,u) +%This function differentiates the dsge model and prepares all the files +%necessary to run solve_dsge.m. +%Input variables: +%f,yp,y,xp,x: the model conditions and variable as in Schmitt-Grohe and Uribe (2004) +%symparams: a symbolic array that lists all parameters. +%approx: order of perturbation +%Phi: expected value of exgoenous variables (leave empty if not +%used) +% +% � Copyright, Oren Levintal, June 13, 2016. + + +disp('Preparing perturbation...') + +currentFolder = pwd; +mkdir('files'); +cd('files') + +syms sigma_perturbation sigmap_perturbation real +Phi=sym(Phi); +f=sym(f); + +x=[x(:);sigma_perturbation]; +xp=[xp(:);sigmap_perturbation]; + +v=[yp(:); y(:); xp(:); x(:)]; + +n_f=length(f); +n_x=length(x); +n_y=length(y); +n_x2=size(Phi,1); +n_x1=n_f-n_y; +n_v=length(v); + +model.f=f; +model.yp=yp; +model.y=y; +model.xp=xp; +model.x=x; +model.v=v; +model.n_f=n_f; +model.n_x=n_x; +model.n_y=n_y; +model.n_x2=n_x2; +model.n_x1=n_x1; +model.n_v=n_v; + +create_compression_matrices_nonzero; + +if approx>=1 + model.f_ind=getderivs_vector(f,v,approx,symparams,'f'); +end + +% Create an m file for Phi and its derivatives w.r.t x + +gen_fun(Phi,symparams,x,'Phi'); +if approx>=1 + model.Phi_ind=getderivs(Phi,x,approx,symparams,'Phi'); +end + +create_OMEGA_x; + +model.UW=UW; + +if approx<3 + OMEGA_x=[]; +end +model.OMEGA_x=OMEGA_x; + +rehash; + +disp('Perturbation prepared successfully.') + +cd(currentFolder) + diff --git a/105/replication_package/solution_methods/Perturbation/disp_deriv.m b/105/replication_package/solution_methods/Perturbation/disp_deriv.m new file mode 100644 index 0000000000000000000000000000000000000000..9522591797c3cbe244c564a1bb4732838dfcf0f6 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/disp_deriv.m @@ -0,0 +1,45 @@ +function disp_deriv( fun_string,i,fun_sym , varargin) +%disp_deriv breaks derivativs into several lines if the length of derivative is +%higher than 1000 characters. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if isempty(varargin) + texp=char(fun_sym(i)); +else + texp=char(fun_sym(varargin{1})); +end +if length(texp)<1000 + disp([fun_string '(' num2str(i) ')=' texp ';']); + texp=''; +else + itexp=1000; + while strcmp(texp(itexp),'+')+strcmp(texp(itexp),'-')+strcmp(texp(itexp),'*')+strcmp(texp(itexp),'/')==0 & itexp0 + itexp=min(1000,length(texp)); + while strcmp(texp(itexp),'+')+strcmp(texp(itexp),'-')+strcmp(texp(itexp),'*')+strcmp(texp(itexp),'/')==0 & itexp1)=perms2(perms2>1)-1; +Matrix=kron(Ix_Ezeta2,hx); + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx0,Vx1,Vxx1); + +% (Vx1*zeta)^(X2)(X)(Vxx1*P(zeta(X)hx) + +perms1=[2,1,3,4]; +perms2=[1,2,3]; +Matrix=kron(Ezeta3,hx); + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx1,Vx1,Vxx1); + +% Vx0^(X2)(X)(Vxx1*zeta^(X2)) + +perms1=[]; +perms2=[]; +Matrix=Ix2_Ezeta2; + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx0,Vx0,Vxx1); + +% P(Vx0(X)(Vx1*zeta))(X)(Vxx1*zeta^(X2)) + +perms1=[1,2,4,3]; +perms2=[1,3,2]; +Matrix=Ix_Ezeta3; + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx0,Vx1,Vxx1); + +% (Vx1*zeta)^(X2)(X)(Vxx1*zeta^(X2)) + +perms1=[]; +perms2=[]; +Matrix=Ezeta4; + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx1,Vx1,Vxx1); diff --git a/105/replication_package/solution_methods/Perturbation/fvvvEvx2_vxxx.m b/105/replication_package/solution_methods/Perturbation/fvvvEvx2_vxxx.m new file mode 100644 index 0000000000000000000000000000000000000000..bd60736778c5b3a99390d93a297df0ee8ec65891 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/fvvvEvx2_vxxx.m @@ -0,0 +1,120 @@ +% +% � Copyright, Oren Levintal, June 13, 2016. + +order=5; + +% Vx0^(X2)(X)Vxxx0 + +derivs=[3,1,1,3]; +perms1=[]; +perms2=perms1; +Matrix=[]; + +result= permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx0,Vx0,Vxxx0); + +% Vx0^(X2)(X)(Vxxx1*P(zeta^(X2)(X)hx)) + +perms1=[2,1,3,4,5;2,3,1,4,5]; +perms2=[1,2,3;1,2,3]; +Matrix=kron(Ix2_Ezeta2,hx); + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx0,Vx0,Vxxx1); + +% Vx0^(X2)(X)(Vxxx1*zeta^(X3)) + +perms1=[]; +perms2=[]; +Matrix=Ix2_Ezeta3; + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx0,Vx0,Vxxx1); + +% P(Vx0(X)(Vx1*zeta))(X)(Vxxx1*P(zeta(X)hx^(X2))) + +perms1=[1,3,2,4,5;3,1,2,4,5;1,2,3,5,4;1,3,2,5,4;3,1,2,5,4]; +perms2=perms1(:,[1,4,5]); perms2(perms2<=3)=1; perms2(perms2>1)=perms2(perms2>1)-2; +Matrix=kron(Ix_Ezeta2,hx2); + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx0,Vx1,Vxxx1); + +% P(Vx0(X)(Vx1*zeta))(X)(Vxxx1*P(zeta^(X2)(X)hx) + +perms1=[2,1,3,4,5;2,3,1,4,5;1,2,3,5,4;2,1,3,5,4;2,3,1,5,4]; +perms2=perms1(:,[1,4,5]); perms2(perms2<=3)=1; perms2(perms2>1)=perms2(perms2>1)-2; +Matrix=kron(Ix_Ezeta3,hx); + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx0,Vx1,Vxxx1); + +% P(Vx0(X)(Vx1*zeta))(X)(Vxxx1*zeta^(X3)) + +perms1=[1,2,3,5,4]; +perms2=perms1(:,[1,4,5]); perms2(perms2<=3)=1; perms2(perms2>1)=perms2(perms2>1)-2; +Matrix=Ix_Ezeta4; + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx0,Vx1,Vxxx1); + +% P(Vx0(X)(Vx1*zeta))(X)(Vxx1*(zeta(X)hxx)*Omega1 + +perms1=[1,2,4,3]; +perms2=perms1(:,[1,3,4]); perms2(perms2<=2)=1; perms2(perms2>1)=perms2(perms2>1)-1; +Matrix=kron(Ix_Ezeta2,Ix); + +tempresult=permutekron2([3,1,1,2],4,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx0,Vx1,Vxx1); + +tempmat_Omega1=reshape(kron(Ix,hxx),n_x^2,n_x^3)*OMEGA_x.OMEGA1; + +clear tempmat + +tempmat_Omega1=reshape(tempmat_Omega1,n_x^2,n_x^3); + +tempresult=reshape([reshape(tempresult,n_f*n_x^2,n_x^2)]',n_x^2*n_f,n_x^2); +tempresult=[reshape([tempresult*tempmat_Omega1]',n_x^5,n_f)]'; + +result=result+tempresult; + +clear tempresult + +% (Vx1*zeta)^(X2)(X)Vxxx0 + +perms1=[]; +perms2=[]; +Matrix=kron(Ezeta2,Ix3); + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx1,Vx1,Vxxx0); + +% (Vx1*zeta)^(X2)(X)(Vxxx1*P(zeta(X)hx^(X2)) + +perms1=[1,3,2,4,5;3,1,2,4,5]; +perms2=[1,2,3;1,2,3]; +Matrix=kron(Ezeta3,hx2); + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx1,Vx1,Vxxx1); +% (Vx1*zeta)^(X2)(X)(Vxxx1*P(zeta^(X2)(X)hx) + +perms1=[2,1,3,4,5;2,3,1,4,5]; +perms2=[1,2,3;1,2,3]; +Matrix=kron(Ezeta4,hx); + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx1,Vx1,Vxxx1); + +% (Vx1*zeta)^(X2)(X)(Vxxx1*zeta^(X3)) + +perms1=[]; +perms2=[]; +Matrix=Ezeta5; + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx1,Vx1,Vxxx1); + +% (Vx1*zeta)^(X2)(X)(Vxx1*(zeta(X)hxx)*Omega1 + +perms1=[]; +perms2=[]; +Matrix=kron(Ezeta3,Ix); + +tempresult=permutekron2([3,1,1,2],4,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx1,Vx1,Vxx1); + +tempresult=reshape([reshape(tempresult,n_f*n_x^2,n_x^2)]',n_x^2*n_f,n_x^2); +tempresult=[reshape([tempresult*tempmat_Omega1]',n_x^5,n_f)]'; + +result=result+tempresult; + +clear tempresult tempmat_Omega1 \ No newline at end of file diff --git a/105/replication_package/solution_methods/Perturbation/fvvvEvx3.m b/105/replication_package/solution_methods/Perturbation/fvvvEvx3.m new file mode 100644 index 0000000000000000000000000000000000000000..ed5161f6dbcbce27d40f5a1315646df49710004f --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/fvvvEvx3.m @@ -0,0 +1,33 @@ +% +% � Copyright, Oren Levintal, June 13, 2016. + +order=3; + +% Vx0^(X3) + +derivs=[3,1,1,1]; +perms1=[]; +perms2=perms1; +Matrix=[]; + +result= permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx0,Vx0,Vx0); + +% P(Vx0(X)[Vx1*zeta)^(X2)] + +perms1=[1,3,2;3,1,2]; +perms2=perms1; +Matrix=Ix_Ezeta2; + +result= result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx0,Vx1,Vx1); + +% (Vx1*zeta)^(X3) + +perms1=[]; +perms2=perms1; +Matrix=Ezeta3; + +result= result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx1,Vx1,Vx1); + + + + diff --git a/105/replication_package/solution_methods/Perturbation/fvvvEvx_vxx2.m b/105/replication_package/solution_methods/Perturbation/fvvvEvx_vxx2.m new file mode 100644 index 0000000000000000000000000000000000000000..5e7bf158aecc04d71833956c3119400de605354d --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/fvvvEvx_vxx2.m @@ -0,0 +1,92 @@ +% +% � Copyright, Oren Levintal, June 13, 2016. + +order=5; + +% Vx0(X)Vxx0^(X2) +derivs=[3,1,2,2]; + +perms1=[]; +perms2=perms1; +Matrix=[]; + +result= permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx0,Vxx0,Vxx0); + +% Vx0(X)P(Vxx0(X)(Vxx1*zeta^(X2)) + +perms1=[3,4,1,2,5]; +perms2=[2,1,3]; +Matrix=Ix3_Ezeta2; + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx0,Vxx0,Vxx1); + +% Vx0(X)P(Vxx1*P(hx(X)zeta))(X)(Vxx1*zeta^(X2)) + +perms1=[1,2,4,3,5;3,4,1,2,5;4,3,1,2,5]; +perms2=[1,2,3;1,2,3;1,2,3]; +Matrix=kron(kron(Ix,hx),Ezeta3); + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx0,Vxx1,Vxx1); + +% Vx0(X)(Vxx1*P(hx(X)zeta))(X)(Vxx1*P(zeta(X)hx)) + +perms1=[2,1,3,4,5;1,2,4,3,5;2,1,4,3,5]; +perms2=[1,2,3;1,2,3;1,2,3]; +Matrix=kron(kron(Ix,hx),kron(Ezeta2,hx)); + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx0,Vxx1,Vxx1); + +% Vx0(X)(Vxx1*zeta^(X2)(X)(Vxx1*zeta^(X2)) + +perms1=[]; +perms2=[]; +Matrix=kron(Ix,Ezeta4); + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx0,Vxx1,Vxx1); + +% (Vx1*zeta)(X)P((Vxx1*P(zeta(X)hx))(X)Vxx0) + +perms1=[1,2,4,3,5;3,4,1,2,5;4,3,1,2,5]; +perms2=[1,2,3;2,1,3;2,1,3]; +Matrix=kron(kron(Ezeta2,hx),Ix2); + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx1,Vxx1,Vxx0); + +% (Vx1*zeta)(X)P((Vxx1*zeta^(X2)(X)Vxx0) + +perms1=[3,4,1,2,5]; +perms2=[2,1,3]; +Matrix=kron(Ezeta3,Ix2); + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx1,Vxx1,Vxx0); + +% (Vx1*zeta)(X)P((Vxx1*zeta^(X2))(X)(Vxx1*P(zeta(X)hx))) + +perms1=[2,1,3,4,5;3,4,1,2,5;3,4,2,1,5]; +perms2=[1,2,3;2,1,3;2,1,3]; +Matrix=kron(Ezeta4,hx); + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx1,Vxx1,Vxx1); + +% (Vx1*zeta)(X)(Vxx1*P(zeta(X)hx))^(X2): this one is different, because the structrue of the +% unpermuted Matrix does not have all zeta's in a row. + +% To calculate expected value of the stochastic Matrix, use +% kron(Ix,Ix,zeta,zeta,zeta) and permute it. +Matrix=kron(Ezeta3,hx2); +tempindex=permute(reshape([1:n_x^5],n_x,n_x,n_x,n_x,n_x),[1,3,2,4,5]); +Matrix=Matrix(tempindex,tempindex); +clear tempindex + +perms1=[2,1,3,4,5;1,2,4,3,5;2,1,4,3,5;]; +perms2=[1,2,3;1,2,3;1,2,3]; + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx1,Vxx1,Vxx1); + +% (Vx1*zeta)(X)(Vxx1*zeta^(X2))^(X2) + +perms1=[]; +perms2=[]; +Matrix=Ezeta5; + +result=result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvv,Vx1,Vxx1,Vxx1); diff --git a/105/replication_package/solution_methods/Perturbation/fvvvvEvx3_vxx.m b/105/replication_package/solution_methods/Perturbation/fvvvvEvx3_vxx.m new file mode 100644 index 0000000000000000000000000000000000000000..2efe5a08561dd1195608499fb888adb7b68602c3 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/fvvvvEvx3_vxx.m @@ -0,0 +1,85 @@ +% +% � Copyright, Oren Levintal, June 13, 2016. + +order=5; + +% Vx0^(X3)(X)Vxx0 + +derivs=[4,1,1,1,2]; +perms1=[]; +perms2=perms1; +Matrix=[]; + +result= permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvvv,Vx0,Vx0,Vx0,Vxx0); + +% Vx0^(X3)(X)(Vxx1*zeta^(X2)) + +perms1=[]; +perms2=perms1; +Matrix=Ix3_Ezeta2; + +result= result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvvv,Vx0,Vx0,Vx0,Vxx1); + +% P(Vx0^(X2)(X)(Vx1*zeta)(X)(Vxx1*P(zeta(X)hx)) + +perms1=[1,2,4,3,5;1,2,4,5,3;2,1,3,4,5;2,1,4,3,5;2,1,4,5,3;]; +perms2=perms1(:,[1,3,4,5]); perms2(perms2==2)=1; perms2(perms2>1)=perms2(perms2>1)-1; +Matrix=kron(Ix2,kron(Ezeta2,hx)); + +result= result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvvv,Vx0,Vx0,Vx1,Vxx1); + +% P(Vx0^(X2)(X)(Vx1*zeta)(X)(Vxx1*zeta^(X2)) + +perms1=[1,2,4,3,5;1,2,4,5,3]; +perms2=perms1(:,[1,3,4,5]); perms2(perms2==2)=1; perms2(perms2>1)=perms2(perms2>1)-1; +Matrix=Ix2_Ezeta3; + +result= result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvvv,Vx0,Vx0,Vx1,Vxx1); + +% P(Vx0(X)(Vx1*zeta^(X2)(X)Vxx0) + +perms1=[1,2,3,5,4;1,2,5,3,4]; +perms2=perms1(:,[1,3,4,5]); perms2(perms2==2)=1; perms2(perms2>1)=perms2(perms2>1)-1; +Matrix=kron(Ix,kron(Ezeta2,Ix2)); + +result= result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvvv,Vx0,Vx1,Vx1,Vxx0); + +% P(Vx0(X)(Vx1*zeta^(X2)(X)(Vxx1*P(zeta(X)hx)) + +perms1=[1,2,3,5,4;1,2,5,3,4;2,1,3,4,5;2,1,3,5,4;2,1,5,3,4]; +perms2=perms1(:,[1,3,4,5]); perms2(perms2==2)=1; perms2(perms2>1)=perms2(perms2>1)-1; +Matrix=kron(Ix,kron(Ezeta3,hx)); + +result= result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvvv,Vx0,Vx1,Vx1,Vxx1); + +% P(Vx0(X)(Vx1*zeta^(X2)(X)(Vxx1*zeta^(X2)) + +perms1=[1,2,3,5,4;1,2,5,3,4]; +perms2=perms1(:,[1,3,4,5]); perms2(perms2==2)=1; perms2(perms2>1)=perms2(perms2>1)-1; +Matrix=Ix_Ezeta4; + +result= result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvvv,Vx0,Vx1,Vx1,Vxx1); + +% (Vx1*zeta)^(X3)(X)Vxx0 + +perms1=[]; +perms2=[]; +Matrix=kron(Ezeta3,Ix2); + +result= result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvvv,Vx1,Vx1,Vx1,Vxx0); + +% (Vx1*zeta)^(X3)(X)(Vxx1*P(zeta(X)hx) + +perms1=[2,1,3,4,5]; +perms2=perms1(:,[1,3,4,5]); perms2(perms2==2)=1; perms2(perms2>1)=perms2(perms2>1)-1; +Matrix=kron(Ezeta4,hx); + +result= result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvvv,Vx1,Vx1,Vx1,Vxx1); + +% (Vx1*zeta)^(X3)(X)(Vxx1*zeta2^(X2)) + +perms1=[]; +perms2=[]; +Matrix=Ezeta5; + +result= result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvvv,Vx1,Vx1,Vx1,Vxx1); diff --git a/105/replication_package/solution_methods/Perturbation/fvvvvEvx3_vxxU5.m b/105/replication_package/solution_methods/Perturbation/fvvvvEvx3_vxxU5.m new file mode 100644 index 0000000000000000000000000000000000000000..6efce66fb795677a9afe3d053b945faf508ee61b --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/fvvvvEvx3_vxxU5.m @@ -0,0 +1,85 @@ +% +% � Copyright, Oren Levintal, June 13, 2016. + +order=5; + +% Vx0^(X3)(X)Vxx0 + +derivs=[4,1,1,1,2]; +perms1=[]; +perms2=perms1; +Matrix=[]; + +result= permutekron3(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,Ui,fvvvv,Vx0,Vx0,Vx0,Vxx0); + +% Vx0^(X3)(X)(Vxx1*zeta^(X2)) + +perms1=[]; +perms2=perms1; +Matrix=Ix3_Ezeta2; + +result= result+permutekron3(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,Ui,fvvvv,Vx0,Vx0,Vx0,Vxx1); + +% P(Vx0^(X2)(X)(Vx1*zeta)(X)(Vxx1*P(zeta(X)hx)) + +perms1=[1,2,4,3,5;1,2,4,5,3;2,1,3,4,5;2,1,4,3,5;2,1,4,5,3;]; +perms2=perms1(:,[1,3,4,5]); perms2(perms2==2)=1; perms2(perms2>1)=perms2(perms2>1)-1; +Matrix=kron(Ix2,kron(Ezeta2,hx)); + +result= result+permutekron3(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,Ui,fvvvv,Vx0,Vx0,Vx1,Vxx1); + +% P(Vx0^(X2)(X)(Vx1*zeta)(X)(Vxx1*zeta^(X2)) + +perms1=[1,2,4,3,5;1,2,4,5,3]; +perms2=perms1(:,[1,3,4,5]); perms2(perms2==2)=1; perms2(perms2>1)=perms2(perms2>1)-1; +Matrix=Ix2_Ezeta3; + +result= result+permutekron3(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,Ui,fvvvv,Vx0,Vx0,Vx1,Vxx1); + +% P(Vx0(X)(Vx1*zeta^(X2)(X)Vxx0) + +perms1=[1,2,3,5,4;1,2,5,3,4]; +perms2=perms1(:,[1,3,4,5]); perms2(perms2==2)=1; perms2(perms2>1)=perms2(perms2>1)-1; +Matrix=kron(Ix,kron(Ezeta2,Ix2)); + +result= result+permutekron3(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,Ui,fvvvv,Vx0,Vx1,Vx1,Vxx0); + +% P(Vx0(X)(Vx1*zeta^(X2)(X)(Vxx1*P(zeta(X)hx)) + +perms1=[1,2,3,5,4;1,2,5,3,4;2,1,3,4,5;2,1,3,5,4;2,1,5,3,4]; +perms2=perms1(:,[1,3,4,5]); perms2(perms2==2)=1; perms2(perms2>1)=perms2(perms2>1)-1; +Matrix=kron(Ix,kron(Ezeta3,hx)); + +result= result+permutekron3(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,Ui,fvvvv,Vx0,Vx1,Vx1,Vxx1); + +% P(Vx0(X)(Vx1*zeta^(X2)(X)(Vxx1*zeta^(X2)) + +perms1=[1,2,3,5,4;1,2,5,3,4]; +perms2=perms1(:,[1,3,4,5]); perms2(perms2==2)=1; perms2(perms2>1)=perms2(perms2>1)-1; +Matrix=Ix_Ezeta4; + +result= result+permutekron3(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,Ui,fvvvv,Vx0,Vx1,Vx1,Vxx1); + +% (Vx1*zeta)^(X3)(X)Vxx0 + +perms1=[]; +perms2=[]; +Matrix=kron(Ezeta3,Ix2); + +result= result+permutekron3(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,Ui,fvvvv,Vx1,Vx1,Vx1,Vxx0); + +% (Vx1*zeta)^(X3)(X)(Vxx1*P(zeta(X)hx) + +perms1=[2,1,3,4,5]; +perms2=perms1(:,[1,3,4,5]); perms2(perms2==2)=1; perms2(perms2>1)=perms2(perms2>1)-1; +Matrix=kron(Ezeta4,hx); + +result= result+permutekron3(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,Ui,fvvvv,Vx1,Vx1,Vx1,Vxx1); + +% (Vx1*zeta)^(X3)(X)(Vxx1*zeta2^(X2)) + +perms1=[]; +perms2=[]; +Matrix=Ezeta5; + +result= result+permutekron3(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,Ui,fvvvv,Vx1,Vx1,Vx1,Vxx1); diff --git a/105/replication_package/solution_methods/Perturbation/fvvvvEvx4.m b/105/replication_package/solution_methods/Perturbation/fvvvvEvx4.m new file mode 100644 index 0000000000000000000000000000000000000000..bf60c7f8cb8b4f96d3bb90f73e171a48ecbec4f0 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/fvvvvEvx4.m @@ -0,0 +1,38 @@ +% +% � Copyright, Oren Levintal, June 13, 2016. + +order=4; + +% Vx0^(X4) + +derivs=[4,1,1,1,1]; +perms1=[]; +perms2=perms1; +Matrix=[]; + +result= permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvvv,Vx0,Vx0,Vx0,Vx0); + +% P(Vx0(X)[Vx1*zeta)^(X3)] + +perms1=[1,2,4,3;1,4,2,3;4,1,2,3]; +perms2=perms1; +Matrix=Ix_Ezeta3; + +result= result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvvv,Vx0,Vx1,Vx1,Vx1); + +% P(Vx0^(X2)(X)(Vx1*zeta)^(X2)) + +perms1=[1,3,2,4;1,3,4,2;3,1,2,4;3,1,4,2;3,4,1,2]; +perms2=perms1; +Matrix=Ix2_Ezeta2; + +result= result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvvv,Vx0,Vx0,Vx1,Vx1); + +% (Vx1*zeta)^(X4) + +perms1=[]; +perms2=perms1; +Matrix=Ezeta4; + +result= result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvvv,Vx1,Vx1,Vx1,Vx1); + diff --git a/105/replication_package/solution_methods/Perturbation/fvvvvvEvx5.m b/105/replication_package/solution_methods/Perturbation/fvvvvvEvx5.m new file mode 100644 index 0000000000000000000000000000000000000000..3ac53c9ea03bb80ab3af34fe3b0c590f0f3a3990 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/fvvvvvEvx5.m @@ -0,0 +1,46 @@ +% +% � Copyright, Oren Levintal, June 13, 2016. + +order=5; + +% Vx0^(X5) + +derivs=[5,1,1,1,1,1]; +perms1=[]; +perms2=perms1; +Matrix=[]; + +result= permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvvvv,Vx0,Vx0,Vx0,Vx0,Vx0); + +% P(Vx0(X)[Vx1*zeta)^(X4)] + +perms1=[1,2,3,5,4;1,2,5,3,4;1,5,2,3,4;5,1,2,3,4]; +perms2=perms1; +Matrix=Ix_Ezeta4; + +result= result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvvvv,Vx0,Vx1,Vx1,Vx1,Vx1); + +% P(Vx0^(X2)(X)(Vx1*zeta)^(X3)) + +perms1=[1,2,4,3,5;1,2,4,5,3;1,4,2,3,5;1,4,2,5,3;1,4,5,2,3;4,1,2,3,5;4,1,2,5,3;4,1,5,2,3;4,5,1,2,3]; +perms2=perms1; +Matrix=Ix2_Ezeta3; + +result= result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvvvv,Vx0,Vx0,Vx1,Vx1,Vx1); + +% P(Vx0^(X3)(X)(Vx1*zeta)^(X2)) + +perms1=[1,3,2,4,5;1,3,4,2,5;1,3,4,5,2;3,1,2,4,5;3,1,4,2,5;3,1,4,5,2;3,4,1,2,5;3,4,1,5,2;3,4,5,1,2]; +perms2=perms1; +Matrix=Ix3_Ezeta2; + +result= result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvvvv,Vx0,Vx0,Vx0,Vx1,Vx1); + +% (Vx1*zeta)^(X5) + +perms1=[]; +perms2=perms1; +Matrix=Ezeta5; + +result= result+permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,fvvvvv,Vx1,Vx1,Vx1,Vx1,Vx1); + diff --git a/105/replication_package/solution_methods/Perturbation/fvvvvvEvx5U5.m b/105/replication_package/solution_methods/Perturbation/fvvvvvEvx5U5.m new file mode 100644 index 0000000000000000000000000000000000000000..5a78247239d1fba7a5f69662f67b0cd7b94ec735 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/fvvvvvEvx5U5.m @@ -0,0 +1,46 @@ +% +% � Copyright, Oren Levintal, June 13, 2016. + +order=5; + +% Vx0^(X5) + +derivs=[5,1,1,1,1,1]; +perms1=[]; +perms2=perms1; +Matrix=[]; + +result= permutekron3(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,Ui,fvvvvv,Vx0,Vx0,Vx0,Vx0,Vx0); + +% P(Vx0(X)[Vx1*zeta)^(X4)] + +perms1=[1,2,3,5,4;1,2,5,3,4;1,5,2,3,4;5,1,2,3,4]; +perms2=perms1; +Matrix=Ix_Ezeta4; + +result= result+permutekron3(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,Ui,fvvvvv,Vx0,Vx1,Vx1,Vx1,Vx1); + +% P(Vx0^(X2)(X)(Vx1*zeta)^(X3)) + +perms1=[1,2,4,3,5;1,2,4,5,3;1,4,2,3,5;1,4,2,5,3;1,4,5,2,3;4,1,2,3,5;4,1,2,5,3;4,1,5,2,3;4,5,1,2,3]; +perms2=perms1; +Matrix=Ix2_Ezeta3; + +result= result+permutekron3(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,Ui,fvvvvv,Vx0,Vx0,Vx1,Vx1,Vx1); + +% P(Vx0^(X3)(X)(Vx1*zeta)^(X2)) + +perms1=[1,3,2,4,5;1,3,4,2,5;1,3,4,5,2;3,1,2,4,5;3,1,4,2,5;3,1,4,5,2;3,4,1,2,5;3,4,1,5,2;3,4,5,1,2]; +perms2=perms1; +Matrix=Ix3_Ezeta2; + +result= result+permutekron3(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,Ui,fvvvvv,Vx0,Vx0,Vx0,Vx1,Vx1); + +% (Vx1*zeta)^(X5) + +perms1=[]; +perms2=perms1; +Matrix=Ezeta5; + +result= result+permutekron3(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,Ui,fvvvvv,Vx1,Vx1,Vx1,Vx1,Vx1); + diff --git a/105/replication_package/solution_methods/Perturbation/gaussian_moments.m b/105/replication_package/solution_methods/Perturbation/gaussian_moments.m new file mode 100644 index 0000000000000000000000000000000000000000..c0f9493a0e199d2013f0f8b12d7f8b656a6f072d --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/gaussian_moments.m @@ -0,0 +1,29 @@ +function [ M ] = gaussian_moments( n_e ) +%Calculate cross moments of a stochastic vector of size n_e-by-1 +%distributed normally with mean zero(n_e,1) and variance matrix eye(n_e). +%The cross moments are defined: +%M2=E(kron(x,x)) +%M3=E(kron(x,x,x)) +%M4=E(kron(x,x,x,x)) +%M5=E(kron(x,x,x,x,x)) +%They are stored as fields of struct M. +% +% � Copyright, Oren Levintal, June 13, 2016. + +M.M2=speye(n_e); M.M2=M.M2(:); +M.M3=sparse(n_e^3,1); +M.M4=sparse(n_e^4,1); +for i=1:n_e + M.M4(sub2ind([n_e,n_e,n_e,n_e],i,i,i,i))=3; +end +for i=1:n_e-1 + for j=i+1:n_e + tempP=perms([i,i,j,j]); + M.M4(sub2ind([n_e,n_e,n_e,n_e],tempP(:,1),tempP(:,2),tempP(:,3),tempP(:,4)))=1; + end +end + +M.M5=sparse(n_e^5,1); + +end + diff --git a/105/replication_package/solution_methods/Perturbation/gen_fun.m b/105/replication_package/solution_methods/Perturbation/gen_fun.m new file mode 100644 index 0000000000000000000000000000000000000000..1db402ced1c90c83c24e75b492e9b8512ca7ba7e --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/gen_fun.m @@ -0,0 +1,49 @@ +function gen_fun(f,symparams,v,fname,varargin) +% +% � Copyright, Oren Levintal, June 13, 2016. + +rowformat=0; % function returns a column vector (number of columns>1 in vectorized form) +if ~isempty(varargin) + if strcmp(varargin{1},'row') + rowformat=1; % function returns a row vector (number of rows>1 in vectorized form) + end +end + +f=f(:); +if numel(f)>1 + nnzf=1-logical(f==0); + index=find(nnzf); +else + index=1; +end +fid = fopen([fname '_fun.m'], 'w'); +fprintf(fid,'%s\n', ['function function_f=' fname '_fun(variables_v,parameters)']); +for i=1:length(symparams) + if strcmp(char(symparams(i)),'function_f') || strcmp(char(symparams(i)),'variables_v') || strcmp(char(symparams(i)),'parameters') + error([char(symparams(i)) 'is reserved. Change variable/parameter name.']); + end + fprintf(fid,'%s\n', [char(symparams(i)) '=parameters(' num2str(i) ');']); +end +for i=1:length(v) + if strcmp(char(v(i)),'function_f') || strcmp(char(v(i)),'variables_v') || strcmp(char(v(i)),'parameters') + error([char(v(i)) 'is reserved. Change variable/parameter name.']); + end + fprintf(fid,'%s\n', [char(v(i)) '=variables_v(' num2str(i) ',:);']); +end +if isempty(f) + fprintf(fid,'%s\n', ['function_f=[];']); +else + if rowformat==0 + fprintf(fid,'%s\n', ['function_f=zeros(' num2str(numel(f)) ',size(variables_v,2));']); + elseif rowformat==1 + fprintf(fid,'%s\n', ['function_f=zeros(size(variables_v,2),' num2str(numel(f)) ');']); + end + for i=index(:)' + if rowformat==0 + disp_fun('function_f',f(i),i,fid); + elseif rowformat==1 + disp_fun_row('function_f',f(i),i,fid); + end + end +end +fclose(fid); diff --git a/105/replication_package/solution_methods/Perturbation/getderivs.m b/105/replication_package/solution_methods/Perturbation/getderivs.m new file mode 100644 index 0000000000000000000000000000000000000000..6e2965368964286e78345011cd19f50653e71047 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/getderivs.m @@ -0,0 +1,104 @@ +function [index]=getderivs(f,v,order,symparams,fname) +%This function differentiates f w.r.t v up to order, and generates +%vectorized functions that calculate these derivatives. The derivatives are +%stored in a sparse matrix of dimensions n_f,n_v^order, where n_f +%is the size of f and n_v is the size of v. +% +% � Copyright, Oren Levintal, June 13, 2016. + + +if order<1 + error('order must be at least 1') +end + +f=f(:); +v=v(:); + +n_f=length(f); +n_v=length(v); + +uncomp=cell(n_f,order); +derivs=cell(n_f,order); + +% differentiate rows of f separately w.r.t to relevant variables ONLY +relevant_v=logical(jacobian(f(:),v)~=0); +for frow=1:n_f + [derivs(frow,:),uncomp(frow,:)]=compderivs(f(frow),v(relevant_v(frow,:)),order); +end + +% transform uncompression matrices into indices, and create totalloc. +% totalloc(frow,k) stores the total number of nonzero k-order derivatives of f(frow), including all (nonzero) mixed derivatives. +index=[]; +totalloc=zeros(n_f,order); +for k=1:order + for frow=1:n_f + [index.loc{frow,k},index.nnz{frow,k}]=find(uncomp{frow,k}); + totalloc(frow,k)=length(index.loc{frow,k}); + if isempty(index.loc{frow,k}) + index.loc{frow,k}=0; + end + end +end + +% create matlab functions to calculate the derivatives +for k=1:order + fun_name=[fname '_d' num2str(k)]; + fid = fopen([fun_name '.m'], 'w'); + fprintf(fid,'%s\n', ['function derivs=' fun_name '(vars,params,index)']); +% fprintf(fid,'%s\n', 'n_s=size(vars,1);'); + for i=1:length(v) + fprintf(fid,'%s\n', [char(v(i)) '=vars(' num2str(i) ');']); + end + for i=1:length(symparams) + fprintf(fid,'%s\n', [char(symparams(i)) '=params(' num2str(i) ');']); + end + fprintf(fid,'%s\n', ['full_rows=zeros(' num2str(sum(totalloc(:,k))) ',1);']); + fprintf(fid,'%s\n', ['full_cols=zeros(' num2str(sum(totalloc(:,k))) ',1);']); + fprintf(fid,'%s\n', ['full_vals=zeros(' num2str(sum(totalloc(:,k))) ',1);']); + + for frow=1:n_f + if totalloc(frow,k)>0 + tempderiv=derivs{frow,k}; + fprintf(fid,'%s\n', ['compressed_deriv=zeros(' num2str(length(tempderiv)) ',1);']); + for i=1:length(tempderiv) + disp_fun('compressed_deriv',tempderiv(i),i,fid); + end + fprintf(fid,'%s\n', ['uncompressed_deriv=compressed_deriv(index.nnz{' num2str(frow) ',' num2str(k) '});']); + tempstart=sum(totalloc(1:frow-1,k)); + tempend=sum(totalloc(1:frow,k)); + fprintf(fid,'%s\n', ['full_vals(' num2str(tempstart+1) ':' num2str(tempend) ')=uncompressed_deriv;']); + + % transform columns to n-dimensions + tempcols='tempcol1'; + n_relevant_v=sum(relevant_v(frow,:)); + tempdim=num2str(n_relevant_v); + for tempk=2:k + tempcols=[tempcols ',tempcol' num2str(tempk)]; + tempdim=[tempdim ',' num2str(n_relevant_v)]; + end + eval(['[' tempcols ']=ind2sub([' tempdim '],index.loc{' num2str(frow) ',' num2str(k) '});']); + tempcols=eval(['[' tempcols ']']); + % each row of f was differentiated w.r.t relevant variables. + % now, translate dimensions to the full vector of variables. + tempv=1:n_v; + takev=tempv(relevant_v(frow,:)); + tempcols=takev(tempcols); + % return to linear index + tempdims='tempcols(:,1)'; + for tempi=2:size(tempcols,2) + tempdims=[tempdims,',tempcols(:,' num2str(tempi) ')']; + end + if k>1 + eval(['tempcols=sub2ind(repmat(' num2str(n_v) ',1,' num2str(k) '),' tempdims ');']); + end + index.loc{frow,k}=tempcols; + fprintf(fid,'%s\n', ['full_cols(' num2str(tempstart+1) ':' num2str(tempend) ')=index.loc{' num2str(frow) ',' num2str(k) '};']); + + fprintf(fid,'%s\n', ['full_rows(' num2str(tempstart+1) ':' num2str(tempend) ')=' num2str(frow) ';']); + end + end + fprintf(fid,'%s\n', ['derivs=sparse(full_rows,full_cols,full_vals,' num2str(n_f) ',' num2str(n_v^k) ');']); + fclose(fid); +end + + diff --git a/105/replication_package/solution_methods/Perturbation/getderivs_vector.m b/105/replication_package/solution_methods/Perturbation/getderivs_vector.m new file mode 100644 index 0000000000000000000000000000000000000000..65b46fb783a35b4da0f250e91f0f64fc0962cd63 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/getderivs_vector.m @@ -0,0 +1,102 @@ +function [index]=getderivs_vector(f,v,order,symparams,fname) +%This function differentiates f w.r.t v up to order, and generates +%vectorized functions that calculate these derivatives. The derivatives are +%stored in a sparse column vector of length n_f*n_v^order, where n_f +%is the size of f and n_v is the size of v. +% +% � Copyright, Oren Levintal, June 13, 2016. + + +if order<1 + error('order must be at least 1') +end + +f=f(:); +v=v(:); + +n_f=length(f); +n_v=length(v); + +uncomp=cell(n_f,order); +derivs=cell(n_f,order); + +% differentiate rows of f separately w.r.t to relevant variables ONLY +relevant_v=logical(jacobian(f(:),v)~=0); +for frow=1:n_f + [derivs(frow,:),uncomp(frow,:)]=compderivs(f(frow),v(relevant_v(frow,:)),order); +end + +% transform uncompression matrices into indices, and create totalloc. +% totalloc(frow,k) stores the total number of nonzero k-order derivatives of f(frow), including all (nonzero) mixed derivatives. +index=[]; +totalloc=zeros(n_f,order); +for k=1:order + for frow=1:n_f + [index.loc{frow,k},index.nnz{frow,k}]=find(uncomp{frow,k}); + totalloc(frow,k)=length(index.loc{frow,k}); + if isempty(index.loc{frow,k}) + index.loc{frow,k}=0; + end + end +end + +% create matlab functions to calculate the derivatives +for k=1:order + fun_name=[fname '_d' num2str(k)]; + fid = fopen([fun_name '.m'], 'w'); + fprintf(fid,'%s\n', ['function derivs=' fun_name '(vars,params,index)']); + for i=1:length(v) + fprintf(fid,'%s\n', [char(v(i)) '=vars(' num2str(i) ');']); + end + for i=1:length(symparams) + fprintf(fid,'%s\n', [char(symparams(i)) '=params(' num2str(i) ');']); + end + fprintf(fid,'%s\n', ['full_rows=zeros(' num2str(sum(totalloc(:,k))) ',1);']); + fprintf(fid,'%s\n', ['full_vals=zeros(' num2str(sum(totalloc(:,k))) ',1);']); + + for frow=1:n_f + if totalloc(frow,k)>0 + tempderiv=derivs{frow,k}; + fprintf(fid,'%s\n', ['compressed_deriv=zeros(' num2str(length(tempderiv)) ',1);']); + for i=1:length(tempderiv) + disp_fun('compressed_deriv',tempderiv(i),i,fid); + end + fprintf(fid,'%s\n', ['uncompressed_deriv=compressed_deriv(index.nnz{' num2str(frow) ',' num2str(k) '});']); + tempstart=sum(totalloc(1:frow-1,k)); + tempend=sum(totalloc(1:frow,k)); + fprintf(fid,'%s\n', ['full_vals(' num2str(tempstart+1) ':' num2str(tempend) ')=uncompressed_deriv;']); + + % transform columns to n-dimensions + tempcols='tempcol1'; + n_relevant_v=sum(relevant_v(frow,:)); + tempdim=num2str(n_relevant_v); + for tempk=2:k + tempcols=[tempcols ',tempcol' num2str(tempk)]; + tempdim=[tempdim ',' num2str(n_relevant_v)]; + end + eval(['[' tempcols ']=ind2sub([' tempdim '],index.loc{' num2str(frow) ',' num2str(k) '});']); + tempcols=eval(['[' tempcols ']']); + % each row of f was differentiated w.r.t relevant variables. + % now, translate dimensions to the full vector of variables. + tempv=1:n_v; + takev=tempv(relevant_v(frow,:)); + tempcols=takev(tempcols); + % create a linear index + tempdims='tempcols(:,1)'; + for tempi=2:size(tempcols,2) + tempdims=[tempdims,',tempcols(:,' num2str(tempi) ')']; + end + if k>1 + eval(['tempcols=sub2ind(repmat(' num2str(n_v) ',1,' num2str(k) '),' tempdims ');']); + end + index.loc{frow,k}=sub2ind([n_f,n_v^k],repmat(frow,length(tempcols),1),tempcols(:)); + + fprintf(fid,'%s\n', ['full_rows(' num2str(tempstart+1) ':' num2str(tempend) ')=index.loc{' num2str(frow) ',' num2str(k) '};']); + + end + end + fprintf(fid,'%s\n', ['derivs=sparse(full_rows,ones(length(full_vals),1),full_vals,' num2str(n_f*n_v^k) ',1);']); + fclose(fid); +end + + diff --git a/105/replication_package/solution_methods/Perturbation/innerkron.m b/105/replication_package/solution_methods/Perturbation/innerkron.m new file mode 100644 index 0000000000000000000000000000000000000000..b0566a60ab28947945e38ed1fff2ed78466fd834 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/innerkron.m @@ -0,0 +1,21 @@ +function [ R ] = innerkron( n_f,n_v,fmat, varargin ) +%innerkron Calculates expressions such as fmat(A*B*C....), where fmat is a +%matrix with symmetric columns. A, B, C, ..., are matrices, and * is a +%Kronecker product. These expressions arise in high order multivariate +%chain rules of the composite function f(v(x)). In this case, fmat is an +%array of high derivatives of f w.r.t v, reshaped into a matrix with the +%same number of rows as f. A, B, C, etc would be derivatives of v w.r.t x. +% +% � Copyright, Oren Levintal, June 13, 2016. + +R=fmat; + +for j=1:length(varargin) + R=reshape(R,numel(R)/n_v,n_v); + R=(R*reshape(varargin{j},n_v,numel(varargin{j})/n_v))'; +end + +R=reshape(R,numel(R)/n_f,n_f)'; + +end + diff --git a/105/replication_package/solution_methods/Perturbation/permutekron2.m b/105/replication_package/solution_methods/Perturbation/permutekron2.m new file mode 100644 index 0000000000000000000000000000000000000000..aab9fa8d0358584d2563f7bbafa7e600f073f15a --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/permutekron2.m @@ -0,0 +1,142 @@ +function [ R ] = permutekron2(derivs,order,perms1,perms2,n_v,n_x,n_f,Matrix,varargin ) +%permutekron: This function calculates expressions such as +%(fvvv*kron(Vx0,Vx1,Vx1))*E(kron(hx,zeta,zeta)), or +%(fvvv*kron(Vx0,Vx1,Vx1))*E(kron(I,zeta,zeta))*(kron(hx,I,I)), which is +%equivalent. The function also calculates permutations of these +%expressions. The permutations are in perms1 and perms2. The output is the sum +%of all permutations. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if isempty(Matrix) % no stochastic matrix + stochastic_matrix_exists=0; + Matrix=1; +else + stochastic_matrix_exists=1; +end + +if nnz(Matrix)==0 % stochastic matrix is all zero + R=sparse(n_f,n_x^order); +else + if isempty(perms2) + perms2_exists=0; % no permutation for nonstochastic part + perms2_trivial=1; + elseif nnz(perms2-repmat(1:size(perms2,2),size(perms2,1),1))==0 + perms2_exists=0; % permutation for nonstochastic part are degenerate + perms2_trivial=1; + else + perms2_exists=1; + perms2_order=size(perms2,2); + end + + % 2. The second term is the stochastic matrix + + R=Matrix; + stochR=R; + % 3. Prepare an index for the permutations. + + if order>1 && ~isempty(perms1) + tempind=[1:n_x^order]; + ind1=reshape(tempind,repmat(n_x,1,order)); + if perms2_exists==1 + ind2=reshape(tempind,[n_x.^derivs(end:-1:2),1]); + end + clear tempind + +% sparseM=speye(n_x^order); + end + + % 4. Calculate permutations and sum. + + for i=1:size(perms1,1) + % a. Permute + if isequal(perms1(i,:),1:order) + perms1_trivial=1; + else + permute_ind1=permute(ind1,perms1(i,:)); + perms1_trivial=0; + end + if perms2_exists==1 + if isequal(perms2(i,:),1:perms2_order) + perms2_trivial=1; + else +% permute_ind2=permute(ind2,perms2(i,:)); + ipermute_ind2=ipermute(ind2,perms2(i,:)); + perms2_trivial=0; + end + end + if perms1_trivial==0 + if perms2_trivial==0 +% permute_stochR=sparseM(:,permute_ind2)*sparseM(:,permute_ind1)'*stochR(:,permute_ind1);%P2*P1'*M*P1 + permute_stochR=stochR(:,permute_ind1); + + permute_stochR=permute_stochR(permute_ind1(ipermute_ind2),:); +% max(max(abs(permute_stochR-ipermute_stochR))) +% isequal(permute_stochR,ipermute_stochR) + else +% permute_stochR=sparseM(:,permute_ind1)'*stochR(:,permute_ind1); + permute_stochR=stochR(:,permute_ind1); + permute_stochR=permute_stochR(permute_ind1,:); +% isequal(permute_stochR,ipermute_stochR) + end + else + if perms2_trivial==0 +% permute_stochR=sparseM(:,permute_ind2)*stochR; + permute_stochR=stochR(ipermute_ind2,:); + else + permute_stochR=stochR; + end + end + % b. Sum + R=R+permute_stochR; + end + + + % 1. Calculate the nonstochastic part: For example: + % fvvv*kron(Vx0,Vx1,Vx1). + if stochastic_matrix_exists==0 + fmat=varargin{1}; + + temp=reshape(fmat,numel(fmat)/n_v,n_v); + for j=1:length(derivs)-2 + temp=Treshape(bigprod(temp,sparse(varargin{j+1})),numel(temp)/n_v^2*n_x^derivs(j+1),n_v); + end + + j=length(derivs)-1; + nonstoch=[reshape([temp*sparse(varargin{j+1})]',numel(temp)/n_v*n_x^derivs(j+1)/n_f,n_f)]'; + R=nonstoch*R; + else + nnzx=logical(sum(logical(R),2)); + + fmat=varargin{1}; + temp=reshape(fmat,numel(fmat)/n_v,n_v); + for j=1:length(derivs)-2 + vmat=sparse(varargin{j+1}); + % choose nonzero columns of vmat + nnzx=reshape(nnzx,n_x^(order-derivs(j+1)),n_x^derivs(j+1)); + tempind=logical(sum(nnzx,1)); % identify relevant columns + vmat=vmat(:,tempind); % extract relevant columns + % add the zero columns + [temprow,tempcol,tempvals]=find(vmat); + ztempind=find(tempind); + vmat=sparse(temprow,ztempind(tempcol),tempvals,size(vmat,1),n_x^derivs(j+1)); + + temp=Treshape(bigprod(temp,vmat),numel(temp)/n_v^2*n_x^derivs(j+1),n_v); + nnzx=nnzx'; + end + + j=length(derivs)-1; + vmat=sparse(varargin{j+1}); + % choose nonzero columns of vmat + nnzx=reshape(nnzx,n_x^(order-derivs(j+1)),n_x^derivs(j+1)); + tempind=logical(sum(nnzx,1)); % identify relevant columns + vmat=vmat(:,tempind); % extract relevant columns + % add the zero columns + [temprow,tempcol,tempvals]=find(vmat); + ztempind=find(tempind); + vmat=sparse(temprow,ztempind(tempcol),tempvals,size(vmat,1),n_x^derivs(j+1)); + nonstoch=[reshape([bigprod(temp,vmat)]',numel(temp)/n_v*n_x^derivs(j+1)/n_f,n_f)]'; + R=nonstoch*R; + end +end + diff --git a/105/replication_package/solution_methods/Perturbation/permutekronB2.m b/105/replication_package/solution_methods/Perturbation/permutekronB2.m new file mode 100644 index 0000000000000000000000000000000000000000..e4c3e7d641ad256a6d652b5c4dc24875dda086cf --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/permutekronB2.m @@ -0,0 +1,40 @@ + +function [ R ] = permutekronB2(order,perms1,n_x,Matrix,varargin ) +%permutekronB: This function calculates product of two or three matrices of +%the form:W3*E(kron(hx,zeta,zeta)) or W3*E(kron(hx,zeta,zeta))*(hx*I*I), and +%permutations of this expression, and sums everything. +% +% � Copyright, Oren Levintal, June 13, 2016. + +W=varargin{1}; +unique=size(W,1); + +if nnz(Matrix)==0 + R=sparse(unique,n_x^order); +else + % 1. Calculate product of first two terms. + + R=W*Matrix; + + % 2. Prepare an index for the permutations. + + if order>1 + ind=reshape([1:n_x^order],repmat(n_x,1,order)); + end + + % 4. Calculate permutations and sum. + + for i=1:size(perms1,1) + % a. permute the (expected value of the) stochastic part by permutation + % indices. + permute_ind=permute(ind,perms1(i,:)); + permute_Matrix=Matrix(permute_ind,permute_ind); + + tempresult=W*permute_Matrix; + + % b. Sum everything. + R=R+tempresult; + end + +end + diff --git a/105/replication_package/solution_methods/Perturbation/policy.m b/105/replication_package/solution_methods/Perturbation/policy.m new file mode 100644 index 0000000000000000000000000000000000000000..b9fc1f9beed8d0d7bfef7240e0a878540e1e8acc --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/policy.m @@ -0,0 +1,56 @@ +function [ g,h ] = policy( nx,nyss,nxss,derivs,approx,varargin ) +%[g,h]=policy(nx,nxss,derivs,approx) evaluates the policy functions g and h +% at state nx, given the steady state values nyss and nxss, the structure +% derivs and the approximation order approx. +% +% � Copyright, Oren Levintal, June 13, 2016. + +[n_y,n_x]=size(derivs.gx); + + +xhat=[nx(:)-nxss(:);1]; + +pf=[derivs.gx;derivs.hx]*xhat; + +n_f=length(pf); + +if isempty(varargin) + + if approx>=2 + xhat2=kron(xhat,xhat); + pf=pf+[derivs.gxx;derivs.hxx]*xhat2/2; + end + if approx>=3 + xhat3=kron(xhat2,xhat); + pf=pf+[derivs.gxxx;derivs.hxxx]*xhat3/6; + end + if approx>=4 + xhat4=kron(xhat3,xhat); + pf=pf+[derivs.gxxxx;derivs.hxxxx]*xhat4/24; + end + if approx>=5 + xhat5=kron(xhat4,xhat); + pf=pf+[derivs.gxxxxx;derivs.hxxxxx]*xhat5/120; + end +else + derivsc=varargin{1}; + if approx>=2 + pf=pf+innerkron(n_f,n_x,[derivsc.gxx;derivsc.hxx],xhat,xhat)/2; + end + if approx>=3 + pf=pf+innerkron(n_f,n_x,[derivsc.gxxx;derivsc.hxxx],xhat,xhat,xhat)/6; + end + if approx>=4 + pf=pf+innerkron(n_f,n_x,[derivsc.gxxxx;derivsc.hxxxx],xhat,xhat,xhat,xhat)/24; + end + if approx>=5 + pf=pf+innerkron(n_f,n_x,[derivsc.gxxxxx;derivsc.hxxxxx],xhat,xhat,xhat,xhat,xhat)/120; + end +end +R=pf+[nyss;nxss]; + +g=R(1:n_y); +h=R(n_y+1:end); + +end + diff --git a/105/replication_package/solution_methods/Perturbation/simul.m b/105/replication_package/solution_methods/Perturbation/simul.m new file mode 100644 index 0000000000000000000000000000000000000000..e7fc15be47741fb89dae034941c858de9abaf555 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/simul.m @@ -0,0 +1,169 @@ +function [yt,xt]=simul(x0,shocks,nyss,nxss,eta,derivs,approx,pruning,varargin) +% [yt,xt]=simul(x0,shocks,nyss,nxss,eta,derivs,approx,pruning) simulates +% the model from the initial state x0. shocks is a matrix with n_e rows +% and T columns, where n_e is the number of shocks (corresponds to the +% columns of eta), and T is the length of the simulation. The function +% returns yt and xt for T+1 periods. The first period is the initial state +% and the rest T periods correspond to the shocks. pruning=0 is a simple +% simulation without pruning. pruning=1 is a pruned simulation. The +% pruning algorithm follows Andreasen, Fernandez-Villaverde and +% Rubio-Ramirez (2013) "The Pruned State-Space System for Non-Linear DSGE Models: +% Theory and Empirical Applications". +% +% � Copyright, Oren Levintal, June 13, 2016. + +if ~isempty(varargin) + model=varargin{1}; + if approx>=2 + tempmat=model.UW.U2*model.UW.W2*model.UW.W2'*model.UW.U2'; + derivsc.gxx=sparse(derivs.gxx)*tempmat; + derivsc.hxx=sparse(derivs.hxx)*tempmat; + end + if approx>=3 + tempmat=model.UW.U3*model.UW.W3*model.UW.W3'*model.UW.U3'; + derivsc.gxxx=sparse(derivs.gxxx)*tempmat; + derivsc.hxxx=sparse(derivs.hxxx)*tempmat; + end + if approx>=4 + tempmat=model.UW.U4*model.UW.W4*model.UW.W4'*model.UW.U4'; + derivsc.gxxxx=sparse(derivs.gxxxx)*tempmat; + derivsc.hxxxx=sparse(derivs.hxxxx)*tempmat; + end + if approx>=5 + tempmat=model.UW.U5*model.UW.W5*model.UW.W5'*model.UW.U5'; + derivsc.gxxxxx=sparse(derivs.gxxxxx)*tempmat; + derivsc.hxxxxx=sparse(derivs.hxxxxx)*tempmat; + end +end + +if approx>=2 + n_x=length(nxss)+1; + derivs.gxx=reshape(derivs.gxx,[],n_x^2); + derivs.hxx=reshape(derivs.hxx,[],n_x^2); +end +if approx>=3 + derivs.gxxx=reshape(derivs.gxxx,[],n_x^3); + derivs.hxxx=reshape(derivs.hxxx,[],n_x^3); +end +if approx>=4 + derivs.gxxxx=reshape(derivs.gxxxx,[],n_x^4); + derivs.hxxxx=reshape(derivs.hxxxx,[],n_x^4); +end +if approx>=5 + derivs.gxxxxx=reshape(derivs.gxxxxx,[],n_x^5); + derivs.hxxxxx=reshape(derivs.hxxxxx,[],n_x^5); +end + +T=size(shocks,2); +n_y=size(derivs.gx,1); +n_x=size(derivs.hx,1); +n_e=size(shocks,1); +shocks=[zeros(n_e,1),shocks,zeros(n_e,1)]; +if pruning==0 + yt=zeros(n_y,T+2); + xt=zeros(n_x,T+2); + xt(:,1)=x0; + for t=1:T+1 + nx=xt(:,t); + if isempty(varargin) + [g,h]=policy( nx,nyss,nxss,derivs,approx ); + else + [g,h]=policy( nx,nyss,nxss,derivs,approx,derivsc ); + end + yt(:,t)=g; + xt(:,t+1)=h+eta*shocks(:,t+1); + end + xt=xt(:,1:T+1); + yt=yt(:,1:T+1); +elseif pruning==1 + xt_f=zeros(n_x+1,T+2); + yt=zeros(n_y,T+2); + if approx>=2 + xt_s=zeros(n_x+1,T+2); + end + if approx>=3 + xt_rd=zeros(n_x+1,T+2); + end + if approx>=4 + xt_4th=zeros(n_x+1,T+2); + end + if approx>=5 + xt_5th=zeros(n_x+1,T+2); + end + + xt_f(1:end-1,1)=x0-nxss; + xt_f(end,:)=1; + + for t=1:T+1 + x_f=xt_f(:,t); + xt_f(1:end-1,t+1)=derivs.hx*x_f+eta*shocks(:,t+1); + if approx>=2 + x_s=xt_s(:,t); + x_f2=kron(x_f,x_f); + xt_s(1:end-1,t+1)=derivs.hx*x_s+derivs.hxx*x_f2/2; + end + if approx>=3 + x_rd=xt_rd(:,t); + x_f3=kron(x_f2,x_f); + x_f_x_s=kron(x_f,x_s); + xt_rd(1:end-1,t+1)=derivs.hx*x_rd+derivs.hxx*(2*x_f_x_s)/2+derivs.hxxx*x_f3/6; + end + if approx>=4 + x_4th=xt_4th(:,t); + x_f4=kron(x_f3,x_f); + x_f2_x_s=kron(x_f,x_f_x_s); + x_s2=kron(x_s,x_s); + x_f_x_rd=kron(x_f,x_rd); + xt_4th(1:end-1,t+1)=derivs.hx*x_4th+derivs.hxx*(2*x_f_x_rd+x_s2)/2 ... + +derivs.hxxx*(3*x_f2_x_s)/6 ... + +derivs.hxxxx*x_f4/24; + end + if approx>=5 + x_5th=xt_5th(:,t); + x_f5=kron(x_f4,x_f); + x_f3_x_s=kron(x_f,x_f2_x_s); + x_f_x_s2=kron(x_f,x_s2); + x_f2_x_rd=kron(x_f,x_f_x_rd); + x_s_x_rd=kron(x_s,x_rd); + x_f_x_4th=kron(x_f,x_4th); + xt_5th(1:end-1,t+1)=derivs.hx*x_5th+derivs.hxx*(2*x_f_x_4th+2*x_s_x_rd)/2 ... + +derivs.hxxx*(3*x_f2_x_rd+3*x_f_x_s2)/6 ... + +derivs.hxxxx*(4*x_f3_x_s)/24 ... + +derivs.hxxxxx*x_f5/120; + end + if approx==1 + yt(:,t)=derivs.gx*(x_f); + elseif approx==2 + yt(:,t)=derivs.gx*(x_f+x_s)+derivs.gxx*(x_f2)/2; + elseif approx==3 + yt(:,t)=derivs.gx*(x_f+x_s+x_rd)+derivs.gxx*(x_f2+2*x_f_x_s)/2 ... + +derivs.gxxx*(x_f3)/6; + elseif approx==4 + yt(:,t)=derivs.gx*(x_f+x_s+x_rd+x_4th)+derivs.gxx*(x_f2+2*x_f_x_s+2*x_f_x_rd+x_s2)/2 ... + +derivs.gxxx*(x_f3+3*x_f2_x_s)/6 ... + +derivs.gxxxx*x_f4/24; + elseif approx==5 + yt(:,t)=derivs.gx*(x_f+x_s+x_rd+x_4th+x_5th)+derivs.gxx*(x_f2+2*x_f_x_s+2*x_f_x_rd+2*x_f_x_4th+x_s2+2*x_s_x_rd)/2 ... + +derivs.gxxx*(x_f3+3*x_f2_x_s+3*x_f2_x_rd+3*x_f_x_s2)/6 ... + +derivs.gxxxx*(x_f4+4*x_f3_x_s)/24 ... + +derivs.gxxxxx*x_f5/120; + end + end + yt=yt(:,1:T+1); + xt=xt_f(:,1:T+1); + if approx>=2 + xt=xt+xt_s(:,1:T+1); + end + if approx>=3 + xt=xt+xt_rd(:,1:T+1); + end + if approx>=4 + xt=xt+xt_4th(:,1:T+1); + end + if approx>=5 + xt=xt+xt_5th(:,1:T+1); + end + yt=yt+repmat(nyss,1,T+1); + xt=xt(1:end-1,:)+repmat(nxss,1,T+1); +end + diff --git a/105/replication_package/solution_methods/Perturbation/solve_dsge.m b/105/replication_package/solution_methods/Perturbation/solve_dsge.m new file mode 100644 index 0000000000000000000000000000000000000000..2d140d42d1ec61beb3a72d4745ab4626c3a20a42 --- /dev/null +++ b/105/replication_package/solution_methods/Perturbation/solve_dsge.m @@ -0,0 +1,1002 @@ +function [derivs,sol_time,deriv_time]=solve_dsge(model,params,M,eta,nxss,nyss,approx,algo,varargin) +%solve_dsge(model,params,M,eta,nxss,nyss,approx,algo,gx,hx) +%This function solves the dsge model with perturbation up to a fifth +%order. +%Input variables: +%model: a structure that is generated automatically by the function +%differentiate_dsge.m +%params: a vector of all parameter values ordered in the same order of symparams. +%M: a structure that contains all the cross moments of the shocks. The fields of +%this structure should be M2,M3,M4,M5. +%eta: The matrix eta as defined in Schmitt-Grohe and Uribe (2004). +%nxss,nyss: steady state values of x and y +%algo: algorithm type. 'dlyap' for dlyap or 'vectorize' for vectorization. +%gx,hx: first order solutions. These arguments are optional. If not supplied, the first order solution is calculated +%by the function gx_hx.m written by Schmitt-Grohe and Uribe (2004). +% +% +% � Copyright, Oren Levintal, June 13, 2016. + +if strcmpi(algo,'binning') + kamenik_type=1; + algo='Kamenik'; +elseif strcmpi(algo,'gensylv') + kamenik_type=2; + algo='Kamenik'; +elseif ~strcmpi(algo,'dlyap') && ~strcmpi(algo,'vectorize') + error('wrong algorithm') +end + +sol_time=0; + +n_f=model.n_f; +n_x=model.n_x; +n_y=model.n_y; +n_x2=model.n_x2; +n_x1=model.n_x1; +n_v=model.n_v; + +f_ind=model.f_ind; +UW=model.UW; % IMPORTANT: THESE COMPRESSION MATRICES ASSUME A CERTAIN NONZERO PATTERN. +OMEGA_x=model.OMEGA_x; + +if isempty(OMEGA_x) + create_OMEGA_x; +end + +n_e=size(eta,2); +eta=[eta;zeros(1,n_e)]; + +nxss=[nxss(:);0]; % add steady state value of the perturbation variable. +nyss=nyss(:); + +nPhi=Phi_fun(nxss,params); +if approx>=1 + nPhix=Phi_d1(nxss',params,model.Phi_ind); +end +if approx>=2 + W2=UW.W2; U2=UW.U2; + nPhixx=Phi_d2(nxss',params,model.Phi_ind); +end +if approx>=3 + W3=UW.W3; U3=UW.U3; + nPhixxx=Phi_d3(nxss',params,model.Phi_ind); +end +if approx>=4 + W4=UW.W4; U4=UW.U4; + nPhixxxx=Phi_d4(nxss',params,model.Phi_ind); +end +if approx>=5 + W5=UW.W5; U5=UW.U5; + nPhixxxxx=Phi_d5(nxss',params,model.Phi_ind); +end + +nv=[nyss;nyss;nxss;nxss]; + +start=tic; +fv=f_d1(nv',params,model.f_ind); +deriv_time=toc(start); +fv=reshape(fv,n_f,n_v); + + +fyp=fv(:,1:n_y); fy=fv(:,n_y+1:2*n_y); fxp=fv(:,2*n_y+1:2*n_y+n_x); fx=fv(:,2*n_y+n_x+1:end); + +% First Order + +% If first order solution not provided, use the function gx_hx of Schmitt-Grohe and Uribe (2004) +if isempty(varargin) + tic + [gx,hx,exitflag]=gx_hx(full([fy;zeros(n_x2,n_y)]),full([fx(:,1:end-1);nPhix(:,1:end-1)]),full([fyp;zeros(n_x2,n_y)]),full([fxp(:,1:end-1);[zeros(n_x2,n_x1),-eye(n_x2)]])); + time=toc; + sol_time=sol_time+time; + gx=[gx,zeros(n_y,1)]; + hx=[hx;zeros(1,n_x-1)]; + hx=[hx,zeros(n_x,1)]; + hx(end,end)=1; + % replace relevant rows of hx with nPhix which is more numerically accurate + hx(n_x1+1:n_x1+n_x2,:)=nPhix; +else + gx=zeros(n_y,n_x); + gx(1:size(varargin{1},1),1:size(varargin{1},2))=varargin{1}; + hx=zeros(n_x,n_x); + hx(end,end)=1; + hx(1:size(varargin{2},1),1:size(varargin{2},2))=varargin{2}; +end + +hx=sparse(hx); +gx=sparse(gx); + +% Second Order +if approx>=2 + M2=M.M2; + eta2_M2=reshape([eta*reshape(M2,n_e,n_e)]',n_e,n_x); + eta2_M2=reshape([eta*eta2_M2]',n_x^2,1); + + start=tic; + fvv=f_d2(nv',params,model.f_ind); + deriv_time=deriv_time+toc(start); + + unique=nchoosek(n_x+2-1,2); + unique=unique-nchoosek(n_x-1+1-1,1); + + Vx0=[gx*hx;gx;hx;speye(n_x)]; + Vx1=[gx;sparse(n_y,n_x);speye(n_x,n_x);sparse(n_x,n_x)]; + + Ezeta2=[ sparse(n_x^2,n_x^2-1) , eta2_M2 ]; + + A=innerkron(n_f,n_v,fvv,Vx0,Vx0)+innerkron(n_f,n_v,fvv,Vx1,Vx1)*Ezeta2; + + fy_fxp_fypgx=[fv(:,n_y+1:2*n_y) fv(:,2*n_y+1:2*n_y+n_x)+fv(:,1:n_y)*gx]; + + G=fy_fxp_fypgx(:,1:n_f); + H=fy_fxp_fypgx(:,n_f+1:n_f+n_x2); + + D=sparse(n_f,n_f); + D(:,1:n_y)=fv(:,1:n_y); + + if strcmp(algo,'Kamenik') + if n_x2==0 + C=A; + else % do not solve exogenous state variables (see appendix A.6 in the paper). H is the last block of G. + C=A+H*(nPhixx); + end + %Block 1: xx + spx=sparse([ones(n_x-1,1);0]); + choosex2=kron(spx,spx); + choosex2=logical(choosex2==1); + tempeye=speye(n_x^2); + Z=tempeye(:,choosex2); + CZ=C*Z; + hx_hat=hx(1:end-1,1:end-1); + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-CZ,2 ); + time=toc; + else + G=full(G); + D=full(D); + hx_hat=full(hx_hat); + tic + [~,Xtemp]=gensylv( 2,G,D,hx_hat,full(-CZ) ); + time=toc; + end + sol_time=sol_time+time; + acc=norm(full(CZ+AkronkC(D*Xtemp,hx_hat,2)+G*Xtemp)); + if acc>1e-8 + warning(['Second order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X=zeros(n_f,n_x^2); + X(:,choosex2)=full(Xtemp); + gxx_hat=Xtemp(1:n_y,:); + hat_eta2_M2=eta2_M2(choosex2,:); + %Block 2: ss + sps=sparse([zeros(n_x-1,1);1]); + choosex2=kron(sps,sps); + choosex2=logical(choosex2==1); + Z=tempeye(:,choosex2); + CZ=C*Z; + tic + Xtemp=-(D+G)\(CZ+(fyp*gxx_hat)*hat_eta2_M2); + time=toc; + sol_time=sol_time+time; + + acc=norm(full(CZ+(fyp*gxx_hat)*hat_eta2_M2+(D+G)*Xtemp)); + if acc>1e-8 + warning(['Second order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex2)=full(Xtemp); clear Xtemp + else + if n_x2==0 + CU2=A*U2; + else % do not solve exogenous state variables (see appendix A.6 in the paper). H is the last block of G. + CU2=A*U2+H*(nPhixx*U2); + end + W2BU2=(innerkron(unique,n_x,W2,hx,hx)+W2*Ezeta2)*U2; + %Block 1: xx + spx=sparse([ones(n_x-1,1);0]); + choosex2=kron(spx,spx); + choosex2U=logical(U2'*choosex2==1); + tempeye=speye(size(U2,2)); + Z=tempeye(:,choosex2U); + CU2Z=CU2*Z; + ZTW2BU2Z=Z'*W2BU2*Z; + if strcmpi(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW2BU2Z',D)+kron(speye(size(Z,2)),G))\CU2Z(:),n_f,size(Z,2)); + elseif strcmpi(algo,'dlyap') + Xtemp=dlyap(ZTW2BU2Z',(-G\D)',(-G\CU2Z)'); + Xtemp=Xtemp'; + elseif strcmpi(algo,'slicot') + Xtemp=HessSchur(full(ZTW2BU2Z'),full((G\D)'),full((-G\CU2Z)')); + Xtemp=Xtemp'; + end + acc=norm(full(G*Xtemp+D*Xtemp*ZTW2BU2Z+CU2Z)); + if acc>1e-8 + warning(['Second order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X=zeros(n_f,size(U2,2)); + X(:,choosex2U)=full(Xtemp); clear Xtemp ZTW2BU2Z + %Block 2 + sps=sparse([zeros(n_x-1,1);1]); + choosex2=kron(sps,sps); + choosex2U=logical(U2'*choosex2==1); + tempeye=speye(size(U2,2)); + Z=tempeye(:,choosex2U); + W2BU2Z=W2BU2*Z; + CU2Z=CU2*Z+D*X*W2BU2Z; + ZTW2BU2Z=Z'*W2BU2*Z; + if strcmpi(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW2BU2Z',D)+kron(speye(size(Z,2)),G))\CU2Z(:),n_f,size(Z,2)); + elseif strcmpi(algo,'dlyap') + Xtemp=dlyap(ZTW2BU2Z',(-G\D)',(-G\CU2Z)'); + Xtemp=Xtemp'; + elseif strcmpi(algo,'slicot') + Xtemp=HessSchur(full(ZTW2BU2Z'),full((G\D)'),full((-G\CU2Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW2BU2Z+CU2Z); + if acc>1e-8 + warning(['Second order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex2U)=full(Xtemp); clear Xtemp W2BU2Z ZTW2BU2Z + X=X*W2; + end + gxx=X(1:n_y,:); + hxx=[X(n_y+1:end,:);nPhixx;zeros(1,n_x^2)]; +end + +% Third Order +if approx>=3 + Vxx0=[chain2(gx,gxx,hx,hxx);gxx;hxx;sparse(n_x,n_x^2)]; + Vxx1=[gxx;sparse(n_y+2*n_x,n_x^2)]; + + M3=M.M3(:); + + eta3_M3=reshape([eta*reshape(M3,n_e,n_e^2)]',n_e,n_e*n_x); + eta3_M3=reshape([eta*eta3_M3]',n_e,n_x^2); + eta3_M3=reshape([eta*eta3_M3]',n_x^3,1); + + Ezeta3=[ sparse(n_x^3,n_x^3-1) , eta3_M3 ]; + Ix=speye(n_x); + Ix_Ezeta2=kron(Ix,Ezeta2); + + start=tic; + fvvv=f_d3(nv',params,model.f_ind); + deriv_time=deriv_time+toc(start); + + unique=nchoosek(n_x+3-1,3); + unique=unique-nchoosek(n_x-1+2-1,2); + A_third_order; % create matrix A of a third order solution + if strcmp(algo,'Kamenik') + if n_x2==0 + C=A; + else % do not solve exogenous state variables (see appendix A.6 in the paper). H is the last block of G. + C=A+H*(nPhixxx); + end + %Block 1:xxx + choosex3=kron(spx,kron(spx,spx)); + choosex3=logical(choosex3==1); + tempeye=speye(n_x^3); + Z=tempeye(:,choosex3); + CZ=C*Z; + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-CZ,3 ); + time=toc; + else + tic + [~,Xtemp]=gensylv( 3,G,D,hx_hat,full(-CZ)); + time=toc; + end + sol_time=sol_time+time; + acc=norm(full(CZ+AkronkC(D*Xtemp,hx_hat,3)+G*Xtemp)); + if acc>1e-8 + warning(['Third order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X=zeros(n_f,n_x^3); + X(:,choosex3)=full(Xtemp); + gxxx_hat=Xtemp(1:n_y,:); + hat_eta3_M3=eta3_M3(choosex3,:); + %Block 2:xss + choosex3=kron(kron(sps,sps),spx); + choosex3=logical(choosex3==1); + Z=tempeye(:,choosex3); + CZ=C*Z; + term2=reshape(fyp*gxxx_hat,n_f*(n_x-1),(n_x-1)^2)*hat_eta2_M2; + term2=reshape(term2',n_f,n_x-1)*hx_hat; + cons=CZ+term2; + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-cons,1 ); + time=toc; + else + tic + [~,Xtemp]=gensylv( 1,G,D,hx_hat,full(-cons)); + time=toc; + end + sol_time=sol_time+time; + acc=norm(full(cons+AkronkC(D*Xtemp,hx_hat,1)+G*Xtemp)); + if acc>1e-8 + warning(['Third order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex3)=full(Xtemp); clear Xtemp + %Block 2:sss + choosex3=kron(kron(sps,sps),sps); + choosex3=logical(choosex3==1); + Z=tempeye(:,choosex3); + CZ=C*Z; + term2=(fyp*gxxx_hat)*hat_eta3_M3; + cons=CZ+term2; + tic + Xtemp=-(D+G)\cons; + time=toc; + sol_time=sol_time+time; + + acc=norm(full(cons+(D+G)*Xtemp)); + if acc>1e-8 + warning(['Third order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex3)=full(Xtemp); clear Xtemp + % add symmetric entries, but first permute the indices, because the + % compression matrices assume i1>=i2>=i3, while block xss has + % i11e-8 + warning(['Third order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X=zeros(n_f,size(U3,2)); + X(:,choosex3U)=full(Xtemp); clear Xtemp ZTW3BU3Z + %Block 2:xss + choosex3=kron(kron(sps,sps),spx); + choosex3=choosex3+kron(kron(sps,spx),sps); + choosex3=choosex3+kron(kron(spx,sps),sps); + choosex3U=logical(U3'*choosex3~=0); + Z=tempeye(:,choosex3U); + W3BU3Z=W3BU3*Z; + CU3Z=CU3*Z+D*X*W3BU3Z; + ZTW3BU3Z=Z'*W3BU3*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW3BU3Z',D)+kron(speye(size(Z,2)),G))\CU3Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW3BU3Z',(-G\D)',(-G\CU3Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW3BU3Z'),full((G\D)'),full((-G\CU3Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW3BU3Z+CU3Z); + if acc>1e-8 + warning(['Third order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex3U)=full(Xtemp); clear Xtemp ZTW3BU3Z + %Block 3:sss + choosex3=kron(kron(sps,sps),sps); + choosex3U=logical(U3'*choosex3~=0); + Z=tempeye(:,choosex3U); + W3BU3Z=W3BU3*Z; + CU3Z=CU3*Z+D*X*W3BU3Z; + ZTW3BU3Z=Z'*W3BU3*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW3BU3Z',D)+kron(speye(size(Z,2)),G))\CU3Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW3BU3Z',(-G\D)',(-G\CU3Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW3BU3Z'),full((G\D)'),full((-G\CU3Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW3BU3Z+CU3Z); + if acc>1e-8 + warning(['Third order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex3U)=full(Xtemp); clear Xtemp ZTW3BU3Z W3BU3 + X=X*W3; + end + + gxxx=X(1:n_y,:); + hxxx=[X(n_y+1:end,:);nPhixxx;zeros(1,n_x^3)]; +end + +% Fourth Order +if approx>=4 + Vxxx0=[chain3(gx,gxx,gxxx,hx,hxx,hxxx,OMEGA_x.OMEGA1);gxxx;hxxx;sparse(n_x,n_x^3)]; + Vxxx1=[gxxx;sparse(n_y+2*n_x,n_x^3)]; + + M4=M.M4(:); + + eta4_M4=reshape([eta*reshape(M4,n_e,n_e^3)]',n_e,n_e^2*n_x); + eta4_M4=reshape([eta*eta4_M4]',n_e,n_e*n_x^2); + eta4_M4=reshape([eta*eta4_M4]',n_e,n_x^3); + eta4_M4=reshape([eta*eta4_M4]',n_x^4,1); + + Ezeta4=[ sparse(n_x^4,n_x^4-1) , eta4_M4 ]; + Ix_Ezeta3=kron(Ix,Ezeta3); + Ix2=speye(n_x^2); + Ix2_Ezeta2=kron(Ix2,Ezeta2); + + hx2=kron(hx,hx); + hx_Ezeta2_hx=kron(kron(hx,Ezeta2),hx); + hx_Ezeta3=kron(hx,Ezeta3); + hx2_Ezeta2=kron(hx2,Ezeta2); + + start=tic; + fvvvv=f_d4(nv',params,model.f_ind); + deriv_time=deriv_time+toc(start); + + unique=nchoosek(n_x+4-1,4); + unique=unique-nchoosek(n_x-1+3-1,3); + + clear result R + A_fourth_order; % create matrix A of a fourth order solution + + if strcmp(algo,'Kamenik') + if n_x2==0 + C=A; + else % do not solve exogenous state variables (see appendix A.6 in the paper). H is the last block of G. + C=A+H*(nPhixxxx); + end + %Block 1:xxxx + choosex4=kron(kron(spx,spx),kron(spx,spx)); + choosex4=logical(choosex4==1); + tempeye=speye(n_x^4); + Z=tempeye(:,choosex4); + CZ=C*Z; + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-CZ,4 ); + time=toc; + else + tic + [~,Xtemp]=gensylv( 4,G,D,hx_hat,full(-CZ)); + time=toc; + end + sol_time=sol_time+time; + acc=norm(full(CZ+AkronkC(D*Xtemp,hx_hat,4)+G*Xtemp)); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X=zeros(n_f,n_x^4); + X(:,choosex4)=full(Xtemp); + gxxxx_hat=Xtemp(1:n_y,:); + hat_eta4_M4=eta4_M4(choosex4,:); + %Block 2:xxss + choosex4=kron(kron(sps,sps),kron(spx,spx)); + choosex4=logical(choosex4==1); + Z=tempeye(:,choosex4); + CZ=C*Z; + term2=reshape(fyp*gxxxx_hat,n_f*(n_x-1)^2,(n_x-1)^2)*hat_eta2_M2; + term2=reshape(term2',n_f*(n_x-1),(n_x-1))*hx_hat; + term2=reshape(term2',(n_x-1)*n_f,(n_x-1))*hx_hat; + term2=reshape(term2',(n_x-1)^2,n_f); + term2=term2'; + cons=CZ+term2; + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-cons,2 ); + time=toc; + else + tic + [~,Xtemp]=gensylv( 2,G,D,hx_hat,full(-cons)); + time=toc; + end + sol_time=sol_time+time; + + acc=norm(full(cons+AkronkC(D*Xtemp,hx_hat,2)+G*Xtemp)); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex4)=full(Xtemp); + gxxss_hat=Xtemp(1:n_y,:); + %Block 2:xsss + choosex4=kron(kron(sps,sps),kron(sps,spx)); + choosex4=logical(choosex4==1); + Z=tempeye(:,choosex4); + CZ=C*Z; + term2=reshape(fyp*gxxxx_hat,n_f*(n_x-1),(n_x-1)^3)*hat_eta3_M3; + term2=reshape(term2',n_f,(n_x-1))*hx_hat; + cons=CZ+term2; + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-cons,1 ); + time=toc; + else + tic + [~,Xtemp]=gensylv( 1,G,D,hx_hat,full(-cons)); + time=toc; + end + sol_time=sol_time+time; + acc=norm(full(cons+AkronkC(D*Xtemp,hx_hat,1)+G*Xtemp)); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex4)=full(Xtemp); + %Block 2:ssss + choosex4=kron(kron(sps,sps),kron(sps,sps)); + choosex4=logical(choosex4==1); + Z=tempeye(:,choosex4); + CZ=C*Z; + term2=(6*fyp*gxxss_hat)*hat_eta2_M2; + term3=(fyp*gxxxx_hat)*hat_eta4_M4; + cons=CZ+term2+term3; + tic + Xtemp=-(D+G)\cons; + time=toc; + sol_time=sol_time+time; + acc=norm(full(cons+(D+G)*Xtemp)); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex4)=full(Xtemp); clear Xtemp + % add symmetric entries, but first permute the indices. + X=reshape(permute(reshape(X,[],n_x,n_x,n_x,n_x),[1,5,4,3,2]),[],n_x^4)*U4*W4; + else + if n_x2==0 + CU4=A*U4; + else + CU4=A*U4+H*(nPhixxxx*U4); + end + kron_hx_hx=kron(hx,hx); + WBU_fourth_order; % create the matrix W4BU4 + %Block 1:xxxx + choosex4=kron(kron(spx,spx),kron(spx,spx)); + choosex4U=logical(U4'*choosex4~=0); + tempeye=speye(size(U4,2)); + Z=tempeye(:,choosex4U); + CU4Z=CU4*Z; + ZTW4BU4Z=Z'*W4BU4*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW4BU4Z',D)+kron(speye(size(Z,2)),G))\CU4Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW4BU4Z',(-G\D)',(-G\CU4Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW4BU4Z'),full((G\D)'),full((-G\CU4Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW4BU4Z+CU4Z); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X=zeros(n_f,size(U4,2)); + X(:,choosex4U)=full(Xtemp); clear Xtemp ZTW4BU4Z + %Block 2:xxss + choosex4=kron(kron(sps,sps),kron(spx,spx)); + choosex4=choosex4+kron(kron(sps,spx),kron(sps,spx)); + choosex4=choosex4+kron(kron(sps,spx),kron(spx,sps)); + choosex4=choosex4+kron(kron(spx,sps),kron(sps,spx)); + choosex4=choosex4+kron(kron(spx,sps),kron(spx,sps)); + choosex4=choosex4+kron(kron(spx,spx),kron(sps,sps)); + choosex4U=logical(U4'*choosex4~=0); + Z=tempeye(:,choosex4U); + W4BU4Z=W4BU4*Z; + CU4Z=CU4*Z+D*X*W4BU4Z; + ZTW4BU4Z=Z'*W4BU4*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW4BU4Z',D)+kron(speye(size(Z,2)),G))\CU4Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW4BU4Z',(-G\D)',(-G\CU4Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW4BU4Z'),full((G\D)'),full((-G\CU4Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW4BU4Z+CU4Z); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex4U)=full(Xtemp); clear Xtemp ZTW4BU4Z + %Block 3:xsss + choosex4=kron(kron(sps,sps),kron(sps,spx)); + choosex4=choosex4+kron(kron(sps,sps),kron(spx,sps)); + choosex4=choosex4+kron(kron(sps,spx),kron(sps,sps)); + choosex4=choosex4+kron(kron(spx,sps),kron(sps,sps)); + choosex4U=logical(U4'*choosex4~=0); + Z=tempeye(:,choosex4U); + W4BU4Z=W4BU4*Z; + CU4Z=CU4*Z+D*X*W4BU4Z; + ZTW4BU4Z=Z'*W4BU4*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW4BU4Z',D)+kron(speye(size(Z,2)),G))\CU4Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW4BU4Z',(-G\D)',(-G\CU4Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW4BU4Z'),full((G\D)'),full((-G\CU4Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW4BU4Z+CU4Z); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex4U)=full(Xtemp); clear Xtemp ZTW4BU4Z + %Block 4:ssss + choosex4=kron(kron(sps,sps),kron(sps,sps)); + choosex4U=logical(U4'*choosex4~=0); + Z=tempeye(:,choosex4U); + W4BU4Z=W4BU4*Z; + CU4Z=CU4*Z+D*X*W4BU4Z; + ZTW4BU4Z=Z'*W4BU4*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW4BU4Z',D)+kron(speye(size(Z,2)),G))\CU4Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW4BU4Z',(-G\D)',(-G\CU4Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW4BU4Z'),full((G\D)'),full((-G\CU4Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW4BU4Z+CU4Z); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex4U)=full(Xtemp); clear Xtemp ZTW4BU4Z + X=X*W4; + end + + gxxxx=X(1:n_y,:); + hxxxx=[X(n_y+1:end,:);nPhixxxx;zeros(1,n_x^4)]; +end + +% Fifth Order +if approx>=5 + Vxxxx0=[chain4(gx,gxx,gxxx,gxxxx,hx,hxx,hxxx,hxxxx,OMEGA_x.OMEGA2,OMEGA_x.OMEGA3,OMEGA_x.OMEGA4);gxxxx;hxxxx;sparse(n_x,n_x^4)]; + Vxxxx1=[gxxxx;sparse(n_y+2*n_x,n_x^4)]; + + M5=M.M5(:); + eta5_M5=reshape([eta*reshape(M5,n_e,n_e^4)]',n_e,n_e^3*n_x); + eta5_M5=reshape([eta*eta5_M5]',n_e,n_e^2*n_x^2); + eta5_M5=reshape([eta*eta5_M5]',n_e,n_e^1*n_x^3); + eta5_M5=reshape([eta*eta5_M5]',n_e,n_x^4); + eta5_M5=reshape([eta*eta5_M5]',n_x^5,1); + + start=tic; + fvvvvv=f_d5(nv',params,model.f_ind); + deriv_time=deriv_time+toc(start); + + clearvars -except n_f n_v n_x n_y n_x2 eta5_M5 Ix* *Ezeta* OMEGA_x U5 W5 gx* hx* nPhix* Vx* fv* fyp algo D G H approx sps spx kron_hx_hx hat_eta2_M2 hat_eta3_M3 hat_eta4_M4 sol_time deriv_time kamenik_type + + Ezeta5=[ sparse(n_x^5,n_x^5-1) , eta5_M5 ]; + Ix_Ezeta4=kron(Ix,Ezeta4); + Ix2_Ezeta3=kron(Ix2,Ezeta3); + Ix3=speye(n_x^3); + Ix3_Ezeta2=kron(Ix3,Ezeta2); + + hx3=kron(hx2,hx); + hx3_Ezeta2=kron(hx3,Ezeta2); + hx2_Ezeta3=kron(hx2,Ezeta3); + hx_Ezeta4=kron(hx,Ezeta4); + + unique=nchoosek(n_x+5-1,5); + unique=unique-nchoosek(n_x-1+4-1,4); + + A_fifth_order; % create matrix A of a fifth order solution + if strcmp(algo,'Kamenik') + if n_x2==0 + C=A; + else % do not solve exogenous state variables (see appendix A.6 in the paper). H is the last block of G. + C=A+H*(nPhixxxxx); + end + %Block 1:xxxxx + choosex5=kron(kron(spx,kron(spx,spx)),kron(spx,spx)); + choosex5=logical(choosex5==1); + tempeye=speye(n_x^5); + Z=tempeye(:,choosex5); + CZ=C*Z; + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-CZ,5 ); + time=toc; + else + tic + [~,Xtemp]=gensylv( 5,G,D,hx_hat,full(-CZ)); + time=toc; + end + sol_time=sol_time+time; + acc=norm(full(CZ+AkronkC(D*Xtemp,hx_hat,5)+G*Xtemp)); + if acc>1e-8 + warning(['Fifth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X=zeros(n_f,n_x^5); + X(:,choosex5)=full(Xtemp); + gxxxxx_hat=Xtemp(1:n_y,:); + hat_eta5_M5=eta5_M5(choosex5,:); + %Block 2:xxxss + choosex5=kron(kron(sps,sps),kron(spx,kron(spx,spx))); + choosex5=logical(choosex5==1); + Z=tempeye(:,choosex5); + CZ=C*Z; + term2=reshape(fyp*gxxxxx_hat,n_f*(n_x-1)^3,(n_x-1)^2)*hat_eta2_M2; + term2=reshape(term2',n_f*(n_x-1)^2,(n_x-1))*hx_hat; + term2=reshape(term2',(n_x-1)*n_f*(n_x-1),(n_x-1))*hx_hat; + term2=reshape(term2',(n_x-1)^2*n_f,(n_x-1))*hx_hat; + term2=reshape(term2',(n_x-1)^3,n_f); + term2=term2'; + cons=CZ+term2; + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-cons,3 ); + time=toc; + else + tic + [~,Xtemp]=gensylv( 3,G,D,hx_hat,full(-cons)); + time=toc; + end + sol_time=sol_time+time; + acc=norm(full(cons+AkronkC(D*Xtemp,hx_hat,3)+G*Xtemp)); + if acc>1e-8 + warning(['Fifth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex5)=full(Xtemp); + gxxxss_hat=Xtemp(1:n_y,:); + %Block 3:xxsss + choosex5=kron(kron(sps,sps),kron(sps,kron(spx,spx))); + choosex5=logical(choosex5==1); + Z=tempeye(:,choosex5); + CZ=C*Z; + term2=reshape(fyp*gxxxxx_hat,n_f*(n_x-1)^2,(n_x-1)^3)*hat_eta3_M3; + term2=reshape(term2',n_f*(n_x-1),(n_x-1))*hx_hat; + term2=reshape(term2',(n_x-1)*n_f,(n_x-1))*hx_hat; + term2=reshape(term2',(n_x-1)^2,n_f); + term2=term2'; + cons=CZ+term2; + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-cons,2 ); + time=toc; + else + tic + [~,Xtemp]=gensylv( 2,G,D,hx_hat,full(-cons)); + time=toc; + end + sol_time=sol_time+time; + acc=norm(full(cons+AkronkC(D*Xtemp,hx_hat,2)+G*Xtemp)); + if acc>1e-8 + warning(['Fifth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex5)=full(Xtemp); + gxxsss_hat=Xtemp(1:n_y,:); + %Block 2:xssss + choosex5=kron(kron(sps,sps),kron(kron(sps,sps),spx)); + choosex5=logical(choosex5==1); + Z=tempeye(:,choosex5); + CZ=C*Z; + term2=reshape(6*fyp*gxxxss_hat,n_f*(n_x-1),(n_x-1)^2)*hat_eta2_M2; + term2=reshape(term2',n_f,(n_x-1))*hx_hat; + term3=reshape(fyp*gxxxxx_hat,n_f*(n_x-1),(n_x-1)^4)*hat_eta4_M4; + term3=reshape(term3',n_f,(n_x-1))*hx_hat; + cons=CZ+term2+term3; + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-cons,1 ); + time=toc; + else + tic + [~,Xtemp]=gensylv( 1,G,D,hx_hat,full(-cons)); + time=toc; + end + sol_time=sol_time+time; + acc=norm(full(cons+AkronkC(D*Xtemp,hx_hat,1)+G*Xtemp)); + if acc>1e-8 + warning(['Fifth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex5)=full(Xtemp); + %Block 5:sssss + choosex5=kron(kron(sps,sps),kron(kron(sps,sps),sps)); + choosex5=logical(choosex5==1); + Z=tempeye(:,choosex5); + CZ=C*Z; + term2=(10*fyp*gxxsss_hat)*hat_eta2_M2; + term3=(10*fyp*gxxxss_hat)*hat_eta3_M3; + term4=(fyp*gxxxxx_hat)*hat_eta5_M5; + cons=CZ+term2+term3+term4; + tic + Xtemp=-(D+G)\cons; + time=toc; + sol_time=sol_time+time; + acc=norm(full(cons+(D+G)*Xtemp)); + if acc>1e-8 + warning(['Fifth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex5)=full(Xtemp); clear Xtemp + % add symmetric entries, but first permute the indices. + X=reshape(permute(reshape(X,[],n_x,n_x,n_x,n_x,n_x),[1,6,5,4,3,2]),[],n_x^5)*U5*W5; + else + if n_x2==0 + CU5=A*U5; + else + CU5=A*U5+H*(nPhixxxxx*U5); + end + WBU_fifth_order; % create the matrix W5BU5 + clearvars -except G D W5BU5 CU5 W5 gx* hx hxx* algo n_y nPhixxxxx n_x n_f unique approx spx sps U5 + %Block 1:xxxxx + choosex5=kron(kron(kron(spx,spx),kron(spx,spx)),spx); + choosex5U=logical(U5'*choosex5~=0); + tempeye=speye(size(U5,2)); + Z=tempeye(:,choosex5U); + CU5Z=CU5*Z; + ZTW5BU5Z=Z'*W5BU5*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW5BU5Z',D)+kron(speye(size(Z,2)),G))\CU5Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW5BU5Z',(-G\D)',(-G\CU5Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW5BU5Z'),full((G\D)'),full((-G\CU5Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW5BU5Z+CU5Z); + if acc>1e-8 + warning(['Fifth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X=zeros(n_f,size(U5,2)); + X(:,choosex5U)=full(Xtemp); clear Xtemp ZTW5BU5Z + %Block 2:xxxss + choosex5=kron(kron(kron(sps,sps),kron(spx,spx)),spx); + choosex5=choosex5+kron(kron(kron(sps,spx),kron(sps,spx)),spx); + choosex5=choosex5+kron(kron(kron(sps,spx),kron(spx,sps)),spx); + choosex5=choosex5+kron(kron(kron(sps,spx),kron(spx,spx)),sps); + choosex5=choosex5+kron(kron(kron(spx,sps),kron(sps,spx)),spx); + choosex5=choosex5+kron(kron(kron(spx,sps),kron(spx,sps)),spx); + choosex5=choosex5+kron(kron(kron(spx,sps),kron(spx,spx)),sps); + choosex5=choosex5+kron(kron(kron(spx,spx),kron(sps,sps)),spx); + choosex5=choosex5+kron(kron(kron(spx,spx),kron(sps,spx)),sps); + choosex5=choosex5+kron(kron(kron(spx,spx),kron(spx,sps)),sps); + choosex5U=logical(U5'*choosex5~=0); + Z=tempeye(:,choosex5U); + W5BU5Z=W5BU5*Z; + CU5Z=CU5*Z+D*X*W5BU5Z; + ZTW5BU5Z=Z'*W5BU5*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW5BU5Z',D)+kron(speye(size(Z,2)),G))\CU5Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW5BU5Z',(-G\D)',(-G\CU5Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW5BU5Z'),full((G\D)'),full((-G\CU5Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW5BU5Z+CU5Z); + if acc>1e-8 + warning(['Fifth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex5U)=full(Xtemp); clear Xtemp ZTW5BU5Z + %Block 3:xxsss + choosex5=kron(kron(kron(spx,spx),kron(sps,sps)),sps); + choosex5=choosex5+kron(kron(kron(spx,sps),kron(spx,sps)),sps); + choosex5=choosex5+kron(kron(kron(spx,sps),kron(sps,spx)),sps); + choosex5=choosex5+kron(kron(kron(spx,sps),kron(sps,sps)),spx); + choosex5=choosex5+kron(kron(kron(sps,spx),kron(spx,sps)),sps); + choosex5=choosex5+kron(kron(kron(sps,spx),kron(sps,spx)),sps); + choosex5=choosex5+kron(kron(kron(sps,spx),kron(sps,sps)),spx); + choosex5=choosex5+kron(kron(kron(sps,sps),kron(spx,spx)),sps); + choosex5=choosex5+kron(kron(kron(sps,sps),kron(spx,sps)),spx); + choosex5=choosex5+kron(kron(kron(sps,sps),kron(sps,spx)),spx); + choosex5U=logical(U5'*choosex5~=0); + Z=tempeye(:,choosex5U); + W5BU5Z=W5BU5*Z; + CU5Z=CU5*Z+D*X*W5BU5Z; + ZTW5BU5Z=Z'*W5BU5*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW5BU5Z',D)+kron(speye(size(Z,2)),G))\CU5Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW5BU5Z',(-G\D)',(-G\CU5Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW5BU5Z'),full((G\D)'),full((-G\CU5Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW5BU5Z+CU5Z); + if acc>1e-8 + warning(['Fifth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex5U)=full(Xtemp); clear Xtemp ZTW5BU5Z + %Block 4:xssss + choosex5=kron(kron(kron(spx,sps),kron(sps,sps)),sps); + choosex5=choosex5+kron(kron(kron(sps,spx),kron(sps,sps)),sps); + choosex5=choosex5+kron(kron(kron(sps,sps),kron(spx,sps)),sps); + choosex5=choosex5+kron(kron(kron(sps,sps),kron(sps,spx)),sps); + choosex5=choosex5+kron(kron(kron(sps,sps),kron(sps,sps)),spx); + choosex5U=logical(U5'*choosex5~=0); + Z=tempeye(:,choosex5U); + W5BU5Z=W5BU5*Z; + CU5Z=CU5*Z+D*X*W5BU5Z; + ZTW5BU5Z=Z'*W5BU5*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW5BU5Z',D)+kron(speye(size(Z,2)),G))\CU5Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW5BU5Z',(-G\D)',(-G\CU5Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW5BU5Z'),full((G\D)'),full((-G\CU5Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW5BU5Z+CU5Z); + if acc>1e-8 + warning(['Fifth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex5U)=full(Xtemp); clear Xtemp ZTW5BU5Z + %Block 5:sssss + choosex5=kron(kron(kron(sps,sps),kron(sps,sps)),sps); + choosex5U=logical(U5'*choosex5~=0); + Z=tempeye(:,choosex5U); + W5BU5Z=W5BU5*Z; + CU5Z=CU5*Z+D*X*W5BU5Z; + ZTW5BU5Z=Z'*W5BU5*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW5BU5Z',D)+kron(speye(size(Z,2)),G))\CU5Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW5BU5Z',(-G\D)',(-G\CU5Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW5BU5Z'),full((G\D)'),full((-G\CU5Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW5BU5Z+CU5Z); + if acc>1e-8 + warning(['Fifth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex5U)=full(Xtemp); clear Xtemp ZTW5BU5Z W5BU5 + X=X*W5; + end + + gxxxxx=X(1:n_y,:); + hxxxxx=[X(n_y+1:end,:);nPhixxxxx;zeros(1,n_x^5)]; +end + +clear derivs +derivs.gx=full(gx); +derivs.hx=full(hx(1:end-1,:)); +if approx>=2 + derivs.gxx=full(gxx); + derivs.hxx=full(hxx(1:end-1,:)); +end +if approx>=3 + derivs.gxxx=full(gxxx); + derivs.hxxx=full(hxxx(1:end-1,:)); +end +if approx>=4 + derivs.gxxxx=full(gxxxx); + derivs.hxxxx=full(hxxxx(1:end-1,:)); +end +if approx>=5 + derivs.gxxxxx=full(gxxxxx); + derivs.hxxxxx=full(hxxxxx(1:end-1,:)); +end + +end + + + diff --git a/105/replication_package/solution_methods/extrenal files/First order solution/gx_hx.m b/105/replication_package/solution_methods/extrenal files/First order solution/gx_hx.m new file mode 100644 index 0000000000000000000000000000000000000000..4ecf0949ced012672d705ab239a0ccaaa972f87d --- /dev/null +++ b/105/replication_package/solution_methods/extrenal files/First order solution/gx_hx.m @@ -0,0 +1,70 @@ +function [gx,hx,exitflag]=gx_hx(fy,fx,fyp,fxp,stake); +%[gx,hx,exitflag]=gx_hx(fy,fx,fyp,fxp,stake); +%computes the matrices gx and hx that define the first-order approximation to the solution +%of a dynamic stochastic general equilibrium model. +%Following the notation in Schmitt-Grohe and Uribe (JEDC, 2004), the model's equilibrium conditions +%take the form +%E_t[f(yp,y,xp,x)=0. +%The solution is of the form +%xp = h(x,sigma) + sigma * eta * ep +%y = g(x,sigma). +%The first-order approximations to the functions g and h around the point (x,sigma)=(xbar,0), where xbar=h(xbar,0), are: +%h(x,sigma) = xbar + hx (x-xbar) +%and +%g(x,sigma) = ybar + gx * (x-xbar), +%where ybar=g(xbar,0). +%The variable exitflag takes the values 0 (no solution), 1 (unique solution), 2 (indeterminacy), or 3 (z11 is not invertible). +%Inputs: fy fyp fx fxp stake +% The parameter stake ensures that all eigenvalues of hx are less than stake in modulus (the default is stake=1). +%Outputs: gx hx exitflag +%This program is a modified version of solab.m by Paul Klein (JEDC, 2000). +%Modified on August 30 2009 by Ryan Chahrour (rc2374@columbia.edu) to replace qzdiv.m by ordqz.m to increase speed. +%(c) Stephanie Schmitt-Grohe and Martin Uribe +%Date July 17, 2001, May 11 2006, November 19, 2009 + +if nargin<5 + stake=1; +end +exitflag = 1; + +%Create system matrices A,B +A = [-fxp -fyp]; +B = [fx fy]; +NK = size(fx,2); + +%Complex Schur Decomposition +[s,t,q,z] = qz(A,B); + +%Pick non-explosive (stable) eigenvalues +slt = (abs(diag(t))NK + warning('The Equilibrium is Locally Indeterminate') + exitflag=2; +elseif nk=1; +% "vcv" is the variance-covariance matrix; N-by-N + +% Outputs: "n_nodes" is the total number of integration nodes; 2*N; +% "epsi_nodes" are the integration nodes; n_nodes-by-N; +% "weight_nodes" are the integration weights; n_nodes-by-1 +% ------------------------------------------------------------------------- +% Copyright � 2011 by Lilia Maliar and Serguei Maliar. All rights reserved. +% The code may be used, modified and redistributed under the terms provided +% in the file "License_Agreement.txt". +% ------------------------------------------------------------------------- + +function [n_nodes,epsi_nodes,weight_nodes] = Monomials_1(N,vcv) + +n_nodes = 2*N; % Total number of integration nodes + +% 1. N-dimensional integration nodes for N uncorrelated random variables with +% zero mean and unit variance +% --------------------------------------------------------------------------- +z1 = zeros(n_nodes,N); % A supplementary matrix for integration nodes; + % n_nodes-by-N + +for i = 1:N % In each node, random variable i takes value either + % 1 or -1, and all other variables take value 0 + z1(2*(i-1)+1:2*i,i) = [1; -1]; +end % For example, for N = 2, z1 = [1 0; -1 0; 0 1; 0 -1] + +% z = z1*sqrt(N); % Integration nodes + +% 2. N-dimensional integration nodes and weights for N correlated random +% variables with zero mean and variance-covaraince matrix vcv +% ---------------------------------------------------------------------- +sqrt_vcv = chol(vcv); % Cholesky decomposition of the variance-covariance + % matrix + +R = sqrt(N)*sqrt_vcv; % Variable R; see condition (B.7) in the Supplement + % to JMM (2011) + +epsi_nodes = z1*R; % Integration nodes; see condition ((B.7) in the + % Supplement% to JMM (2011); n_nodes-by-N + +% 3. Integration weights +%----------------------- +weight_nodes = ones(n_nodes,1)/n_nodes; + % Integration weights are equal for all integration + % nodes; n_nodes-by-1; the weights are the same for + % the cases of correlated and uncorrelated random + % variables diff --git a/105/replication_package/solution_methods/extrenal files/Maliar codes/Monomials_2.m b/105/replication_package/solution_methods/extrenal files/Maliar codes/Monomials_2.m new file mode 100644 index 0000000000000000000000000000000000000000..2dd7be9c72b489305e249e64e33b8fa0f9b7928a --- /dev/null +++ b/105/replication_package/solution_methods/extrenal files/Maliar codes/Monomials_2.m @@ -0,0 +1,87 @@ +% Monomials_2.m is a routine that constructs integration nodes and weights +% under N-dimensional monomial (non-product) integration rule with 2N^2+1 +% nodes; see supplement to "Numerically Stable and Accurate Stochastic +% Simulation Approaches for Solving Dynamic Economic Models" by Kenneth L. +% Judd, Lilia Maliar and Serguei Maliar, (2011), Quantitative Economics 2/2, +% 173�210 (henceforth, JMM, 2011). +% +% This version: July 14, 2011. First version: August 27, 2009. +% ------------------------------------------------------------------------- +% Inputs: "N" is the number of random variables; N>=1; +% "vcv" is the variance-covariance matrix; N-by-N; + +% Outputs: "n_nodes" is the total number of integration nodes; 2*N^2+1; +% "epsi_nodes" are the integration nodes; n_nodes-by-N; +% "weight_nodes" are the integration weights; n_nodes-by-1 +% ------------------------------------------------------------------------- +% Copyright � 2011 by Lilia Maliar and Serguei Maliar. All rights reserved. +% The code may be used, modified and redistributed under the terms provided +% in the file "License_Agreement.txt". +% ------------------------------------------------------------------------- + + +function [n_nodes,epsi_nodes,weight_nodes] = Monomials_2(N,vcv) + +n_nodes = 2*N^2+1; % Total number of integration nodes + +% 1. N-dimensional integration nodes for N uncorrelated random variables with +% zero mean and unit variance +% --------------------------------------------------------------------------- + +% 1.1 The origin point +% -------------------- +z0 = zeros(1,N); % A supplementary matrix for integration nodes: the + % origin point + +% 1.2 Deviations in one dimension +% ------------------------------- +z1 = zeros(2*N,N); % A supplementary matrix for integration nodes; + % n_nodes-by-N + +for i = 1:N % In each node, random variable i takes value either + % 1 or -1, and all other variables take value 0 + z1(2*(i-1)+1:2*i,i) = [1; -1]; +end % For example, for N = 2, z1 = [1 0; -1 0; 0 1; 0 -1] + +% 1.3 Deviations in two dimensions +% -------------------------------- +z2 = zeros(2*N*(N-1),N); % A supplementary matrix for integration nodes; + % 2N(N-1)-by-N + +i=0; % In each node, a pair of random variables (p,q) + % takes either values (1,1) or (1,-1) or (-1,1) or + % (-1,-1), and all other variables take value 0 +for p = 1:N-1 + for q = p+1:N + i=i+1; + z2(4*(i-1)+1:4*i,p) = [1;-1;1;-1]; + z2(4*(i-1)+1:4*i,q) = [1;1;-1;-1]; + end +end % For example, for N = 2, z2 = [1 1;1 -1;-1 1;-1 1] + +% z = [z0;z1*sqrt(N+2);z2*sqrt((N+2)/2)]; % Integration nodes + +% 2. N-dimensional integration nodes and weights for N correlated random +% variables with zero mean and variance-covaraince matrix vcv +% ---------------------------------------------------------------------- +sqrt_vcv = chol(vcv); % Cholesky decomposition of the variance- + % covariance matrix + +R = sqrt(N+2)*sqrt_vcv; % Variable R; see condition (B.8) in the + % Supplement to JMM (2011) + +S = sqrt((N+2)/2)* sqrt_vcv; % Variable S; see condition (B.8) in the + % Supplement to JMM (2011) + +epsi_nodes = [z0;z1*R;z2*S]; + % Integration nodes; see condition (B.8) + % in the Supplement to JMM (2011); + % n_nodes-by-N + +% 3. Integration weights +%----------------------- +weight_nodes = [2/(N+2)*ones(size(z0,1),1);(4-N)/2/(N+2)^2*ones(size(z1,1),1);1/(N+2)^2*ones(size(z2,1),1)]; + % See condition in (B.8) in the Supplement + % to JMM (2011); n_nodes-by-1; the weights + % are the same for the cases of correlated + % and uncorrelated random variables \ No newline at end of file diff --git a/105/replication_package/solution_methods/extrenal files/gensylv/gensylv.mexw64 b/105/replication_package/solution_methods/extrenal files/gensylv/gensylv.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..1cda78ac91ee81f5e27a872ed9b64497c2bfd84e Binary files /dev/null and b/105/replication_package/solution_methods/extrenal files/gensylv/gensylv.mexw64 differ diff --git a/105/replication_package/solution_methods/extrenal files/gensylv/license.txt b/105/replication_package/solution_methods/extrenal files/gensylv/license.txt new file mode 100644 index 0000000000000000000000000000000000000000..8e1c2f1d5b551da7170ce12c83cd1144ec695d41 --- /dev/null +++ b/105/replication_package/solution_methods/extrenal files/gensylv/license.txt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bfaf86e8f67a59725bc688982e2aae5db5bad761d9cd72c921b4716f6e689060 +size 13778 diff --git a/105/replication_package/solution_methods/taylor_projection/GetInitial.m b/105/replication_package/solution_methods/taylor_projection/GetInitial.m new file mode 100644 index 0000000000000000000000000000000000000000..2ac183ccf0a211eeed6e67a876d15f35a79c30a5 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/GetInitial.m @@ -0,0 +1,75 @@ +function [ pert_coeffs,power_coeffs ] = GetInitial( order,derivs,choose,nyss,nxss,n_x,n_x1 ) +%This function transforms a pertrubation solution to an initial guess for Taylor +%Projection. Two types of guess are available: pert_coeffs includes +%correction for volatility. power_coeffs does not include correction for +%volatility. +% +% � Copyright, Oren Levintal, June 13, 2016. + + +if order==1 + [GH0,GH1]=shiftpoly([nxss;1],[nxss;0],1:n_x,[nyss;nxss(1:n_x1,:)],[derivs.gx(choose,:);derivs.hx(1:n_x1,:)]); + pert_coeffs=[GH0,GH1]; + if nargout==2 + [GH0,GH1]=shiftpoly([nxss;0],[nxss;0],1:n_x,[nyss;nxss(1:n_x1,:)],[derivs.gx(choose,:);derivs.hx(1:n_x1,:)]); + power_coeffs=[GH0,GH1]; + end +elseif order==2 + [GH0,GH1,GH2]=shiftpoly([nxss;1],[nxss;0],1:n_x,[nyss;nxss(1:n_x1,:)],[derivs.gx(choose,:);derivs.hx(1:n_x1,:)],... + [derivs.gxx(choose,:);derivs.hxx(1:n_x1,:)]/2); + [U2,~]=create_UW(n_x,2); + pert_coeffs=[GH0,GH1,GH2*U2]; + if nargout==2 + [GH0,GH1,GH2]=shiftpoly([nxss;0],[nxss;0],1:n_x,[nyss;nxss(1:n_x1,:)],[derivs.gx(choose,:);derivs.hx(1:n_x1,:)],... + [derivs.gxx(choose,:);derivs.hxx(1:n_x1,:)]/2); + power_coeffs=[GH0,GH1,GH2*U2]; + end +elseif order==3 + [GH0,GH1,GH2,GH3]=shiftpoly([nxss;1],[nxss;0],1:n_x,[nyss;nxss(1:n_x1,:)],[derivs.gx(choose,:);derivs.hx(1:n_x1,:)],... + [derivs.gxx(choose,:);derivs.hxx(1:n_x1,:)]/2,[derivs.gxxx(choose,:);derivs.hxxx(1:n_x1,:)]/factorial(3)); + [U2,~]=create_UW(n_x,2); + [U3,~]=create_UW(n_x,3); + pert_coeffs=[GH0,GH1,GH2*U2,GH3*U3]; + if nargout==2 + [GH0,GH1,GH2,GH3]=shiftpoly([nxss;0],[nxss;0],1:n_x,[nyss;nxss(1:n_x1,:)],[derivs.gx(choose,:);derivs.hx(1:n_x1,:)],... + [derivs.gxx(choose,:);derivs.hxx(1:n_x1,:)]/2,[derivs.gxxx(choose,:);derivs.hxxx(1:n_x1,:)]/factorial(3)); + power_coeffs=[GH0,GH1,GH2*U2,GH3*U3]; + end +elseif order==4 + [GH0,GH1,GH2,GH3,GH4]=shiftpoly([nxss;1],[nxss;0],1:n_x,[nyss;nxss(1:n_x1,:)],[derivs.gx(choose,:);derivs.hx(1:n_x1,:)],... + [derivs.gxx(choose,:);derivs.hxx(1:n_x1,:)]/2,[derivs.gxxx(choose,:);derivs.hxxx(1:n_x1,:)]/factorial(3),... + [derivs.gxxxx(choose,:);derivs.hxxxx(1:n_x1,:)]/factorial(4)); + [U2,~]=create_UW(n_x,2); + [U3,~]=create_UW(n_x,3); + [U4,~]=create_UW(n_x,4); + pert_coeffs=[GH0,GH1,GH2*U2,GH3*U3,GH4*U4]; + if nargout==2 + [GH0,GH1,GH2,GH3,GH4]=shiftpoly([nxss;0],[nxss;0],1:n_x,[nyss;nxss(1:n_x1,:)],[derivs.gx(choose,:);derivs.hx(1:n_x1,:)],... + [derivs.gxx(choose,:);derivs.hxx(1:n_x1,:)]/2,[derivs.gxxx(choose,:);derivs.hxxx(1:n_x1,:)]/factorial(3),... + [derivs.gxxxx(choose,:);derivs.hxxxx(1:n_x1,:)]/factorial(4)); + power_coeffs=[GH0,GH1,GH2*U2,GH3*U3,GH4*U4]; + end +elseif order==5 + [GH0,GH1,GH2,GH3,GH4,GH5]=shiftpoly([nxss;1],[nxss;0],1:n_x,[nyss;nxss(1:n_x1,:)],[derivs.gx(choose,:);derivs.hx(1:n_x1,:)],... + [derivs.gxx(choose,:);derivs.hxx(1:n_x1,:)]/2,[derivs.gxxx(choose,:);derivs.hxxx(1:n_x1,:)]/factorial(3),... + [derivs.gxxxx(choose,:);derivs.hxxxx(1:n_x1,:)]/factorial(4),[derivs.gxxxxx(choose,:);derivs.hxxxxx(1:n_x1,:)]/factorial(5)); + [U2,~]=create_UW(n_x,2); + [U3,~]=create_UW(n_x,3); + [U4,~]=create_UW(n_x,4); + [U5,~]=create_UW(n_x,5); + pert_coeffs=[GH0,GH1,GH2*U2,GH3*U3,GH4*U4,GH5*U5]; + if nargout==2 + [GH0,GH1,GH2,GH3,GH4,GH5]=shiftpoly([nxss;0],[nxss;0],1:n_x,[nyss;nxss(1:n_x1,:)],[derivs.gx(choose,:);derivs.hx(1:n_x1,:)],... + [derivs.gxx(choose,:);derivs.hxx(1:n_x1,:)]/2,[derivs.gxxx(choose,:);derivs.hxxx(1:n_x1,:)]/factorial(3),... + [derivs.gxxxx(choose,:);derivs.hxxxx(1:n_x1,:)]/factorial(4),[derivs.gxxxxx(choose,:);derivs.hxxxxx(1:n_x1,:)]/factorial(5)); + power_coeffs=[GH0,GH1,GH2*U2,GH3*U3,GH4*U4,GH5*U5]; + end +end +pert_coeffs=pert_coeffs(:); + +if nargout==2 + power_coeffs=power_coeffs(:); +end + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/LICENSE.txt b/105/replication_package/solution_methods/taylor_projection/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..d46926707a031aac19829334b7671dbd9270759d --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/LICENSE.txt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:55dad499f94ec1db4229ecb667529e5ed4b118e5d5fc96a70ff4ecb5d5652e3a +size 1043 diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU2IC_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU2IC_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..73cf48aea647e6c34df2702680f7634f007b6eda --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU2IC_mex.F @@ -0,0 +1,228 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [IC_1,IC_2] = AkronBU2IC_mex(l,m,n,IA,JA,IB,JB) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateNumericArray + integer*4 mxGetClassID + +C Arguments for mxCreateNumericArray + integer*4 classid + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l,m,n,IA,JA + mwPointer IB,JB + mwPointer IC_1,IC_2 + +C Array information: + mwSize IArows,JArows + mwSize IBrows, JBrows,ndim + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 7) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '7 inputs required.') + endif + if(nlhs .gt. 2) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'Max 2 outputs required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(4)) + JArows = mxGetM(prhs(5)) + + IBrows = mxGetM(prhs(6)) + JBrows = mxGetM(prhs(7)) + +C Create Fortran array from the input arguments. + l = mxGetPr(prhs(1)) + m = mxGetPr(prhs(2)) + n = mxGetPr(prhs(3)) + IA = mxGetPr(prhs(4)) + JA = mxGetPr(prhs(5)) + IB = mxGetPr(prhs(6)) + JB = mxGetPr(prhs(7)) + +C Create matrix for the return arguments. + classid = mxGetClassID(prhs(4)) + + complexflag = 0 + ndim=1 + plhs(1) = mxCreateNumericArray(ndim, IArows, + + classid, + + complexflag) + + IC_1 = mxGetPr(plhs(1)) + + plhs(2) = mxCreateNumericArray(ndim, IArows, + + classid, + + complexflag) + + IC_2 = mxGetPr(plhs(2)) + +C Call the computational routine. + call compute(%VAL(l),%VAL(m),%VAL(n), + + %VAL(IA),%VAL(JA), + + %VAL(IB),%VAL(JB), + + %VAL(IC_1),%VAL(IC_2), + + IArows,JArows,IBrows,JBrows) + + return + end + +C Computational subroutine + subroutine compute(l,m,n,IA,JA, + + IB,JB, + + IC_1,IC_2, + + IArows,JArows, + + IBrows,JBrows) + +C Declarations + implicit none + + mwSize l,m,n + mwSize IArows,JArows + mwSize IBrows,JBrows + + mwSize, pointer :: pIA(:) + mwSize, pointer :: pJA(:,:) + mwSize, pointer :: pIB(:) + + mwSize, allocatable :: w(:,:) + + mwSize, target :: IA(IArows) + mwSize, target :: JA(JArows,2) + + mwSize, target :: IB(IBrows) + mwSize JB(JBrows) + + mwSize, target :: IC_1(IArows) + mwSize, target :: IC_2(IArows) + + mwSize, target,allocatable :: JC_2(:,:) + + mwSize i,jp,j,kp,k1,k2,vp,v1,v2,nz + mwSize kpstart + + integer AllocateStatus + +C first contraction + + allocate (w(m,n), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory.') + endif + + w=0 + nz=1 + + pIA=>IA + pJA=>JA + + pIB=>IB + + do i=1,l + IC_2(i)=nz + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,2) + k1=pJA(jp,1) + do kp=pIB(j),pIB(j+1)-1 + k2=JB(kp) + if (w(k1,k2)IC_2 + pJA=>JC_2 + + pIB=>IB + + do i=1,l + IC_1(i)=nz + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k2)) then + kpstart=pIB(j) + do while (JB(kpstart)IA + pJA=>JA + + pIB=>IB + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,2) + k1=pJA(jp,1) + do kp=pIB(j),pIB(j+1)-1 + k2=JB(kp) + if (w(k1,k2)IC_2 + pJA=>JC_2 + + pIB=>IB + + do i=1,l + + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k2)) then + kpstart=pIB(j) + do while (JB(kpstart)IA + pJA=>JA + + pIB=>IB + pJB=>JB + + pIC=>IC_2 + pJC=>tempJC2 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,2) + k1=pJA(jp,1) + do kp=pIB(j),pIB(j+1)-1 + k2=pJB(kp) +C collect information for pJC and initialize x to zero + if (w(k1,k2)sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + end do + +C assign the result in tempNC2 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC2(js,vp)=x(is,v1,v2) + x(is,v1,v2)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + +C second contraction + rows=IC_1(ICrows_1)-1 + allocate (w(n,n), + + x(min(sC,maxload),n,n), + + tempJC1(JCrows_1,2), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory4.') + endif + + w=0 + nz=1 + + pIA=>IC_2 + pJA=>tempJC2 + + pIB=>IB + pJB=>JB + + pIC=>IC_1 + pJC=>tempJC1 + + sA=sC2 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + if (sC2>1) then + pNA=>tempNC2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC2 + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (pJB(pIB(j+1)-1).ge.k2)) then + kpstart=pIB(j) + do while (pJB(kpstart)1) then +C Choose among three options and do not sum across rows + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(1,jp)*pNB(is,kp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2)=x(1,k1,k2)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2)=x(1,k1,k2)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(1,k1,k2)=x(1,k1,k2)+pNA(1,jp)*pNB(is,kp) + end do + endif + endif + + end do + endif + + end do + +C assign the result in NC + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x(is,v1,v2) + x(is,v1,v2)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x(1,v1,v2) + x(1,v1,v2)=0.0 + endif + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC2,tempJC2,tempJC1) + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU2vec_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU2vec_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..6baa828e0bfbcfb3b9a8989a76508717b206456e --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU2vec_mex.F @@ -0,0 +1,428 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [NC] = AkronBU2vec_mex(l,m,n,IA,JA,NA,... +C IB,JB,NB,... +C IC_1,JC_1,IC_2,JC_2,... +C maxload,dosum) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateDoubleMatrix + real*8 mxGetScalar + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l,IA,JA + mwPointer m,n + mwPointer IB,JB + mwPointer IC_1,IC_2 + mwPointer JC_1,JC_2 + mwPointer maxload,dosum + mwPointer NA,NB + + mwPointer NC + +C Array information: + mwSize IArows,JArows + mwSize IBrows, JBrows + mwSize ICrows_1,ICrows_2 + mwSize JCrows_1,JCrows_2 + + mwSize s,sC,sA,sB + real*8 do_sum + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 15) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '19 inputs required.') + endif + if(nlhs .gt. 1) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'Max 1 outputs required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(4)) + JArows = mxGetM(prhs(5)) + + IBrows = mxGetM(prhs(7)) + JBrows = mxGetM(prhs(8)) + + ICrows_1 = mxGetM(prhs(10)) + JCrows_1 = mxGetM(prhs(11)) + + ICrows_2 = mxGetM(prhs(12)) + JCrows_2 = mxGetM(prhs(13)) + +C Create Fortran array from the input arguments. + l = mxGetPr(prhs(1)) + m = mxGetPr(prhs(2)) + n = mxGetPr(prhs(3)) + IA = mxGetPr(prhs(4)) + JA = mxGetPr(prhs(5)) + NA = mxGetPr(prhs(6)) + IB = mxGetPr(prhs(7)) + JB = mxGetPr(prhs(8)) + NB = mxGetPr(prhs(9)) + IC_1 = mxGetPr(prhs(10)) + JC_1 = mxGetPr(prhs(11)) + IC_2 = mxGetPr(prhs(12)) + JC_2 = mxGetPr(prhs(13)) + maxload = mxGetPr(prhs(14)) + +C Get number of states + sA = mxGetM(prhs(6)) + sB = mxGetM(prhs(9)) + +C check compatibility of states + s=max(sA,sB) + if ((sA.ne.s .and. sA.ne.1) .or. (sB.ne.s .and. sB.ne.1)) + + then + call mexErrMsgIdAndTxt ('MATLAB:states', + + 'incompatible states.') + endif + +C sum across rows of C if dosum==1 + do_sum=mxGetScalar(prhs(15)) + + if (do_sum==1) then + sC=1 + else + sC=s + endif + +C Create matrix for NC. + complexflag=0 + plhs(1) = mxCreateDoubleMatrix(sC,JCrows_1, complexflag) + NC = mxGetPr(plhs(1)) + +C Call the computational routine. + call compute(%VAL(l),%VAL(m), + + %VAL(n), + + %VAL(IA),%VAL(JA),%VAL(NA), + + %VAL(IB),%VAL(JB),%VAL(NB), + + %VAL(IC_1),%VAL(JC_1),%VAL(IC_2),%VAL(JC_2), + + %VAL(maxload), + + %VAL(NC), + + IArows,JArows,IBrows,JBrows, + + ICrows_1,JCrows_1,ICrows_2,JCrows_2, + + sC,sA,sB) + + return + end + +C Computational subroutine + subroutine compute(l,m,n,IA,JA,NA, + + IB,JB,NB, + + IC_1,JC_1,IC_2,JC_2, + + maxload, + + NC, + + IArows,JArows, + + IBrows,JBrows, + + ICrows_1,JCrows_1,ICrows_2,JCrows_2, + + sC,sA,sB) + +C Declarations + implicit none + + mwSize l,m,n,sC,sA,sB + mwSize IArows,JArows + mwSize IBrows,JBrows + mwSize ICrows_1,ICrows_2 + mwSize JCrows_1,JCrows_2 + + mwSize s,sC2,rows + mwSize maxload,n_vecload,loadi,load_ + + real*8, target :: NA(sA,JArows) + real*8, target :: NB(sB,JBrows) + + real*8 NC(sC,JCrows_1) + + real*8, pointer :: pNA(:,:),pNB(:,:) + mwSize, pointer :: pIA(:),pIB(:),pIC(:) + mwSize, pointer :: pJA(:,:),pJC(:,:) + mwSize, pointer :: pJB(:) + + mwSize, allocatable :: vecload(:) + + real*8, allocatable :: x(:,:,:) + logical, allocatable :: w(:,:) + +C two temporary crs var is needed, 2 + real*8, target, allocatable :: tempNC2(:,:) + + mwSize, target :: IA(IArows) + mwSize, target :: JA(JArows,2) + + mwSize, target :: IB(IBrows) + mwSize, target :: JB(JBrows) + + mwSize, target :: IC_1(ICrows_1) + mwSize, target :: JC_1(JCrows_1,3) + + mwSize, target :: IC_2(ICrows_2) + mwSize, target :: JC_2(JCrows_2,2) + + mwSize i,jp,j,kp,k1,k2,vp,v1,v2 + mwSize is,js,nz + + mwSize mati,k,kpstart,loc,j2 + real*8 mat(2,2), fact(2), prod1 + + + integer AllocateStatus + +C vecload + s=max(sA,sB) + + n_vecload=(s-1)/maxload+2 + + allocate (vecload(n_vecload),STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory1.') + endif + + vecload(1)=1 + vecload(n_vecload)=s+1 + do i=2,n_vecload-1 + vecload(i)=vecload(i-1)+maxload + end do + +C prepare matrices for factorials and products + k=2 + mat(1,1:k)=(/ (mati, mati = n+1, n+k) /) + mat(2,1:k)=(/ (mati, mati = n, n+k-1) /) + + fact(1)=1 + do j=2,k + fact(j)=fact(j-1)*j + end do + prod1=product(mat(2,:)) + +C first contraction + sC2=max(sA,sB) + rows=IC_2(ICrows_2)-1 + allocate (w(m,n), + + x(min(sC2,maxload),m,n), + + tempNC2(sC2,rows), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory2.') + endif + + w=.false. + nz=1 + + pIA=>IA + pJA=>JA + + pIB=>IB + pJB=>JB + + pIC=>IC_2 + pJC=>JC_2 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,2) + k1=pJA(jp,1) + do kp=pIB(j),pIB(j+1)-1 + k2=pJB(kp) +C initialize x to zero + if (w(k1,k2)==.false.) then + w(k1,k2)=.true. + x(:,k1,k2)=0 + endif + +C Choose among three options: + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + end do + +C assign the result in tempNC2 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC2(js,vp)=x(is,v1,v2) + x(is,v1,v2)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + +C second contraction + rows=IC_1(ICrows_1)-1 + allocate (w(n,n), + + x(min(sC,maxload),n,n), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory4.') + endif + + w=.false. + nz=1 + + pIA=>IC_2 + pJA=>JC_2 + + pIB=>IB + pJB=>JB + + pIC=>IC_1 + pJC=>JC_1 + + sA=sC2 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC2>1) then + pNA=>tempNC2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC2 + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (pJB(pIB(j+1)-1).ge.k2)) then + kpstart=pIB(j) + do while (pJB(kpstart)1) then +C Choose among three options and do not sum across rows + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(1,jp)*pNB(is,kp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2)=x(1,k1,k2)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2)=x(1,k1,k2)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(1,k1,k2)=x(1,k1,k2)+pNA(1,jp)*pNB(is,kp) + end do + endif + endif + + end do + endif + end do + +C assign the result in NC + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,2) + v2=pJC(vp,3) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x(is,v1,v2) + x(is,v1,v2)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x(1,v1,v2) + x(1,v1,v2)=0.0 + endif + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC2) + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU3IC_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU3IC_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..89bd30f93cd9deedea407bb878d14f14b5ded674 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU3IC_mex.F @@ -0,0 +1,322 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [IC_1,IC_2,IC_3] = AkronBU3IC_mex(l,m,n,IA,JA,IB,JB) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateNumericArray + integer*4 mxGetClassID + +C Arguments for mxCreateNumericArray + integer*4 classid + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l,m,n,IA,JA + mwPointer IB,JB + mwPointer IC_1,IC_2,IC_3 + +C Array information: + mwSize IArows,JArows + mwSize IBrows, JBrows,ndim + + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 7) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '14 inputs required.') + endif + if(nlhs .gt. 3) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'Max 3 outputs required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(4)) + JArows = mxGetM(prhs(5)) + + IBrows = mxGetM(prhs(6)) + JBrows = mxGetM(prhs(7)) + +C Create Fortran array from the input arguments. + l = mxGetPr(prhs(1)) + m = mxGetPr(prhs(2)) + n = mxGetPr(prhs(3)) + IA = mxGetPr(prhs(4)) + JA = mxGetPr(prhs(5)) + IB = mxGetPr(prhs(6)) + JB = mxGetPr(prhs(7)) + +C Create matrix for the return arguments. + classid = mxGetClassID(prhs(4)) + + complexflag = 0 + ndim=1 + plhs(1) = mxCreateNumericArray(ndim, IArows, + + classid, + + complexflag) + + IC_1 = mxGetPr(plhs(1)) + + plhs(2) = mxCreateNumericArray(ndim, IArows, + + classid, + + complexflag) + + IC_2 = mxGetPr(plhs(2)) + + plhs(3) = mxCreateNumericArray(ndim, IArows, + + classid, + + complexflag) + + IC_3 = mxGetPr(plhs(3)) + +C Call the computational routine. + call compute(%VAL(l),%VAL(m),%VAL(n), + + %VAL(IA),%VAL(JA), + + %VAL(IB),%VAL(JB), + + %VAL(IC_1),%VAL(IC_2),%VAL(IC_3), + + IArows,JArows,IBrows,JBrows) + + return + end + +C Computational subroutine + subroutine compute(l,m,n,IA,JA, + + IB,JB, + + IC_1,IC_2,IC_3, + + IArows,JArows, + + IBrows,JBrows) + +C Declarations + implicit none + + mwSize l,m,n + mwSize IArows,JArows + mwSize IBrows,JBrows + + mwSize, pointer :: pIA(:) + mwSize, pointer :: pJA(:,:) + mwSize, pointer :: pIB(:) + + mwSize, allocatable :: w(:,:,:) + + mwSize, target :: IA(IArows) + mwSize, target :: JA(JArows,3) + + mwSize, target :: IB(IBrows) + mwSize JB(JBrows) + + mwSize, target :: IC_1(IArows) + mwSize, target :: IC_2(IArows) + mwSize, target :: IC_3(IArows) + + mwSize, target,allocatable :: JC_2(:,:) + mwSize, target,allocatable :: JC_3(:,:) + + mwSize i,jp,j,kp,k1,k2,k3,vp,v1,v2,v3,nz + + mwSize kpstart + + integer AllocateStatus + +C first contraction + allocate (w(m,m,n), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory.') + endif + + w=0 + nz=1 + + pIA=>IA + pJA=>JA + + pIB=>IB + + do i=1,l + IC_3(i)=nz + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + j=pJA(jp,3) + do kp=pIB(j),pIB(j+1)-1 + k3=JB(kp) + if (w(k1,k2,k3)IC_3 + pJA=>JC_3 + + pIB=>IB + + do i=1,l + IC_2(i)=nz + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + j=pJA(jp,2) + k3=pJA(jp,3) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k3)) then + kpstart=pIB(j) + do while (JB(kpstart)IC_2 + pJA=>JC_2 + + pIB=>IB + + do i=1,l + IC_1(i)=nz + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k2)) then + kpstart=pIB(j) + do while (JB(kpstart)IA + pJA=>JA + + pIB=>IB + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + j=pJA(jp,3) + do kp=pIB(j),pIB(j+1)-1 + k3=JB(kp) + if (w(k1,k2,k3)IC_3 + pJA=>JC_3 + + pIB=>IB + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + j=pJA(jp,2) + k3=pJA(jp,3) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k3)) then + kpstart=pIB(j) + do while (JB(kpstart)IC_2 + pJA=>JC_2 + + pIB=>IB + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k2)) then + kpstart=pIB(j) + do while (JB(kpstart)IA + pJA=>JA + + pIB=>IB + pJB=>JB + + pIC=>IC_3 + pJC=>tempJC3 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + j=pJA(jp,3) + do kp=pIB(j),pIB(j+1)-1 + k3=pJB(kp) +C collect information for pJC and initialize x to zero + if (w(k1,k2,k3)sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + end do + +C assign the result in tempNC3 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC3(js,vp)=x(is,v1,v2,v3) + x(is,v1,v2,v3)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + +C second contraction + sC2=max(sC3,sB) + rows=IC_2(ICrows_2)-1 + allocate (w(m,n,n), + + x(min(sC2,maxload),m,n,n), + + tempNC2(sC2,rows), + + tempJC2(rows,3), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory3.') + endif + + w=0 + nz=1 + + pIA=>IC_3 + pJA=>tempJC3 + + pIB=>IB + pJB=>JB + + pIC=>IC_2 + pJC=>tempJC2 + + sA=sC3 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC3>1) then + pNA=>tempNC3(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC3 + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + j=pJA(jp,2) + k3=pJA(jp,3) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k3)) then + kpstart=pIB(j) + do while (JB(kpstart)sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + endif + end do + + +C assign the result in tempNC2 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC2(js,vp)=x(is,v1,v2,v3) + x(is,v1,v2,v3)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC3,tempJC3) + +C third contraction + rows=IC_1(ICrows_1)-1 + allocate (w(n,n,n), + + x(min(sC,maxload),n,n,n), + + tempJC1(JCrows_1,3), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory4.') + endif + + w=0 + nz=1 + + pIA=>IC_2 + pJA=>tempJC2 + + pIB=>IB + pJB=>JB + + pIC=>IC_1 + pJC=>tempJC1 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC2>1) then + pNA=>tempNC2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC2 + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k2)) then + kpstart=pIB(j) + do while (JB(kpstart)1) then +C Choose among three options and do not sum across rows + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(1,jp)*pNB(is,kp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3)=x(1,k1,k2,k3)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3)=x(1,k1,k2,k3)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3)=x(1,k1,k2,k3)+pNA(1,jp)*pNB(is,kp) + end do + endif + endif + + end do + endif + end do + +C assign the result in NC + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x(is,v1,v2,v3) + x(is,v1,v2,v3)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x(1,v1,v2,v3) + x(1,v1,v2,v3)=0.0 + endif + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC2,tempJC2,tempJC1) + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU3vec_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU3vec_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..cdd1aea5bccf4b2208397c69dd550c2dd8965908 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU3vec_mex.F @@ -0,0 +1,545 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [NC] = AkronBU3vec_mex(l,m,n,IA,JA,NA,... +C IB,JB,NB,... +C IC_1,JC_1,IC_2,JC_2,IC_3,JC_3,... +C maxload,dosum) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateDoubleMatrix + real*8 mxGetScalar + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l,IA,JA + mwPointer m,n + mwPointer IB,JB + mwPointer IC_1,IC_2,IC_3 + mwPointer JC_1,JC_2,JC_3 + mwPointer maxload,dosum + mwPointer NA,NB + + mwPointer NC + +C Array information: + mwSize IArows,JArows + mwSize IBrows, JBrows + mwSize ICrows_1,ICrows_2,ICrows_3 + mwSize JCrows_1,JCrows_2,JCrows_3 + + mwSize s,sC,sA,sB + real*8 do_sum + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 17) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '17 inputs required.') + endif + if(nlhs .gt. 1) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'Max 1 output required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(4)) + JArows = mxGetM(prhs(5)) + + IBrows = mxGetM(prhs(7)) + JBrows = mxGetM(prhs(8)) + + ICrows_1 = mxGetM(prhs(10)) + JCrows_1 = mxGetM(prhs(11)) + + ICrows_2 = mxGetM(prhs(12)) + JCrows_2 = mxGetM(prhs(13)) + + ICrows_3 = mxGetM(prhs(14)) + JCrows_3 = mxGetM(prhs(15)) + +C Create Fortran array from the input arguments. + l = mxGetPr(prhs(1)) + m = mxGetPr(prhs(2)) + n = mxGetPr(prhs(3)) + IA = mxGetPr(prhs(4)) + JA = mxGetPr(prhs(5)) + NA = mxGetPr(prhs(6)) + IB = mxGetPr(prhs(7)) + JB = mxGetPr(prhs(8)) + NB = mxGetPr(prhs(9)) + IC_1 = mxGetPr(prhs(10)) + JC_1 = mxGetPr(prhs(11)) + IC_2 = mxGetPr(prhs(12)) + JC_2 = mxGetPr(prhs(13)) + IC_3 = mxGetPr(prhs(14)) + JC_3 = mxGetPr(prhs(15)) + maxload = mxGetPr(prhs(16)) + +C Get number of states + sA = mxGetM(prhs(6)) + sB = mxGetM(prhs(9)) + +C check compatibility of states + s=max(sA,sB) + if ((sA.ne.s .and. sA.ne.1) .or. (sB.ne.s .and. sB.ne.1)) + + then + call mexErrMsgIdAndTxt ('MATLAB:states', + + 'incompatible states.') + endif + +C sum across rows of C if dosum==1 + do_sum=mxGetScalar(prhs(17)) + + if (do_sum==1) then + sC=1 + else + sC=s + endif + +C Create matrix for NC. + complexflag=0 + plhs(1) = mxCreateDoubleMatrix(sC,JCrows_1,complexflag) + NC = mxGetPr(plhs(1)) + +C Call the computational routine. + call compute(%VAL(l),%VAL(m), + + %VAL(n), + + %VAL(IA),%VAL(JA),%VAL(NA), + + %VAL(IB),%VAL(JB),%VAL(NB), + + %VAL(IC_1),%VAL(JC_1),%VAL(IC_2),%VAL(JC_2), + + %VAL(IC_3),%VAL(JC_3),%VAL(maxload), + + %VAL(NC), + + IArows,JArows,IBrows,JBrows, + + ICrows_1,JCrows_1,ICrows_2,JCrows_2, + + ICrows_3,JCrows_3, + + sC,sA,sB) + + return + end + +C Computational subroutine + subroutine compute(l,m,n,IA,JA,NA, + + IB,JB,NB, + + IC_1,JC_1,IC_2,JC_2,IC_3,JC_3, + + maxload, + + NC, + + IArows,JArows, + + IBrows,JBrows, + + ICrows_1,JCrows_1,ICrows_2,JCrows_2, + + ICrows_3,JCrows_3, + + sC,sA,sB) + + +C Declarations + implicit none + + mwSize l,m,n,sC,sA,sB + mwSize IArows,JArows + mwSize IBrows,JBrows + mwSize ICrows_1,ICrows_2,ICrows_3 + mwSize JCrows_1,JCrows_2,JCrows_3 + + mwSize s,sC3,sC2,rows + mwSize maxload,n_vecload,loadi,load_ + + real*8, target :: NA(sA,JArows) + real*8, target :: NB(sB,JBrows) + + real*8 NC(sC,JCrows_1) + + real*8, pointer :: pNA(:,:),pNB(:,:) + mwSize, pointer :: pIA(:),pIB(:),pIC(:) + mwSize, pointer :: pJA(:,:),pJC(:,:) + mwSize, pointer :: pJB(:) + + mwSize, allocatable :: vecload(:) + + real*8, allocatable :: x(:,:,:,:) + logical, allocatable :: w(:,:,:) + +C two temporary crs vars are needed, 2 and 3 + real*8, target, allocatable :: tempNC3(:,:) + real*8, target, allocatable :: tempNC2(:,:) + + mwSize, target :: IA(IArows) + mwSize, target :: JA(JArows,3) + + mwSize, target :: IB(IBrows) + mwSize, target :: JB(JBrows) + + mwSize, target :: IC_1(ICrows_1) + mwSize, target :: JC_1(JCrows_1,4) + + mwSize, target :: IC_2(ICrows_2) + mwSize, target :: JC_2(JCrows_2,3) + + mwSize, target :: IC_3(ICrows_3) + mwSize, target :: JC_3(JCrows_3,3) + + mwSize i,jp,j,kp,k1,k2,k3,vp,v1,v2,v3 + mwSize is,js,nz + + mwSize mati,k,kpstart,loc,j2 + real*8 mat(2,2), fact(2), prod1 + + + integer AllocateStatus + +C vecload + s=max(sA,sB) + + n_vecload=(s-1)/maxload+2 + + allocate (vecload(n_vecload),STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory1.') + endif + + vecload(1)=1 + vecload(n_vecload)=s+1 + do i=2,n_vecload-1 + vecload(i)=vecload(i-1)+maxload + end do + +C prepare matrices for factorials and products + + mat(1,1:k)=(/ (mati, mati = n+1, n+k) /) + mat(2,1:k)=(/ (mati, mati = n, n+k-1) /) + do j=2,k-1 + mat(j+1,1:k-j+1)=(/ (mati, mati = n+k-j+1, n+1, -1) /) + end do + fact(1)=1 + do j=2,k + fact(j)=fact(j-1)*j + end do + prod1=product(mat(2,:)) + +C first contraction + sC3=max(sA,sB) + rows=IC_3(ICrows_3)-1 + allocate (w(m,m,n), + + x(min(sC3,maxload),m,m,n), + + tempNC3(sC3,rows), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory2.') + endif + + w=.false. + nz=1 + + pIA=>IA + pJA=>JA + + pIB=>IB + pJB=>JB + + pIC=>IC_3 + pJC=>JC_3 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + j=pJA(jp,3) + do kp=pIB(j),pIB(j+1)-1 + k3=pJB(kp) +C initialize x to zero + if (w(k1,k2,k3)==.false.) then + w(k1,k2,k3)=.true. + x(:,k1,k2,k3)=0 + endif + +C Choose among three options: + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + end do + +C assign the result in tempNC3 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC3(js,vp)=x(is,v1,v2,v3) + x(is,v1,v2,v3)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + +C second contraction + sC2=max(sC3,sB) + rows=IC_2(ICrows_2)-1 + allocate (w(m,n,n), + + x(min(sC2,maxload),m,n,n), + + tempNC2(sC2,rows), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory3.') + endif + + w=.false. + nz=1 + + pIA=>IC_3 + pJA=>JC_3 + + pIB=>IB + pJB=>JB + + pIC=>IC_2 + pJC=>JC_2 + + sA=sC3 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC3>1) then + pNA=>tempNC3(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC3 + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + j=pJA(jp,2) + k3=pJA(jp,3) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k3)) then + kpstart=pIB(j) + do while (JB(kpstart)sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + endif + end do + +C assign the result in tempNC2 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC2(js,vp)=x(is,v1,v2,v3) + x(is,v1,v2,v3)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC3) + +C third contraction + rows=IC_1(ICrows_1)-1 + allocate (w(n,n,n), + + x(min(sC,maxload),n,n,n), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory4.') + endif + + w=.false. + nz=1 + + pIA=>IC_2 + pJA=>JC_2 + + pIB=>IB + pJB=>JB + + pIC=>IC_1 + pJC=>JC_1 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC2>1) then + pNA=>tempNC2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC2 + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k2)) then + kpstart=pIB(j) + do while (JB(kpstart)1) then +C Choose among three options and do not sum across rows + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(1,jp)*pNB(is,kp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3)=x(1,k1,k2,k3)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3)=x(1,k1,k2,k3)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3)=x(1,k1,k2,k3)+pNA(1,jp)*pNB(is,kp) + end do + endif + endif + + end do + endif + end do + +C assign the result in NC + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,2) + v2=pJC(vp,3) + v3=pJC(vp,4) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x(is,v1,v2,v3) + x(is,v1,v2,v3)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x(1,v1,v2,v3) + x(1,v1,v2,v3)=0.0 + endif + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC2) + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU4IC_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU4IC_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..e54505824cb4581aebb6e241fb06b9efa2191b32 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU4IC_mex.F @@ -0,0 +1,414 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [IC_1,IC_2,IC_3,IC_4] = AkronBU4IC_mex(l,m,n,IA,JA,IB,JB) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateNumericArray + integer*4 mxGetClassID + +C Arguments for mxCreateNumericArray + integer*4 classid + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l,m,n,IA,JA + mwPointer IB,JB + mwPointer IC_1,IC_2,IC_3,IC_4 + +C Array information: + mwSize IArows,JArows + mwSize IBrows, JBrows,ndim + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 7) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '7 inputs required.') + endif + if(nlhs .gt. 4) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'Max 4 outputs required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(4)) + JArows = mxGetM(prhs(5)) + + IBrows = mxGetM(prhs(6)) + JBrows = mxGetM(prhs(7)) + +C Create Fortran array from the input arguments. + l = mxGetPr(prhs(1)) + m = mxGetPr(prhs(2)) + n = mxGetPr(prhs(3)) + IA = mxGetPr(prhs(4)) + JA = mxGetPr(prhs(5)) + IB = mxGetPr(prhs(6)) + JB = mxGetPr(prhs(7)) + +C Create matrix for the return arguments. + classid = mxGetClassID(prhs(4)) + ndim=1 + complexflag = 0 + plhs(1) = mxCreateNumericArray(ndim, IArows, + + classid, + + complexflag) + + IC_1 = mxGetPr(plhs(1)) + + plhs(2) = mxCreateNumericArray(ndim, IArows, + + classid, + + complexflag) + + IC_2 = mxGetPr(plhs(2)) + + plhs(3) = mxCreateNumericArray(ndim, IArows, + + classid, + + complexflag) + + IC_3 = mxGetPr(plhs(3)) + + plhs(4) = mxCreateNumericArray(ndim, IArows, + + classid, + + complexflag) + + IC_4 = mxGetPr(plhs(4)) + +C Call the computational routine. + call compute(%VAL(l),%VAL(m),%VAL(n), + + %VAL(IA),%VAL(JA), + + %VAL(IB),%VAL(JB), + + %VAL(IC_1),%VAL(IC_2),%VAL(IC_3),%VAL(IC_4), + + IArows,JArows,IBrows,JBrows) + + return + end + +C Computational subroutine + subroutine compute(l,m,n,IA,JA, + + IB,JB, + + IC_1,IC_2,IC_3,IC_4, + + IArows,JArows, + + IBrows,JBrows) + +C Declarations + implicit none + + mwSize l,m,n + mwSize IArows,JArows + mwSize IBrows,JBrows + + mwSize, pointer :: pIA(:) + mwSize, pointer :: pJA(:,:) + mwSize, pointer :: pIB(:) + + mwSize, allocatable :: w(:,:,:,:) + + mwSize, target :: IA(IArows) + mwSize, target :: JA(JArows,2) + + mwSize, target :: IB(IBrows) + mwSize JB(JBrows) + + mwSize, target :: IC_1(IArows) + mwSize, target :: IC_2(IArows) + mwSize, target :: IC_3(IArows) + mwSize, target :: IC_4(IArows) + + mwSize, target,allocatable :: JC_2(:,:) + mwSize, target,allocatable :: JC_3(:,:) + mwSize, target,allocatable :: JC_4(:,:) + + mwSize i,jp,j,kp,k1,k2,k3,k4,vp,v1,v2,v3,v4,nz + + mwSize kpstart + + integer AllocateStatus + +C first contraction + allocate (w(m,m,m,n), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory.') + endif + + w=0 + nz=1 + + pIA=>IA + pJA=>JA + + pIB=>IB + + do i=1,l + IC_4(i)=nz + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + j=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k4=JB(kp) + if (w(k1,k2,k3,k4)IC_4 + pJA=>JC_4 + + pIB=>IB + + do i=1,l + IC_3(i)=nz + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + j=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k4)) then + kpstart=pIB(j) + do while (JB(kpstart)IC_3 + pJA=>JC_3 + + pIB=>IB + + do i=1,l + IC_2(i)=nz + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + j=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k3)) then + kpstart=pIB(j) + do while (JB(kpstart)IC_2 + pJA=>JC_2 + + pIB=>IB + + do i=1,l + IC_1(i)=nz + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k2)) then + kpstart=pIB(j) + do while (JB(kpstart)IA + pJA=>JA + + pIB=>IB + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + j=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k4=JB(kp) + if (w(k1,k2,k3,k4)IC_4 + pJA=>JC_4 + + pIB=>IB + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + j=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k4)) then + kpstart=pIB(j) + do while (JB(kpstart)IC_3 + pJA=>JC_3 + + pIB=>IB + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + j=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k3)) then + kpstart=pIB(j) + do while (JB(kpstart)IC_2 + pJA=>JC_2 + + pIB=>IB + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k2)) then + kpstart=pIB(j) + do while (JB(kpstart)IA + pJA=>JA + + pIB=>IB + + do i=1,l + IC_4(i)=nz + do jp=pIA(i),pIA(i+1)-1 + k1=convertind(i,pJA(jp,1)) + k2=convertind(i,pJA(jp,2)) + k3=convertind(i,pJA(jp,3)) + j=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k4=JB(kp) + if (w(k1,k2,k3,k4)IC_4 + pJA=>JC_4 + + pIB=>IB + + do i=1,l + IC_3(i)=nz + do jp=pIA(i),pIA(i+1)-1 + k1=convertind(i,pJA(jp,1)) + k2=convertind(i,pJA(jp,2)) + j=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k4)) then + kpstart=pIB(j) + do while (JB(kpstart)IC_3 + pJA=>JC_3 + + pIB=>IB + + do i=1,l + IC_2(i)=nz + do jp=pIA(i),pIA(i+1)-1 + k1=convertind(i,pJA(jp,1)) + j=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k3)) then + kpstart=pIB(j) + do while (JB(kpstart)IC_2 + pJA=>JC_2 + + pIB=>IB + + do i=1,l + IC_1(i)=nz + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k2)) then + kpstart=pIB(j) + do while (JB(kpstart)IA + pJA=>JA + + pIB=>IB + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=convertind(i,pJA(jp,1)) + k2=convertind(i,pJA(jp,2)) + k3=convertind(i,pJA(jp,3)) + j=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k4=JB(kp) + if (w(k1,k2,k3,k4)IC_4 + pJA=>JC_4 + + pIB=>IB + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=convertind(i,pJA(jp,1)) + k2=convertind(i,pJA(jp,2)) + j=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k4)) then + kpstart=pIB(j) + do while (JB(kpstart)IC_3 + pJA=>JC_3 + + pIB=>IB + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=convertind(i,pJA(jp,1)) + j=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k3)) then + kpstart=pIB(j) + do while (JB(kpstart)IC_2 + pJA=>JC_2 + + pIB=>IB + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k2)) then + kpstart=pIB(j) + do while (JB(kpstart)IA + pJA=>JA + + pIB=>IB + pJB=>JB + + pIC=>IC_4 + pJC=>tempJC4 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + + do jp=pIA(i),pIA(i+1)-1 + k1=convertind(i,pJA(jp,1)) + k2=convertind(i,pJA(jp,2)) + k3=convertind(i,pJA(jp,3)) + j=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k4=JB(kp) + +C collect information for pJC and initialize x to zero + if (w(k1,k2,k3,k4)sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + end do + +C assign the result in tempNC4 + do vp=pIC(i),pIC(i+1)-1 + v1=convertind(i,pJC(vp,1)) + v2=convertind(i,pJC(vp,2)) + v3=convertind(i,pJC(vp,3)) + v4=pJC(vp,4) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC4(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + +C second contraction + sC3=max(sC4,sB) + rows=IC_3(ICrows_3)-1 + allocate (w(smallm,smallm,n,n), + + x(min(sC3,maxload),smallm,smallm,n,n), + + tempNC3(sC3,rows), + + tempJC3(rows,4), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory2.') + endif + + w=0 + nz=1 + + pIA=>IC_4 + pJA=>tempJC4 + + pIB=>IB + pJB=>JB + + pIC=>IC_3 + pJC=>tempJC3 + + sA=sC4 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC4>1) then + pNA=>tempNC4(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC4 + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=convertind(i,pJA(jp,1)) + k2=convertind(i,pJA(jp,2)) + j=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k4)) then + kpstart=pIB(j) + do while (JB(kpstart)sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + endif + end do + +C assign the result in tempNC3 + do vp=pIC(i),pIC(i+1)-1 + v1=convertind(i,pJC(vp,1)) + v2=convertind(i,pJC(vp,2)) + v3=pJC(vp,3) + v4=pJC(vp,4) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC3(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC4,tempJC4) + +C third contraction + sC2=max(sC3,sB) + rows=IC_2(ICrows_2)-1 + allocate (w(smallm,n,n,n), + + x(min(sC2,maxload),smallm,n,n,n), + + tempNC2(sC2,rows), + + tempJC2(rows,4), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory3.') + endif + + w=0 + nz=1 + + pIA=>IC_3 + pJA=>tempJC3 + + pIB=>IB + pJB=>JB + + pIC=>IC_2 + pJC=>tempJC2 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC3>1) then + pNA=>tempNC3(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC3 + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=convertind(i,pJA(jp,1)) + j=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k3)) then + kpstart=pIB(j) + do while (JB(kpstart)sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + endif + end do + +C assign the result in tempNC2 + do vp=pIC(i),pIC(i+1)-1 + v1=convertind(i,pJC(vp,1)) + v2=pJC(vp,2) + v3=pJC(vp,3) + v4=pJC(vp,4) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC2(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC3,tempJC3) + +C fourth contraction + rows=IC_1(ICrows_1)-1 + allocate (w(n,n,n,n), + + x(min(sC,maxload),n,n,n,n), + + tempJC1(JCrows_1,4), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory4.') + endif + + w=0 + nz=1 + + pIA=>IC_2 + pJA=>tempJC2 + + pIB=>IB + pJB=>JB + + pIC=>IC_1 + pJC=>tempJC1 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC2>1) then + pNA=>tempNC2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC2 + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k2)) then + kpstart=pIB(j) + do while (JB(kpstart)1) then +C Choose among three options and do not sum across rows + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3,k4)=x(1,k1,k2,k3,k4)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3,k4)=x(1,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3,k4)=x(1,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + endif + + end do + endif + end do + +C assign the result in NC + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + v4=pJC(vp,4) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x(1,v1,v2,v3,v4) + x(1,v1,v2,v3,v4)=0.0 + endif + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC2,tempJC2,tempJC1) + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU4ivec_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU4ivec_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..43c9c78213a2f9f66b7cbff24d8d4d12934e3f62 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU4ivec_mex.F @@ -0,0 +1,675 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [NC] = AkronBU4ivec_mex(l,m,n,IA,JA,NA,... +C IB,JB,NB,... +C IC_1,JC_1,IC_2,JC_2,IC_3,JC_3,IC_4,JC_4,... +C maxload,dosum,convertind,maxind) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateDoubleMatrix + real*8 mxGetScalar + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l,IA,JA + mwPointer m,n + mwPointer IB,JB + mwPointer IC_1,IC_2,IC_3,IC_4 + mwPointer JC_1,JC_2,JC_3,JC_4 + mwPointer maxload,dosum + mwPointer NA,NB + mwPointer convertind,maxind + + mwPointer NC + +C Array information: + mwSize IArows,JArows + mwSize IBrows, JBrows + + mwSize ICrows_1,ICrows_2,ICrows_3,ICrows_4 + mwSize JCrows_1,JCrows_2,JCrows_3,JCrows_4 + + mwSize s,sC,sA,sB + real*8 do_sum + + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 21) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '21 inputs required.') + endif + if(nlhs .gt. 1) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'Max 1 output required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(4)) + JArows = mxGetM(prhs(5)) + + IBrows = mxGetM(prhs(7)) + JBrows = mxGetM(prhs(8)) + + ICrows_1 = mxGetM(prhs(10)) + JCrows_1 = mxGetM(prhs(11)) + + ICrows_2 = mxGetM(prhs(12)) + JCrows_2 = mxGetM(prhs(13)) + + ICrows_3 = mxGetM(prhs(14)) + JCrows_3 = mxGetM(prhs(15)) + + ICrows_4 = mxGetM(prhs(16)) + JCrows_4 = mxGetM(prhs(17)) + + +C Create Fortran array from the input arguments. + l = mxGetPr(prhs(1)) + m = mxGetPr(prhs(2)) + n = mxGetPr(prhs(3)) + IA = mxGetPr(prhs(4)) + JA = mxGetPr(prhs(5)) + NA = mxGetPr(prhs(6)) + IB = mxGetPr(prhs(7)) + JB = mxGetPr(prhs(8)) + NB = mxGetPr(prhs(9)) + + IC_1 = mxGetPr(prhs(10)) + JC_1 = mxGetPr(prhs(11)) + IC_2 = mxGetPr(prhs(12)) + JC_2 = mxGetPr(prhs(13)) + IC_3 = mxGetPr(prhs(14)) + JC_3 = mxGetPr(prhs(15)) + IC_4 = mxGetPr(prhs(16)) + JC_4 = mxGetPr(prhs(17)) + maxload = mxGetPr(prhs(18)) + + convertind = mxGetPr(prhs(20)) + maxind = mxGetPr(prhs(21)) + +C Get number of states + sA = mxGetM(prhs(6)) + sB = mxGetM(prhs(9)) + +C check compatibility of states + s=max(sA,sB) + if ((sA.ne.s .and. sA.ne.1) .or. (sB.ne.s .and. sB.ne.1)) + + then + call mexErrMsgIdAndTxt ('MATLAB:states', + + 'incompatible states.') + endif + +C sum across rows of C if dosum==1 + do_sum=mxGetScalar(prhs(19)) + + if (do_sum==1) then + sC=1 + else + sC=s + endif + +C Create matrix for NC. + complexflag=0 + plhs(1) = mxCreateDoubleMatrix(sC,JCrows_1,complexflag) + NC = mxGetPr(plhs(1)) + + +C Call the computational routine. + call compute(%VAL(l),%VAL(m), + + %VAL(n), + + %VAL(IA),%VAL(JA),%VAL(NA), + + %VAL(IB),%VAL(JB),%VAL(NB), + + %VAL(IC_1),%VAL(JC_1),%VAL(IC_2),%VAL(JC_2), + + %VAL(IC_3),%VAL(JC_3),%VAL(IC_4),%VAL(JC_4), + + %VAL(maxload),%VAL(NC), + + %VAL(convertind),%VAL(maxind), + + IArows,JArows,IBrows,JBrows, + + ICrows_1,JCrows_1,ICrows_2,JCrows_2, + + ICrows_3,JCrows_3,ICrows_4,JCrows_4, + + sC,sA,sB) + + return + end + +C Computational subroutine + subroutine compute(l,m,n,IA,JA,NA, + + IB,JB,NB, + + IC_1,JC_1,IC_2,JC_2,IC_3,JC_3,IC_4,JC_4, + + maxload, + + NC, + + convertind,maxind, + + IArows,JArows, + + IBrows,JBrows, + + ICrows_1,JCrows_1,ICrows_2,JCrows_2, + + ICrows_3,JCrows_3,ICrows_4,JCrows_4, + + sC,sA,sB) + +C Declarations + implicit none + + mwSize l,m,n,sC,sA,sB,smallm + mwSize IArows,JArows + mwSize IBrows,JBrows + mwSize ICrows_1,ICrows_2,ICrows_3,ICrows_4 + mwSize JCrows_1,JCrows_2,JCrows_3,JCrows_4 + + mwSize s,sC4,sC3,sC2,rows + mwSize maxload,n_vecload,loadi,load_ + + real*8, target :: NA(sA,JArows) + real*8, target :: NB(sB,JBrows) + + real*8 NC(sC,JCrows_1) + + real*8, pointer :: pNA(:,:),pNB(:,:) + mwSize, pointer :: pIA(:),pIB(:),pIC(:) + mwSize, pointer :: pJA(:,:),pJC(:,:) + mwSize, pointer :: pJB(:) + + mwSize, allocatable :: vecload(:) + + real*8, allocatable :: x(:,:,:,:,:) + logical, allocatable :: w(:,:,:,:) + +C three temporary crs vars are needed + real*8, target, allocatable :: tempNC4(:,:) + real*8, target, allocatable :: tempNC3(:,:) + real*8, target, allocatable :: tempNC2(:,:) + + mwSize, target :: IA(IArows) + mwSize, target :: JA(JArows,4) + + mwSize, target :: IB(IBrows) + mwSize, target :: JB(JBrows) + + mwSize, target :: IC_1(ICrows_1) + mwSize, target :: JC_1(JCrows_1,5) + + mwSize, target :: IC_2(ICrows_2) + mwSize, target :: JC_2(JCrows_2,4) + + mwSize, target :: IC_3(ICrows_3) + mwSize, target :: JC_3(JCrows_3,4) + + mwSize, target :: IC_4(ICrows_4) + mwSize, target :: JC_4(JCrows_4,4) + + mwSize i,jp,j,kp,k1,k2,k3,k4,vp,v1,v2,v3,v4 + mwSize is,js,nz + + mwSize mati,k,kpstart,loc,j2,maxind + mwSize convertind(l,m) + + real*8 mat(2,2), fact(2), prod1 + + integer AllocateStatus + +C vecload + s=max(sA,sB) + + n_vecload=(s-1)/maxload+2 + + allocate (vecload(n_vecload),STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory1.') + endif + + vecload(1)=1 + vecload(n_vecload)=s+1 + do i=2,n_vecload-1 + vecload(i)=vecload(i-1)+maxload + end do + +C prepare matrices for factorials and products + + mat(1,1:k)=(/ (mati, mati = n+1, n+k) /) + mat(2,1:k)=(/ (mati, mati = n, n+k-1) /) + do j=2,k-1 + mat(j+1,1:k-j+1)=(/ (mati, mati = n+k-j+1, n+1, -1) /) + end do + fact(1)=1 + do j=2,k + fact(j)=fact(j-1)*j + end do + prod1=product(mat(2,:)) + + smallm=maxind ! here is the memory saving + +C first contraction + sC4=max(sA,sB) + rows=IC_4(ICrows_4)-1 + allocate (w(smallm,smallm,smallm,n), + + x(min(sC4,maxload),smallm,smallm,smallm,n), + + tempNC4(sC4,rows), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory2.') + endif + + w=.false. + nz=1 + + pIA=>IA + pJA=>JA + + pIB=>IB + pJB=>JB + + pIC=>IC_4 + pJC=>JC_4 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + + do jp=pIA(i),pIA(i+1)-1 + k1=convertind(i,pJA(jp,1)) + k2=convertind(i,pJA(jp,2)) + k3=convertind(i,pJA(jp,3)) + j=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k4=pJB(kp) +C initialize x to zero + if (w(k1,k2,k3,k4)==.false.) then + w(k1,k2,k3,k4)=.true. + x(:,k1,k2,k3,k4)=0 + endif + +C Choose among three options: + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + end do + +C assign the result in tempNC4 + do vp=pIC(i),pIC(i+1)-1 + v1=convertind(i,pJC(vp,1)) + v2=convertind(i,pJC(vp,2)) + v3=convertind(i,pJC(vp,3)) + v4=pJC(vp,4) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC4(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + +C second contraction + sC3=max(sC4,sB) + rows=IC_3(ICrows_3)-1 + allocate (w(smallm,smallm,n,n), + + x(min(sC3,maxload),smallm,smallm,n,n), + + tempNC3(sC3,rows), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory2.') + endif + + w=.false. + nz=1 + + pIA=>IC_4 + pJA=>JC_4 + + pIB=>IB + pJB=>JB + + pIC=>IC_3 + pJC=>JC_3 + + sA=sC4 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC4>1) then + pNA=>tempNC4(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC4 + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=convertind(i,pJA(jp,1)) + k2=convertind(i,pJA(jp,2)) + j=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k4)) then + kpstart=pIB(j) + do while (JB(kpstart)sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + endif + end do + +C assign the result in tempNC3 + do vp=pIC(i),pIC(i+1)-1 + v1=convertind(i,pJC(vp,1)) + v2=convertind(i,pJC(vp,2)) + v3=pJC(vp,3) + v4=pJC(vp,4) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC3(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC4) + +C third contraction + sC2=max(sC3,sB) + rows=IC_2(ICrows_2)-1 + allocate (w(smallm,n,n,n), + + x(min(sC2,maxload),smallm,n,n,n), + + tempNC2(sC2,rows), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory3.') + endif + + w=.false. + nz=1 + + pIA=>IC_3 + pJA=>JC_3 + + pIB=>IB + pJB=>JB + + pIC=>IC_2 + pJC=>JC_2 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC3>1) then + pNA=>tempNC3(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC3 + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=convertind(i,pJA(jp,1)) + j=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k3)) then + kpstart=pIB(j) + do while (JB(kpstart)sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + endif + end do + +C assign the result in tempNC2 + do vp=pIC(i),pIC(i+1)-1 + v1=convertind(i,pJC(vp,1)) + v2=pJC(vp,2) + v3=pJC(vp,3) + v4=pJC(vp,4) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC2(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC3) + +C fourth contraction + rows=IC_1(ICrows_1)-1 + allocate (w(n,n,n,n), + + x(min(sC,maxload),n,n,n,n), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory4.') + endif + + w=.false. + nz=1 + + pIA=>IC_2 + pJA=>JC_2 + + pIB=>IB + pJB=>JB + + pIC=>IC_1 + pJC=>JC_1 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC2>1) then + pNA=>tempNC2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC2 + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k2)) then + kpstart=pIB(j) + do while (JB(kpstart)1) then +C Choose among three options and do not sum across rows + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3,k4)=x(1,k1,k2,k3,k4)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3,k4)=x(1,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3,k4)=x(1,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + endif + + end do + endif + end do + +C assign the result in NC + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,2) + v2=pJC(vp,3) + v3=pJC(vp,4) + v4=pJC(vp,5) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x(1,v1,v2,v3,v4) + x(1,v1,v2,v3,v4)=0.0 + endif + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC2) + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU4vecI_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU4vecI_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..bad83e99446e63f9bb0fdff9f5c458a15093e2cd --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU4vecI_mex.F @@ -0,0 +1,706 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [NC,JC_1] = AkronBU4vecI_mex(l,m,n,IA,JA,NA,... +C IB,JB,NB,... +C IC_1,IC_2,IC_3,IC_4,JCrows_1,... +C maxload,dosum) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateDoubleMatrix + mwPointer mxCreateNumericArray + integer*4 mxGetClassID + real*8 mxGetScalar + +C Arguments for mxCreateNumericArray + integer*4 classid + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l,IA,JA + mwPointer m,n + mwPointer IB,JB + mwPointer IC_1,IC_2,IC_3,IC_4 + mwPointer maxload,dosum + mwPointer NA,NB + + mwPointer NC,JC_1 + +C Array information: + mwSize IArows,JArows + mwSize IBrows, JBrows + mwSize ICrows_1,ICrows_2,ICrows_3,ICrows_4 + mwSize JCrows_1 + + mwSize s,sC,sA,sB + real*8 do_sum + + mwSize rows + mwSize JCdims(2),ndim + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 16) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '16 inputs required.') + endif + if(nlhs .gt. 2) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'Max 2 outputs required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(4)) + JArows = mxGetM(prhs(5)) + + IBrows = mxGetM(prhs(7)) + JBrows = mxGetM(prhs(8)) + + ICrows_1 = mxGetM(prhs(10)) + ICrows_2 = mxGetM(prhs(11)) + ICrows_3 = mxGetM(prhs(12)) + ICrows_4 = mxGetM(prhs(13)) + + rows = mxGetScalar(prhs(14)) + +C Create Fortran array from the input arguments. + l = mxGetPr(prhs(1)) + m = mxGetPr(prhs(2)) + n = mxGetPr(prhs(3)) + IA = mxGetPr(prhs(4)) + JA = mxGetPr(prhs(5)) + NA = mxGetPr(prhs(6)) + IB = mxGetPr(prhs(7)) + JB = mxGetPr(prhs(8)) + NB = mxGetPr(prhs(9)) + + IC_1 = mxGetPr(prhs(10)) + IC_2 = mxGetPr(prhs(11)) + IC_3 = mxGetPr(prhs(12)) + IC_4 = mxGetPr(prhs(13)) + JCrows_1 = mxGetPr(prhs(14)) + maxload = mxGetPr(prhs(15)) + +C Get number of states + sA = mxGetM(prhs(6)) + sB = mxGetM(prhs(9)) + +C check compatibility of states + s=max(sA,sB) + if ((sA.ne.s .and. sA.ne.1) .or. (sB.ne.s .and. sB.ne.1)) + + then + call mexErrMsgIdAndTxt ('MATLAB:states', + + 'incompatible states.') + endif + +C sum across rows of C if dosum==1 + do_sum=mxGetScalar(prhs(16)) + + if (do_sum==1) then + sC=1 + else + sC=s + endif + +C Create matrix for NC. + complexflag = 0 + + plhs(1) = mxCreateDoubleMatrix(sC,rows,complexflag) + NC = mxGetPr(plhs(1)) + +C Create matrix for JC_1. + + classid = mxGetClassID(prhs(5)) + + JCdims(1)=rows + JCdims(2)=1 + ndim=2 + plhs(2) = mxCreateNumericArray(ndim, JCdims, + + classid, + + complexflag) + + JC_1 = mxGetPr(plhs(2)) + +C Call the computational routine. + call compute(%VAL(l),%VAL(m), + + %VAL(n), + + %VAL(IA),%VAL(JA),%VAL(NA), + + %VAL(IB),%VAL(JB),%VAL(NB), + + %VAL(IC_1),%VAL(IC_2),%VAL(IC_3),%VAL(IC_4), + + %VAL(JCrows_1),%VAL(maxload), + + %VAL(NC),%VAL(JC_1), + + IArows,JArows,IBrows,JBrows, + + ICrows_1,ICrows_2,ICrows_3,ICrows_4, + + sC,sA,sB) + + return + end + +C Computational subroutine + subroutine compute(l,m,n,IA,JA,NA, + + IB,JB,NB, + + IC_1,IC_2,IC_3,IC_4, + + JCrows_1,maxload, + + NC,JC_1, + + IArows,JArows, + + IBrows,JBrows, + + ICrows_1,ICrows_2,ICrows_3,ICrows_4, + + sC,sA,sB) + +C Declarations + implicit none + + mwSize l,m,n,sC,sA,sB + mwSize IArows,JArows + mwSize IBrows,JBrows + mwSize ICrows_1,ICrows_2,ICrows_3,ICrows_4 + mwSize JCrows_1,JCrows_2,JCrows_3,JCrows_4 + + mwSize s,sC4,sC3,sC2,rows + mwSize maxload,n_vecload,loadi,load_ + + real*8, target :: NA(sA,JArows) + real*8, target :: NB(sB,JBrows) + + real*8 NC(sC,JCrows_1) + + real*8, pointer :: pNA(:,:),pNB(:,:) + mwSize, pointer :: pIA(:),pIB(:),pIC(:) + mwSize, pointer :: pJA(:,:),pJC(:,:) + mwSize, pointer :: pJB(:) + + mwSize, allocatable :: vecload(:) + + real*8, allocatable :: x(:,:,:,:,:) + mwSize, allocatable :: w(:,:,:,:) + +C three temporary crs vars are needed + real*8, target, allocatable :: tempNC4(:,:) + mwSize, target, allocatable :: tempJC4(:,:) + real*8, target, allocatable :: tempNC3(:,:) + mwSize, target, allocatable :: tempJC3(:,:) + real*8, target, allocatable :: tempNC2(:,:) + mwSize, target, allocatable :: tempJC2(:,:) + + mwSize, target, allocatable :: tempJC1(:,:) + + mwSize, target :: IA(IArows) + mwSize, target :: JA(JArows,4) + + mwSize, target :: IB(IBrows) + mwSize, target :: JB(JBrows) + + mwSize, target :: IC_1(ICrows_1) + mwSize, target :: JC_1(JCrows_1,1) + + mwSize, target :: IC_2(ICrows_2) + mwSize, target :: IC_3(ICrows_3) + mwSize, target :: IC_4(ICrows_4) + + mwSize i,jp,j,kp,k1,k2,k3,k4,vp,v1,v2,v3,v4 + mwSize is,js,nz + + mwSize mati,k,kpstart,loc,j2 + parameter (k=4) + real*8 mat(k,k), fact(k), prod1 + + integer AllocateStatus + +C vecload + s=max(sA,sB) + + n_vecload=(s-1)/maxload+2 + + allocate (vecload(n_vecload),STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory1.') + endif + + vecload(1)=1 + vecload(n_vecload)=s+1 + do i=2,n_vecload-1 + vecload(i)=vecload(i-1)+maxload + end do + +C prepare matrices for factorials and products + + mat(1,1:k)=(/ (mati, mati = n+1, n+k) /) + mat(2,1:k)=(/ (mati, mati = n, n+k-1) /) + do j=2,k-1 + mat(j+1,1:k-j+1)=(/ (mati, mati = n+k-j+1, n+1, -1) /) + end do + fact(1)=1 + do j=2,k + fact(j)=fact(j-1)*j + end do + prod1=product(mat(2,:)) + +C first contraction + sC4=max(sA,sB) + rows=IC_4(ICrows_4)-1 + allocate (w(m,m,m,n), + + x(min(sC4,maxload),m,m,m,n), + + tempNC4(sC4,rows), + + tempJC4(rows,4), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory2.') + endif + + w=0 + nz=1 + + pIA=>IA + pJA=>JA + + pIB=>IB + pJB=>JB + + pIC=>IC_4 + pJC=>tempJC4 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + j=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k4=JB(kp) + +C collect information for pJC and initialize x to zero + if (w(k1,k2,k3,k4)sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + end do + +C assign the result in tempNC4 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + v4=pJC(vp,4) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC4(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + +C second contraction + sC3=max(sC4,sB) + rows=IC_3(ICrows_3)-1 + allocate (w(m,m,n,n), + + x(min(sC3,maxload),m,m,n,n), + + tempNC3(sC3,rows), + + tempJC3(rows,4), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory2.') + endif + + w=0 + nz=1 + + pIA=>IC_4 + pJA=>tempJC4 + + pIB=>IB + pJB=>JB + + pIC=>IC_3 + pJC=>tempJC3 + + sA=sC4 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC4>1) then + pNA=>tempNC4(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC4 + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + j=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k4)) then + kpstart=pIB(j) + do while (JB(kpstart)sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + endif + end do + +C assign the result in tempNC3 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + v4=pJC(vp,4) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC3(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC4,tempJC4) + +C third contraction + sC2=max(sC3,sB) + rows=IC_2(ICrows_2)-1 + allocate (w(m,n,n,n), + + x(min(sC2,maxload),m,n,n,n), + + tempNC2(sC2,rows), + + tempJC2(rows,4), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory3.') + endif + + w=0 + nz=1 + + pIA=>IC_3 + pJA=>tempJC3 + + pIB=>IB + pJB=>JB + + pIC=>IC_2 + pJC=>tempJC2 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC3>1) then + pNA=>tempNC3(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC3 + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + j=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k3)) then + kpstart=pIB(j) + do while (JB(kpstart)sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + endif + end do + +C assign the result in tempNC2 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + v4=pJC(vp,4) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC2(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC3,tempJC3) + +C fourth contraction + rows=IC_1(ICrows_1)-1 + allocate (w(n,n,n,n), + + x(min(sC,maxload),n,n,n,n), + + tempJC1(JCrows_1,4), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory4.') + endif + + w=0 + nz=1 + + pIA=>IC_2 + pJA=>tempJC2 + + pIB=>IB + pJB=>JB + + pIC=>IC_1 + pJC=>tempJC1 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC2>1) then + pNA=>tempNC2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC2 + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k2)) then + kpstart=pIB(j) + do while (JB(kpstart)1) then +C Choose among three options and do not sum across rows + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3,k4)=x(1,k1,k2,k3,k4)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3,k4)=x(1,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3,k4)=x(1,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + endif + + end do + endif + end do + +C assign the result in NC + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + v4=pJC(vp,4) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x(1,v1,v2,v3,v4) + x(1,v1,v2,v3,v4)=0.0 + endif + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC2,tempJC2,tempJC1) + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU4vec_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU4vec_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..a2e454685ddab3293973c426ecededdf93d1671a --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/AkronBU4vec_mex.F @@ -0,0 +1,665 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [NC] = AkronBU4vec_mex(l,m,n,IA,JA,NA,... +C IB,JB,NB,... +C IC_1,JC_1,IC_2,JC_2,IC_3,JC_3,IC_4,JC_4,... +C maxload,dosum) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateDoubleMatrix + real*8 mxGetScalar + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l,IA,JA + mwPointer m,n + mwPointer IB,JB + mwPointer IC_1,IC_2,IC_3,IC_4 + mwPointer JC_1,JC_2,JC_3,JC_4 + mwPointer maxload,dosum + mwPointer NA,NB + + mwPointer NC + +C Array information: + mwSize IArows,JArows + mwSize IBrows, JBrows + + mwSize ICrows_1,ICrows_2,ICrows_3,ICrows_4 + mwSize JCrows_1,JCrows_2,JCrows_3,JCrows_4 + + mwSize s,sC,sA,sB + real*8 do_sum + + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 19) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '19 inputs required.') + endif + if(nlhs .gt. 1) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'Max 1 output required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(4)) + JArows = mxGetM(prhs(5)) + + IBrows = mxGetM(prhs(7)) + JBrows = mxGetM(prhs(8)) + + ICrows_1 = mxGetM(prhs(10)) + JCrows_1 = mxGetM(prhs(11)) + + ICrows_2 = mxGetM(prhs(12)) + JCrows_2 = mxGetM(prhs(13)) + + ICrows_3 = mxGetM(prhs(14)) + JCrows_3 = mxGetM(prhs(15)) + + ICrows_4 = mxGetM(prhs(16)) + JCrows_4 = mxGetM(prhs(17)) + + +C Create Fortran array from the input arguments. + l = mxGetPr(prhs(1)) + m = mxGetPr(prhs(2)) + n = mxGetPr(prhs(3)) + IA = mxGetPr(prhs(4)) + JA = mxGetPr(prhs(5)) + NA = mxGetPr(prhs(6)) + IB = mxGetPr(prhs(7)) + JB = mxGetPr(prhs(8)) + NB = mxGetPr(prhs(9)) + + IC_1 = mxGetPr(prhs(10)) + JC_1 = mxGetPr(prhs(11)) + IC_2 = mxGetPr(prhs(12)) + JC_2 = mxGetPr(prhs(13)) + IC_3 = mxGetPr(prhs(14)) + JC_3 = mxGetPr(prhs(15)) + IC_4 = mxGetPr(prhs(16)) + JC_4 = mxGetPr(prhs(17)) + maxload = mxGetPr(prhs(18)) + +C Get number of states + sA = mxGetM(prhs(6)) + sB = mxGetM(prhs(9)) + +C check compatibility of states + s=max(sA,sB) + if ((sA.ne.s .and. sA.ne.1) .or. (sB.ne.s .and. sB.ne.1)) + + then + call mexErrMsgIdAndTxt ('MATLAB:states', + + 'incompatible states.') + endif + +C sum across rows of C if dosum==1 + do_sum=mxGetScalar(prhs(19)) + + if (do_sum==1) then + sC=1 + else + sC=s + endif + +C Create matrix for NC. + complexflag=0 + plhs(1) = mxCreateDoubleMatrix(sC,JCrows_1,complexflag) + NC = mxGetPr(plhs(1)) + + +C Call the computational routine. + call compute(%VAL(l),%VAL(m), + + %VAL(n), + + %VAL(IA),%VAL(JA),%VAL(NA), + + %VAL(IB),%VAL(JB),%VAL(NB), + + %VAL(IC_1),%VAL(JC_1),%VAL(IC_2),%VAL(JC_2), + + %VAL(IC_3),%VAL(JC_3),%VAL(IC_4),%VAL(JC_4), + + %VAL(maxload),%VAL(NC), + + IArows,JArows,IBrows,JBrows, + + ICrows_1,JCrows_1,ICrows_2,JCrows_2, + + ICrows_3,JCrows_3,ICrows_4,JCrows_4, + + sC,sA,sB) + + return + end + +C Computational subroutine + subroutine compute(l,m,n,IA,JA,NA, + + IB,JB,NB, + + IC_1,JC_1,IC_2,JC_2,IC_3,JC_3,IC_4,JC_4, + + maxload, + + NC, + + IArows,JArows, + + IBrows,JBrows, + + ICrows_1,JCrows_1,ICrows_2,JCrows_2, + + ICrows_3,JCrows_3,ICrows_4,JCrows_4, + + sC,sA,sB) + +C Declarations + implicit none + + mwSize l,m,n,sC,sA,sB + mwSize IArows,JArows + mwSize IBrows,JBrows + mwSize ICrows_1,ICrows_2,ICrows_3,ICrows_4 + mwSize JCrows_1,JCrows_2,JCrows_3,JCrows_4 + + mwSize s,sC4,sC3,sC2,rows + mwSize maxload,n_vecload,loadi,load_ + + real*8, target :: NA(sA,JArows) + real*8, target :: NB(sB,JBrows) + + real*8 NC(sC,JCrows_1) + + real*8, pointer :: pNA(:,:),pNB(:,:) + mwSize, pointer :: pIA(:),pIB(:),pIC(:) + mwSize, pointer :: pJA(:,:),pJC(:,:) + mwSize, pointer :: pJB(:) + + mwSize, allocatable :: vecload(:) + + real*8, allocatable :: x(:,:,:,:,:) + logical, allocatable :: w(:,:,:,:) + +C three temporary crs vars are needed + real*8, target, allocatable :: tempNC4(:,:) + real*8, target, allocatable :: tempNC3(:,:) + real*8, target, allocatable :: tempNC2(:,:) + + mwSize, target :: IA(IArows) + mwSize, target :: JA(JArows,4) + + mwSize, target :: IB(IBrows) + mwSize, target :: JB(JBrows) + + mwSize, target :: IC_1(ICrows_1) + mwSize, target :: JC_1(JCrows_1,5) + + mwSize, target :: IC_2(ICrows_2) + mwSize, target :: JC_2(JCrows_2,4) + + mwSize, target :: IC_3(ICrows_3) + mwSize, target :: JC_3(JCrows_3,4) + + mwSize, target :: IC_4(ICrows_4) + mwSize, target :: JC_4(JCrows_4,4) + + mwSize i,jp,j,kp,k1,k2,k3,k4,vp,v1,v2,v3,v4 + mwSize is,js,nz + + mwSize mati,k,kpstart,loc,j2 + real*8 mat(2,2), fact(2), prod1 + + integer AllocateStatus + +C vecload + s=max(sA,sB) + + n_vecload=(s-1)/maxload+2 + + allocate (vecload(n_vecload),STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory1.') + endif + + vecload(1)=1 + vecload(n_vecload)=s+1 + do i=2,n_vecload-1 + vecload(i)=vecload(i-1)+maxload + end do + +C prepare matrices for factorials and products + + mat(1,1:k)=(/ (mati, mati = n+1, n+k) /) + mat(2,1:k)=(/ (mati, mati = n, n+k-1) /) + do j=2,k-1 + mat(j+1,1:k-j+1)=(/ (mati, mati = n+k-j+1, n+1, -1) /) + end do + fact(1)=1 + do j=2,k + fact(j)=fact(j-1)*j + end do + prod1=product(mat(2,:)) + +C first contraction + sC4=max(sA,sB) + rows=IC_4(ICrows_4)-1 + allocate (w(m,m,m,n), + + x(min(sC4,maxload),m,m,m,n), + + tempNC4(sC4,rows), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory2.') + endif + + w=.false. + nz=1 + + pIA=>IA + pJA=>JA + + pIB=>IB + pJB=>JB + + pIC=>IC_4 + pJC=>JC_4 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + j=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k4=pJB(kp) +C initialize x to zero + if (w(k1,k2,k3,k4)==.false.) then + w(k1,k2,k3,k4)=.true. + x(:,k1,k2,k3,k4)=0 + endif + +C Choose among three options: + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + end do + +C assign the result in tempNC4 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + v4=pJC(vp,4) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC4(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + +C second contraction + sC3=max(sC4,sB) + rows=IC_3(ICrows_3)-1 + allocate (w(m,m,n,n), + + x(min(sC3,maxload),m,m,n,n), + + tempNC3(sC3,rows), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory2.') + endif + + w=.false. + nz=1 + + pIA=>IC_4 + pJA=>JC_4 + + pIB=>IB + pJB=>JB + + pIC=>IC_3 + pJC=>JC_3 + + sA=sC4 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC4>1) then + pNA=>tempNC4(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC4 + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + j=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k4)) then + kpstart=pIB(j) + do while (JB(kpstart)sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + endif + end do + +C assign the result in tempNC3 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + v4=pJC(vp,4) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC3(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC4) + +C third contraction + sC2=max(sC3,sB) + rows=IC_2(ICrows_2)-1 + allocate (w(m,n,n,n), + + x(min(sC2,maxload),m,n,n,n), + + tempNC2(sC2,rows), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory3.') + endif + + w=.false. + nz=1 + + pIA=>IC_3 + pJA=>JC_3 + + pIB=>IB + pJB=>JB + + pIC=>IC_2 + pJC=>JC_2 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC3>1) then + pNA=>tempNC3(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC3 + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + j=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k3)) then + kpstart=pIB(j) + do while (JB(kpstart)sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + endif + end do + +C assign the result in tempNC2 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + v4=pJC(vp,4) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC2(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC3) + +C fourth contraction + rows=IC_1(ICrows_1)-1 + allocate (w(n,n,n,n), + + x(min(sC,maxload),n,n,n,n), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory4.') + endif + + w=.false. + nz=1 + + pIA=>IC_2 + pJA=>JC_2 + + pIB=>IB + pJB=>JB + + pIC=>IC_1 + pJC=>JC_1 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC2>1) then + pNA=>tempNC2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC2 + endif + + if (sB>1) then + pNB=>NB(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + if ((pIB(j).le.(pIB(j+1)-1)) .and. (JB(pIB(j+1)-1).ge.k2)) then + kpstart=pIB(j) + do while (JB(kpstart)1) then +C Choose among three options and do not sum across rows + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3,k4)=x(1,k1,k2,k3,k4)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3,k4)=x(1,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3,k4)=x(1,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + endif + + end do + endif + end do + +C assign the result in NC + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,2) + v2=pJC(vp,3) + v3=pJC(vp,4) + v4=pJC(vp,5) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x(1,v1,v2,v3,v4) + x(1,v1,v2,v3,v4)=0.0 + endif + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC2) + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/col2ptr_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/col2ptr_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..f569473bee021cebb6d1714d9411602537c29d7e --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/col2ptr_mex.F @@ -0,0 +1,204 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" + +C [ newptr,newcols,newvals ] = col2ptr_mex( ptr,cols,vals,l,coldim,colptr,ptrcoldim ) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + + mwPointer mxGetPr + mwPointer mxCreateDoubleMatrix + mwPointer mxCreateNumericArray + integer*4 mxGetClassID + mwPointer mxGetM, mxGetN + real*8 mxGetScalar + integer*4 mexPrintf + + mwPointer ptr,cols,vals,l,coldim,colptr + mwPointer newcols,newvals + + mwSize ptrM,colsM,colsN,valsM,valsN,coldimM,coldimN + mwSize newptrM,newptrN + mwSize ptrcoldim + +C Arguments for mxCreateNumericArray + integer*4 classid + integer*4 complexflag + mwSize ndim + mwSize dims(2) + mwSize newptr + + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 7) then + call mexErrMsgIdAndTxt ('MATLAB:compress:nInput', + + '7 inputs required.') + endif + if(nlhs .gt. 3) then + call mexErrMsgIdAndTxt ('MATLAB:compress:nOutput', + + '3 outputs required.') + endif + + +C Create Fortran array from the input arguments. + + ptr = mxGetPr(prhs(1)) + cols = mxGetPr(prhs(2)) + vals = mxGetPr(prhs(3)) + l = mxGetPr(prhs(4)) + coldim = mxGetPr(prhs(5)) + colptr = mxGetPr(prhs(6)) + + ptrM = mxGetM(prhs(1)) + + colsM = mxGetM(prhs(2)) + colsN = mxGetN(prhs(2)) + + valsM = mxGetM(prhs(3)) + valsN = mxGetN(prhs(3)) + + coldimM = mxGetM(prhs(5)) + coldimN = mxGetN(prhs(5)) + coldimN = coldimM*coldimN + +C Create matrix for the return arguments. +C 2 dimensional ptr + + ptrcoldim=mxGetScalar(prhs(7)) ! second dimension of newptr + + + newptrM=ptrM-1 + newptrN=ptrcoldim + + classid = mxGetClassID(prhs(1)) + ndim=2 + dims(1)=newptrM + dims(2)=newptrN + complexflag = 0 + + plhs(1) = mxCreateNumericArray(ndim, dims, + + classid, + + complexflag) + + newptr = mxGetPr(plhs(1)) + + classid = mxGetClassID(prhs(2)) + ndim = 2 + dims(1) = colsM + dims(2) = colsN-1 + plhs(2) = mxCreateNumericArray(ndim, dims, + + classid, + + complexflag) + + newcols = mxGetPr(plhs(2)) + + plhs(3) = mxCreateDoubleMatrix(valsM,valsN,complexflag) + + newvals = mxGetPr(plhs(3)) + +C Call the computational routine. + call compute(%VAL(ptr),%VAL(cols),%VAL(vals), + + %VAL(l),%VAL(coldim),%VAL(colptr), + + ptrM,colsM,colsN,valsM,valsN,coldimN, + + %VAL(newptr),%VAL(newcols),%VAL(newvals), + + newptrM,newptrN) + + return + end + + + subroutine compute(ptr,cols,vals,l,coldim,colptr, + + ptrM,colsM,colsN,valsM,valsN,coldimN, + + newptr,newcols,newvals, + + newptrM,newptrN) + implicit none + + mwSize ptrM,colsM,colsN,valsM,valsN,coldimN,newptrM,newptrN + mwSize ptr(ptrM),coldim(coldimN) + + mwSize l,colptr,colptrdim,newcolsind(colsN-1) + mwSize, target :: cols(colsM,colsN) + mwSize, pointer :: pcol(:,:) + + mwSize newptr(newptrM,newptrN),newcols(colsM,colsN-1) + real*8 vals(valsM,valsN),newvals(valsM,valsN) + + mwSize i,n_vals,j,temploc1,temploc2,n_valsi + + mwSize, allocatable :: countcol(:),z(:),loc(:),ind(:),tempptr(:) + + integer AllocateStatus + + colptrdim=coldim(colptr) + n_vals=ptr(ptrM)-1 + newcolsind(1:colptr-1)=(/(i,i=1,colptr-1)/) + newcolsind(colptr:colsN-1)=(/(i,i=colptr+1,colsN)/) + + allocate (countcol(colptrdim),z(colptrdim+1), + + tempptr(colptrdim+1),loc(colptrdim),ind(n_vals), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory.') + endif + do i=1,l + n_valsi=ptr(i+1)-ptr(i) +C count cols + countcol=0 + do j=ptr(i),ptr(i+1)-1 + countcol(cols(j,colptr))=countcol(cols(j,colptr))+1 + end do + +C create ptr for the column dimension + z(1)=1 + z(2:colptrdim+1)=countcol + call cumsum(tempptr,z,colptrdim+1) + +C assign in newptr + newptr(i,:)=tempptr+ptr(i)-1 + +C create sort index + loc=tempptr(1:colptrdim) + do j=1,n_valsi + temploc1=ptr(i)+j-1 + ind(j)=loc(cols(temploc1,colptr)) + loc(cols(temploc1,colptr))=loc(cols(temploc1,colptr))+1 + end do + +C sort + do j=1,n_valsi + temploc1=ptr(i)+ind(j)-1 + temploc2=ptr(i)+j-1 + newvals(:,temploc1)=vals(:,temploc2) + newcols(temploc1,1:colsN-1)=cols(temploc2,newcolsind) + end do + end do + + deallocate(countcol,z, + + tempptr,loc,ind, + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'cannot deallocate.') + endif + + return + end + + subroutine cumsum(cumx, x, n_x) + implicit none + + mwSize i, n_x + mwSize cumx(n_x), x(n_x) + + cumx(1)=x(1) + do i=2,n_x + cumx(i)=cumx(i-1)+x(i) + end do + + return + end diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU2IC_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU2IC_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..2ec1156dee746594a86051e00b09866789b399f2 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU2IC_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU2JC_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU2JC_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..227717a5ed3c7ab1bac885d99ab0f6c2c70e1c7e Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU2JC_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU2vecI_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU2vecI_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..f89ea8573d35221111e6eb9ca416fd31f8b40ef6 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU2vecI_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU2vec_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU2vec_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..0d47cc27c6055bfac108718b2e68b8fe61f1e592 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU2vec_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU3IC_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU3IC_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..caa3ea541d636210146caebf4691e5a7cf534899 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU3IC_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU3JC_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU3JC_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..fd2281bc917c85e473b375e4cefc46087b205c0a Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU3JC_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU3vecI_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU3vecI_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..1a5006c1c36af55db3dad7f1b889d1c9ad5b0059 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU3vecI_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU3vec_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU3vec_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..8c64233caa72860e2f3d045805ec627628749653 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU3vec_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4IC_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4IC_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..b53df15ea4fcd6b14ce3b03290c6b9e82ee04a30 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4IC_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4JC_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4JC_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..38437ca907b8a9cd83f4a7a71b13bc8558160848 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4JC_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4iIC_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4iIC_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..2aafca84bea05d85aef462374e74a5f90934d9cc Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4iIC_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4iJC_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4iJC_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..d64a132ccb8bdfbe3a90dffe644fb329e8d595cb Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4iJC_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4ivecI_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4ivecI_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..16c9dc78f39bda431010cb709264a46d3adf9ce9 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4ivecI_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4ivec_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4ivec_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..3c044855b8eeb9a715dcb7405dd4929996a45e24 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4ivec_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4vecI_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4vecI_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..39b3d788ee0fab49b30e3c965cc9792928a18204 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4vecI_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4vec_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4vec_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..49e58ee512fd63a275fb7775745a5dc3ec892638 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU4vec_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU5iIC_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU5iIC_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..80f509c5ae4ed56786573ad719c41d94de5ee479 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU5iIC_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU5ivecI_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU5ivecI_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..70c43ff5f32a130dd6bd28077cef3fdeec894503 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/AkronBU5ivecI_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/col2ptr_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/col2ptr_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..3d968bcdab0c04c82a72a5d962678aaa4b6827e5 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/col2ptr_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/compress_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/compress_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..20fff6f4c9294148fb5a8e51f6adee3474d94bd9 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/compress_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1IC2D_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1IC2D_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..c2951e3cbeed08471a11f107230600932c1aa58c Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1IC2D_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1IC_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1IC_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..ccecd500e017f0e6fbfb76dee28f47c090b5ce3b Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1IC_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1JC2D_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1JC2D_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..ec5545aac9bc98c81b02a29352b27c989e0870c2 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1JC2D_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1JC_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1JC_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..9e30dd230518e608f76a36d7c2200569c9024db0 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1JC_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1vec2D_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1vec2D_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..f635f0f206a308c04f60d9bbdfab2756a439ed6d Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1vec2D_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1vecI2D_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1vecI2D_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..c036be8a56034f00ef7fdbd7bd81eeb416a83b8f Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1vecI2D_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1vecIW_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1vecIW_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..bfd1c67468ea2632cc1e34454bc5b1f6314e601a Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1vecIW_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1vecI_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1vecI_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..c682649c21358d7ce8f34a1b57b2696ccde30048 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1vecI_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1vecW_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1vecW_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..ae24e735b4b38a95cf131944e9ed17540c8265de Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1vecW_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1vec_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1vec_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..47e162eec925a3f2c6ab5fc1708d437bc0b22563 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction1vec_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction2IC_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction2IC_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..1d52eb3fc28e8ef96f1cdb847cd720cc94b32b10 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction2IC_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction2JC_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction2JC_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..fb46ec336705d98a1cb65dd1c34e0331ef91403f Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction2JC_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction2vecI_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction2vecI_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..bc8537a5423a9f6bde4fc409b158af60cc730fad Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction2vecI_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction2vec_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction2vec_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..22114980945cd124d6574916cf142dd06009d061 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction2vec_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction3IC_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction3IC_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..3b1a42a833d5f21c3b4bcafffbabaef861ef7009 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction3IC_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction3JC_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction3JC_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..9e3ea4c3b27fd459dcc98ddf425220b2177881fa Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction3JC_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction3vecI_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction3vecI_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..5f95c0892c6d2c69cfd605c655b1652ab9d587b7 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction3vecI_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction3vec_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction3vec_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..f19e343cc8954d8dc1e60b26d34567504d561f0b Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction3vec_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction4IC_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction4IC_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..887b233b267c1640ed477bfae41ffcad56bfcf6f Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction4IC_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction4JC_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction4JC_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..b17730a2b7bc16919cb20de3ef6a278e71bb6181 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction4JC_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction4vecI_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction4vecI_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..54be3a726c70d3de47272a9612dfae78fd1cdd9e Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction4vecI_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction4vec_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction4vec_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..4074333763cb87040fd46adbb34c7fd94c0e879a Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/contraction4vec_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/multcol.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/multcol.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..7248ffb777aadc4cbcd61e17894b72a66af97ebe Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/multcol.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/multrow.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/multrow.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..44dbad7643553f5362e62ecc054cf81fe513231b Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/multrow.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/perm_rows.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/perm_rows.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..d6a062eb2f79b09589c5a4135cf90eb6913d7aff Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/perm_rows.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/ptr2col_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/ptr2col_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..00a1eac4e4d746f5170b855acd7456d5aabad42e Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/ptr2col_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/sortcol_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/sortcol_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..8ffa0f3ff0a536aafd52155d015a50ac5e9ed3f1 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/sortcol_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/takerows_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/takerows_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..5c22ffec94e598a74543c8b3544bb3f149ec7f65 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/takerows_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/tplus1_2D_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/tplus1_2D_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..72c956b967e18d83ed79d5711cfd03e65c327755 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/tplus1_2D_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/tplus1_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/tplus1_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..f0bef5b029068a67e9daeeaf13d0f56f2ebe605e Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/tplus1_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/tplus2_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/tplus2_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..13681518e37857623992f2d605cd66b4c5e57ab2 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/tplus2_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/tplus3_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/tplus3_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..cfb1ef565b269ca33cdfcbe0e1c8de084082e75c Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/tplus3_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/tplus4_mex.mexw64 b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/tplus4_mex.mexw64 new file mode 100644 index 0000000000000000000000000000000000000000..176b4fce5618bcd0aa03e5337b9cbf3abef23950 Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/MEX_files/compiled_on_Windows10/tplus4_mex.mexw64 differ diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/compress_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/compress_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..c4d5d641023d3df784748bdc83527e3d3e528e47 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/compress_mex.F @@ -0,0 +1,193 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" + +C [ newvals,ptr,newcols ] = compress( vals,row,cols,rowdim,n_vals ) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + + mwPointer mxGetPr + mwPointer mxCreateDoubleMatrix + mwPointer mxCreateNumericArray + integer*4 mxClassIDFromClassName + mwPointer mxGetM, mxGetN + real*8 mxGetScalar + integer*4 mexPrintf + + mwPointer vals,row,cols + mwPointer rowdim, n_vals + + mwPointer newvals,ptr,newcols + mwSize n_ptr + +C Arguments for mxCreateNumericArray + integer*4 classid + integer*4 complexflag + mwSize ndim + mwSize dims(2) + + mwSize valsM, valsN, colsM, colsN + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 5) then + call mexErrMsgIdAndTxt ('MATLAB:compress:nInput', + + '5 inputs required.') + endif + if(nlhs .gt. 3) then + call mexErrMsgIdAndTxt ('MATLAB:compress:nOutput', + + '3 outputs required.') + endif + + +C Create Fortran array from the input arguments. + vals = mxGetPr(prhs(1)) + row = mxGetPr(prhs(2)) + cols = mxGetPr(prhs(3)) + rowdim = mxGetPr(prhs(4)) + n_vals = mxGetPr(prhs(5)) + + valsM = mxGetM(prhs(1)) + valsN = mxGetN(prhs(1)) + + colsM = mxGetM(prhs(3)) + colsN = mxGetN(prhs(3)) + +C Create matrix for the return arguments. + plhs(1) = mxCreateDoubleMatrix(valsM, valsN, 0) + + n_ptr=mxGetScalar(prhs(4))+1 + + if (sizeof (n_ptr) == 4 ) then + classid = mxClassIDFromClassName('int32') + else if (sizeof (n_ptr) == 8 ) then + classid = mxClassIDFromClassName('int64') + else + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'failed') + end if + + + complexflag = 0 + plhs(2) = mxCreateNumericArray(1, n_ptr, + + classid, + + complexflag) + + ndim = 2 + dims(1) = colsM + dims(2) = colsN + plhs(3) = mxCreateNumericArray(ndim, dims, + + classid, + + complexflag) + + + newvals = mxGetPr(plhs(1)) + ptr = mxGetPr(plhs(2)) + newcols = mxGetPr(plhs(3)) + +C Call the computational routine. + call compute(%VAL(vals),%VAL(row),%VAL(cols), + + %VAL(n_vals),%VAL(rowdim), + + valsM,valsN,colsM,colsN, + + %VAL(newvals),%VAL(ptr),%VAL(newcols)) + + + + return + end + + + subroutine compute(vals,row,cols, n_vals, rowdim, + + valsM,valsN,colsM,colsN, + + newvals,ptr,newcols) + implicit none + + mwSize i, n, size, valsM, valsN, colsM, colsN + mwSize n_vals, rowdim + + real*8 vals(valsM,valsN), newvals(valsM,valsN) + mwSize cols(colsM,colsN), newcols(colsM,colsN) + mwSize row(n_vals), ptr(rowdim+1) + + + + mwSize, allocatable :: countrow(:), z(:), loc(:), ind(:) + + integer AllocateStatus + + allocate (countrow(rowdim),z(rowdim+1), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory.') + endif + + call countdim(countrow, row, n_vals, rowdim) + + + z(1)=1 + z(2:rowdim+1)=countrow + + deallocate(countrow) + + call cumsum(ptr,z,rowdim+1) + + deallocate(z) + allocate (loc(rowdim), ind(n_vals), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory.') + endif + + loc=ptr(1:rowdim) + + do i=1,n_vals + ind(i)=loc(row(i)) + loc(row(i))=loc(row(i))+1 + end do + + do i=1,n_vals + newvals(1:valsM,ind(i))=vals(1:valsM,i) + newcols(ind(i),1:colsN)=cols(i,1:colsN) + end do + + deallocate(loc,ind,STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'cannot deallocate.') + endif + + return + end + + subroutine countdim(countd, d, n_d, dim) + implicit none + + mwSize i, n_d, dim + mwSize countd(dim), d(n_d) + + countd=0 + do i=1,n_d + countd(d(i))=countd(d(i))+1 + end do + + return + end + + subroutine cumsum(cumx, x, n_x) + implicit none + + mwSize i, n_x + mwSize cumx(n_x), x(n_x) + + cumx(1)=x(1) + do i=2,n_x + cumx(i)=cumx(i-1)+x(i) + end do + + return + end diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction1IC2D_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction1IC2D_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..8fdc20abe8f3fa24e8528d0865d53dcdf48c9535 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction1IC2D_mex.F @@ -0,0 +1,148 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [IC_1] = contraction1IC2D_mex(l,n1,IA,JA,IB1,JB1) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateNumericArray + integer*4 mxGetClassID + +C Arguments for mxCreateNumericArray + integer*4 classid + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l,n1,IA,JA,IB1,JB1 + mwPointer IC_1 + +C Array information: + mwSize IArows,JArows + mwSize IB1rows,IB1cols,JB1rows,ndim,dims(2) + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 6) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '6 inputs required.') + endif + if(nlhs .gt. 1) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + '1 output required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(3)) + JArows = mxGetM(prhs(4)) + + IB1rows = mxGetM(prhs(5)) + IB1cols = mxGetN(prhs(5)) + JB1rows = mxGetM(prhs(6)) + +C Create Fortran array from the input arguments. + l = mxGetPr(prhs(1)) + n1 = mxGetPr(prhs(2)) + IA = mxGetPr(prhs(3)) + JA = mxGetPr(prhs(4)) + IB1 = mxGetPr(prhs(5)) + JB1 = mxGetPr(prhs(6)) + +C Create matrix for the return arguments. + + classid = mxGetClassID(prhs(3)) + complexflag = 0 + ndim=2 + dims(1)=IArows-1 + dims(2)=IB1cols + plhs(1) = mxCreateNumericArray(ndim, dims, + + classid, + + complexflag) + + IC_1 = mxGetPr(plhs(1)) + + +C Call the computational routine. + call compute(%VAL(l),%VAL(n1), + + %VAL(IA),%VAL(JA),%VAL(IB1),%VAL(JB1), + + %VAL(IC_1), + + IArows,JArows,IB1rows,IB1cols,JB1rows) + + return + end + +C Computational subroutine + subroutine compute(l,n1,IA,JA,IB1,JB1, + + IC_1, + + IArows,JArows,IB1rows,IB1cols,JB1rows) + +C Declarations + implicit none + + mwSize l,n1 + mwSize IArows,JArows + mwSize IB1rows,IB1cols,JB1rows + + mwSize, pointer :: pIA(:) + mwSize, pointer :: pJA(:) + mwSize, pointer :: pIB(:,:) + + mwSize, allocatable :: w(:) + + mwSize, target :: IA(IArows) + mwSize, target :: JA(JArows) + + mwSize, target :: IB1(IB1rows,IB1cols) + mwSize JB1(JB1rows) + + mwSize, target :: IC_1(IArows-1,IB1cols) + + mwSize i,jp,j,kp,k1,vp,v1,nz,i2 + + integer AllocateStatus + + allocate (w(n1), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory.') + endif + + nz=1 + + pIA=>IA + pJA=>JA + + pIB=>IB1 + + do i=1,l + w=0 + do i2=1,IB1cols-1 + IC_1(i,i2)=nz + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp) + do kp=pIB(j,i2),pIB(j,i2+1)-1 + k1=JB1(kp) + if (w(k1)IA + pJA=>JA + + pIB=>IB1 + + do i=1,l + IC_1(i)=nz + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp) + do kp=pIB(j),pIB(j+1)-1 + k1=JB1(kp) + if (w(k1)IA + pJA=>JA + + pIB=>IB1 + + do i=1,l + w=0 + do i2=1,IB1cols-1 + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp) + do kp=pIB(j,i2),pIB(j,i2+1)-1 + k1=JB1(kp) + if (w(k1)IA + pJA=>JA + + pIB=>IB1 + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp) + do kp=pIB(j),pIB(j+1)-1 + k1=JB1(kp) + if (w(k1)sB .and. sB.ne.1) .or. (sA1) then + allocate (x1(min(sC,maxload),n1), + + STAT = AllocateStatus) + else + allocate (x1(1,n1), + + STAT = AllocateStatus) + endif + + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory.') + endif + + x1=0.0 + +C NC=0.0, mxCreateDoubleMatrix already initializes to zero + + n_vecload=(s-1)/maxload+2 + + allocate (vecload(n_vecload),STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory.') + endif + + vecload(1)=1 + vecload(n_vecload)=s+1 + do i=2,n_vecload-1 + vecload(i)=vecload(i-1)+maxload + end do + + do loadi=1,n_vecload-1 + + load_=vecload(loadi+1)-vecload(loadi) + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + pIA=>IA + pJA=>JA + + pIC=>IC_1 + pJC=>JC_1 + + if (sB>1) then + pNB=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB1 + endif + pIB=>IB1 + + do i=1,l + do i2=1,IB1cols-1 + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp) + do kp=pIB(j,i2),pIB(j,i2+1)-1 + k1=JB1(kp) + if (sC>1) then +C Choose among three options and do not sum across rows: 1. A and B are both vectorized. 2. Only A is vectorized. 3. only B is vectorized. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x1(is,k1)=x1(is,k1)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x1(is,k1)=x1(is,k1)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x1(is,k1)=x1(is,k1)+pNA(1,jp)*pNB(is,kp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x1(1,k1)=x1(1,k1)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x1(1,k1)=x1(1,k1)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x1(1,k1)=x1(1,k1)+pNA(1,jp)*pNB(is,kp) + end do + endif + endif + end do + end do + +C assign the result in NC + do vp=pIC(i,i2),pIC(i,i2+1)-1 + v1=pJC(vp) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x1(is,v1) + x1(is,v1)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x1(1,v1) + x1(1,v1)=0.0 + endif + + end do + end do + end do + end do + deallocate (vecload) + deallocate (x1) + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction1vecI2D_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction1vecI2D_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..8efb3a16faf34311f226930b4ae8770c6004acf6 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction1vecI2D_mex.F @@ -0,0 +1,406 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [NC,JC] = contraction1IC2D_mex(l,n1,IA,JA,NA,IB1,JB1,NB1,IC_1,JCrows_1,maxload,dosum) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxCreateDoubleMatrix + mwPointer mxGetM, mxGetN + mwPointer mxCreateNumericArray + integer*4 mxGetClassID + real*8 mxGetScalar + +C Arguments for mxCreateNumericArray + integer*4 classid + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l,n1,IA,JA,NA,IB1,JB1,NB1 + mwPointer IC_1,JCrows_1 + mwPointer maxload, dosum + + mwPointer NC,JC1_1 + +C Array information: + mwSize IArows,JArows + mwSize IB1rows,IB1cols,JB1rows + mwSize ICrows_1,ICcols_1,rows + + mwSize sC,sA,sB,ndim,dims(2) + real*8 do_sum + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 12) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '12 inputs required.') + endif + if(nlhs .gt. 2) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'max 2 outputs required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(3)) + JArows = mxGetM(prhs(4)) + + IB1rows = mxGetM(prhs(6)) + IB1cols = mxGetN(prhs(6)) + JB1rows = mxGetM(prhs(7)) + + ICrows_1 = mxGetM(prhs(9)) + ICcols_1 = mxGetN(prhs(9)) + rows = mxGetScalar(prhs(10)) + +C Create Fortran array from the input arguments. + l = mxGetPr(prhs(1)) + n1 = mxGetPr(prhs(2)) + IA = mxGetPr(prhs(3)) + JA = mxGetPr(prhs(4)) + NA = mxGetPr(prhs(5)) + IB1 = mxGetPr(prhs(6)) + JB1 = mxGetPr(prhs(7)) + NB1 = mxGetPr(prhs(8)) + IC_1 = mxGetPr(prhs(9)) + JCrows_1 = mxGetPr(prhs(10)) + maxload = mxGetPr(prhs(11)) + dosum = mxGetPr(prhs(12)) + +C Get number of states + sA = mxGetM(prhs(5)) + sB = mxGetM(prhs(8)) + +C sum across rows of C if dosum==1 + do_sum=mxGetScalar(prhs(12)) + + if (do_sum==1) then + sC=1 + else + sC=max(sA,sB) + endif +C Create matrix for NC. + complexflag = 0 + + plhs(1) = mxCreateDoubleMatrix(sC,rows, complexflag) + NC = mxGetPr(plhs(1)) + +C Create matrix for JC1_1. + + classid = mxGetClassID(prhs(4)) + + ndim=1 + plhs(2) = mxCreateNumericArray(ndim, rows, + + classid, + + complexflag) + + JC1_1 = mxGetPr(plhs(2)) + + +C Call the computational routine. + call compute(%VAL(l), %VAL(n1), + + %VAL(IA), %VAL(JA),%VAL(NA), + + %VAL(IB1), %VAL(JB1),%VAL(NB1), + + %VAL(IC_1), %VAL(JCrows_1), + + %VAL(maxload), + + IArows,JArows, + + IB1rows,IB1cols,JB1rows, + + ICrows_1,ICcols_1, + + %VAL(NC),%VAL(JC1_1),sC,sA,sB) + + return + end + +C Computational subroutine + subroutine compute(l,n1, + + IA,JA,NA, + + IB1,JB1,NB1, + + IC_1,JCrows_1, + + maxload, + + IArows,JArows, + + IB1rows,IB1cols,JB1rows, + + ICrows_1,ICcols_1, + + NC,JC_1,sC,sA,sB) + +C Declarations + implicit none + + mwSize l,n1,s,sC,sA,sB,maxload,n_vecload,loadi,load_ + mwSize IArows,JArows,temp + mwSize IB1rows,IB1cols,JB1rows + mwSize ICrows_1,ICcols_1,JCrows_1 + + real*8, target :: NA(sA,JArows) + real*8, target :: NB1(sB,JB1rows) + real*8 NC(sC,JCrows_1) + + real*8, pointer :: pNA(:,:) + mwSize, pointer :: pIA(:) + mwSize, pointer :: pJA(:) + mwSize, pointer :: pIC(:,:) + mwSize, pointer :: pJC(:) + real*8, pointer :: NB(:,:) + mwSize, pointer :: pIB(:,:) + + mwSize, allocatable :: vecload(:) + + real*8, allocatable :: x1(:,:) + mwSize, allocatable :: w(:) + + mwSize, target :: IA(IArows) + mwSize, target :: JA(JArows) + + mwSize, target :: IB1(IB1rows,IB1cols) + mwSize JB1(JB1rows) + + mwSize, target :: IC_1(ICrows_1,ICcols_1) + mwSize, target :: JC_1(JCrows_1) + + mwSize i,jp,j,kp,k1,vp,v1,is,js,nz,i2 + + + mwSize jpstart, jpend + mwSize kpstart, kpend + mwSize vpstart, vpend + + integer AllocateStatus + + s=max(sA,sB) + + if ((sA>sB .and. sB.ne.1) .or. (sA1) then + allocate (x1(min(sC,maxload),n1),w(n1), + + STAT = AllocateStatus) + else + allocate (x1(1,n1),w(n1), + + STAT = AllocateStatus) + endif + + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory.') + endif + + x1=0.0 + w=0 + nz=1 + +C NC=0.0, mxCreateDoubleMatrix already initializes to zero + + n_vecload=(s-1)/maxload+2 + + allocate (vecload(n_vecload),STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory.') + endif + + vecload(1)=1 + vecload(n_vecload)=s+1 + do i=2,n_vecload-1 + vecload(i)=vecload(i-1)+maxload + end do + +C Run first time and calculate JC + do loadi=1,2-1 + + load_=vecload(loadi+1)-vecload(loadi) + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + pIA=>IA + pJA=>JA + + pIC=>IC_1 + pJC=>JC_1 + + if (sB>1) then + NB=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + else + NB=>NB1 + endif + pIB=>IB1 + + do i=1,l + w=0 + do i2=1,IB1cols-1 + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp) + do kp=pIB(j,i2),pIB(j,i2+1)-1 + k1=JB1(kp) +C collect information for JC_1 + if (w(k1)1) then +C Choose among three options and do not sum across rows: 1. A and B are both vectorized. 2. Only A is vectorized. 3. only B is vectorized. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x1(is,k1)=x1(is,k1)+pNA(is,jp)*NB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x1(is,k1)=x1(is,k1)+pNA(is,jp)*NB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x1(is,k1)=x1(is,k1)+pNA(1,jp)*NB(is,kp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x1(1,k1)=x1(1,k1)+pNA(is,jp)*NB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x1(1,k1)=x1(1,k1)+pNA(is,jp)*NB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x1(1,k1)=x1(1,k1)+pNA(1,jp)*NB(is,kp) + end do + endif + endif + end do + end do + +C assign the result in NC + do vp=pIC(i,i2),pIC(i,i2+1)-1 + v1=pJC(vp) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x1(is,v1) + x1(is,v1)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x1(1,v1) + x1(1,v1)=0.0 + endif + + end do + end do + + end do + end do + +C If n_vecload>2 run again but don't calculate JC this time + + do loadi=2,n_vecload-1 + + load_=vecload(loadi+1)-vecload(loadi) + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + pIA=>IA + pJA=>JA + + pIC=>IC_1 + pJC=>JC_1 + + if (sB>1) then + NB=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + else + NB=>NB1 + endif + pIB=>IB1 + + do i=1,l + do i2=1,IB1cols-1 + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp) + do kp=pIB(j,i2),pIB(j,i2+1)-1 + k1=JB1(kp) + if (sC>1) then +C Choose among three options and do not sum across rows: 1. A and B are both vectorized. 2. Only A is vectorized. 3. only B is vectorized. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x1(is,k1)=x1(is,k1)+pNA(is,jp)*NB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x1(is,k1)=x1(is,k1)+pNA(is,jp)*NB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x1(is,k1)=x1(is,k1)+pNA(1,jp)*NB(is,kp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x1(1,k1)=x1(1,k1)+pNA(is,jp)*NB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x1(1,k1)=x1(1,k1)+pNA(is,jp)*NB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x1(1,k1)=x1(1,k1)+pNA(1,jp)*NB(is,kp) + end do + endif + endif + end do + end do + +C assign the result in NC + do vp=pIC(i,i2),pIC(i,i2+1)-1 + v1=pJC(vp) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x1(is,v1) + x1(is,v1)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x1(1,v1) + x1(1,v1)=0.0 + endif + + end do + end do + + end do + end do + + deallocate (vecload) + deallocate (x1,w) + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction1vecIW_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction1vecIW_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..6e8308278fc87de1af5cce3da85de9da31c6d6c3 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction1vecIW_mex.F @@ -0,0 +1,302 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C Gateway subroutine + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + +C Declarations + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxCreateDoubleMatrix + mwPointer mxGetM, mxGetN + mwPointer mxCreateNumericArray + integer*4 mxClassIDFromClassName + integer*4 mxGetClassID + real*8 mxGetScalar + +C Arguments for mxCreateNumericArray + integer*4 classid + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer pr_in1,pr_in2 + mwPointer pr_in3,pr_in4,pr_in5,pr_in6 + mwPointer pr_in7,pr_in8,pr_in9,pr_in10 + mwPointer pr_in11, dosum + + mwPointer NC,JC1_1 + +C Array information: + mwSize IArows,JArows + mwSize IB1rows, JB1rows + mwSize ICrows_1,JCrows_1 + + mwSize sC,sA,sB + real*8 do_sum + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 12) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '12 inputs required.') + endif + if(nlhs .gt. 2) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'max 2 outputs required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(3)) + JArows = mxGetM(prhs(4)) + + IB1rows = mxGetM(prhs(6)) + JB1rows = mxGetM(prhs(7)) + + ICrows_1 = mxGetM(prhs(9)) + JCrows_1 = mxGetScalar(prhs(10)) + + + +C Create Fortran array from the input arguments. + pr_in1 = mxGetPr(prhs(1)) + pr_in2 = mxGetPr(prhs(2)) + pr_in3 = mxGetPr(prhs(3)) + pr_in4 = mxGetPr(prhs(4)) + pr_in5 = mxGetPr(prhs(5)) + pr_in6 = mxGetPr(prhs(6)) + pr_in7 = mxGetPr(prhs(7)) + pr_in8 = mxGetPr(prhs(8)) + pr_in9 = mxGetPr(prhs(9)) + pr_in10 = mxGetPr(prhs(10)) + pr_in11 = mxGetPr(prhs(11)) + +C Get number of states + sA = mxGetM(prhs(5)) + sB = 1 ! B1 is a W matrix + +C sum across rows of C if dosum==1 + do_sum=mxGetScalar(prhs(12)) + + if (do_sum==1) then + sC=1 + else + sC=max(sA,sB) + endif +C Create matrix for NC. + complexflag=0 + plhs(1) = mxCreateDoubleMatrix(sC,JCrows_1, complexflag) + NC = mxGetPr(plhs(1)) + +C Create matrix for JC1_1. + + classid = mxGetClassID(prhs(4)) + + plhs(2) = mxCreateNumericArray(1, JCrows_1, + + classid, + + complexflag) + + JC1_1 = mxGetPr(plhs(2)) + + +C Call the computational routine. + call compute(%VAL(pr_in1), %VAL(pr_in2), + + %VAL(pr_in3), %VAL(pr_in4), + + %VAL(pr_in5), %VAL(pr_in6), + + %VAL(pr_in7), %VAL(pr_in8), + + %VAL(pr_in9),%VAL(pr_in10), + + %VAL(pr_in11), + + IArows,JArows, + + IB1rows,JB1rows, + + ICrows_1,JCrows_1, + + %VAL(NC),%VAL(JC1_1),sC,sA,sB) + + return + end + +C Computational subroutine + subroutine compute(l,n1, + + IA,JA,NA, + + IB1,JB1,NB1, + + IC_1,temp, + + maxload, + + IArows,JArows, + + IB1rows,JB1rows, + + ICrows_1,JCrows_1, + + NC,JC1_1,sC,sA,sB) + +C Declarations + implicit none + + mwSize l,n1,s,sC,sA,sB,maxload,n_vecload,loadi,load_ + mwSize IArows,JArows,temp + mwSize IB1rows,JB1rows + mwSize ICrows_1,JCrows_1 + + real*8, target :: NA(sA,JArows) + real*8, target :: NB1(sB,JB1rows) + real*8 NC(sC,JCrows_1) + + real*8, pointer :: pNA(:,:) + mwSize, pointer :: pIA(:) + mwSize, pointer :: pJA(:) + mwSize, pointer :: IC(:) + mwSize, pointer :: JC1(:) + real*8, pointer :: NB(:,:) + mwSize, pointer :: IB(:) + + mwSize, allocatable :: vecload(:) + + real*8, allocatable :: x1(:,:) + mwSize, allocatable :: w(:) + + mwSize, target :: IA(IArows) + mwSize, target :: JA(JArows) + + mwSize, target :: IB1(IB1rows) + mwSize JB1(JB1rows) + + mwSize, target :: IC_1(ICrows_1) + mwSize, target :: JC1_1(JCrows_1) + + mwSize i,jp,j,kp,k1,vp,v1,is,js,nz + + + mwSize jpstart, jpend + mwSize kpstart, kpend + mwSize vpstart, vpend + + integer AllocateStatus + + s=max(sA,sB) + + if ((sA>sB .and. sB.ne.1) .or. (sA1) then + allocate (x1(maxload,n1),w(n1), + + STAT = AllocateStatus) + else + allocate (x1(1,n1),w(n1), + + STAT = AllocateStatus) + endif + + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory.') + endif + +C x1=0.0 +C w=0 + nz=1 + +C NC=0.0, mxCreateDoubleMatrix already initializes to zero + + n_vecload=(s-1)/maxload+2 + + allocate (vecload(n_vecload),STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory.') + endif + + vecload(1)=1 + vecload(n_vecload)=s+1 + do i=2,n_vecload-1 + vecload(i)=vecload(i-1)+maxload + end do + + do loadi=1,n_vecload-1 + + load_=vecload(loadi+1)-vecload(loadi) + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + pIA=>IA + pJA=>JA + + IC=>IC_1 + JC1=>JC1_1 + + IB=>IB1 + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp) + do kp=IB(j),IB(j+1)-1 + k1=JB1(kp) +C collect information for JC_1 +C if (w(k1)1) then +C Choose among three options and do not sum across rows: 1. A and B are both vectorized. 2. Only A is vectorized. 3. only B is vectorized. + if (sA.ge.sB) then + !DEC$ simd + do is=1,load_ + NC(is,nz)=pNA(is,jp) + end do + else + !DEC$ simd + do is=1,load_ + NC(is,nz)=pNA(1,jp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA.ge.sB) then + !DEC$ simd + do is=1,load_ + NC(1,nz)=NC(1,nz)+pNA(is,jp) + end do + else + !DEC$ simd + do is=1,load_ + NC(1,nz)=NC(1,nz)+pNA(1,jp) + end do + endif + endif + nz=nz+1 + end do + end do + +#if 0 +C assign the result in NC + do vp=IC(i),IC(i+1)-1 + v1=JC1(vp) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x1(is,v1) + x1(is,v1)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x1(1,v1) + x1(1,v1)=0.0 + endif + + end do +#endif + + end do + + end do + deallocate (vecload) + deallocate (x1,w) + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction1vecI_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction1vecI_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..fd98d47bdd73fd2674ff790977b6e2e707811fee --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction1vecI_mex.F @@ -0,0 +1,309 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [NC,JC] = contraction1IC_mex(l,n1,IA,JA,NA,IB1,JB1,NB1,IC_1,JCrows_1,maxload,dosum) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxCreateDoubleMatrix + mwPointer mxGetM, mxGetN + mwPointer mxCreateNumericArray + integer*4 mxGetClassID + real*8 mxGetScalar + +C Arguments for mxCreateNumericArray + integer*4 classid + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l,n1,IA,JA,NA,IB1,JB1,NB1 + mwPointer IC_1,JCrows_1 + mwPointer maxload, dosum + + mwPointer NC,JC1_1 + +C Array information: + mwSize IArows,JArows + mwSize IB1rows, JB1rows + mwSize ICrows_1,rows + + mwSize sC,sA,sB,ndim + real*8 do_sum + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 12) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '12 inputs required.') + endif + if(nlhs .gt. 2) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'max 2 outputs required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(3)) + JArows = mxGetM(prhs(4)) + + IB1rows = mxGetM(prhs(6)) + JB1rows = mxGetM(prhs(7)) + + ICrows_1 = mxGetM(prhs(9)) + rows = mxGetScalar(prhs(10)) + +C Create Fortran array from the input arguments. + l = mxGetPr(prhs(1)) + n1 = mxGetPr(prhs(2)) + IA = mxGetPr(prhs(3)) + JA = mxGetPr(prhs(4)) + NA = mxGetPr(prhs(5)) + IB1 = mxGetPr(prhs(6)) + JB1 = mxGetPr(prhs(7)) + NB1 = mxGetPr(prhs(8)) + IC_1 = mxGetPr(prhs(9)) + JCrows_1 = mxGetPr(prhs(10)) + maxload = mxGetPr(prhs(11)) + dosum = mxGetPr(prhs(12)) + +C Get number of states + sA = mxGetM(prhs(5)) + sB = mxGetM(prhs(8)) + +C sum across rows of C if dosum==1 + do_sum=mxGetScalar(prhs(12)) + + if (do_sum==1) then + sC=1 + else + sC=max(sA,sB) + endif +C Create matrix for NC. + complexflag = 0 + + plhs(1) = mxCreateDoubleMatrix(sC,rows, complexflag) + NC = mxGetPr(plhs(1)) + +C Create matrix for JC1_1. + + classid = mxGetClassID(prhs(4)) + + ndim=1 + plhs(2) = mxCreateNumericArray(ndim, rows, + + classid, + + complexflag) + + JC1_1 = mxGetPr(plhs(2)) + + +C Call the computational routine. + call compute(%VAL(l), %VAL(n1), + + %VAL(IA), %VAL(JA),%VAL(NA), + + %VAL(IB1), %VAL(JB1),%VAL(NB1), + + %VAL(IC_1), %VAL(JCrows_1), + + %VAL(maxload), + + IArows,JArows, + + IB1rows,JB1rows, + + ICrows_1, + + %VAL(NC),%VAL(JC1_1),sC,sA,sB) + + return + end + +C Computational subroutine + subroutine compute(l,n1, + + IA,JA,NA, + + IB1,JB1,NB1, + + IC_1,JCrows_1, + + maxload, + + IArows,JArows, + + IB1rows,JB1rows, + + ICrows_1, + + NC,JC1_1,sC,sA,sB) + +C Declarations + implicit none + + mwSize l,n1,s,sC,sA,sB,maxload,n_vecload,loadi,load_ + mwSize IArows,JArows,temp + mwSize IB1rows,JB1rows + mwSize ICrows_1,JCrows_1 + + real*8, target :: NA(sA,JArows) + real*8, target :: NB1(sB,JB1rows) + real*8 NC(sC,JCrows_1) + + real*8, pointer :: pNA(:,:) + mwSize, pointer :: pIA(:) + mwSize, pointer :: pJA(:) + mwSize, pointer :: IC(:) + mwSize, pointer :: JC1(:) + real*8, pointer :: NB(:,:) + mwSize, pointer :: IB(:) + + mwSize, allocatable :: vecload(:) + + real*8, allocatable :: x1(:,:) + mwSize, allocatable :: w(:) + + mwSize, target :: IA(IArows) + mwSize, target :: JA(JArows) + + mwSize, target :: IB1(IB1rows) + mwSize JB1(JB1rows) + + mwSize, target :: IC_1(ICrows_1) + mwSize, target :: JC1_1(JCrows_1) + + mwSize i,jp,j,kp,k1,vp,v1,is,js,nz + + + mwSize jpstart, jpend + mwSize kpstart, kpend + mwSize vpstart, vpend + + integer AllocateStatus + + s=max(sA,sB) + + if ((sA>sB .and. sB.ne.1) .or. (sA1) then + allocate (x1(min(sC,maxload),n1),w(n1), + + STAT = AllocateStatus) + else + allocate (x1(1,n1),w(n1), + + STAT = AllocateStatus) + endif + + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory.') + endif + + x1=0.0 + w=0 + nz=1 + +C NC=0.0, mxCreateDoubleMatrix already initializes to zero + + n_vecload=(s-1)/maxload+2 + + allocate (vecload(n_vecload),STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory.') + endif + + vecload(1)=1 + vecload(n_vecload)=s+1 + do i=2,n_vecload-1 + vecload(i)=vecload(i-1)+maxload + end do + + do loadi=1,n_vecload-1 + + load_=vecload(loadi+1)-vecload(loadi) + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + pIA=>IA + pJA=>JA + + IC=>IC_1 + JC1=>JC1_1 + + if (sB>1) then + NB=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + else + NB=>NB1 + endif + IB=>IB1 + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp) + do kp=IB(j),IB(j+1)-1 + k1=JB1(kp) +C collect information for JC_1 + if (w(k1)1) then +C Choose among three options and do not sum across rows: 1. A and B are both vectorized. 2. Only A is vectorized. 3. only B is vectorized. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x1(is,k1)=x1(is,k1)+pNA(is,jp)*NB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x1(is,k1)=x1(is,k1)+pNA(is,jp)*NB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x1(is,k1)=x1(is,k1)+pNA(1,jp)*NB(is,kp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x1(1,k1)=x1(1,k1)+pNA(is,jp)*NB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x1(1,k1)=x1(1,k1)+pNA(is,jp)*NB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x1(1,k1)=x1(1,k1)+pNA(1,jp)*NB(is,kp) + end do + endif + endif + end do + end do + +C assign the result in NC + do vp=IC(i),IC(i+1)-1 + v1=JC1(vp) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x1(is,v1) + x1(is,v1)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x1(1,v1) + x1(1,v1)=0.0 + endif + + end do + end do + + end do + deallocate (vecload) + deallocate (x1,w) + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction1vecW_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction1vecW_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..f6ddbc0c58139f39b94a57556faf92b6dcd9c68b --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction1vecW_mex.F @@ -0,0 +1,274 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C Gateway subroutine + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + +C Declarations + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxCreateDoubleMatrix + mwPointer mxGetM, mxGetN + real*8 mxGetScalar + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer pr_in1,pr_in2 + mwPointer pr_in3,pr_in4,pr_in5,pr_in6 + mwPointer pr_in7,pr_in8,pr_in9,pr_in10 + mwPointer pr_in11, dosum + + mwPointer pr_out + +C Array information: + mwSize IArows,JArows + mwSize IB1rows, JB1rows + mwSize ICrows_1,JCrows_1 + + mwSize sC,sA,sB + real*8 do_sum + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 12) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '12 inputs required.') + endif + if(nlhs .gt. 1) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'One output required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(3)) + JArows = mxGetM(prhs(4)) + + IB1rows = mxGetM(prhs(6)) + JB1rows = mxGetM(prhs(7)) + + ICrows_1 = mxGetM(prhs(9)) + JCrows_1 = mxGetM(prhs(10)) + + + +C Create Fortran array from the input arguments. + pr_in1 = mxGetPr(prhs(1)) + pr_in2 = mxGetPr(prhs(2)) + pr_in3 = mxGetPr(prhs(3)) + pr_in4 = mxGetPr(prhs(4)) + pr_in5 = mxGetPr(prhs(5)) + pr_in6 = mxGetPr(prhs(6)) + pr_in7 = mxGetPr(prhs(7)) + pr_in8 = mxGetPr(prhs(8)) + pr_in9 = mxGetPr(prhs(9)) + pr_in10 = mxGetPr(prhs(10)) + pr_in11 = mxGetPr(prhs(11)) + +C Get number of states + sA = mxGetM(prhs(5)) + sB = 1 ! B1 is a W matrix + +C sum across rows of C if dosum==1 + do_sum=mxGetScalar(prhs(12)) + + if (do_sum==1) then + sC=1 + else + sC=max(sA,sB) + endif +C Create matrix for the return argument. + complexflag = 0 + plhs(1) = mxCreateDoubleMatrix(sC,JCrows_1, complexflag) + pr_out = mxGetPr(plhs(1)) + +C Call the computational routine. + call compute(%VAL(pr_in1), %VAL(pr_in2), + + %VAL(pr_in3), %VAL(pr_in4), + + %VAL(pr_in5), %VAL(pr_in6), + + %VAL(pr_in7), %VAL(pr_in8), + + %VAL(pr_in9), %VAL(pr_in10), + + %VAL(pr_in11), + + IArows,JArows, + + IB1rows,JB1rows, + + ICrows_1,JCrows_1, + + %VAL(pr_out),sC,sA,sB) + + return + end + +C Computational subroutine + subroutine compute(l,n1, + + IA,JA,NA, + + IB1,JB1,NB1, + + IC_1,JC1_1, + + maxload, + + IArows,JArows, + + IB1rows,JB1rows, + + ICrows_1,JCrows_1, + + NC,sC,sA,sB) + +C Declarations + implicit none + + mwSize l,n1,s,sC,sA,sB,maxload,n_vecload,loadi,load_ + mwSize IArows,JArows + mwSize IB1rows,JB1rows + mwSize ICrows_1,JCrows_1 + + real*8, target :: NA(sA,JArows) + real*8, target :: NB1(sB,JB1rows) + real*8 NC(sC,JCrows_1) + + real*8, pointer :: pNA(:,:) + mwSize, pointer :: pIA(:) + mwSize, pointer :: pJA(:) + mwSize, pointer :: IC(:) + mwSize, pointer :: JC1(:) + real*8, pointer :: NB(:,:) + mwSize, pointer :: IB(:) + + mwSize, allocatable :: vecload(:) + + real*8, allocatable :: x1(:,:) + + mwSize, target :: IA(IArows) + mwSize, target :: JA(JArows) + + mwSize, target :: IB1(IB1rows) + mwSize JB1(JB1rows) + + mwSize, target :: IC_1(ICrows_1) + mwSize, target :: JC1_1(JCrows_1) + + mwSize i,jp,j,kp,k1,vp,v1,is,js,nz + + + mwSize jpstart, jpend + mwSize kpstart, kpend + mwSize vpstart, vpend + + integer AllocateStatus + + s=max(sA,sB) + + if ((sA>sB .and. sB.ne.1) .or. (sA1) then + allocate (x1(maxload,n1), + + STAT = AllocateStatus) + else + allocate (x1(1,n1), + + STAT = AllocateStatus) + endif + + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory.') + endif + +C x1=0.0 + +C NC=0.0, mxCreateDoubleMatrix already initializes to zero + + n_vecload=(s-1)/maxload+2 + + allocate (vecload(n_vecload),STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory.') + endif + + vecload(1)=1 + vecload(n_vecload)=s+1 + do i=2,n_vecload-1 + vecload(i)=vecload(i-1)+maxload + end do + + do loadi=1,n_vecload-1 + + load_=vecload(loadi+1)-vecload(loadi) + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + pIA=>IA + pJA=>JA + + IC=>IC_1 + JC1=>JC1_1 + + IB=>IB1 + nz=1 + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp) + do kp=IB(j),IB(j+1)-1 +C k1=JB1(kp) + if (sC>1) then +C Choose among three options and do not sum across rows: 1. A and B are both vectorized. 2. Only A is vectorized. 3. only B is vectorized. + if (sA.ge.sB) then + !DEC$ simd + do is=1,load_ + NC(is,nz)=pNA(is,jp) + end do + else + !DEC$ simd + do is=1,load_ + NC(is,nz)=pNA(1,jp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA.ge.sB) then + !DEC$ simd + do is=1,load_ + NC(1,nz)=NC(1,nz)+pNA(is,jp) + end do + else + !DEC$ simd + do is=1,load_ + NC(1,nz)=NC(1,nz)+pNA(1,jp) + end do + endif + endif + nz=nz+1 + end do + end do +#if 0 +C assign the result in NC + do vp=IC(i),IC(i+1)-1 + v1=JC1(vp) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x1(is,v1) + x1(is,v1)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x1(1,v1) + x1(1,v1)=0.0 + endif + + end do +#endif + + end do + end do + deallocate (vecload) + deallocate (x1) + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction1vec_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction1vec_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..1b7152772e496f080f896548302f2a0b1832098e --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction1vec_mex.F @@ -0,0 +1,280 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [NC] = contraction1IC_mex(l,n1,IA,JA,NA,IB1,JB1,NB1,IC_1,JC_1,maxload,dosum) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxCreateDoubleMatrix + mwPointer mxGetM, mxGetN + real*8 mxGetScalar + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l,n1,IA,JA,NA,IB1,JB1,NB1 + mwPointer IC_1,JC_1 + mwPointer maxload, dosum + + mwPointer NC + +C Array information: + mwSize IArows,JArows + mwSize IB1rows, JB1rows + mwSize ICrows_1,JCrows_1 + + mwSize sC,sA,sB + real*8 do_sum + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 12) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '12 inputs required.') + endif + if(nlhs .gt. 1) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'One output required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(3)) + JArows = mxGetM(prhs(4)) + + IB1rows = mxGetM(prhs(6)) + JB1rows = mxGetM(prhs(7)) + + ICrows_1 = mxGetM(prhs(9)) + JCrows_1 = mxGetM(prhs(10)) + +C Create Fortran array from the input arguments. + l = mxGetPr(prhs(1)) + n1 = mxGetPr(prhs(2)) + IA = mxGetPr(prhs(3)) + JA = mxGetPr(prhs(4)) + NA = mxGetPr(prhs(5)) + IB1 = mxGetPr(prhs(6)) + JB1 = mxGetPr(prhs(7)) + NB1 = mxGetPr(prhs(8)) + IC_1 = mxGetPr(prhs(9)) + JC_1 = mxGetPr(prhs(10)) + maxload = mxGetPr(prhs(11)) + +C Get number of states + sA = mxGetM(prhs(5)) + sB = mxGetM(prhs(8)) + +C sum across rows of C if dosum==1 + do_sum=mxGetScalar(prhs(12)) + + if (do_sum==1) then + sC=1 + else + sC=max(sA,sB) + endif +C Create matrix for the return argument. + complexflag=0 + plhs(1) = mxCreateDoubleMatrix(sC,JCrows_1, complexflag) + NC = mxGetPr(plhs(1)) + +C Call the computational routine. + call compute(%VAL(l), %VAL(n1), + + %VAL(IA), %VAL(JA),%VAL(NA), + + %VAL(IB1), %VAL(JB1),%VAL(NB1), + + %VAL(IC_1), %VAL(JC_1), + + %VAL(maxload), + + IArows,JArows, + + IB1rows,JB1rows, + + ICrows_1,JCrows_1, + + %VAL(NC),sC,sA,sB) + + return + end + +C Computational subroutine + subroutine compute(l,n1, + + IA,JA,NA, + + IB1,JB1,NB1, + + IC_1,JC_1, + + maxload, + + IArows,JArows, + + IB1rows,JB1rows, + + ICrows_1,JCrows_1, + + NC,sC,sA,sB) + +C Declarations + implicit none + + mwSize l,n1,s,sC,sA,sB,maxload,n_vecload,loadi,load_ + mwSize IArows,JArows + mwSize IB1rows,JB1rows + mwSize ICrows_1,JCrows_1 + + real*8, target :: NA(sA,JArows) + real*8, target :: NB1(sB,JB1rows) + real*8 NC(sC,JCrows_1) + + real*8, pointer :: pNA(:,:) + mwSize, pointer :: pIA(:) + mwSize, pointer :: pJA(:) + mwSize, pointer :: IC(:) + mwSize, pointer :: JC(:) + real*8, pointer :: NB(:,:) + mwSize, pointer :: IB(:) + + mwSize, allocatable :: vecload(:) + + real*8, allocatable :: x1(:,:) + + mwSize, target :: IA(IArows) + mwSize, target :: JA(JArows) + + mwSize, target :: IB1(IB1rows) + mwSize JB1(JB1rows) + + mwSize, target :: IC_1(ICrows_1) + mwSize, target :: JC_1(JCrows_1) + + mwSize i,jp,j,kp,k1,vp,v1,is,js + + + mwSize jpstart, jpend + mwSize kpstart, kpend + mwSize vpstart, vpend + + integer AllocateStatus + + s=max(sA,sB) + + if ((sA>sB .and. sB.ne.1) .or. (sA1) then + allocate (x1(min(sC,maxload),n1), + + STAT = AllocateStatus) + else + allocate (x1(1,n1), + + STAT = AllocateStatus) + endif + + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory.') + endif + + x1=0.0 + +C NC=0.0, mxCreateDoubleMatrix already initializes to zero + + n_vecload=(s-1)/maxload+2 + + allocate (vecload(n_vecload),STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory.') + endif + + vecload(1)=1 + vecload(n_vecload)=s+1 + do i=2,n_vecload-1 + vecload(i)=vecload(i-1)+maxload + end do + + do loadi=1,n_vecload-1 + + load_=vecload(loadi+1)-vecload(loadi) + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + pIA=>IA + pJA=>JA + + IC=>IC_1 + JC=>JC_1 + + if (sB>1) then + NB=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + else + NB=>NB1 + endif + IB=>IB1 + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp) + do kp=IB(j),IB(j+1)-1 + k1=JB1(kp) + if (sC>1) then +C Choose among three options and do not sum across rows: 1. A and B are both vectorized. 2. Only A is vectorized. 3. only B is vectorized. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x1(is,k1)=x1(is,k1)+pNA(is,jp)*NB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x1(is,k1)=x1(is,k1)+pNA(is,jp)*NB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x1(is,k1)=x1(is,k1)+pNA(1,jp)*NB(is,kp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x1(1,k1)=x1(1,k1)+pNA(is,jp)*NB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x1(1,k1)=x1(1,k1)+pNA(is,jp)*NB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x1(1,k1)=x1(1,k1)+pNA(1,jp)*NB(is,kp) + end do + endif + endif + end do + end do + +C assign the result in NC + do vp=IC(i),IC(i+1)-1 + v1=JC(vp) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x1(is,v1) + x1(is,v1)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x1(1,v1) + x1(1,v1)=0.0 + endif + + end do + end do + end do + deallocate (vecload) + deallocate (x1) + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction2IC_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction2IC_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..ce96d3a90ed5f0a01d72c8544da431f4b89cab02 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction2IC_mex.F @@ -0,0 +1,229 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [IC_1,IC_2] = contraction2IC_mex(l,m1,n1,n2,IA,JA,IB1,JB1,IB2,JB2) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateNumericArray + integer*4 mxGetClassID + +C Arguments for mxCreateNumericArray + integer*4 classid + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l,m1,n1,n2,IA,JA + mwPointer IB1,JB1,IB2,JB2 + mwPointer IC_1,IC_2 + +C Array information: + mwSize IArows,JArows + mwSize IB1rows, JB1rows + mwSize IB2rows, JB2rows,ndim + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 10) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '10 inputs required.') + endif + if(nlhs .gt. 2) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'Max 2 outputs required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(5)) + JArows = mxGetM(prhs(6)) + + IB1rows = mxGetM(prhs(7)) + JB1rows = mxGetM(prhs(8)) + IB2rows = mxGetM(prhs(9)) + JB2rows = mxGetM(prhs(10)) + +C Create Fortran array from the input arguments. + l = mxGetPr(prhs(1)) + m1 = mxGetPr(prhs(2)) + n1 = mxGetPr(prhs(3)) + n2 = mxGetPr(prhs(4)) + IA = mxGetPr(prhs(5)) + JA = mxGetPr(prhs(6)) + IB1 = mxGetPr(prhs(7)) + JB1 = mxGetPr(prhs(8)) + IB2 = mxGetPr(prhs(9)) + JB2 = mxGetPr(prhs(10)) + +C Create matrix for the return arguments. + classid = mxGetClassID(prhs(5)) + ndim=1 + complexflag = 0 + plhs(1) = mxCreateNumericArray(ndim, IArows, + + classid, + + complexflag) + + IC_1 = mxGetPr(plhs(1)) + + plhs(2) = mxCreateNumericArray(ndim, IArows, + + classid, + + complexflag) + + IC_2 = mxGetPr(plhs(2)) + +C Call the computational routine. + call compute(%VAL(l),%VAL(m1),%VAL(n1),%VAL(n2), + + %VAL(IA),%VAL(JA), + + %VAL(IB1),%VAL(JB1),%VAL(IB2),%VAL(JB2), + + %VAL(IC_1),%VAL(IC_2), + + IArows,JArows,IB1rows,JB1rows,IB2rows,JB2rows) + + return + end + +C Computational subroutine + subroutine compute(l,m1,n1,n2,IA,JA, + + IB1,JB1,IB2,JB2, + + IC_1,IC_2, + + IArows,JArows, + + IB1rows,JB1rows,IB2rows,JB2rows) + +C Declarations + implicit none + + mwSize l,m1,n1,n2 + mwSize IArows,JArows + mwSize IB1rows,JB1rows,IB2rows,JB2rows + + mwSize, pointer :: pIA(:) + mwSize, pointer :: pJA(:,:) + mwSize, pointer :: pIB(:) + + mwSize, allocatable :: w(:,:) + + mwSize, target :: IA(IArows) + mwSize, target :: JA(JArows,2) + + mwSize, target :: IB1(IB1rows) + mwSize JB1(JB1rows) + mwSize, target :: IB2(IB2rows) + mwSize JB2(JB2rows) + + + mwSize, target :: IC_1(IArows) + mwSize, target :: IC_2(IArows) + + mwSize, target,allocatable :: JC_2(:,:) + + mwSize i,jp,j,kp,k1,k2,vp,v1,v2,nz + + integer AllocateStatus + +C first contraction + + allocate (w(m1,n2), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory.') + endif + + w=0 + nz=1 + + pIA=>IA + pJA=>JA + + pIB=>IB2 + + do i=1,l + IC_2(i)=nz + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,2) + k1=pJA(jp,1) + do kp=pIB(j),pIB(j+1)-1 + k2=JB2(kp) + if (w(k1,k2)IC_2 + pJA=>JC_2 + + pIB=>IB1 + + do i=1,l + IC_1(i)=nz + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + do kp=pIB(j),pIB(j+1)-1 + k1=JB1(kp) + if (w(k1,k2)IA + pJA=>JA + + pIB=>IB2 + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,2) + k1=pJA(jp,1) + do kp=pIB(j),pIB(j+1)-1 + k2=JB2(kp) + if (w(k1,k2)IC_2 + pJA=>JC_2 + + pIB=>IB1 + + do i=1,l + + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + do kp=pIB(j),pIB(j+1)-1 + k1=JB1(kp) + if (w(k1,k2)IA + pJA=>JA + + pIB=>IB2 + pJB=>JB2 + + pIC=>IC_2 + pJC=>tempJC2 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + + if (sB2>1) then + pNB=>NB2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB2 + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,2) + k1=pJA(jp,1) + do kp=pIB(j),pIB(j+1)-1 + k2=pJB(kp) +C collect information for pJC and initialize x to zero + if (w(k1,k2)sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + end do + +C assign the result in tempNC2 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC2(js,vp)=x(is,v1,v2) + x(is,v1,v2)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + +C second contraction + rows=IC_1(ICrows_1)-1 + allocate (w(n1,n2), + + x(min(sC,maxload),n1,n2), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory4.') + endif + + w=0 + nz=1 + + pIA=>IC_2 + pJA=>tempJC2 + + pIB=>IB1 + pJB=>JB1 + + pIC=>IC_1 + pJC=>JC_1 + + sA=sC2 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC2>1) then + pNA=>tempNC2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC2 + endif + + if (sB1>1) then + pNB=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB1 + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + do kp=pIB(j),pIB(j+1)-1 + k1=pJB(kp) +C collect information for pJC and initialize x to zero + if (w(k1,k2)1) then +C Choose among three options and do not sum across rows + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(1,jp)*pNB(is,kp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2)=x(1,k1,k2)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2)=x(1,k1,k2)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(1,k1,k2)=x(1,k1,k2)+pNA(1,jp)*pNB(is,kp) + end do + endif + endif + + end do + end do + +C assign the result in NC + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x(is,v1,v2) + x(is,v1,v2)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x(1,v1,v2) + x(1,v1,v2)=0.0 + endif + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC2,tempJC2) + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction2vec_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction2vec_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..f47d9d63cb88ddad109ffd6bab1ea5f9d93ee8db --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction2vec_mex.F @@ -0,0 +1,425 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [NC] = contraction2vec_mex(l,m1,n1,n2,IA,JA,NA,... +C IB1,JB1,NB1,IB2,JB2,NB2,... +C IC_1,JC_1,IC_2,JC_2,... +C maxload,dosum) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateDoubleMatrix + integer*4 complexflag + real*8 mxGetScalar + +C Pointers to input/output mxArrays: + mwPointer l,IA,JA + mwPointer m1,n1,n2 + mwPointer IB1,JB1,IB2,JB2 + mwPointer IC_1,IC_2 + mwPointer JC_1,JC_2 + mwPointer maxload,dosum + mwPointer NA,NB1,NB2 + + mwPointer NC + +C Array information: + mwSize IArows,JArows + mwSize IB1rows, JB1rows + mwSize IB2rows, JB2rows + mwSize ICrows_1,ICrows_2 + mwSize JCrows_1,JCrows_2 + + mwSize s,sC,sA,sB1,sB2 + real*8 do_sum + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 19) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '19 inputs required.') + endif + if(nlhs .gt. 1) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'Max 1 outputs required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(5)) + JArows = mxGetM(prhs(6)) + + IB1rows = mxGetM(prhs(8)) + JB1rows = mxGetM(prhs(9)) + IB2rows = mxGetM(prhs(11)) + JB2rows = mxGetM(prhs(12)) + + ICrows_1 = mxGetM(prhs(14)) + JCrows_1 = mxGetM(prhs(15)) + + ICrows_2 = mxGetM(prhs(16)) + JCrows_2 = mxGetM(prhs(17)) + +C Create Fortran array from the input arguments. + l = mxGetPr(prhs(1)) + m1 = mxGetPr(prhs(2)) + n1 = mxGetPr(prhs(3)) + n2 = mxGetPr(prhs(4)) + IA = mxGetPr(prhs(5)) + JA = mxGetPr(prhs(6)) + NA = mxGetPr(prhs(7)) + IB1 = mxGetPr(prhs(8)) + JB1 = mxGetPr(prhs(9)) + NB1 = mxGetPr(prhs(10)) + IB2 = mxGetPr(prhs(11)) + JB2 = mxGetPr(prhs(12)) + NB2 = mxGetPr(prhs(13)) + IC_1 = mxGetPr(prhs(14)) + JC_1 = mxGetPr(prhs(15)) + IC_2 = mxGetPr(prhs(16)) + JC_2 = mxGetPr(prhs(17)) + maxload = mxGetPr(prhs(18)) + +C Get number of states + sA = mxGetM(prhs(7)) + sB1 = mxGetM(prhs(10)) + sB2 = mxGetM(prhs(13)) + +C check compatibility of states + s=max(sA,sB1,sB2) + if ((sA.ne.s .and. sA.ne.1) .or. (sB1.ne.s .and. sB1.ne.1) + + .or. (sB1.ne.sB2)) then + call mexErrMsgIdAndTxt ('MATLAB:states', + + 'incompatible states.') + endif + +C sum across rows of C if dosum==1 + do_sum=mxGetScalar(prhs(19)) + + if (do_sum==1) then + sC=1 + else + sC=s + endif + +C Create matrix for NC. + complexflag = 0 + plhs(1) = mxCreateDoubleMatrix(sC,JCrows_1, complexflag) + NC = mxGetPr(plhs(1)) + +C Call the computational routine. + call compute(%VAL(l),%VAL(m1), + + %VAL(n1),%VAL(n2), + + %VAL(IA),%VAL(JA),%VAL(NA), + + %VAL(IB1),%VAL(JB1),%VAL(NB1), + + %VAL(IB2),%VAL(JB2),%VAL(NB2), + + %VAL(IC_1),%VAL(JC_1),%VAL(IC_2),%VAL(JC_2), + + %VAL(maxload), + + %VAL(NC), + + IArows,JArows,IB1rows,JB1rows,IB2rows,JB2rows, + + ICrows_1,JCrows_1,ICrows_2,JCrows_2, + + sC,sA,sB1,sB2) + + return + end + +C Computational subroutine + subroutine compute(l,m1,n1,n2,IA,JA,NA, + + IB1,JB1,NB1,IB2,JB2,NB2, + + IC_1,JC_1,IC_2,JC_2, + + maxload, + + NC, + + IArows,JArows, + + IB1rows,JB1rows,IB2rows,JB2rows, + + ICrows_1,JCrows_1,ICrows_2,JCrows_2, + + sC,sA,sB1,sB2) + +C Declarations + implicit none + + mwSize l,m1,n1,n2,sC,sA,sB1,sB2 + mwSize IArows,JArows + mwSize IB1rows,JB1rows,IB2rows,JB2rows + mwSize ICrows_1,ICrows_2 + mwSize JCrows_1,JCrows_2 + + mwSize s,sB,sC2,rows + mwSize maxload,n_vecload,loadi,load_ + + real*8, target :: NA(sA,JArows) + real*8, target :: NB1(sB1,JB1rows) + real*8, target :: NB2(sB2,JB2rows) + + real*8 NC(sC,JCrows_1) + + real*8, pointer :: pNA(:,:),pNB(:,:) + mwSize, pointer :: pIA(:),pIB(:),pIC(:) + mwSize, pointer :: pJA(:,:),pJC(:,:) + mwSize, pointer :: pJB(:) + + mwSize, allocatable :: vecload(:) + + real*8, allocatable :: x(:,:,:) + logical, allocatable :: w(:,:) + +C one temporary crs var is needed, 2 + real*8, target, allocatable :: tempNC2(:,:) + + mwSize, target :: IA(IArows) + mwSize, target :: JA(JArows,2) + + mwSize, target :: IB1(IB1rows) + mwSize, target :: JB1(JB1rows) + mwSize, target :: IB2(IB2rows) + mwSize, target :: JB2(JB2rows) + + mwSize, target :: IC_1(ICrows_1) + mwSize, target :: JC_1(JCrows_1,2) + + mwSize, target :: IC_2(ICrows_2) + mwSize, target :: JC_2(JCrows_2,2) + + mwSize i,jp,j,kp,k1,k2,vp,v1,v2 + mwSize is,js,nz + + mwSize jpstart, jpend + mwSize kpstart, kpend + mwSize vpstart, vpend + + integer AllocateStatus + +C vecload + s=max(sA,sB1,sB2) + + n_vecload=(s-1)/maxload+2 + + allocate (vecload(n_vecload),STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory1.') + endif + + vecload(1)=1 + vecload(n_vecload)=s+1 + do i=2,n_vecload-1 + vecload(i)=vecload(i-1)+maxload + end do + + sB=sB1 ! sB1 and sB2 must all be equal + +C first contraction + sC2=max(sA,sB2) + rows=IC_2(ICrows_2)-1 + allocate (w(m1,n2), + + x(min(sC2,maxload),m1,n2), + + tempNC2(sC2,rows), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory2.') + endif + + w=.false. + nz=1 + + pIA=>IA + pJA=>JA + + pIB=>IB2 + pJB=>JB2 + + pIC=>IC_2 + pJC=>JC_2 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + + if (sB2>1) then + pNB=>NB2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB2 + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,2) + k1=pJA(jp,1) + do kp=pIB(j),pIB(j+1)-1 + k2=pJB(kp) +C initialize x to zero + if (w(k1,k2)==.false.) then + w(k1,k2)=.true. + x(:,k1,k2)=0 + endif + +C Choose among three options: + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + end do + +C assign the result in tempNC2 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC2(js,vp)=x(is,v1,v2) + x(is,v1,v2)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + +C second contraction + rows=IC_1(ICrows_1)-1 + allocate (w(n1,n2), + + x(min(sC,maxload),n1,n2), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory4.') + endif + + w=.false. + nz=1 + + pIA=>IC_2 + pJA=>JC_2 + + pIB=>IB1 + pJB=>JB1 + + pIC=>IC_1 + pJC=>JC_1 + + sA=sC2 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC2>1) then + pNA=>tempNC2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC2 + endif + + if (sB1>1) then + pNB=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB1 + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + do kp=pIB(j),pIB(j+1)-1 + k1=pJB(kp) +C initialize x to zero + if (w(k1,k2)==.false.) then + w(k1,k2)=.true. + x(:,k1,k2)=0 + endif + + if (sC>1) then +C Choose among three options and do not sum across rows + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2)=x(is,k1,k2)+pNA(1,jp)*pNB(is,kp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2)=x(1,k1,k2)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2)=x(1,k1,k2)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(1,k1,k2)=x(1,k1,k2)+pNA(1,jp)*pNB(is,kp) + end do + endif + endif + + end do + end do + +C assign the result in NC + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x(is,v1,v2) + x(is,v1,v2)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x(1,v1,v2) + x(1,v1,v2)=0.0 + endif + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC2) + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction3IC_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction3IC_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..80f07167f75a8f467676bbb920b8fb587c3ac8bc --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction3IC_mex.F @@ -0,0 +1,324 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [IC_1,IC_2,IC_3] = contraction3IC_mex(l,m1,m2,n1,n2,n3,IA,JA,IB1,JB1,IB2,JB2,IB3,JB3) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateNumericArray + integer*4 mxGetClassID + +C Arguments for mxCreateNumericArray + integer*4 classid + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l,IA,JA + mwPointer m1,m2,n1,n2,n3 + mwPointer IB1,JB1,IB2,JB2,IB3,JB3 + mwPointer IC_1,IC_2,IC_3 + +C Array information: + mwSize IArows,JArows + mwSize IB1rows, JB1rows + mwSize IB2rows, JB2rows + mwSize IB3rows, JB3rows,ndim + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 14) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '14 inputs required.') + endif + if(nlhs .gt. 3) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'Max 3 outputs required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(7)) + JArows = mxGetM(prhs(8)) + + IB1rows = mxGetM(prhs(9)) + JB1rows = mxGetM(prhs(10)) + IB2rows = mxGetM(prhs(11)) + JB2rows = mxGetM(prhs(12)) + IB3rows = mxGetM(prhs(13)) + JB3rows = mxGetM(prhs(14)) + +C Create Fortran array from the input arguments. + l = mxGetPr(prhs(1)) + m1 = mxGetPr(prhs(2)) + m2 = mxGetPr(prhs(3)) + n1 = mxGetPr(prhs(4)) + n2 = mxGetPr(prhs(5)) + n3 = mxGetPr(prhs(6)) + IA = mxGetPr(prhs(7)) + JA = mxGetPr(prhs(8)) + IB1 = mxGetPr(prhs(9)) + JB1 = mxGetPr(prhs(10)) + IB2 = mxGetPr(prhs(11)) + JB2 = mxGetPr(prhs(12)) + IB3 = mxGetPr(prhs(13)) + JB3 = mxGetPr(prhs(14)) + +C Create matrix for the return arguments. + classid = mxGetClassID(prhs(7)) + + ndim=1 + complexflag = 0 + plhs(1) = mxCreateNumericArray(ndim, IArows, + + classid, + + complexflag) + + IC_1 = mxGetPr(plhs(1)) + + plhs(2) = mxCreateNumericArray(ndim, IArows, + + classid, + + complexflag) + + IC_2 = mxGetPr(plhs(2)) + + plhs(3) = mxCreateNumericArray(ndim, IArows, + + classid, + + complexflag) + + IC_3 = mxGetPr(plhs(3)) + +C Call the computational routine. + call compute(%VAL(l),%VAL(m1),%VAL(m2), + + %VAL(n1),%VAL(n2),%VAL(n3), + + %VAL(IA),%VAL(JA), + + %VAL(IB1),%VAL(JB1),%VAL(IB2),%VAL(JB2), + + %VAL(IB3),%VAL(JB3), + + %VAL(IC_1),%VAL(IC_2),%VAL(IC_3), + + IArows,JArows,IB1rows,JB1rows,IB2rows,JB2rows, + + IB3rows,JB3rows) + + return + end + +C Computational subroutine + subroutine compute(l,m1,m2,n1,n2,n3,IA,JA, + + IB1,JB1,IB2,JB2,IB3,JB3, + + IC_1,IC_2,IC_3, + + IArows,JArows, + + IB1rows,JB1rows,IB2rows,JB2rows, + + IB3rows,JB3rows) + +C Declarations + implicit none + + mwSize l,m1,m2,n1,n2,n3 + mwSize IArows,JArows + mwSize IB1rows,JB1rows,IB2rows,JB2rows + mwSize IB3rows,JB3rows + + mwSize, pointer :: pIA(:) + mwSize, pointer :: pJA(:,:) + mwSize, pointer :: pIB(:) + + mwSize, allocatable :: w(:,:,:) + + mwSize, target :: IA(IArows) + mwSize, target :: JA(JArows,3) + + mwSize, target :: IB1(IB1rows) + mwSize JB1(JB1rows) + mwSize, target :: IB2(IB2rows) + mwSize JB2(JB2rows) + mwSize, target :: IB3(IB3rows) + mwSize JB3(JB3rows) + + mwSize, target :: IC_1(IArows) + mwSize, target :: IC_2(IArows) + mwSize, target :: IC_3(IArows) + + mwSize, target,allocatable :: JC_2(:,:) + mwSize, target,allocatable :: JC_3(:,:) + + mwSize i,jp,j,kp,k1,k2,k3,vp,v1,v2,v3,nz + + integer AllocateStatus + +C first contraction + allocate (w(m1,m2,n3), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory.') + endif + + w=0 + nz=1 + + pIA=>IA + pJA=>JA + + pIB=>IB3 + + do i=1,l + IC_3(i)=nz + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + j=pJA(jp,3) + do kp=pIB(j),pIB(j+1)-1 + k3=JB3(kp) + if (w(k1,k2,k3)IC_3 + pJA=>JC_3 + + pIB=>IB2 + + do i=1,l + IC_2(i)=nz + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + j=pJA(jp,2) + k3=pJA(jp,3) + do kp=pIB(j),pIB(j+1)-1 + k2=JB2(kp) + if (w(k1,k2,k3)IC_2 + pJA=>JC_2 + + pIB=>IB1 + + do i=1,l + IC_1(i)=nz + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + do kp=pIB(j),pIB(j+1)-1 + k1=JB1(kp) + if (w(k1,k2,k3)IA + pJA=>JA + + pIB=>IB3 + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + j=pJA(jp,3) + do kp=pIB(j),pIB(j+1)-1 + k3=JB3(kp) + if (w(k1,k2,k3)IC_3 + pJA=>JC_3 + + pIB=>IB2 + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + j=pJA(jp,2) + k3=pJA(jp,3) + do kp=pIB(j),pIB(j+1)-1 + k2=JB2(kp) + if (w(k1,k2,k3)IC_2 + pJA=>JC_2 + + pIB=>IB1 + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + do kp=pIB(j),pIB(j+1)-1 + k1=JB1(kp) + if (w(k1,k2,k3)IA + pJA=>JA + + pIB=>IB3 + pJB=>JB3 + + pIC=>IC_3 + pJC=>tempJC3 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + + if (sB3>1) then + pNB=>NB3(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB3 + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + j=pJA(jp,3) + do kp=pIB(j),pIB(j+1)-1 + k3=JB3(kp) +C collect information for pJC and initialize x to zero + if (w(k1,k2,k3)sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + end do + +C assign the result in tempNC3 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC3(js,vp)=x(is,v1,v2,v3) + x(is,v1,v2,v3)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + +C second contraction + sC2=max(sC3,sB2) + rows=IC_2(ICrows_2)-1 + allocate (w(m1,n2,n3), + + x(min(sC2,maxload),m1,n2,n3), + + tempNC2(sC2,rows), + + tempJC2(rows,3), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory3.') + endif + + w=0 + nz=1 + + pIA=>IC_3 + pJA=>tempJC3 + + pIB=>IB2 + pJB=>JB2 + + pIC=>IC_2 + pJC=>tempJC2 + + sA=sC3 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC3>1) then + pNA=>tempNC3(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC3 + endif + + if (sB2>1) then + pNB=>NB2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB2 + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + j=pJA(jp,2) + k3=pJA(jp,3) + do kp=pIB(j),pIB(j+1)-1 + k2=JB2(kp) +C collect information for pJC and initializes x to zero + if (w(k1,k2,k3)sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + end do + +C assign the result in tempNC2 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC2(js,vp)=x(is,v1,v2,v3) + x(is,v1,v2,v3)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC3,tempJC3) + +C third contraction + rows=IC_1(ICrows_1)-1 + allocate (w(n1,n2,n3), + + x(min(sC,maxload),n1,n2,n3), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory4.') + endif + + w=0 + nz=1 + + pIA=>IC_2 + pJA=>tempJC2 + + pIB=>IB1 + pJB=>JB1 + + pIC=>IC_1 + pJC=>JC_1 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC2>1) then + pNA=>tempNC2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC2 + endif + + if (sB1>1) then + pNB=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB1 + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + do kp=pIB(j),pIB(j+1)-1 + k1=JB1(kp) +C collect information for pJC and initializes x to zero + if (w(k1,k2,k3)1) then +C Choose among three options and do not sum across rows + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(1,jp)*pNB(is,kp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3)=x(1,k1,k2,k3)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3)=x(1,k1,k2,k3)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3)=x(1,k1,k2,k3)+pNA(1,jp)*pNB(is,kp) + end do + endif + endif + + end do + end do + +C assign the result in NC + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x(is,v1,v2,v3) + x(is,v1,v2,v3)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x(1,v1,v2,v3) + x(1,v1,v2,v3)=0.0 + endif + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC2,tempJC2) + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction3vec_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction3vec_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..c49585445a8db9ddd822dda828b407f070f1839f --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction3vec_mex.F @@ -0,0 +1,551 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [NC] = contraction3vec_mex(l,m1,m2,n1,n2,n3,IA,JA,NA,... +C IB1,JB1,NB1,IB2,JB2,NB2,IB3,JB3,NB3,... +C IC_1,JC_1,IC_2,JC_2,IC_3,JC_3,... +C maxload,dosum) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateDoubleMatrix + mwPointer mxCreateNumericArray + real*8 mxGetScalar + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l,IA,JA + mwPointer m1,m2,n1,n2,n3 + mwPointer IB1,JB1,IB2,JB2,IB3,JB3 + mwPointer IC_1,IC_2,IC_3 + mwPointer JC_1,JC_2,JC_3 + mwPointer maxload,dosum + mwPointer NA,NB1,NB2,NB3 + + mwPointer NC + +C Array information: + mwSize IArows,JArows + mwSize IB1rows, JB1rows + mwSize IB2rows, JB2rows + mwSize IB3rows, JB3rows + mwSize ICrows_1,ICrows_2,ICrows_3 + mwSize JCrows_1,JCrows_2,JCrows_3 + + mwSize s,sC,sA,sB1,sB2,sB3 + real*8 do_sum + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 26) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '26 inputs required.') + endif + if(nlhs .gt. 1) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'Max 1 output required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(7)) + JArows = mxGetM(prhs(8)) + + IB1rows = mxGetM(prhs(10)) + JB1rows = mxGetM(prhs(11)) + IB2rows = mxGetM(prhs(13)) + JB2rows = mxGetM(prhs(14)) + IB3rows = mxGetM(prhs(16)) + JB3rows = mxGetM(prhs(17)) + + ICrows_1 = mxGetM(prhs(19)) + JCrows_1 = mxGetM(prhs(20)) + + ICrows_2 = mxGetM(prhs(21)) + JCrows_2 = mxGetM(prhs(22)) + + ICrows_3 = mxGetM(prhs(23)) + JCrows_3 = mxGetM(prhs(24)) + +C Create Fortran array from the input arguments. + l = mxGetPr(prhs(1)) + m1 = mxGetPr(prhs(2)) + m2 = mxGetPr(prhs(3)) + n1 = mxGetPr(prhs(4)) + n2 = mxGetPr(prhs(5)) + n3 = mxGetPr(prhs(6)) + IA = mxGetPr(prhs(7)) + JA = mxGetPr(prhs(8)) + NA = mxGetPr(prhs(9)) + IB1 = mxGetPr(prhs(10)) + JB1 = mxGetPr(prhs(11)) + NB1 = mxGetPr(prhs(12)) + IB2 = mxGetPr(prhs(13)) + JB2 = mxGetPr(prhs(14)) + NB2 = mxGetPr(prhs(15)) + IB3 = mxGetPr(prhs(16)) + JB3 = mxGetPr(prhs(17)) + NB3 = mxGetPr(prhs(18)) + IC_1 = mxGetPr(prhs(19)) + JC_1 = mxGetPr(prhs(20)) + IC_2 = mxGetPr(prhs(21)) + JC_2 = mxGetPr(prhs(22)) + IC_3 = mxGetPr(prhs(23)) + JC_3 = mxGetPr(prhs(24)) + maxload = mxGetPr(prhs(25)) + +C Get number of states + sA = mxGetM(prhs(9)) + sB1 = mxGetM(prhs(12)) + sB2 = mxGetM(prhs(15)) + sB3 = mxGetM(prhs(18)) + +C check compatibility of states + s=max(sA,sB1,sB2,sB3) + if ((sA.ne.s .and. sA.ne.1) .or. (sB1.ne.s .and. sB1.ne.1) + + .or. (sB1.ne.sB2) .or. (sB1.ne.sB3)) then + call mexErrMsgIdAndTxt ('MATLAB:states', + + 'incompatible states.') + endif + +C sum across rows of C if dosum==1 + do_sum=mxGetScalar(prhs(26)) + + if (do_sum==1) then + sC=1 + else + sC=s + endif + +C Create matrix for NC. + complexflag=0 + plhs(1) = mxCreateDoubleMatrix(sC,JCrows_1, complexflag) + NC = mxGetPr(plhs(1)) + +C Call the computational routine. + call compute(%VAL(l),%VAL(m1),%VAL(m2), + + %VAL(n1),%VAL(n2),%VAL(n3), + + %VAL(IA),%VAL(JA),%VAL(NA), + + %VAL(IB1),%VAL(JB1),%VAL(NB1), + + %VAL(IB2),%VAL(JB2),%VAL(NB2), + + %VAL(IB3),%VAL(JB3),%VAL(NB3), + + %VAL(IC_1),%VAL(JC_1),%VAL(IC_2),%VAL(JC_2), + + %VAL(IC_3),%VAL(JC_3),%VAL(maxload), + + %VAL(NC), + + IArows,JArows,IB1rows,JB1rows,IB2rows,JB2rows, + + IB3rows,JB3rows, + + ICrows_1,JCrows_1,ICrows_2,JCrows_2, + + ICrows_3,JCrows_3, + + sC,sA,sB1,sB2,sB3) + + return + end + +C Computational subroutine + subroutine compute(l,m1,m2,n1,n2,n3,IA,JA,NA, + + IB1,JB1,NB1,IB2,JB2,NB2,IB3,JB3,NB3, + + IC_1,JC_1,IC_2,JC_2,IC_3,JC_3, + + maxload, + + NC, + + IArows,JArows, + + IB1rows,JB1rows,IB2rows,JB2rows, + + IB3rows,JB3rows, + + ICrows_1,JCrows_1,ICrows_2,JCrows_2, + + ICrows_3,JCrows_3, + + sC,sA,sB1,sB2,sB3) + + +C Declarations + implicit none + + mwSize l,m1,m2,n1,n2,n3,sC,sA,sB1,sB2,sB3 + mwSize IArows,JArows + mwSize IB1rows,JB1rows,IB2rows,JB2rows + mwSize IB3rows,JB3rows + mwSize ICrows_1,ICrows_2,ICrows_3 + mwSize JCrows_1,JCrows_2,JCrows_3 + + mwSize s,sB,sC3,sC2,rows + mwSize maxload,n_vecload,loadi,load_ + + real*8, target :: NA(sA,JArows) + real*8, target :: NB1(sB1,JB1rows) + real*8, target :: NB2(sB2,JB2rows) + real*8, target :: NB3(sB3,JB3rows) + + real*8 NC(sC,JCrows_1) + + real*8, pointer :: pNA(:,:),pNB(:,:) + mwSize, pointer :: pIA(:),pIB(:),pIC(:) + mwSize, pointer :: pJA(:,:),pJC(:,:) + mwSize, pointer :: pJB(:) + + mwSize, allocatable :: vecload(:) + + real*8, allocatable :: x(:,:,:,:) + logical, allocatable :: w(:,:,:) + +C two temporary crs vars are needed, 2 and 3 + real*8, target, allocatable :: tempNC3(:,:) + real*8, target, allocatable :: tempNC2(:,:) + + mwSize, target :: IA(IArows) + mwSize, target :: JA(JArows,3) + + mwSize, target :: IB1(IB1rows) + mwSize, target :: JB1(JB1rows) + mwSize, target :: IB2(IB2rows) + mwSize, target :: JB2(JB2rows) + mwSize, target :: IB3(IB3rows) + mwSize, target :: JB3(JB3rows) + + mwSize, target :: IC_1(ICrows_1) + mwSize, target :: JC_1(JCrows_1,3) + + mwSize, target :: IC_2(ICrows_2) + mwSize, target :: JC_2(JCrows_2,3) + + mwSize, target :: IC_3(ICrows_3) + mwSize, target :: JC_3(JCrows_3,3) + + mwSize i,jp,j,kp,k1,k2,k3,vp,v1,v2,v3 + mwSize is,js,nz + + mwSize jpstart, jpend + mwSize kpstart, kpend + mwSize vpstart, vpend + + integer AllocateStatus + +C vecload + s=max(sA,sB1,sB2,sB3) + + n_vecload=(s-1)/maxload+2 + + allocate (vecload(n_vecload),STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory1.') + endif + + vecload(1)=1 + vecload(n_vecload)=s+1 + do i=2,n_vecload-1 + vecload(i)=vecload(i-1)+maxload + end do + + sB=sB1 ! sB1, sB2 and sB3 must all be equal + +C first contraction + sC3=max(sA,sB3) + rows=IC_3(ICrows_3)-1 + allocate (w(m1,m2,n3), + + x(min(sC3,maxload),m1,m2,n3), + + tempNC3(sC3,rows), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory2.') + endif + + w=.false. + nz=1 + + pIA=>IA + pJA=>JA + + pIB=>IB3 + pJB=>JB3 + + pIC=>IC_3 + pJC=>JC_3 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + + if (sB3>1) then + pNB=>NB3(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB3 + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + j=pJA(jp,3) + do kp=pIB(j),pIB(j+1)-1 + k3=JB3(kp) +C initialize x to zero + if (w(k1,k2,k3)==.false.) then + w(k1,k2,k3)=.true. + x(:,k1,k2,k3)=0 + endif + +C Choose among three options: + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + end do + +C assign the result in tempNC3 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC3(js,vp)=x(is,v1,v2,v3) + x(is,v1,v2,v3)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + +C second contraction + sC2=max(sC3,sB2) + rows=IC_2(ICrows_2)-1 + allocate (w(m1,n2,n3), + + x(min(sC2,maxload),m1,n2,n3), + + tempNC2(sC2,rows), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory3.') + endif + + w=.false. + nz=1 + + pIA=>IC_3 + pJA=>JC_3 + + pIB=>IB2 + pJB=>JB2 + + pIC=>IC_2 + pJC=>JC_2 + + sA=sC3 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC3>1) then + pNA=>tempNC3(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC3 + endif + + if (sB2>1) then + pNB=>NB2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB2 + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + j=pJA(jp,2) + k3=pJA(jp,3) + do kp=pIB(j),pIB(j+1)-1 + k2=JB2(kp) +C initialize x to zero + if (w(k1,k2,k3)==.false.) then + w(k1,k2,k3)=.true. + x(:,k1,k2,k3)=0 + endif + +C Choose among three options: + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + end do + +C assign the result in tempNC2 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC2(js,vp)=x(is,v1,v2,v3) + x(is,v1,v2,v3)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC3) + +C third contraction + rows=IC_1(ICrows_1)-1 + allocate (w(n1,n2,n3), + + x(min(sC,maxload),n1,n2,n3), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory4.') + endif + + w=.false. + nz=1 + + pIA=>IC_2 + pJA=>JC_2 + + pIB=>IB1 + pJB=>JB1 + + pIC=>IC_1 + pJC=>JC_1 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC2>1) then + pNA=>tempNC2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC2 + endif + + if (sB1>1) then + pNB=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB1 + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + do kp=pIB(j),pIB(j+1)-1 + k1=JB1(kp) +C initialize x to zero + if (w(k1,k2,k3)==.false.) then + w(k1,k2,k3)=.true. + x(:,k1,k2,k3)=0 + endif + + if (sC>1) then +C Choose among three options and do not sum across rows + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3)=x(is,k1,k2,k3)+pNA(1,jp)*pNB(is,kp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3)=x(1,k1,k2,k3)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3)=x(1,k1,k2,k3)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3)=x(1,k1,k2,k3)+pNA(1,jp)*pNB(is,kp) + end do + endif + endif + + end do + end do + +C assign the result in NC + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x(is,v1,v2,v3) + x(is,v1,v2,v3)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x(1,v1,v2,v3) + x(1,v1,v2,v3)=0.0 + endif + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC2) + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction4IC_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction4IC_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..69b44ac7c51c710e391c70b1e8b6a080923e31c4 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction4IC_mex.F @@ -0,0 +1,414 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [IC_1,IC_2,IC_3,IC_4] = contraction4IC_mex(l,m1,m2,m3,n1,n2,n3,n4,IA,JA,IB1,JB1,IB2,JB2,IB3,JB3,IB4,JB4) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateNumericArray + integer*4 mxGetClassID + +C Arguments for mxCreateNumericArray + integer*4 classid + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l,IA,JA + mwPointer m1,m2,m3,n1,n2,n3,n4 + mwPointer IB1,JB1,IB2,JB2,IB3,JB3,IB4,JB4 + mwPointer IC_1,IC_2,IC_3,IC_4 + +C Array information: + mwSize IArows,JArows + mwSize IB1rows, JB1rows + mwSize IB2rows, JB2rows + mwSize IB3rows, JB3rows + mwSize IB4rows, JB4rows,ndim + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 18) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '18 inputs required.') + endif + if(nlhs .gt. 4) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'Max 4 outputs required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(9)) + JArows = mxGetM(prhs(10)) + + IB1rows = mxGetM(prhs(11)) + JB1rows = mxGetM(prhs(12)) + IB2rows = mxGetM(prhs(13)) + JB2rows = mxGetM(prhs(14)) + IB3rows = mxGetM(prhs(15)) + JB3rows = mxGetM(prhs(16)) + IB4rows = mxGetM(prhs(17)) + JB4rows = mxGetM(prhs(18)) + +C Create Fortran array from the input arguments. + l = mxGetPr(prhs(1)) + m1 = mxGetPr(prhs(2)) + m2 = mxGetPr(prhs(3)) + m3 = mxGetPr(prhs(4)) + n1 = mxGetPr(prhs(5)) + n2 = mxGetPr(prhs(6)) + n3 = mxGetPr(prhs(7)) + n4 = mxGetPr(prhs(8)) + IA = mxGetPr(prhs(9)) + JA = mxGetPr(prhs(10)) + IB1 = mxGetPr(prhs(11)) + JB1 = mxGetPr(prhs(12)) + IB2 = mxGetPr(prhs(13)) + JB2 = mxGetPr(prhs(14)) + IB3 = mxGetPr(prhs(15)) + JB3 = mxGetPr(prhs(16)) + IB4 = mxGetPr(prhs(17)) + JB4 = mxGetPr(prhs(18)) + +C Create matrix for the return arguments. + classid = mxGetClassID(prhs(9)) + ndim=1 + complexflag = 0 + plhs(1) = mxCreateNumericArray(ndim, IArows, + + classid, + + complexflag) + + IC_1 = mxGetPr(plhs(1)) + + plhs(2) = mxCreateNumericArray(ndim, IArows, + + classid, + + complexflag) + + IC_2 = mxGetPr(plhs(2)) + + plhs(3) = mxCreateNumericArray(ndim, IArows, + + classid, + + complexflag) + + IC_3 = mxGetPr(plhs(3)) + + plhs(4) = mxCreateNumericArray(ndim, IArows, + + classid, + + complexflag) + + IC_4 = mxGetPr(plhs(4)) + +C Call the computational routine. + call compute(%VAL(l),%VAL(m1),%VAL(m2),%VAL(m3), + + %VAL(n1),%VAL(n2),%VAL(n3),%VAL(n4), + + %VAL(IA),%VAL(JA), + + %VAL(IB1),%VAL(JB1),%VAL(IB2),%VAL(JB2), + + %VAL(IB3),%VAL(JB3),%VAL(IB4),%VAL(JB4), + + %VAL(IC_1),%VAL(IC_2),%VAL(IC_3),%VAL(IC_4), + + IArows,JArows,IB1rows,JB1rows,IB2rows,JB2rows, + + IB3rows,JB3rows,IB4rows,JB4rows) + + return + end + +C Computational subroutine + subroutine compute(l,m1,m2,m3,n1,n2,n3,n4,IA,JA, + + IB1,JB1,IB2,JB2,IB3,JB3,IB4,JB4, + + IC_1,IC_2,IC_3,IC_4, + + IArows,JArows, + + IB1rows,JB1rows,IB2rows,JB2rows, + + IB3rows,JB3rows,IB4rows,JB4rows) + +C Declarations + implicit none + + mwSize l,m1,m2,m3,n1,n2,n3,n4 + mwSize IArows,JArows + mwSize IB1rows,JB1rows,IB2rows,JB2rows + mwSize IB3rows,JB3rows,IB4rows,JB4rows + + mwSize, pointer :: pIA(:) + mwSize, pointer :: pJA(:,:) + mwSize, pointer :: pIB(:) + + mwSize, allocatable :: w(:,:,:,:) + + mwSize, target :: IA(IArows) + mwSize, target :: JA(JArows,4) + + mwSize, target :: IB1(IB1rows) + mwSize JB1(JB1rows) + mwSize, target :: IB2(IB2rows) + mwSize JB2(JB2rows) + mwSize, target :: IB3(IB3rows) + mwSize JB3(JB3rows) + mwSize, target :: IB4(IB4rows) + mwSize JB4(JB4rows) + + mwSize, target :: IC_1(IArows) + mwSize, target :: IC_2(IArows) + mwSize, target :: IC_3(IArows) + mwSize, target :: IC_4(IArows) + + mwSize, target,allocatable :: JC_2(:,:) + mwSize, target,allocatable :: JC_3(:,:) + mwSize, target,allocatable :: JC_4(:,:) + + mwSize i,jp,j,kp,k1,k2,k3,k4,vp,v1,v2,v3,v4,nz + + integer AllocateStatus + +C first contraction + allocate (w(m1,m2,m3,n4), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory.') + endif + + w=0 + nz=1 + + pIA=>IA + pJA=>JA + + pIB=>IB4 + + do i=1,l + IC_4(i)=nz + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + j=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k4=JB4(kp) + if (w(k1,k2,k3,k4)IC_4 + pJA=>JC_4 + + pIB=>IB3 + + do i=1,l + IC_3(i)=nz + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + j=pJA(jp,3) + k4=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k3=JB3(kp) + if (w(k1,k2,k3,k4)IC_3 + pJA=>JC_3 + + pIB=>IB2 + + do i=1,l + IC_2(i)=nz + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + j=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k2=JB2(kp) + if (w(k1,k2,k3,k4)IC_2 + pJA=>JC_2 + + pIB=>IB1 + + do i=1,l + IC_1(i)=nz + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k1=JB1(kp) + if (w(k1,k2,k3,k4)IA + pJA=>JA + + pIB=>IB4 + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + j=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k4=JB4(kp) + if (w(k1,k2,k3,k4)IC_4 + pJA=>JC_4 + + pIB=>IB3 + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + j=pJA(jp,3) + k4=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k3=JB3(kp) + if (w(k1,k2,k3,k4)IC_3 + pJA=>JC_3 + + pIB=>IB2 + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + j=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k2=JB2(kp) + if (w(k1,k2,k3,k4)IC_2 + pJA=>JC_2 + + pIB=>IB1 + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k1=JB1(kp) + if (w(k1,k2,k3,k4)IA + pJA=>JA + + pIB=>IB4 + pJB=>JB4 + + pIC=>IC_4 + pJC=>tempJC4 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + + if (sB4>1) then + pNB=>NB4(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB4 + endif + + do i=1,l + + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + j=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k4=JB4(kp) + +C collect information for pJC and initialize x to zero + if (w(k1,k2,k3,k4)sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + end do + +C assign the result in tempNC4 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + v4=pJC(vp,4) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC4(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + +C second contraction + sC3=max(sC4,sB3) + rows=IC_3(ICrows_3)-1 + allocate (w(m1,m2,n3,n4), + + x(min(sC3,maxload),m1,m2,n3,n4), + + tempNC3(sC3,rows), + + tempJC3(rows,4), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory2.') + endif + + w=0 + nz=1 + + pIA=>IC_4 + pJA=>tempJC4 + + pIB=>IB3 + pJB=>JB3 + + pIC=>IC_3 + pJC=>tempJC3 + + sA=sC4 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC4>1) then + pNA=>tempNC4(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC4 + endif + + if (sB3>1) then + pNB=>NB3(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB3 + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + j=pJA(jp,3) + k4=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k3=JB3(kp) +C collect information for pJC and initialize x to zero + if (w(k1,k2,k3,k4)sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + end do + +C assign the result in tempNC3 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + v4=pJC(vp,4) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC3(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC4,tempJC4) + +C third contraction + sC2=max(sC3,sB2) + rows=IC_2(ICrows_2)-1 + allocate (w(m1,n2,n3,n4), + + x(min(sC2,maxload),m1,n2,n3,n4), + + tempNC2(sC2,rows), + + tempJC2(rows,4), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory3.') + endif + + w=0 + nz=1 + + pIA=>IC_3 + pJA=>tempJC3 + + pIB=>IB2 + pJB=>JB2 + + pIC=>IC_2 + pJC=>tempJC2 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC3>1) then + pNA=>tempNC3(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC3 + endif + + if (sB2>1) then + pNB=>NB2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB2 + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + j=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k2=JB2(kp) +C collect information for pJC and initializes x to zero + if (w(k1,k2,k3,k4)sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + end do + +C assign the result in tempNC2 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + v4=pJC(vp,4) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC2(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC3,tempJC3) + +C fourth contraction + rows=IC_1(ICrows_1)-1 + allocate (w(n1,n2,n3,n4), + + x(min(sC,maxload),n1,n2,n3,n4), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory4.') + endif + + w=0 + nz=1 + + pIA=>IC_2 + pJA=>tempJC2 + + pIB=>IB1 + pJB=>JB1 + + pIC=>IC_1 + pJC=>JC_1 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC2>1) then + pNA=>tempNC2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC2 + endif + + if (sB1>1) then + pNB=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB1 + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k1=JB1(kp) +C collect information for pJC and initializes x to zero + if (w(k1,k2,k3,k4)1) then +C Choose among three options and do not sum across rows + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3,k4)=x(1,k1,k2,k3,k4)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3,k4)=x(1,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3,k4)=x(1,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + endif + + end do + end do + +C assign the result in NC + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + v4=pJC(vp,4) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x(1,v1,v2,v3,v4) + x(1,v1,v2,v3,v4)=0.0 + endif + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC2,tempJC2) + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction4vec_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction4vec_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..44a67f52a61c45251b5ef4bd1878096c08042ed6 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/contraction4vec_mex.F @@ -0,0 +1,676 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [NC] = contraction4vec_mex(l,m1,m2,m3,n1,n2,n3,n4,IA,JA,NA,... +C IB1,JB1,NB1,IB2,JB2,NB2,IB3,JB3,NB3,IB4,JB4,NB4,... +C IC_1,JC_1,IC_2,JC_2,IC_3,JC_3,IC_4,JC_4,... +C maxload,dosum) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateDoubleMatrix + real*8 mxGetScalar + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l,IA,JA + mwPointer m1,m2,m3,n1,n2,n3,n4 + mwPointer IB1,JB1,IB2,JB2,IB3,JB3,IB4,JB4 + mwPointer IC_1,IC_2,IC_3,IC_4 + mwPointer JC_1,JC_2,JC_3,JC_4 + mwPointer maxload,dosum + mwPointer NA,NB1,NB2,NB3,NB4 + + mwPointer NC + +C Array information: + mwSize IArows,JArows + mwSize IB1rows, JB1rows + mwSize IB2rows, JB2rows + mwSize IB3rows, JB3rows + mwSize IB4rows, JB4rows + mwSize ICrows_1,ICrows_2,ICrows_3,ICrows_4 + mwSize JCrows_1,JCrows_2,JCrows_3,JCrows_4 + + mwSize s,sC,sA,sB1,sB2,sB3,sB4 + real*8 do_sum + + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 33) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '33 inputs required.') + endif + if(nlhs .gt. 1) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'Max 1 output required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(9)) + JArows = mxGetM(prhs(10)) + + IB1rows = mxGetM(prhs(12)) + JB1rows = mxGetM(prhs(13)) + IB2rows = mxGetM(prhs(15)) + JB2rows = mxGetM(prhs(16)) + IB3rows = mxGetM(prhs(18)) + JB3rows = mxGetM(prhs(19)) + IB4rows = mxGetM(prhs(21)) + JB4rows = mxGetM(prhs(22)) + + ICrows_1 = mxGetM(prhs(24)) + JCrows_1 = mxGetM(prhs(25)) + + ICrows_2 = mxGetM(prhs(26)) + JCrows_2 = mxGetM(prhs(27)) + + ICrows_3 = mxGetM(prhs(28)) + JCrows_3 = mxGetM(prhs(29)) + + ICrows_4 = mxGetM(prhs(30)) + JCrows_4 = mxGetM(prhs(31)) + + +C Create Fortran array from the input arguments. + l = mxGetPr(prhs(1)) + m1 = mxGetPr(prhs(2)) + m2 = mxGetPr(prhs(3)) + m3 = mxGetPr(prhs(4)) + n1 = mxGetPr(prhs(5)) + n2 = mxGetPr(prhs(6)) + n3 = mxGetPr(prhs(7)) + n4 = mxGetPr(prhs(8)) + IA = mxGetPr(prhs(9)) + JA = mxGetPr(prhs(10)) + NA = mxGetPr(prhs(11)) + IB1 = mxGetPr(prhs(12)) + JB1 = mxGetPr(prhs(13)) + NB1 = mxGetPr(prhs(14)) + IB2 = mxGetPr(prhs(15)) + JB2 = mxGetPr(prhs(16)) + NB2 = mxGetPr(prhs(17)) + IB3 = mxGetPr(prhs(18)) + JB3 = mxGetPr(prhs(19)) + NB3 = mxGetPr(prhs(20)) + IB4 = mxGetPr(prhs(21)) + JB4 = mxGetPr(prhs(22)) + NB4 = mxGetPr(prhs(23)) + IC_1 = mxGetPr(prhs(24)) + JC_1 = mxGetPr(prhs(25)) + IC_2 = mxGetPr(prhs(26)) + JC_2 = mxGetPr(prhs(27)) + IC_3 = mxGetPr(prhs(28)) + JC_3 = mxGetPr(prhs(29)) + IC_4 = mxGetPr(prhs(30)) + JC_4 = mxGetPr(prhs(31)) + maxload = mxGetPr(prhs(32)) + +C Get number of states + sA = mxGetM(prhs(11)) + sB1 = mxGetM(prhs(14)) + sB2 = mxGetM(prhs(17)) + sB3 = mxGetM(prhs(20)) + sB4 = mxGetM(prhs(23)) + +C check compatibility of states + s=max(sA,sB1,sB2,sB3,sB4) + if ((sA.ne.s .and. sA.ne.1) .or. (sB1.ne.s .and. sB1.ne.1) + + .or. (sB1.ne.sB2) .or. (sB1.ne.sB3) .or. (sB1.ne.sB4)) then + call mexErrMsgIdAndTxt ('MATLAB:states', + + 'incompatible states.') + endif + +C sum across rows of C if dosum==1 + do_sum=mxGetScalar(prhs(33)) + + if (do_sum==1) then + sC=1 + else + sC=s + endif + +C Create matrix for NC. + complexflag=0 + plhs(1) = mxCreateDoubleMatrix(sC,JCrows_1, complexflag) + NC = mxGetPr(plhs(1)) + + +C Call the computational routine. + call compute(%VAL(l),%VAL(m1),%VAL(m2),%VAL(m3), + + %VAL(n1),%VAL(n2),%VAL(n3),%VAL(n4), + + %VAL(IA),%VAL(JA),%VAL(NA), + + %VAL(IB1),%VAL(JB1),%VAL(NB1), + + %VAL(IB2),%VAL(JB2),%VAL(NB2), + + %VAL(IB3),%VAL(JB3),%VAL(NB3), + + %VAL(IB4),%VAL(JB4),%VAL(NB4), + + %VAL(IC_1),%VAL(JC_1),%VAL(IC_2),%VAL(JC_2), + + %VAL(IC_3),%VAL(JC_3),%VAL(IC_4),%VAL(JC_4), + + %VAL(maxload),%VAL(NC), + + IArows,JArows,IB1rows,JB1rows,IB2rows,JB2rows, + + IB3rows,JB3rows,IB4rows,JB4rows, + + ICrows_1,JCrows_1,ICrows_2,JCrows_2, + + ICrows_3,JCrows_3,ICrows_4,JCrows_4, + + sC,sA,sB1,sB2,sB3,sB4) + + return + end + +C Computational subroutine + subroutine compute(l,m1,m2,m3,n1,n2,n3,n4,IA,JA,NA, + + IB1,JB1,NB1,IB2,JB2,NB2,IB3,JB3,NB3,IB4,JB4,NB4, + + IC_1,JC_1,IC_2,JC_2,IC_3,JC_3,IC_4,JC_4, + + maxload, + + NC, + + IArows,JArows, + + IB1rows,JB1rows,IB2rows,JB2rows, + + IB3rows,JB3rows,IB4rows,JB4rows, + + ICrows_1,JCrows_1,ICrows_2,JCrows_2, + + ICrows_3,JCrows_3,ICrows_4,JCrows_4, + + sC,sA,sB1,sB2,sB3,sB4) + +C Declarations + implicit none + + mwSize l,m1,m2,m3,n1,n2,n3,n4,sC,sA,sB1,sB2,sB3,sB4 + mwSize IArows,JArows + mwSize IB1rows,JB1rows,IB2rows,JB2rows + mwSize IB3rows,JB3rows,IB4rows,JB4rows + mwSize ICrows_1,ICrows_2,ICrows_3,ICrows_4 + mwSize JCrows_1,JCrows_2,JCrows_3,JCrows_4 + + mwSize s,sB,sC4,sC3,sC2,rows + mwSize maxload,n_vecload,loadi,load_ + + real*8, target :: NA(sA,JArows) + real*8, target :: NB1(sB1,JB1rows) + real*8, target :: NB2(sB2,JB2rows) + real*8, target :: NB3(sB3,JB3rows) + real*8, target :: NB4(sB4,JB4rows) + + real*8 NC(sC,JCrows_1) + + real*8, pointer :: pNA(:,:),pNB(:,:) + mwSize, pointer :: pIA(:),pIB(:),pIC(:) + mwSize, pointer :: pJA(:,:),pJC(:,:) + mwSize, pointer :: pJB(:) + + mwSize, allocatable :: vecload(:) + + real*8, allocatable :: x(:,:,:,:,:) + logical, allocatable :: w(:,:,:,:) + +C three temporary crs vars are needed + real*8, target, allocatable :: tempNC4(:,:) + real*8, target, allocatable :: tempNC3(:,:) + real*8, target, allocatable :: tempNC2(:,:) + + mwSize, target :: IA(IArows) + mwSize, target :: JA(JArows,4) + + mwSize, target :: IB1(IB1rows) + mwSize, target :: JB1(JB1rows) + mwSize, target :: IB2(IB2rows) + mwSize, target :: JB2(JB2rows) + mwSize, target :: IB3(IB3rows) + mwSize, target :: JB3(JB3rows) + mwSize, target :: IB4(IB4rows) + mwSize, target :: JB4(JB4rows) + + mwSize, target :: IC_1(ICrows_1) + mwSize, target :: JC_1(JCrows_1,4) + + mwSize, target :: IC_2(ICrows_2) + mwSize, target :: JC_2(JCrows_2,4) + + mwSize, target :: IC_3(ICrows_3) + mwSize, target :: JC_3(JCrows_3,4) + + mwSize, target :: IC_4(ICrows_4) + mwSize, target :: JC_4(JCrows_4,4) + + mwSize i,jp,j,kp,k1,k2,k3,k4,vp,v1,v2,v3,v4 + mwSize is,js,nz + + mwSize jpstart, jpend + mwSize kpstart, kpend + mwSize vpstart, vpend + + integer AllocateStatus + +C vecload + s=max(sA,sB1,sB2,sB3,sB4) + + n_vecload=(s-1)/maxload+2 + + allocate (vecload(n_vecload),STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory1.') + endif + + vecload(1)=1 + vecload(n_vecload)=s+1 + do i=2,n_vecload-1 + vecload(i)=vecload(i-1)+maxload + end do + + sB=sB1 ! sB1, sB2, sB3 and sB4 must all be equal + +C first contraction + sC4=max(sA,sB4) + rows=IC_4(ICrows_4)-1 + allocate (w(m1,m2,m3,n4), + + x(min(sC4,maxload),m1,m2,m3,n4), + + tempNC4(sC4,rows), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory2.') + endif + + w=.false. + nz=1 + + pIA=>IA + pJA=>JA + + pIB=>IB4 + pJB=>JB4 + + pIC=>IC_4 + pJC=>JC_4 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sA>1) then + pNA=>NA(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>NA + endif + + if (sB4>1) then + pNB=>NB4(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB4 + endif + + do i=1,l + + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + j=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k4=JB4(kp) +C initialize x to zero + if (w(k1,k2,k3,k4)==.false.) then + w(k1,k2,k3,k4)=.true. + x(:,k1,k2,k3,k4)=0 + endif + +C Choose among three options: + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + end do + +C assign the result in tempNC4 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + v4=pJC(vp,4) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC4(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + +C second contraction + sC3=max(sC4,sB3) + rows=IC_3(ICrows_3)-1 + allocate (w(m1,m2,n3,n4), + + x(min(sC3,maxload),m1,m2,n3,n4), + + tempNC3(sC3,rows), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory2.') + endif + + w=.false. + nz=1 + + pIA=>IC_4 + pJA=>JC_4 + + pIB=>IB3 + pJB=>JB3 + + pIC=>IC_3 + pJC=>JC_3 + + sA=sC4 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC4>1) then + pNA=>tempNC4(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC4 + endif + + if (sB3>1) then + pNB=>NB3(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB3 + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + k2=pJA(jp,2) + j=pJA(jp,3) + k4=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k3=JB3(kp) +C initialize x to zero + if (w(k1,k2,k3,k4)==.false.) then + w(k1,k2,k3,k4)=.true. + x(:,k1,k2,k3,k4)=0 + endif + +C Choose among three options: + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + end do + +C assign the result in tempNC3 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + v4=pJC(vp,4) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC3(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC4) + +C third contraction + sC2=max(sC3,sB2) + rows=IC_2(ICrows_2)-1 + allocate (w(m1,n2,n3,n4), + + x(min(sC2,maxload),m1,n2,n3,n4), + + tempNC2(sC2,rows), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory3.') + endif + + w=.false. + nz=1 + + pIA=>IC_3 + pJA=>JC_3 + + pIB=>IB2 + pJB=>JB2 + + pIC=>IC_2 + pJC=>JC_2 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC3>1) then + pNA=>tempNC3(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC3 + endif + + if (sB2>1) then + pNB=>NB2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB2 + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + k1=pJA(jp,1) + j=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k2=JB2(kp) +C initialize x to zero + if (w(k1,k2,k3,k4)==.false.) then + w(k1,k2,k3,k4)=.true. + x(:,k1,k2,k3,k4)=0 + endif + +C Choose among three options: + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + + end do + end do + +C assign the result in tempNC2 + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + v4=pJC(vp,4) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + tempNC2(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC3) + +C fourth contraction + rows=IC_1(ICrows_1)-1 + allocate (w(n1,n2,n3,n4), + + x(min(sC,maxload),n1,n2,n3,n4), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory4.') + endif + + w=.false. + nz=1 + + pIA=>IC_2 + pJA=>JC_2 + + pIB=>IB1 + pJB=>JB1 + + pIC=>IC_1 + pJC=>JC_1 + + do loadi=1,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (sC2>1) then + pNA=>tempNC2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNA=>tempNC2 + endif + + if (sB1>1) then + pNB=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB=>NB1 + endif + + do i=1,l + do jp=pIA(i),pIA(i+1)-1 + j=pJA(jp,1) + k2=pJA(jp,2) + k3=pJA(jp,3) + k4=pJA(jp,4) + do kp=pIB(j),pIB(j+1)-1 + k1=JB1(kp) +C initialize x to zero + if (w(k1,k2,k3,k4)==.false.) then + w(k1,k2,k3,k4)=.true. + x(:,k1,k2,k3,k4)=0 + endif + + if (sC>1) then +C Choose among three options and do not sum across rows + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(is,k1,k2,k3,k4)=x(is,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + else +C Choose among three options and sum across rows. + if (sA==sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3,k4)=x(1,k1,k2,k3,k4)+pNA(is,jp)*pNB(is,kp) + end do + elseif (sA>sB) then + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3,k4)=x(1,k1,k2,k3,k4)+pNA(is,jp)*pNB(1,kp) + end do + else + !DEC$ simd + do is=1,load_ + x(1,k1,k2,k3,k4)=x(1,k1,k2,k3,k4)+pNA(1,jp)*pNB(is,kp) + end do + endif + endif + + end do + end do + +C assign the result in NC + do vp=pIC(i),pIC(i+1)-1 + v1=pJC(vp,1) + v2=pJC(vp,2) + v3=pJC(vp,3) + v4=pJC(vp,4) + if (sC>1) then + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x(is,v1,v2,v3,v4) + x(is,v1,v2,v3,v4)=0.0 + end do + else + NC(1,vp)=NC(1,vp)+x(1,v1,v2,v3,v4) + x(1,v1,v2,v3,v4)=0.0 + endif + end do + + end do + + end do + + deallocate (w,x) + deallocate (tempNC2) + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/do_mex.m b/105/replication_package/solution_methods/taylor_projection/MEX_files/do_mex.m new file mode 100644 index 0000000000000000000000000000000000000000..cffd6feb448423255ba13286c2649c6f747d0004 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/do_mex.m @@ -0,0 +1,8 @@ +folder_name='compiled_on_Windows10'; + +mkdir(folder_name); + +for file = dir('*.F')' + mex('-largeArrayDims', file.name, '-outdir',folder_name) + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/multcol.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/multcol.F new file mode 100644 index 0000000000000000000000000000000000000000..79751317e19f21028d15b5d0f588e2f6c27ad8be --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/multcol.F @@ -0,0 +1,102 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [A] = multcol(mat,vec) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateDoubleMatrix + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer mat,vec,A + +C Array information: + mwSize matM,matN + mwSize vecM,vecN + + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 2) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '2 inputs required.') + endif + if(nlhs .gt. 1) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'Max 1 output required.') + endif + +C Get the size of the inputs array. + + matM = mxGetM(prhs(1)) + matN = mxGetN(prhs(1)) + + vecM = mxGetM(prhs(2)) + vecN = mxGetN(prhs(2)) + +C Create Fortran array from the input arguments. + mat = mxGetPr(prhs(1)) + vec = mxGetPr(prhs(2)) + +C Create matrix for the return arguments. + complexflag=0 + + plhs(1) = mxCreateDoubleMatrix(matM,matN,complexflag) + A = mxGetPr(plhs(1)) + + +C Call the computational routine. + call compute(%VAL(mat),%VAL(vec),%VAL(A), + + matM,matN,vecM,vecN) + + return + end + +C Computational subroutine + subroutine compute(mat,vec,A, + + matM,matN,vecM,vecN) + +C Declarations + implicit none + + mwSize matM,matN,vecM,vecN,i,j + real*8 mat(matM,matN),A(matM,matN),vec(vecM,vecN) + + if ((vecM>1) .and. (vecN>1)) then + call mexErrMsgIdAndTxt ('MATLAB:multrow', + + 'second argument is not a vector.') + elseif ((vecM>1) .and. (matM.ne.vecM)) then + call mexErrMsgIdAndTxt ('MATLAB:multrow', + + 'incompatible dimensions.') + elseif ((vecN>1) .and. (matM.ne.vecN)) then + call mexErrMsgIdAndTxt ('MATLAB:multrow', + + 'incompatible dimensions.') + endif + + if (vecN==1) then + do j=1,matN + !DEC$ simd + do i=1,matM + A(i,j)=mat(i,j)*vec(i,1) + end do + end do + else + do j=1,matN + !DEC$ simd + do i=1,matM + A(i,j)=mat(i,j)*vec(1,i) + end do + end do + endif + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/multrow.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/multrow.F new file mode 100644 index 0000000000000000000000000000000000000000..4d6084975b7bc108e90b0297e2996c5bedd63201 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/multrow.F @@ -0,0 +1,101 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [A] = multrow(mat,vec) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateDoubleMatrix + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer mat,vec,A + +C Array information: + mwSize matM,matN + mwSize vecM,vecN + + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 2) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '2 inputs required.') + endif + if(nlhs .gt. 1) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'Max 1 output required.') + endif + +C Get the size of the inputs array. + + matM = mxGetM(prhs(1)) + matN = mxGetN(prhs(1)) + + vecM = mxGetM(prhs(2)) + vecN = mxGetN(prhs(2)) + +C Create Fortran array from the input arguments. + mat = mxGetPr(prhs(1)) + vec = mxGetPr(prhs(2)) + +C Create matrix for the return arguments. + complexflag=0 + plhs(1) = mxCreateDoubleMatrix(matM,matN,complexflag) + A = mxGetPr(plhs(1)) + + +C Call the computational routine. + call compute(%VAL(mat),%VAL(vec),%VAL(A), + + matM,matN,vecM,vecN) + + return + end + +C Computational subroutine + subroutine compute(mat,vec,A, + + matM,matN,vecM,vecN) + +C Declarations + implicit none + + mwSize matM,matN,vecM,vecN,i,j + real*8 mat(matM,matN),A(matM,matN),vec(vecM,vecN) + + if ((vecM>1) .and. (vecN>1)) then + call mexErrMsgIdAndTxt ('MATLAB:multrow', + + 'second argument is not a vector.') + elseif ((vecM>1) .and. (matN.ne.vecM)) then + call mexErrMsgIdAndTxt ('MATLAB:multrow', + + 'incompatible dimensions.') + elseif ((vecN>1) .and. (matN.ne.vecN)) then + call mexErrMsgIdAndTxt ('MATLAB:multrow', + + 'incompatible dimensions.') + endif + + if (vecN==1) then + do j=1,matN + !DEC$ simd + do i=1,matM + A(i,j)=mat(i,j)*vec(j,1) + end do + end do + else + do j=1,matN + !DEC$ simd + do i=1,matM + A(i,j)=mat(i,j)*vec(1,j) + end do + end do + endif + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/perm_rows.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/perm_rows.F new file mode 100644 index 0000000000000000000000000000000000000000..d4782bd1aa6abfa0d82ec385ca655e59154628b2 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/perm_rows.F @@ -0,0 +1,172 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [IC,JC,NC] = perm_rows(IA,JA,NA,l,perml) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateDoubleMatrix + mwPointer mxCreateNumericArray + integer*4 mxGetClassID + real*8 mxGetScalar + +C Arguments for mxCreateNumericArray + integer*4 classid + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l,perml,IA,JA,NA + mwPointer IC,JC,NC + +C Array information: + mwSize IArows,JArows,JAcols,NArows,NAcols + + mwSize sA,dims(2),ndims + + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 5) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '5 inputs required.') + endif + if(nlhs .gt. 3) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'Max 3 outputs required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(1)) + JArows = mxGetM(prhs(2)) + NArows = mxGetM(prhs(3)) + + JAcols = mxGetN(prhs(2)) + NAcols = mxGetN(prhs(3)) + +C Create Fortran array from the input arguments. + IA = mxGetPr(prhs(1)) + JA = mxGetPr(prhs(2)) + NA = mxGetPr(prhs(3)) + l = mxGetPr(prhs(4)) + perml = mxGetPr(prhs(5)) + +C Create return arguments. + + classid = mxGetClassID(prhs(1)) + complexflag = 0 + ndims=1 + plhs(1) = mxCreateNumericArray(ndims, IArows, + + classid, + + complexflag) + + IC = mxGetPr(plhs(1)) + + classid = mxGetClassID(prhs(2)) + ndims=2 + dims(1)=JArows + dims(2)=JAcols + plhs(2) = mxCreateNumericArray(ndims, dims, + + classid, + + complexflag) + + JC = mxGetPr(plhs(2)) + + plhs(3) = mxCreateDoubleMatrix(NArows,NAcols,complexflag) + NC = mxGetPr(plhs(3)) + +C Call the computational routine. + if (NArows==1) then + call compute1(%VAL(IA),%VAL(JA),%VAL(NA), + + %VAL(l),%VAL(perml), + + %VAL(IC),%VAL(JC),%VAL(NC), + + IArows,JArows,JAcols,NArows,NAcols) + else + call compute2(%VAL(IA),%VAL(JA),%VAL(NA), + + %VAL(l),%VAL(perml), + + %VAL(IC),%VAL(JC),%VAL(NC), + + IArows,JArows,JAcols,NArows,NAcols) + endif + + return + end + +C Computational subroutine + subroutine compute1(IA,JA,NA,l,perml, + + IC,JC,NC, + + IArows,JArows,JAcols,NArows,NAcols) + +C Declarations + implicit none + + mwSize IArows,JArows,JAcols,NArows,NAcols,l + mwSize IA(IArows),IC(IArows) + mwSize JA(JArows,JAcols),JC(JArows,JAcols) + real*8 NA(NAcols),NC(NAcols) + + mwSize perml(l),i,j,k,startj,endj,si + +C create IC,JC,NC + IC(1)=1 + do i=1,l + startj=IA(perml(i)) + endj=IA(perml(i)+1)-1 + IC(i+1)=IC(i)+endj-startj+1 + !DEC$ simd + do j=startj,endj + NC(IC(i)+j-startj)=NA(j) + enddo + do k=1,JAcols + !DEC$ simd + do j=startj,endj + JC(IC(i)+j-startj,k)=JA(j,k) + enddo + enddo + enddo + return + end + + + subroutine compute2(IA,JA,NA,l,perml, + + IC,JC,NC, + + IArows,JArows,JAcols,NArows,NAcols) + +C Declarations + implicit none + + mwSize IArows,JArows,JAcols,NArows,NAcols,l + mwSize IA(IArows),IC(IArows) + mwSize JA(JArows,JAcols),JC(JArows,JAcols) + real*8 NA(NArows,NAcols),NC(NArows,NAcols) + + mwSize perml(l),i,j,k,startj,endj,si + +C create IC,JC,NC + IC(1)=1 + do i=1,l + startj=IA(perml(i)) + endj=IA(perml(i)+1)-1 + IC(i+1)=IC(i)+endj-startj+1 + do j=startj,endj + !DEC$ simd + do si=1,NArows + NC(si,IC(i)+j-startj)=NA(si,j) + enddo + enddo + do k=1,JAcols + !DEC$ simd + do j=startj,endj + JC(IC(i)+j-startj,k)=JA(j,k) + enddo + enddo + enddo + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/ptr2col_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/ptr2col_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..26d13eddc49455e633f5cde30b045474878a1fb4 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/ptr2col_mex.F @@ -0,0 +1,91 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" + +C [ newcols ] = ptr2col_mex( ptr,n_vals ) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + + mwPointer mxGetPr + mwPointer mxCreateDoubleMatrix + mwPointer mxCreateNumericArray + integer*4 mxGetClassID + mwPointer mxGetM, mxGetN + real*8 mxGetScalar + + mwPointer ptr + mwPointer newcols + + mwSize ptrM + +C Arguments for mxCreateNumericArray + integer*4 classid + integer*4 complexflag + mwSize ndim + mwSize dims(1) + mwSize l1,l2 + real*8 n_vals + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 2) then + call mexErrMsgIdAndTxt ('MATLAB:compress:nInput', + + '2 inputs required.') + endif + if(nlhs .gt. 1) then + call mexErrMsgIdAndTxt ('MATLAB:compress:nOutput', + + '1 output required.') + endif + + +C Create Fortran array from the input arguments. + + ptr = mxGetPr(prhs(1)) + + l1 = mxGetM(prhs(1)) + l2 = mxGetN(prhs(1))-1 + +C Create matrix for the return arguments. + + n_vals=mxGetScalar(prhs(2)) + + complexflag = 0 + + classid = mxGetClassID(prhs(1)) + ndim = 1 + dims(1) = n_vals + plhs(1) = mxCreateNumericArray(ndim, dims, + + classid, + + complexflag) + + newcols = mxGetPr(plhs(1)) + +C Call the computational routine. + call compute(%VAL(ptr),l1,l2,%VAL(newcols),n_vals) + + return + end + + + subroutine compute(ptr,l1,l2,newcols,n_vals) + implicit none + + real*8 n_vals + mwSize l1,l2 + mwSize ptr(l1,l2+1),newcols(n_vals) + + mwSize i1,i2,i + do i1=1,l1 + do i2=1,l2 + do i=ptr(i1,i2),ptr(i1,i2+1)-1 + newcols(i)=i2 + enddo + enddo + enddo + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/sortcol_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/sortcol_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..b57232d3a655cecf9f10a689e35c517e6e7736df --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/sortcol_mex.F @@ -0,0 +1,175 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" + +C [ newcols,newvals ] = sortcol_mex( ptr,cols,vals,l,coldim,coli,colidim ) +C the function sorts columns by coli + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + + mwPointer mxGetPr + mwPointer mxCreateDoubleMatrix + mwPointer mxCreateNumericArray + integer*4 mxGetClassID + + mwPointer mxGetM, mxGetN + + mwPointer ptr,cols,vals,l,coldim,coli + mwPointer newcols,newvals + + mwSize ptrM,colsM,colsN,valsM,valsN,coldimM,coldimN + mwSize colidim + +C Arguments for mxCreateNumericArray + integer*4 classid + integer*4 complexflag + mwSize ndim + mwSize dims(2) + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 7) then + call mexErrMsgIdAndTxt ('MATLAB:compress:nInput', + + '7 inputs required.') + endif + if(nlhs .gt. 2) then + call mexErrMsgIdAndTxt ('MATLAB:compress:nOutput', + + '2 outputs required.') + endif + + +C Create Fortran array from the input arguments. + + ptr = mxGetPr(prhs(1)) + cols = mxGetPr(prhs(2)) + vals = mxGetPr(prhs(3)) + l = mxGetPr(prhs(4)) + coldim = mxGetPr(prhs(5)) + coli = mxGetPr(prhs(6)) + + ptrM = mxGetM(prhs(1)) + + colsM = mxGetM(prhs(2)) + colsN = mxGetN(prhs(2)) + + valsM = mxGetM(prhs(3)) + valsN = mxGetN(prhs(3)) + + coldimM = mxGetM(prhs(5)) + coldimN = mxGetN(prhs(5)) + coldimN = coldimM*coldimN + +C Create matrix for the return arguments. + + classid = mxGetClassID(prhs(2)) + complexflag=0 + + ndim = 2 + dims(1) = colsM + dims(2) = colsN + plhs(1) = mxCreateNumericArray(ndim, dims, + + classid, + + complexflag) + + newcols = mxGetPr(plhs(1)) + + plhs(2) = mxCreateDoubleMatrix(valsM, valsN, complexflag) + + newvals = mxGetPr(plhs(2)) + +C Call the computational routine. + call compute(%VAL(ptr),%VAL(cols),%VAL(vals), + + %VAL(l),%VAL(coldim),%VAL(coli), + + ptrM,colsM,colsN,valsM,valsN,coldimN, + + %VAL(newcols),%VAL(newvals)) + + return + end + + subroutine compute(ptr,cols,vals,l,coldim,coli, + + ptrM,colsM,colsN,valsM,valsN,coldimN, + + newcols,newvals) + implicit none + + mwSize ptrM,colsM,colsN,valsM,valsN,coldimN + mwSize ptr(ptrM),coldim(coldimN) + + mwSize l,coli,colidim + mwSize cols(colsM,colsN) + + mwSize newcols(colsM,colsN) + real*8 vals(valsM,valsN),newvals(valsM,valsN) + + mwSize i,n_vals,j,temploc1,temploc2,n_valsi + + mwSize, allocatable :: countcol(:),z(:),loc(:),ind(:),tempptr(:) + + integer AllocateStatus + + colidim=coldim(coli) + n_vals=ptr(ptrM)-1 + + allocate (countcol(colidim),z(colidim+1), + + tempptr(colidim+1),loc(colidim),ind(n_vals), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory.') + endif + do i=1,l + n_valsi=ptr(i+1)-ptr(i) +C count cols + countcol=0 + do j=ptr(i),ptr(i+1)-1 + countcol(cols(j,coli))=countcol(cols(j,coli))+1 + end do + +C create ptr for the column dimension + z(1)=1 + z(2:colidim+1)=countcol + call cumsum(tempptr,z,colidim+1) + +C create sort index + loc=tempptr(1:colidim) + do j=1,n_valsi + temploc1=ptr(i)+j-1 + ind(j)=loc(cols(temploc1,coli)) + loc(cols(temploc1,coli))=loc(cols(temploc1,coli))+1 + end do + +C sort + do j=1,n_valsi + temploc1=ptr(i)+ind(j)-1 + temploc2=ptr(i)+j-1 + newvals(:,temploc1)=vals(:,temploc2) + newcols(temploc1,:)=cols(temploc2,:) + end do + end do + + deallocate(countcol,z, + + tempptr,loc,ind, + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'cannot deallocate.') + endif + + return + end + + subroutine cumsum(cumx, x, n_x) + implicit none + + mwSize i, n_x + mwSize cumx(n_x), x(n_x) + + cumx(1)=x(1) + do i=2,n_x + cumx(i)=cumx(i-1)+x(i) + end do + + return + end diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/takerows_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/takerows_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..fdb34bd97152cc27af9b08c47840c994667fc2bb --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/takerows_mex.F @@ -0,0 +1,126 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [IC,JC,NC] = takerows_mex(IA,JA,NA,l,takel) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateDoubleMatrix + mwPointer mxCreateNumericArray + integer*4 mxGetClassID + real*8 mxGetScalar + +C Arguments for mxCreateNumericArray + integer*4 classid + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l,takel,IA,JA,NA + mwPointer IC,JC,NC + +C Array information: + mwSize IArows,JArows,JAcols,NArows,NAcols + + mwSize sA,dims(2),ndims,n_takel + + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 5) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '5 inputs required.') + endif + if(nlhs .gt. 3) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'Max 3 outputs required.') + endif + +C Get the size of the inputs array. + + IArows = mxGetM(prhs(1)) + JArows = mxGetM(prhs(2)) + NArows = mxGetM(prhs(3)) + + JAcols = mxGetN(prhs(2)) + NAcols = mxGetN(prhs(3)) + + n_takel=mxGetM(prhs(5))*mxGetN(prhs(5)) + +C Create Fortran array from the input arguments. + IA = mxGetPr(prhs(1)) + JA = mxGetPr(prhs(2)) + NA = mxGetPr(prhs(3)) + l = mxGetPr(prhs(4)) + takel = mxGetPr(prhs(5)) + +C Create return arguments. + + classid = mxGetClassID(prhs(1)) + complexflag = 0 + ndims=1 + plhs(1) = mxCreateNumericArray(ndims, IArows, + + classid, + + complexflag) + + IC = mxGetPr(plhs(1)) + + classid = mxGetClassID(prhs(2)) + ndims=2 + dims(1)=JArows + dims(2)=JAcols + plhs(2) = mxCreateNumericArray(ndims, dims, + + classid, + + complexflag) + + JC = mxGetPr(plhs(2)) + + plhs(3) = mxCreateDoubleMatrix(NArows,NAcols,complexflag) + NC = mxGetPr(plhs(3)) + +C Call the computational routine. + call compute(%VAL(IA),%VAL(JA),%VAL(NA), + + %VAL(l),%VAL(takel), + + %VAL(IC),%VAL(JC),%VAL(NC), + + IArows,JArows,JAcols,NArows,NAcols,n_takel) + + return + end + +C Computational subroutine + subroutine compute(IA,JA,NA,l,takel, + + IC,JC,NC, + + IArows,JArows,JAcols,NArows,NAcols,n_takel) + +C Declarations + implicit none + + mwSize IArows,JArows,JAcols,NArows,NAcols,n_takel + mwSize IA(IArows),IC(IArows) + mwSize JA(JArows,JAcols),JC(JArows,JAcols) + real*8 NA(NArows,NAcols),NC(NArows,NAcols) + + mwSize l,takel(n_takel),i,j,k,nz,startc,endc + +C create IC,JC,NC + nz=0 + k=0 + IC(1)=1 + do i=1,n_takel + k=k+1 + j=takel(i) + IC(k+1)=IC(k)+IA(j+1)-IA(j) + JC(IC(k):IC(k+1)-1,:)=JA(IA(j):IA(j+1)-1,:) + NC(:,IC(k):IC(k+1)-1)=NA(:,IA(j):IA(j+1)-1) + + enddo + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/tplus1_2D_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/tplus1_2D_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..667b38df83661ac2ae6ac2006b26755fd044734d --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/tplus1_2D_mex.F @@ -0,0 +1,320 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [NC,IC,JC] = tplus1_2D_mex(l1,l2,m1,... +C IB1,JB1,NB1,IB2,JB2,NB2, +C maxload) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateDoubleMatrix + mwPointer mxCreateNumericArray + integer*4 mxGetClassID + +C Arguments for mxCreateNumericArray + integer*4 classid + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l1,l2,m1 + mwPointer IB1,JB1,IB2,JB2 + mwPointer IC + mwPointer JC + mwPointer maxload + mwPointer NB1,NB2 + + mwPointer NC + +C Array information: + mwSize IB1rows, IB1cols, JB1rows + mwSize IB2rows, JB2rows + mwSize ICrows,ICcols + mwSize JCrows + + mwSize s,sB1,sB2,ndim + mwSize dim(2) + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 10) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '10 inputs required.') + endif + if(nlhs .gt. 3) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'Max 3 outputs required.') + endif + +C Get the size of the inputs array. + + IB1rows = mxGetM(prhs(4)) + IB1cols = mxGetN(prhs(4)) + JB1rows = mxGetM(prhs(5)) + IB2rows = mxGetM(prhs(7)) + JB2rows = mxGetM(prhs(8)) + + ICrows=IB1rows + ICcols=IB1cols + + JCrows=JB1rows+JB2rows ! temporary size, should be adjusted after calling the mex function. + +C Create Fortran array from the input arguments. + l1 = mxGetPr(prhs(1)) + l2 = mxGetPr(prhs(2)) + m1 = mxGetPr(prhs(3)) + IB1 = mxGetPr(prhs(4)) + JB1 = mxGetPr(prhs(5)) + NB1 = mxGetPr(prhs(6)) + IB2 = mxGetPr(prhs(7)) + JB2 = mxGetPr(prhs(8)) + NB2 = mxGetPr(prhs(9)) + maxload = mxGetPr(prhs(10)) + +C Get number of states + sB1 = mxGetM(prhs(6)) + sB2 = mxGetM(prhs(9)) + + s=sB1 + +C check compatibility of states + if (sB1.ne.sB2) then + call mexErrMsgIdAndTxt ('MATLAB:states', + + 'incompatible states.') + endif + +C Create matrix for NC. + complexflag = 0 + + plhs(1) = mxCreateDoubleMatrix(s,JCrows,complexflag) + NC = mxGetPr(plhs(1)) + +C Create matrix for IC and JC + classid = mxGetClassID(prhs(4)) + ndim=2 + dim(1)=ICrows + dim(2)=ICcols + plhs(2) = mxCreateNumericArray(ndim, dim, + + classid, + + complexflag) + + IC = mxGetPr(plhs(2)) + + classid = mxGetClassID(prhs(5)) + ndim=2 + dim(1)=JCrows + dim(2)=1 + plhs(3) = mxCreateNumericArray(ndim, dim, + + classid, + + complexflag) + + JC = mxGetPr(plhs(3)) + +C Call the computational routine. + call compute(%VAL(l1),%VAL(l2),%VAL(m1), + + %VAL(IB1),%VAL(JB1),%VAL(NB1), + + %VAL(IB2),%VAL(JB2),%VAL(NB2), + + %VAL(maxload), + + %VAL(NC),%VAL(IC),%VAL(JC), + + IB1rows,JB1rows,IB2rows,JB2rows, + + ICrows,JCrows, + + s) + + return + end + +C Computational subroutine + subroutine compute(l1,l2,m1, + + IB1,JB1,NB1,IB2,JB2,NB2, + + maxload, + + NC,IC,JC, + + IB1rows,JB1rows,IB2rows,JB2rows, + + ICrows,JCrows, + + s) + +C Declarations + implicit none + + mwSize l1,l2,m1,s + mwSize IB1rows,JB1rows,IB2rows,JB2rows + mwSize ICrows,ICcols + mwSize JCrows + + mwSize maxload,n_vecload,loadi,load_ + logical doind + real*8, target :: NB1(s,JB1rows) + real*8, target :: NB2(s,JB2rows) + + real*8, pointer :: pNB1(:,:) + real*8, pointer :: pNB2(:,:) + + real*8 NC(s,JCrows) + + mwSize, allocatable :: vecload(:) + + real*8, allocatable :: x(:,:) + mwSize, allocatable :: w(:) + + mwSize, target :: IB1(l1,l2+1) + mwSize, target :: JB1(JB1rows,1) + mwSize, target :: IB2(l1,l2+1) + mwSize, target :: JB2(JB2rows,1) + + mwSize, target :: IC(l1,l2+1) + mwSize, target :: JC(JCrows,1) + + mwSize i,i1,i2,jp,j,kp,k1,k2,vp,v1,v2 + mwSize is,js,nz + + mwSize jpstart, jpend + mwSize kpstart, kpend + mwSize vpstart, vpend + + integer AllocateStatus + +C vecload + n_vecload=(s-1)/maxload+2 + + allocate (vecload(n_vecload),STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory1.') + endif + + vecload(1)=1 + vecload(n_vecload)=s+1 + do i=2,n_vecload-1 + vecload(i)=vecload(i-1)+maxload + end do + +C allocate + allocate (w(m1), + + x(min(s,maxload),m1), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory.') + endif + + nz=1 + +C run first time and calculate indices + loadi=1 + load_=vecload(loadi+1)-vecload(loadi) + + if (s>1) then + pNB1=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + pNB2=>NB2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB1=>NB1 + pNB2=>NB2 + endif + + do i1=1,l1 + w=0 + do i2=1,l2 + IC(i1,i2)=nz +C run over rows of B1 + do jp=IB1(i1,i2),IB1(i1,i2+1)-1 + j=JB1(jp,1) + !DEC$ simd + do is=1,load_ + x(is,j)=pNB1(is,jp) + end do + JC(nz,1)=j + w(j)=i2 + nz=nz+1 + end do +C run over rows of B2 + do jp=IB2(i1,i2),IB2(i1,i2+1)-1 + j=JB2(jp,1) + if (w(j)2) then + w=0 + endif + + do loadi=2,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (s>1) then + pNB1=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + pNB2=>NB2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB1=>NB1 + pNB2=>NB2 + endif + + do i1=1,l1 + do i2=1,l2 +C run over rows of B1 + do jp=IB1(i1,i2),IB1(i1,i2+1)-1 + j=JB1(jp,1) + !DEC$ simd + do is=1,load_ + x(is,j)=pNB1(is,jp) + end do + end do +C run over rows of B2 + do jp=IB2(i1,i2),IB2(i1,i2+1)-1 + j=JB2(jp,1) + !DEC$ simd + do is=1,load_ + x(is,j)=x(is,j)+pNB2(is,jp) + end do + end do +C assign result in NC + do vp=IC(i1,i2),IC(i1,i2+1)-1 + v1=JC(vp,1) + !DEC$ simd + do is=1,load_ + js=vecload(loadi)+is-1 + NC(js,vp)=x(is,v1) + x(is,v1)=0.0 + end do + end do + end do + + end do + end do + + deallocate (w,x) + + return + end + diff --git a/105/replication_package/solution_methods/taylor_projection/MEX_files/tplus1_mex.F b/105/replication_package/solution_methods/taylor_projection/MEX_files/tplus1_mex.F new file mode 100644 index 0000000000000000000000000000000000000000..607d939b4dc1ab72f9c35e5074d7d2d9a6c48c94 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/MEX_files/tplus1_mex.F @@ -0,0 +1,319 @@ +C � Copyright, Oren Levintal, June 13, 2016. + +#include "fintrf.h" +C [NC,IC,JC] = tplus1_mex(l,m1,... +C IB1,JB1,NB1,IB2,JB2,NB2, +C maxload) + subroutine mexfunction(nlhs, plhs, nrhs, prhs) + implicit none + +C mexFunction arguments: + mwPointer plhs(*), prhs(*) + integer nlhs, nrhs + +C Function declarations: + mwPointer mxGetPr + mwPointer mxGetM, mxGetN + mwPointer mxCreateDoubleMatrix + mwPointer mxCreateNumericArray + integer*4 mxGetClassID + +C Arguments for mxCreateNumericArray + integer*4 classid + integer*4 complexflag + +C Pointers to input/output mxArrays: + mwPointer l,m1 + mwPointer IB1,JB1,IB2,JB2 + mwPointer IC + mwPointer JC + mwPointer maxload + mwPointer NB1,NB2 + + mwPointer NC + +C Array information: + mwSize IB1rows, JB1rows + mwSize IB2rows, JB2rows + mwSize ICrows + mwSize JCrows + + mwSize s,sB1,sB2,ndim + mwSize dim(2) + +C----------------------------------------------------------------------- +C Check for proper number of arguments. + if(nrhs .ne. 9) then + call mexErrMsgIdAndTxt ('MATLAB:contraction2:nInput', + + '9 inputs required.') + endif + if(nlhs .gt. 3) then + call mexErrMsgIdAndTxt ('MATLAB:contraction1:nOutput', + + 'Max 3 outputs required.') + endif + +C Get the size of the inputs array. + + IB1rows = mxGetM(prhs(3)) + JB1rows = mxGetM(prhs(4)) + IB2rows = mxGetM(prhs(6)) + JB2rows = mxGetM(prhs(7)) + + ICrows=IB1rows + JCrows=JB1rows+JB2rows ! temporary size, should be adjusted after calling the mex function. + +C Create Fortran array from the input arguments. + l = mxGetPr(prhs(1)) + m1 = mxGetPr(prhs(2)) + IB1 = mxGetPr(prhs(3)) + JB1 = mxGetPr(prhs(4)) + NB1 = mxGetPr(prhs(5)) + IB2 = mxGetPr(prhs(6)) + JB2 = mxGetPr(prhs(7)) + NB2 = mxGetPr(prhs(8)) + maxload = mxGetPr(prhs(9)) + +C Get number of states + sB1 = mxGetM(prhs(5)) + sB2 = mxGetM(prhs(8)) + + s=sB1 + +C check compatibility of states + if (sB1.ne.sB2) then + call mexErrMsgIdAndTxt ('MATLAB:states', + + 'incompatible states.') + endif + +C Create matrix for NC. + complexflag = 0 + + plhs(1) = mxCreateDoubleMatrix(s,JCrows, complexflag) + NC = mxGetPr(plhs(1)) + +C Create matrix for IC and JC + classid = mxGetClassID(prhs(3)) + ndim=1 + plhs(2) = mxCreateNumericArray(ndim, ICrows, + + classid, + + complexflag) + + IC = mxGetPr(plhs(2)) + + classid = mxGetClassID(prhs(4)) + ndim=2 + dim(1)=JCrows + dim(2)=1 + plhs(3) = mxCreateNumericArray(ndim, dim, + + classid, + + complexflag) + + JC = mxGetPr(plhs(3)) + +C Call the computational routine. + call compute(%VAL(l),%VAL(m1), + + %VAL(IB1),%VAL(JB1),%VAL(NB1), + + %VAL(IB2),%VAL(JB2),%VAL(NB2), + + %VAL(maxload), + + %VAL(NC),%VAL(IC),%VAL(JC), + + IB1rows,JB1rows,IB2rows,JB2rows, + + ICrows,JCrows, + + s) + + return + end + +C Computational subroutine + subroutine compute(l,m1, + + IB1,JB1,NB1,IB2,JB2,NB2, + + maxload, + + NC,IC,JC, + + IB1rows,JB1rows,IB2rows,JB2rows, + + ICrows,JCrows, + + s) + +C Declarations + implicit none + + mwSize l,m1,s + mwSize IB1rows,JB1rows,IB2rows,JB2rows + mwSize ICrows + mwSize JCrows + + mwSize maxload,n_vecload,loadi,load_ + logical doind + real*8, target :: NB1(s,JB1rows) + real*8, target :: NB2(s,JB2rows) + + real*8, pointer :: pNB1(:,:) + real*8, pointer :: pNB2(:,:) + + real*8 NC(s,JCrows) + + mwSize, allocatable :: vecload(:) + + real*8, allocatable :: x(:,:) + mwSize, allocatable :: w(:) + + mwSize, target :: IB1(IB1rows) + mwSize, target :: JB1(JB1rows,1) + mwSize, target :: IB2(IB2rows) + mwSize, target :: JB2(JB2rows,1) + + mwSize, target :: IC(ICrows) + mwSize, target :: JC(JCrows,1) + + mwSize i,jp,j,kp,k1,k2,vp,v1,v2 + mwSize is,js,nz + + mwSize jpstart, jpend + mwSize kpstart, kpend + mwSize vpstart, vpend + + integer AllocateStatus + +C vecload + n_vecload=(s-1)/maxload+2 + + allocate (vecload(n_vecload),STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:compress:OutofMemory', + + 'Out of memory1.') + endif + + vecload(1)=1 + vecload(n_vecload)=s+1 + do i=2,n_vecload-1 + vecload(i)=vecload(i-1)+maxload + end do + +C allocate + allocate (w(m1), + + x(min(s,maxload),m1), + + STAT = AllocateStatus) + IF (AllocateStatus .ne. 0) then + call mexErrMsgIdAndTxt ('MATLAB:OutOfMemory', + + 'Out of memory.') + endif + + w=0 + nz=1 + +C run first time and calculate indices + loadi=1 + load_=vecload(loadi+1)-vecload(loadi) + + if (s>1) then + pNB1=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + pNB2=>NB2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB1=>NB1 + pNB2=>NB2 + endif + + do i=1,l + IC(i)=nz +C run over rows of B1 + do jp=IB1(i),IB1(i+1)-1 + j=JB1(jp,1) + !DEC$ simd + do is=1,load_ + x(is,j)=pNB1(is,jp) + end do + JC(nz,1)=j + w(j)=i + nz=nz+1 + end do +C run over rows of B2 + do jp=IB2(i),IB2(i+1)-1 + j=JB2(jp,1) + if (w(j)2) then + w=0 + endif + + do loadi=2,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (s>1) then + pNB1=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + pNB2=>NB2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB1=>NB1 + pNB2=>NB2 + endif + + do i=1,l +C run over rows of B1 + do jp=IB1(i),IB1(i+1)-1 + j=JB1(jp,1) + !DEC$ simd + do is=1,load_ + x(is,j)=pNB1(is,jp) + end do + w(j)=i + end do +C run over rows of B2 + do jp=IB2(i),IB2(i+1)-1 + j=JB2(jp,1) + if (w(j)1) then + pNB1=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + pNB2=>NB2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB1=>NB1 + pNB2=>NB2 + endif + + do i=1,l + IC(i)=nz +C run over rows of B1 + do jp=IB1(i),IB1(i+1)-1 + j1=JB1(jp,1) + j2=JB1(jp,2) + !DEC$ simd + do is=1,load_ + x(is,j1,j2)=pNB1(is,jp) + end do + JC(nz,1)=j1 + JC(nz,2)=j2 + w(j1,j2)=i + nz=nz+1 + end do +C run over rows of B2 + do jp=IB2(i),IB2(i+1)-1 + j1=JB2(jp,1) + j2=JB2(jp,2) + if (w(j1,j2)2) then + w=0 + endif + + do loadi=2,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (s>1) then + pNB1=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + pNB2=>NB2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB1=>NB1 + pNB2=>NB2 + endif + + do i=1,l +C run over rows of B1 + do jp=IB1(i),IB1(i+1)-1 + j1=JB1(jp,1) + j2=JB1(jp,2) + !DEC$ simd + do is=1,load_ + x(is,j1,j2)=pNB1(is,jp) + end do + w(j1,j2)=i + end do +C run over rows of B2 + do jp=IB2(i),IB2(i+1)-1 + j1=JB2(jp,1) + j2=JB2(jp,2) + if (w(j1,j2)1) then + pNB1=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + pNB2=>NB2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB1=>NB1 + pNB2=>NB2 + endif + + do i=1,l + IC(i)=nz +C run over rows of B1 + do jp=IB1(i),IB1(i+1)-1 + j1=JB1(jp,1) + j2=JB1(jp,2) + j3=JB1(jp,3) + !DEC$ simd + do is=1,load_ + x(is,j1,j2,j3)=pNB1(is,jp) + end do + JC(nz,1)=j1 + JC(nz,2)=j2 + JC(nz,3)=j3 + w(j1,j2,j3)=i + nz=nz+1 + end do +C run over rows of B2 + do jp=IB2(i),IB2(i+1)-1 + j1=JB2(jp,1) + j2=JB2(jp,2) + j3=JB2(jp,3) + if (w(j1,j2,j3)2) then + w=0 + endif + + do loadi=2,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (s>1) then + pNB1=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + pNB2=>NB2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB1=>NB1 + pNB2=>NB2 + endif + + do i=1,l +C run over rows of B1 + do jp=IB1(i),IB1(i+1)-1 + j1=JB1(jp,1) + j2=JB1(jp,2) + j3=JB1(jp,3) + !DEC$ simd + do is=1,load_ + x(is,j1,j2,j3)=pNB1(is,jp) + end do + w(j1,j2,j3)=i + end do +C run over rows of B2 + do jp=IB2(i),IB2(i+1)-1 + j1=JB2(jp,1) + j2=JB2(jp,2) + j3=JB2(jp,3) + if (w(j1,j2,j3)1) then + pNB1=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + pNB2=>NB2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB1=>NB1 + pNB2=>NB2 + endif + + do i=1,l + IC(i)=nz +C run over rows of B1 + do jp=IB1(i),IB1(i+1)-1 + j1=JB1(jp,1) + j2=JB1(jp,2) + j3=JB1(jp,3) + j4=JB1(jp,4) + !DEC$ simd + do is=1,load_ + x(is,j1,j2,j3,j4)=pNB1(is,jp) + end do + JC(nz,1)=j1 + JC(nz,2)=j2 + JC(nz,3)=j3 + JC(nz,4)=j4 + w(j1,j2,j3,j4)=i + nz=nz+1 + end do +C run over rows of B2 + do jp=IB2(i),IB2(i+1)-1 + j1=JB2(jp,1) + j2=JB2(jp,2) + j3=JB2(jp,3) + j4=JB2(jp,4) + if (w(j1,j2,j3,j4)2) then + w=0 + endif + + do loadi=2,n_vecload-1 + load_=vecload(loadi+1)-vecload(loadi) + + if (s>1) then + pNB1=>NB1(vecload(loadi):vecload(loadi+1)-1,:) + pNB2=>NB2(vecload(loadi):vecload(loadi+1)-1,:) + else + pNB1=>NB1 + pNB2=>NB2 + endif + + do i=1,l +C run over rows of B1 + do jp=IB1(i),IB1(i+1)-1 + j1=JB1(jp,1) + j2=JB1(jp,2) + j3=JB1(jp,3) + j4=JB1(jp,4) + !DEC$ simd + do is=1,load_ + x(is,j1,j2,j3,j4)=pNB1(is,jp) + end do + w(j1,j2,j3,j4)=i + end do +C run over rows of B2 + do jp=IB2(i),IB2(i+1)-1 + j1=JB2(jp,1) + j2=JB2(jp,2) + j3=JB2(jp,3) + j4=JB2(jp,4) + if (w(j1,j2,j3,j4)6 + error('wrong number of input arguments') +end + +if A.tsize(2)~=B.tsize(1) + error('incompatible dimensions') +end +dosum=0; +if nargin==6 + if strcmp(varargin{4},'sum') + dosum=1; + elseif ~strcmp(varargin{4},'vec') + error(['sixth argument must be charater ' '''' 'sum' '''' ' or ' '''' 'vec' '''']) + end +end +if nargin==2 + type=0; % index is not available + maxload=intarray(1); +end +if nargin==3 + if varargin{1}==1 + type=1; + elseif varargin{1}==2 + type=2; + else + error('number of precomputed indices should be 1 or 2') + end +end +calculate_ind=0; +if nargin>=4 + if varargin{2}==1 + type=3; + elseif varargin{2}==2 + type=4; + else + error('number of precomputed indices should be 1 or 2') + end + if isempty(varargin{1}) + calculate_ind=1; + else + ind=varargin{1}; + if ~isa(ind,'struct') + error('index variable incorrectly defined') + end + if ~isfield(ind,'IC_1') + error('index variable incorrectly defined') + end + if varargin{2}==2 + if ~isfield(ind,'JC_1') + error('index variable incorrectly defined') + end + end + end +end +if nargin==4 + maxload=intarray(1); +elseif nargin>=4 + maxload=intarray(varargin{3}); +end + +l=A.tsize(1); +m=A.tsize(2); +if length(A.tsize)~=3 + error('columns must be 2D') +end +if A.tsize(3)~=m + error('columns are not symmetric') +end +n=B.tsize(2); +if B.colsorted~=1 + error('not sorted') +end +IA=A.ptr; +JA=A.cols; +IB=B.ptr; +JB=B.cols; +if type==0 % calculate A*kron(B,B)U without precomputed index + varout1=sptensor; + [IC_1,IC_2] = AkronBU2IC_mex(l,m,n,IA,JA,IB,JB); + JCrows_1=IC_1(end)-1; + NA=A.vals; + NB=B.vals; + if ~isreal(NA) || ~isreal(NB) + error('complex numbers not supported') + end + [varout1.vals,JC_1] = AkronBU2vecI_mex( l,m,n,IA,JA,NA,IB,... + JB,NB,IC_1,IC_2,JCrows_1,maxload,dosum); + varout1.ptr=IC_1; + varout1.cols=JC_1; + varout1.tsize=[l,nchoosek(n+1,2)]; +elseif type==1 % compute IC + [varout1.IC_1,varout1.IC_2] = AkronBU2IC_mex(l,m,n,IA,JA,IB,JB); +elseif type==2 % compute IC and JC + [IC_1,IC_2] = AkronBU2IC_mex(l,m,n,IA,JA,IB,JB); + JCrows_1=IC_1(end)-1; + JCrows_2=IC_2(end)-1; + [ varout1.JC_1,varout1.JC_2 ] = AkronBU2JC_mex( l,m,n,IA,JA,IB,JB,JCrows_1,JCrows_2,IC_2 ); + % note: JC_1 has 3 columns. First column stores the location in the + % compressed matrix. Other columns store the location in a 2-D + % tensor. + varout1.IC_1=IC_1; + varout1.IC_2=IC_2; +elseif type==3 % compute A*kron(B,B)U with one precomputed index IC + varout1=sptensor; + if calculate_ind==1 + [IC_1,IC_2] = AkronBU2IC_mex(l,m,n,IA,JA,IB,JB); + else + IC_1=ind.IC_1; + IC_2=ind.IC_2; + end + JCrows_1=IC_1(end)-1; + NA=A.vals; + NB=B.vals; + if ~isreal(NA) || ~isreal(NB) + error('complex numbers not supported') + end + [varout1.vals,JC_1] = AkronBU2vecI_mex( l,m,n,IA,JA,NA,IB,... + JB,NB,IC_1,IC_2,JCrows_1,maxload,dosum); + varout1.ptr=IC_1; + varout1.cols=JC_1; + varout1.tsize=[l,nchoosek(n+1,2)]; + varout2.IC_1=IC_1; + varout2.IC_2=IC_2; +elseif type==4 % compute A*kron(B,B)U with two precomputed indices IC,JC + varout1=sptensor; + if calculate_ind==1 + [IC_1,IC_2] = AkronBU2IC_mex(l,m,n,IA,JA,IB,JB); + JCrows_1=IC_1(end)-1; + JCrows_2=IC_2(end)-1; + [ JC_1,JC_2 ] = AkronBU2JC_mex( l,m,n,IA,JA,IB,JB,JCrows_1,JCrows_2,IC_2 ); + else + IC_1=ind.IC_1; + IC_2=ind.IC_2; + JC_1=ind.JC_1; + JC_2=ind.JC_2; + end + NA=A.vals; + NB=B.vals; + if ~isreal(NA) || ~isreal(NB) + error('complex numbers not supported') + end + varout1.vals = AkronBU2vec_mex( l,m,n,IA,JA,NA,IB,... + JB,NB,IC_1,JC_1,IC_2,JC_2,maxload,dosum); + varout1.ptr=IC_1; + varout1.cols=JC_1(:,1); % note that JC_1 stores 2 columns. First column is the compressed format, and other columns are the corresponding 2-D indices + varout1.tsize=[l,nchoosek(n+1,2)]; + varout2.IC_1=IC_1; + varout2.IC_2=IC_2; + varout2.JC_1=JC_1; + varout2.JC_2=JC_2; +end + +if isfield(A,'ptr2d') % if the pointer of A is 2D varout is also 2D + varout1.ptr2d=A.ptr2d; +end +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/AkronBU3.m b/105/replication_package/solution_methods/taylor_projection/Tensors/AkronBU3.m new file mode 100644 index 0000000000000000000000000000000000000000..fb37f802f21be280b241ada31143f9b8a952d0b5 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/AkronBU3.m @@ -0,0 +1,191 @@ +function [varout1,varout2]=AkronBU3(A,B,varargin) +%C=AkronBU3(A,B) calculates C=A*kron(B,B,B)*U3. +%[C,ind]=AkronBU3(A,B,ind,1,maxload) calculates C using one precomputed +%index ind. If ind=[] the function returns ind. The option maxload controls +%the maximum number of flops performed in parallel by the simd. This is +%relevant only if A or B represent sets of s tensors. +%[C,ind]=AkronBU3(A,B,ind,2,maxload) calculates C using two precomputed +%indices ind. +%[C,ind]=AkronBU3(A,B,ind,1,maxload,'sum') sums across s if A +%or B represent sets of s tensors. This option is useful for calculating +%expected value of C. +%[C,ind]=AkronBU3(A,B,ind,2,maxload,'sum') is similar but uses two +%precomputed indices. +%ind=AkronBU3(A,B,1) returns a structure ind with one field +%to speed up calculation. +%ind=AkronBU3(A,B,2) returns a structure ind with two fields. Speedup +%is larger compared to one field, but requires more memory. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if nargin<2 || nargin>6 + error('wrong number of input arguments') +end + +if A.tsize(2)~=B.tsize(1) + error('incompatible dimensions') +end +dosum=0; +if nargin==6 + if strcmp(varargin{4},'sum') + dosum=1; + elseif ~strcmp(varargin{4},'vec') + error(['eighth argument must be charater ' '''' 'sum' '''' ' or ' '''' 'vec' '''']) + end +end +if nargin==2 + type=0; % index is not available + maxload=intarray(1); +end +if nargin==3 + if varargin{1}==1 + type=1; + elseif varargin{1}==2 + type=2; + else + error('number of precomputed indices should be 1 or 2') + end +end +calculate_ind=0; +if nargin>=4 + if varargin{2}==1 + type=3; + elseif varargin{2}==2 + type=4; + else + error('number of precomputed indices should be 1 or 2') + end + if isempty(varargin{1}) + calculate_ind=1; + else + ind=varargin{1}; + if ~isa(ind,'struct') + error('index variable incorrectly defined') + end + if ~isfield(ind,'IC_1') + error('index variable incorrectly defined') + end + if varargin{2}==2 + if ~isfield(ind,'JC_1') + error('index variable incorrectly defined') + end + end + end +end +if nargin==4 + maxload=intarray(1); +elseif nargin>=4 + maxload=intarray(varargin{3}); +end + +l=A.tsize(1); +m=A.tsize(2); +if length(A.tsize)~=4 + error('columns must be 3D') +end +if A.tsize(3)~=m || A.tsize(4)~=m + error('columns are not symmetric') +end +n=B.tsize(2); +if B.colsorted~=1 + error('not sorted') +end +IA=A.ptr; +JA=A.cols; +IB=B.ptr; +JB=B.cols; +if type==0 % calculate A*kron(B,B,B)*U3 without precomputed index + varout1=sptensor; + [IC_1,IC_2,IC_3] = AkronBU3IC_mex(l,m,n,IA,JA,IB,JB); + JCrows_1=IC_1(end)-1; + NA=A.vals; + NB=B.vals; + if ~isreal(NA) || ~isreal(NB) + error('complex numbers not supported') + end + [varout1.vals,JC_1] = AkronBU3vecI_mex(l,m,n,IA,JA,NA,... + IB,JB,NB,... + IC_1,IC_2,IC_3,JCrows_1,... + maxload,dosum); + varout1.ptr=IC_1; + varout1.cols=JC_1; + varout1.tsize=[l,nchoosek(n+2,3)]; +elseif type==1 % compute IC + [varout1.IC_1,varout1.IC_2,varout1.IC_3] = AkronBU3IC_mex(l,m,n,IA,JA,IB,JB); +elseif type==2 % compute IC and JC + [IC_1,IC_2,IC_3] = AkronBU3IC_mex(l,m,n,IA,JA,IB,JB); + JCrows_1=IC_1(end)-1; + JCrows_2=IC_2(end)-1; + JCrows_3=IC_3(end)-1; + [ varout1.JC_1,varout1.JC_2,varout1.JC_3 ] = AkronBU3JC_mex( l,m,n,IA,JA,IB,JB,... + JCrows_1,JCrows_2,JCrows_3,IC_2,IC_3 ); + varout1.IC_1=IC_1; + varout1.IC_2=IC_2; + varout1.IC_3=IC_3; +elseif type==3 % compute A*kron(B,B,B)*U with one precomputed index IC + varout1=sptensor; + if calculate_ind==1 + [IC_1,IC_2,IC_3] = AkronBU3IC_mex(l,m,n,IA,JA,IB,JB); + else + IC_1=ind.IC_1; + IC_2=ind.IC_2; + IC_3=ind.IC_3; + end + JCrows_1=IC_1(end)-1; + NA=A.vals; + NB=B.vals; + if ~isreal(NA) || ~isreal(NB) + error('complex numbers not supported') + end + [varout1.vals,JC_1] = AkronBU3vecI_mex(l,m,n,IA,JA,NA,... + IB,JB,NB,... + IC_1,IC_2,IC_3,JCrows_1,... + maxload,dosum); + varout1.ptr=IC_1; + varout1.cols=JC_1; + varout1.tsize=[l,nchoosek(n+2,3)]; + varout2.IC_1=IC_1; + varout2.IC_2=IC_2; + varout2.IC_3=IC_3; +elseif type==4 % compute A*kron(B,B,B)*U with two precomputed indices IC,JC + varout1=sptensor; + if calculate_ind==1 + [IC_1,IC_2,IC_3] = AkronBU3IC_mex(l,m,n,IA,JA,IB,JB); + JCrows_1=IC_1(end)-1; + JCrows_2=IC_2(end)-1; + JCrows_3=IC_3(end)-1; + [JC_1,JC_2,JC_3 ] = AkronBU3JC_mex( l,m,n,IA,JA,IB,JB,... + JCrows_1,JCrows_2,JCrows_3,IC_2,IC_3 ); + else + IC_1=ind.IC_1; + IC_2=ind.IC_2; + IC_3=ind.IC_3; + JC_1=ind.JC_1; + JC_2=ind.JC_2; + JC_3=ind.JC_3; + end + NA=A.vals; + NB=B.vals; + if ~isreal(NA) || ~isreal(NB) + error('complex numbers not supported') + end + varout1.vals = AkronBU3vec_mex(l,m,n,IA,JA,NA,... + IB,JB,NB,... + IC_1,JC_1,IC_2,JC_2,IC_3,JC_3,... + maxload,dosum); + varout1.ptr=IC_1; + varout1.cols=JC_1(:,1); % recall that JC_1 contains the compressed index in the first column and the corresponding indices in the other columns. + varout1.tsize=[l,nchoosek(n+2,3)]; + varout2.IC_1=IC_1; + varout2.IC_2=IC_2; + varout2.IC_3=IC_3; + varout2.JC_1=JC_1; + varout2.JC_2=JC_2; + varout2.JC_3=JC_3; +end + +if isfield(A,'ptr2d') % if the pointer of A is 2D varout is also 2D + varout1.ptr2d=A.ptr2d; +end + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/AkronBU4.m b/105/replication_package/solution_methods/taylor_projection/Tensors/AkronBU4.m new file mode 100644 index 0000000000000000000000000000000000000000..b5f78bd82f2228f0cb597420f5dbbbe154b52d14 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/AkronBU4.m @@ -0,0 +1,192 @@ +function [varout1,varout2]=AkronBU4(A,B,varargin) + %C=AkronBU4(A,B) calculates C=A*kron(B,B,B,B)*U. + %[C,ind]=AkronBU4(A,B,ind,1,maxload) calculates C using one precomputed + %index ind. If ind=[] the function returns ind. The option maxload controls + %the maximum number of flops performed in parallel by the simd. This is + %relevant only if A or B represent sets of s tensors. + %[C,ind]=AkronBU4(A,B,ind,2,maxload) calculates C using two precomputed + %indices ind. + %[C,ind]=AkronBU4(A,B,ind,1,maxload,'sum') sums across s if A + %or B represent sets of s tensors. This option is useful for calculating + %expected value of C. + %[C,ind]=AkronBU4(A,B,ind,2,maxload,'sum') is similar but uses two + %precomputed indices. + %ind=AkronBU4(A,B,1) returns a structure ind with one field + %to speed up calculation. + %ind=AkronBU4(A,B,2) returns a structure ind with two fields. Speedup + %is larger compared to one field, but requires more memory. + + if nargin<2 || nargin>6 + error('wrong number of input arguments') + end + + if A.tsize(2)~=B.tsize(1) + error('incompatible dimensions') + end + dosum=0; + if nargin==6 + if strcmp(varargin{4},'sum') + dosum=1; + elseif ~strcmp(varargin{4},'vec') + error(['sixth argument must be charater ' '''' 'sum' '''' ' or ' '''' 'vec' '''']) + end + end + if nargin==2 + type=0; % index is not available + maxload=intarray(1); + end + if nargin==3 + if varargin{1}==1 + type=1; + elseif varargin{1}==2 + type=2; + else + error('number of precomputed indices should be 1 or 2') + end + end + calculate_ind=0; + if nargin>=4 + if varargin{2}==1 + type=3; + elseif varargin{2}==2 + type=4; + else + error('number of precomputed indices should be 1 or 2') + end + if isempty(varargin{1}) + calculate_ind=1; + else + ind=varargin{1}; + if ~isa(ind,'struct') + error('index variable incorrectly defined') + end + if ~isfield(ind,'IC_1') + error('index variable incorrectly defined') + end + if varargin{2}==2 + if ~isfield(ind,'JC_1') + error('index variable incorrectly defined') + end + end + end + end + if nargin==4 + maxload=intarray(1); + elseif nargin>=4 + maxload=intarray(varargin{3}); + end + + l=A.tsize(1); + m=A.tsize(2); + if length(A.tsize)~=5 + error('columns must be 4D') + end + if A.tsize(3)~=m || A.tsize(4)~=m || A.tsize(5)~=m + error('columns are not symmetric') + end + n=B.tsize(2); + if B.colsorted~=1 + error('not sorted') + end + IA=A.ptr; + JA=A.cols; + IB=B.ptr; + JB=B.cols; + IB=B.ptr; + if type==0 % calculate A*kron(B,B,B,B)*U without precomputed index + varout1=sptensor; + [IC_1,IC_2,IC_3,IC_4] = AkronBU4IC_mex(l,m,n,IA,JA,IB,JB); + JCrows_1=IC_1(end)-1; + NA=A.vals; + NB=B.vals; + if ~isreal(NA) || ~isreal(NB) + error('complex numbers not supported') + end + [varout1.vals,JC_1] = AkronBU4vecI_mex(l,m,n,IA,JA,NA,... + IB,JB,NB,... + IC_1,IC_2,IC_3,IC_4,JCrows_1,... + maxload,dosum); + varout1.ptr=IC_1; + varout1.cols=JC_1; + varout1.tsize=[l,nchoosek(n+3,4)]; + elseif type==1 % compute IC + [varout1.IC_1,varout1.IC_2,varout1.IC_3,varout1.IC_4] = AkronBU4IC_mex(l,m,n,IA,JA,IB,JB); + elseif type==2 % compute IC and JC + [IC_1,IC_2,IC_3,IC_4] = AkronBU4IC_mex(l,m,n,IA,JA,IB,JB); + JCrows_1=IC_1(end)-1; + JCrows_2=IC_2(end)-1; + JCrows_3=IC_3(end)-1; + JCrows_4=IC_4(end)-1; + [ varout1.JC_1,varout1.JC_2,varout1.JC_3,varout1.JC_4 ] = AkronBU4JC_mex( l,m,n,IA,JA,IB,JB,JCrows_1,JCrows_2,JCrows_3,JCrows_4,IC_2,IC_3,IC_4); + varout1.IC_1=IC_1; + varout1.IC_2=IC_2; + varout1.IC_3=IC_3; + varout1.IC_4=IC_4; + elseif type==3 % compute A*kron(B,B,B,B)*U with one precomputed index IC + varout1=sptensor; + if calculate_ind==1 + [IC_1,IC_2,IC_3,IC_4] = AkronBU4IC_mex(l,m,n,IA,JA,IB,JB); + else + IC_1=ind.IC_1; + IC_2=ind.IC_2; + IC_3=ind.IC_3; + IC_4=ind.IC_4; + end + JCrows_1=IC_1(end)-1; + NA=A.vals; + NB=B.vals; + if ~isreal(NA) || ~isreal(NB) + error('complex numbers not supported') + end + [varout1.vals,JC_1] = AkronBU4vecI_mex(l,m,n,IA,JA,NA,... + IB,JB,NB,... + IC_1,IC_2,IC_3,IC_4,JCrows_1,... + maxload,dosum); + varout1.ptr=IC_1; + varout1.cols=JC_1; + varout1.tsize=[l,nchoosek(n+3,4)]; + varout2.IC_1=IC_1; + varout2.IC_2=IC_2; + varout2.IC_3=IC_3; + varout2.IC_4=IC_4; + elseif type==4 % compute A*kron(B4,B3,B2,B1) with two precomputed indices IC,JC + varout1=sptensor; + if calculate_ind==1 + [IC_1,IC_2,IC_3,IC_4] = AkronBU4IC_mex(l,m,n,IA,JA,IB,JB); + JCrows_1=IC_1(end)-1; + JCrows_2=IC_2(end)-1; + JCrows_3=IC_3(end)-1; + JCrows_4=IC_4(end)-1; + [ JC_1,JC_2,JC_3,JC_4 ] = AkronBU4JC_mex( l,m,n,IA,JA,IB,JB,JCrows_1,JCrows_2,JCrows_3,JCrows_4,IC_2,IC_3,IC_4); + else + IC_1=ind.IC_1; + IC_2=ind.IC_2; + IC_3=ind.IC_3; + IC_4=ind.IC_4; + JC_1=ind.JC_1; + JC_2=ind.JC_2; + JC_3=ind.JC_3; + JC_4=ind.JC_4; + end + NA=A.vals; + NB=B.vals; + if ~isreal(NA) || ~isreal(NB) + error('complex numbers not supported') + end + varout1.vals = AkronBU4vec_mex(l,m,n,IA,JA,NA,... + IB,JB,NB,... + IC_1,JC_1,IC_2,JC_2,IC_3,JC_3,IC_4,JC_4,... + maxload,dosum); + varout1.ptr=IC_1; + varout1.cols=JC_1(:,1); + varout1.tsize=[l,nchoosek(n+3,4)]; + varout2.IC_1=IC_1; + varout2.IC_2=IC_2; + varout2.IC_3=IC_3; + varout2.IC_4=IC_4; + varout2.JC_1=JC_1; + varout2.JC_2=JC_2; + varout2.JC_3=JC_3; + varout2.JC_4=JC_4; + end +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/AkronBU4i.m b/105/replication_package/solution_methods/taylor_projection/Tensors/AkronBU4i.m new file mode 100644 index 0000000000000000000000000000000000000000..bda7493c72581eb41957e94ae705f5595b6eec00 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/AkronBU4i.m @@ -0,0 +1,139 @@ +function [varout1,varout2]=AkronBU4i(A,B,ind,n_ind,maxload,dosum,convertind,maxind) +%calculate C=A*kron(B,B,B,B)*U, row by row. Like AkronBU4 but more memory +%efficient. +%[C,ind]=AkronBU4i(A,B,ind,n_ind,maxload,dosum,convertind,maxind). +%convertind is a l-by-m matrix. Each row records the variables that have a +%nonzero effect on A. maxind is the maximum number of such variables across +%rows. +% +% � Copyright, Oren Levintal, June 13, 2016. +% changed on January 20, 2017 (argin check for convertind was added) +if A.tsize(2)~=B.tsize(1) + error('incompatible dimensions') +end +if size(convertind,1)~=A.tsize(1) || size(convertind,2)~=B.tsize(1) + error('wrong conversion index') +end +if strcmp(dosum,'sum') + dosum=1; +elseif strcmp(dosum,'vec') + dosum=0; +else + error(['sixth argument must be charater ' '''' 'sum' '''' ' or ' '''' 'vec' '''']) +end + +maxload=intarray(min(1,maxload)); +maxind=intarray(maxind); +convertind=intarray(convertind); + +if n_ind==1 + type=3; +elseif n_ind==2 + type=4; +else + error('number of precomputed indices should be 1 or 2') +end + +calculate_ind=0; + +if isempty(ind) + calculate_ind=1; +else + if ~isa(ind,'struct') + error('index variable incorrectly defined') + end + if ~isfield(ind,'IC_1') + error('index variable incorrectly defined') + end + if n_ind==2 + if ~isfield(ind,'JC_1') + error('index variable incorrectly defined') + end + end +end + +l=A.tsize(1); +m=A.tsize(2); +if length(A.tsize)~=5 + error('columns must be 4D') +end +if A.tsize(3)~=m || A.tsize(4)~=m || A.tsize(5)~=m + error('columns are not symmetric') +end +n=B.tsize(2); +if B.colsorted~=1 + error('not sorted') +end +IA=A.ptr; +JA=A.cols; +IB=B.ptr; +JB=B.cols; + +if type==3 % compute A*kron(B,B,B,B)*U with one precomputed index IC + varout1=sptensor; + if calculate_ind==1 + [IC_1,IC_2,IC_3,IC_4] = AkronBU4iIC_mex(l,m,n,IA,JA,IB,JB,convertind,maxind); + else + IC_1=ind.IC_1; + IC_2=ind.IC_2; + IC_3=ind.IC_3; + IC_4=ind.IC_4; + end + JCrows_1=IC_1(end)-1; + NA=A.vals; + NB=B.vals; + if ~isreal(NA) || ~isreal(NB) + error('complex numbers not supported') + end + [varout1.vals,JC_1] = AkronBU4ivecI_mex(l,m,n,IA,JA,NA,... + IB,JB,NB,... + IC_1,IC_2,IC_3,IC_4,JCrows_1,... + maxload,dosum,convertind,maxind); + varout1.ptr=IC_1; + varout1.cols=JC_1; + varout1.tsize=[l,nchoosek(n+3,4)]; + varout2.IC_1=IC_1; + varout2.IC_2=IC_2; + varout2.IC_3=IC_3; + varout2.IC_4=IC_4; +elseif type==4 % compute A*kron(B4,B3,B2,B1) with two precomputed indices IC,JC + varout1=sptensor; + if calculate_ind==1 + [IC_1,IC_2,IC_3,IC_4] = AkronBU4iIC_mex(l,m,n,IA,JA,IB,JB,convertind,maxind); + JCrows_1=IC_1(end)-1; + JCrows_2=IC_2(end)-1; + JCrows_3=IC_3(end)-1; + JCrows_4=IC_4(end)-1; + [ JC_1,JC_2,JC_3,JC_4 ] = AkronBU4iJC_mex( l,m,n,IA,JA,IB,JB,JCrows_1,JCrows_2,JCrows_3,JCrows_4,IC_2,IC_3,IC_4,convertind,maxind); + else + IC_1=ind.IC_1; + IC_2=ind.IC_2; + IC_3=ind.IC_3; + IC_4=ind.IC_4; + JC_1=ind.JC_1; + JC_2=ind.JC_2; + JC_3=ind.JC_3; + JC_4=ind.JC_4; + end + NA=A.vals; + NB=B.vals; + if ~isreal(NA) || ~isreal(NB) + error('complex numbers not supported') + end + varout1.vals = AkronBU4ivec_mex(l,m,n,IA,JA,NA,... + IB,JB,NB,... + IC_1,JC_1,IC_2,JC_2,IC_3,JC_3,IC_4,JC_4,... + maxload,dosum,convertind,maxind); + varout1.ptr=IC_1; + varout1.cols=JC_1(:,1); + varout1.tsize=[l,nchoosek(n+3,4)]; + varout2.IC_1=IC_1; + varout2.IC_2=IC_2; + varout2.IC_3=IC_3; + varout2.IC_4=IC_4; + varout2.JC_1=JC_1; + varout2.JC_2=JC_2; + varout2.JC_3=JC_3; + varout2.JC_4=JC_4; +end +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/changecols.m b/105/replication_package/solution_methods/taylor_projection/Tensors/changecols.m new file mode 100644 index 0000000000000000000000000000000000000000..0dedf3ed6409b6c63b4663c9041374f93a20a285 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/changecols.m @@ -0,0 +1,10 @@ +function [A]=changecols(A,newcols,coldim,coli) +%Change the cols of tensor A +% +% � Copyright, Oren Levintal, June 13, 2016. + +newcols=intarray(newcols); +A.cols(:,coli)=newcols(A.cols(:,coli)); +A.tsize(coli+1)=intarray(coldim); + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/changerows.m b/105/replication_package/solution_methods/taylor_projection/Tensors/changerows.m new file mode 100644 index 0000000000000000000000000000000000000000..1c3e6ccd34b3a18d5b8dbad4c0936c35bd411f27 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/changerows.m @@ -0,0 +1,15 @@ +function [A]=changerows(A,newrows,rowdim) +%Change the rows of tensor A +% +% � Copyright, Oren Levintal, June 13, 2016. + +if isfield(A,'ptr2d') + error('2D pointer not supported') +end +rowcount=zeros(rowdim,1); +rowcount(newrows)=diff(A.ptr); +A.ptr=intarray(cumsum([1;rowcount])); +A.tsize(1)=intarray(rowdim); + + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/col2ptr.m b/105/replication_package/solution_methods/taylor_projection/Tensors/col2ptr.m new file mode 100644 index 0000000000000000000000000000000000000000..af87d8bf36e74c0247a709898a90fb1e24e67f60 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/col2ptr.m @@ -0,0 +1,27 @@ +function [ R ] = col2ptr( ten,colptr ) +%A=col2ptr(A,j) converts the pointer of A into a 2D pointer. +%A sparse tensor of size l,m1,m2,..,mk has a pointer for the row dimension +%l. This function makes a pointer for l,mj, which is similar to permuting +%and reshaping the tensor to size l*mj,m1,m2,..,mj-1,mj+1,..,mk. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if size(ten.ptr,2)>1 + error('pointer must be 1D') +end +l=ten.tsize(1); +coldim=ten.tsize(2:end); +colptr=intarray(colptr); +ptrcoldim=coldim(colptr)+1; + +[ newptr,newcols,newvals ] = col2ptr_mex( ten.ptr,ten.cols,ten.vals,l,coldim,colptr,ptrcoldim ); + +R=sptensor; +R.ptr=newptr; +R.cols=newcols; +R.vals=newvals; +R.tsize=[l,coldim(colptr),coldim(1:colptr-1),coldim(colptr+1:end)]; +R.ptr2d=R.tsize(1:2); + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/colsort.m b/105/replication_package/solution_methods/taylor_projection/Tensors/colsort.m new file mode 100644 index 0000000000000000000000000000000000000000..2dc93e584ce9db5283e8ffb8c7f1328d30cbb3c0 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/colsort.m @@ -0,0 +1,37 @@ +function [ A,index ] = colsort( ten,varargin ) +%sorts tensor columns +% +% � Copyright, Oren Levintal, June 13, 2016. + +if size(ten.ptr,2)>1 + error('2D ptr not supported') +end + +if nargin==2 + index=varargin{1}; +elseif nargin==1 + index=[]; +end + + +if isempty(index) % sorting index is not available + if nargout==2 % regular sort with an index + [i,j]=tfind(ten); + [sortij,index]=sortrows([i,j]); + A=sptensor(sortij(:,1),sortij(:,2:end),ten.vals(:,index),ten.tsize(1),ten.tsize(2:end)); + elseif nargout==1 % a mex sort without index + for coli=length(ten.tsize)-1:-1:1 % sort each col dimension + [ ten.cols,ten.vals ] = sortcol_mex( ten.ptr,ten.cols,ten.vals,ten.tsize(1),ten.tsize(2:end),intarray(coli),ten.tsize(coli+1) ); + end + A=ten; + end +else % sorting index is available + A=ten; + A.vals=ten.vals(:,index); + A.cols=ten.cols(index,:); +end + +A.colsorted=1; + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/contraction1.m b/105/replication_package/solution_methods/taylor_projection/Tensors/contraction1.m new file mode 100644 index 0000000000000000000000000000000000000000..247e11ade0a491ad8621b8e1816ff307e9cf033f --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/contraction1.m @@ -0,0 +1,206 @@ +function [varout1,varout2]=contraction1(A,B1,varargin) +%C=contraction1(A,B1) calculates C=A*B1. +%[C,ind]=contraction1(A,B1,ind,1,maxload) calculates C=A*B1 using one precomputed +%index ind. If ind=[] the function returns ind. The option maxload controls +%the maximum number of flops performed in parallel by the simd. This is +%relevant only if A or B1 represent sets of s tensors. +%[C,ind]=contraction1(A,B1,ind,2,maxload) calculates C=A*B1 using two precomputed +%indices ind. +%[C,ind]=contraction1(A,B1,ind,1,maxload,'sum') sums across s if A or B1 +%represent sets of s tensors. This option is useful for calculating +%expected value of C. +%[C,ind]=contraction1(A,B1,ind,2,maxload,'sum') is similar but uses two +%precomputed indices. +%ind=contraction1(A,B1,1) returns a structure ind with one field +%to speed up calculation. +%ind=contraction1(A,B1,2) returns a structure ind with two fields. Speedup +%is larger compared to one field, but requires more memory. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if nargin<2 || nargin>6 + error('wrong number of input arguments') +end + +if A.tsize(2)~=B1.tsize(1) + error('incompatible dimensions') +end +if size(A.ptr,2)>1 + error('use ptr1d to convert A to 1D') +end +dosum=0; +if nargin==6 + if strcmp(varargin{4},'sum') + dosum=1; + elseif ~strcmp(varargin{4},'vec') + error(['sixth argument must be charater ' '''' 'sum' '''' ' or ' '''' 'vec' '''']) + end +end +if nargin==2 + type=0; % index is not available + maxload=intarray(1); +end +if nargin==3 + if varargin{1}==1 + type=1; + elseif varargin{1}==2 + type=2; + else + error('number of precomputed indices should be 1 or 2') + end +end +calculate_ind=0; +if nargin>=4 + if varargin{2}==1 + type=3; + elseif varargin{2}==2 + type=4; + else + error('number of precomputed indices should be 1 or 2') + end + if isempty(varargin{1}) + calculate_ind=1; + else + ind=varargin{1}; + if ~isa(ind,'struct') + error('index variable incorrectly defined') + end + if ~isfield(ind,'IC_1') + error('index variable incorrectly defined') + end + if varargin{2}==2 + if ~isfield(ind,'JC_1') + error('index variable incorrectly defined') + end + end + end +end +if nargin==4 + maxload=intarray(1); +elseif nargin>=5 + maxload=intarray(varargin{3}); +end + +l=A.tsize(1); +n1=B1.tsize(2); +IA=A.ptr; +JA1=A.cols; +IB1=B1.ptr; +JB1=B1.cols; + +ptr2D=0; +if size(B1.ptr,2)>1 + ptr2D=1; + n1=B1.tsize(3); +end + +if type==0 % calculate A*B1 without precomputed index + varout1=sptensor; + [ IC_1 ] = contraction1IC_mex( l,n1,IA,JA1,IB1,JB1 ); + JCrows_1=IC_1(end)-1; + NA=A.vals; + NB1=B1.vals; + if ~isreal(NA) || ~isreal(NB1) + error('complex numbers not supported') + end + [varout1.vals,JC1_1] = contraction1vecI_mex( l,n1,IA,JA1,NA,IB1,JB1,NB1,IC_1,JCrows_1,maxload,dosum); + varout1.ptr=IC_1; + varout1.cols=JC1_1; + varout1.tsize=[l,n1]; +elseif type==1 % compute IC_1 + if ptr2D==0 + [ varout1.IC_1 ] = contraction1IC_mex( l,n1,IA,JA1,IB1,JB1 ); + else + [ varout1.IC_1 ] = contraction1IC2D_mex( l,n1,IA,JA1,IB1,JB1 ); + end +elseif type==2 % compute IC_1 and JC_1 + if ptr2D==0 + [ IC_1 ] = contraction1IC_mex( l,n1,IA,JA1,IB1,JB1 ); + JCrows_1=IC_1(end)-1; + [ JC_1 ] = contraction1JC_mex( l,n1,IA,JA1,IB1,JB1,JCrows_1 ); + else + [ IC_1 ] = contraction1IC2D_mex( l,n1,IA,JA1,IB1,JB1 ); + JCrows_1=IC_1(end)-1; + [ JC_1 ] = contraction1JC2D_mex( l,n1,IA,JA1,IB1,JB1,JCrows_1 ); + end + varout1.IC_1=IC_1; + varout1.JC_1=JC_1; +elseif type==3 % compute A*B1 with one precomputed index IC + varout1=sptensor; + if calculate_ind==1 + if ptr2D==0 + [ IC_1 ] = contraction1IC_mex( l,n1,IA,JA1,IB1,JB1 ); + else + [ IC_1 ] = contraction1IC2D_mex( l,n1,IA,JA1,IB1,JB1 ); + end + else + IC_1=ind.IC_1; + end + JCrows_1=IC_1(end)-1; + NA=A.vals; + NB1=B1.vals; + if ~isreal(NA) || ~isreal(NB1) + error('complex numbers not supported') + end + if ptr2D==0 + [varout1.vals,JC_1] = contraction1vecI_mex( l,n1,IA,JA1,NA,IB1,JB1,NB1,IC_1,JCrows_1,maxload,dosum); + varout1.tsize=[l,n1]; + varout1.ptr=IC_1; + varout1.cols=JC_1; + varout2.IC_1=IC_1; + else + [varout1.vals,JC_1] = contraction1vecI2D_mex( l,n1,IA,JA1,NA,IB1,JB1,NB1,IC_1,JCrows_1,maxload,dosum); + varout1.tsize=intarray([l,B1.tsize(2),n1]); + varout1.ptr=IC_1; + varout1.cols=JC_1; + varout1.ptr2d=varout1.tsize(1:2); + varout2.IC_1=IC_1; + end +elseif type==4 % compute A*B1 with two precomputed indices IC,JC + varout1=sptensor; + if calculate_ind==1 + if ptr2D==0 + [ IC_1 ] = contraction1IC_mex( l,n1,IA,JA1,IB1,JB1 ); + JCrows_1=IC_1(end)-1; + [ JC_1 ] = contraction1JC_mex( l,n1,IA,JA1,IB1,JB1,JCrows_1 ); + else + [ IC_1 ] = contraction1IC2D_mex( l,n1,IA,JA1,IB1,JB1 ); + JCrows_1=IC_1(end)-1; + [ JC_1 ] = contraction1JC2D_mex( l,n1,IA,JA1,IB1,JB1,JCrows_1 ); + end + else + IC_1=ind.IC_1; + JC_1=ind.JC_1; + end + NA=A.vals; + NB1=B1.vals; + if ~isreal(NA) || ~isreal(NB1) + error('complex numbers not supported') + end + if ptr2D==0 + varout1.vals = contraction1vec_mex( l,n1,IA,JA1,NA,IB1,JB1,NB1,IC_1,JC_1,maxload,dosum); + varout1.ptr=IC_1; + varout1.cols=JC_1; + varout1.tsize=[l,n1]; + varout2.IC_1=IC_1; + varout2.JC_1=JC_1; + else + [varout1.vals] = contraction1vec2D_mex( l,n1,IA,JA1,NA,IB1,JB1,NB1,IC_1,JC_1,maxload,dosum); + varout1.tsize=intarray([l,B1.tsize(2),n1]); + varout1.ptr=IC_1; + varout1.cols=JC_1; + varout1.ptr2d=varout1.tsize(1:2); + varout2.IC_1=IC_1; + varout2.JC_1=JC_1; + end +end + +if isfield(A,'ptr2d') % if the pointer of A is 2D varout is also 2D + if isfield(varout1,'ptr2d') + varout1.ptr2d=[A.ptr2d,varout1.ptr2d(2)]; + else + varout1.ptr2d=[A.ptr2d]; + end +end + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/contraction2.m b/105/replication_package/solution_methods/taylor_projection/Tensors/contraction2.m new file mode 100644 index 0000000000000000000000000000000000000000..23d9df8a6a6dfe27b50e044b3ca5aaeeb23b3a9e --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/contraction2.m @@ -0,0 +1,172 @@ +function [varout1,varout2]=contraction2(A,B2,B1,varargin) +%C=contraction2(A,B2,B1) calculates C=A*kron(B2,B1). +%[C,ind]=contraction2(A,B2,B1,ind,1,maxload) calculates C using one precomputed +%index ind. If ind=[] the function returns ind. The option maxload controls +%the maximum number of flops performed in parallel by the simd. This is +%relevant only if A or B1,B2 represent sets of s tensors. +%[C,ind]=contraction2(A,B2,B1,ind,2,maxload) calculates C using two precomputed +%indices ind. +%[C,ind]=contraction2(A,B2,B1,ind,1,maxload,'sum') sums across s if A +%or B1,B2 represent sets of s tensors. This option is useful for calculating +%expected value of C. +%[C,ind]=contraction2(A,B2,B1,ind,2,maxload,'sum') is similar but uses two +%precomputed indices. +%ind=contraction2(A,B2,B1,1) returns a structure ind with one field +%to speed up calculation. +%ind=contraction2(A,B2,B1,2) returns a structure ind with two fields. Speedup +%is larger compared to one field, but requires more memory. +% +% � Copyright, Oren Levintal, June 13, 2016. + +varout2=[]; +if nargin<3 || nargin>7 + error('wrong number of input arguments') +end + +if A.tsize(2)~=B1.tsize(1) || A.tsize(3)~=B2.tsize(1) + error('incompatible dimensions') +end +dosum=0; +if nargin==7 + if strcmp(varargin{4},'sum') + dosum=1; + elseif ~strcmp(varargin{4},'vec') + error(['seventh argument must be charater ' '''' 'sum' '''' ' or ' '''' 'vec' '''']) + end +end +if nargin==3 + type=0; % index is not available + maxload=intarray(1); +end +if nargin==4 + if varargin{1}==1 + type=1; + elseif varargin{1}==2 + type=2; + else + error('number of precomputed indices should be 1 or 2') + end +end +calculate_ind=0; +if nargin>=5 + if varargin{2}==1 + type=3; + elseif varargin{2}==2 + type=4; + else + error('number of precomputed indices should be 1 or 2') + end + if isempty(varargin{1}) + calculate_ind=1; + else + ind=varargin{1}; + if ~isa(ind,'struct') + error('index variable incorrectly defined') + end + if ~isfield(ind,'IC_1') + error('index variable incorrectly defined') + end + if varargin{2}==2 + if ~isfield(ind,'JC_1') + error('index variable incorrectly defined') + end + end + end +end +if nargin==5 + maxload=intarray(1); +elseif nargin>=5 + maxload=intarray(varargin{3}); +end + +l=A.tsize(1); +m1=A.tsize(2); +n1=B1.tsize(2); +n2=B2.tsize(2); +IA=A.ptr; +JA=A.cols; +IB1=B1.ptr; +JB1=B1.cols; +IB2=B2.ptr; +JB2=B2.cols; +if type==0 % calculate A*kron(B2,B1) without precomputed index + varout1=sptensor; + [IC_1,IC_2] = contraction2IC_mex(l,m1,n1,n2,IA,JA,IB1,JB1,IB2,JB2); + JCrows_1=IC_1(end)-1; + NA=A.vals; + NB1=B1.vals; + NB2=B2.vals; + if ~isreal(NA) || ~isreal(NB1) || ~isreal(NB2) + error('complex numbers not supported') + end + [varout1.vals,JC_1] = contraction2vecI_mex( l,m1,n1,n2,IA,JA,NA,IB1,... + JB1,NB1,IB2,JB2,NB2,IC_1,IC_2,JCrows_1,maxload,dosum); + varout1.ptr=IC_1; + varout1.cols=JC_1; + varout1.tsize=[l,n1,n2]; +elseif type==1 % compute IC + [varout1.IC_1,varout1.IC_2] = contraction2IC_mex(l,m1,n1,n2,IA,JA,IB1,JB1,IB2,JB2); +elseif type==2 % compute IC and JC + [IC_1,IC_2] = contraction2IC_mex(l,m1,n1,n2,IA,JA,IB1,JB1,IB2,JB2); + JCrows_1=IC_1(end)-1; + JCrows_2=IC_2(end)-1; + [ varout1.JC_1,varout1.JC_2 ] = contraction2JC_mex( l,m1,n1,n2,IA,JA,IB1,JB1,IB2,JB2,JCrows_1,JCrows_2,IC_2 ); + varout1.IC_1=IC_1; + varout1.IC_2=IC_2; +elseif type==3 % compute A*kron(B2,B1) with one precomputed index IC + varout1=sptensor; + if calculate_ind==1 + [IC_1,IC_2] = contraction2IC_mex(l,m1,n1,n2,IA,JA,IB1,JB1,IB2,JB2); + else + IC_1=ind.IC_1; + IC_2=ind.IC_2; + end + JCrows_1=IC_1(end)-1; + NA=A.vals; + NB1=B1.vals; + NB2=B2.vals; + if ~isreal(NA) || ~isreal(NB1) || ~isreal(NB2) + error('complex numbers not supported') + end + [varout1.vals,JC_1] = contraction2vecI_mex( l,m1,n1,n2,IA,JA,NA,IB1,... + JB1,NB1,IB2,JB2,NB2,IC_1,IC_2,JCrows_1,maxload,dosum); + varout1.ptr=IC_1; + varout1.cols=JC_1; + varout1.tsize=[l,n1,n2]; + varout2.IC_1=IC_1; + varout2.IC_2=IC_2; +elseif type==4 % compute A*kron(B2,B1) with two precomputed indices IC,JC + varout1=sptensor; + if calculate_ind==1 + [IC_1,IC_2] = contraction2IC_mex(l,m1,n1,n2,IA,JA,IB1,JB1,IB2,JB2); + JCrows_1=IC_1(end)-1; + JCrows_2=IC_2(end)-1; + [ JC_1,JC_2 ] = contraction2JC_mex( l,m1,n1,n2,IA,JA,IB1,JB1,IB2,JB2,JCrows_1,JCrows_2,IC_2 ); + else + IC_1=ind.IC_1; + IC_2=ind.IC_2; + JC_1=ind.JC_1; + JC_2=ind.JC_2; + end + NA=A.vals; + NB1=B1.vals; + NB2=B2.vals; + if ~isreal(NA) || ~isreal(NB1) || ~isreal(NB2) + error('complex numbers not supported') + end + varout1.vals = contraction2vec_mex( l,m1,n1,n2,IA,JA,NA,IB1,... + JB1,NB1,IB2,JB2,NB2,IC_1,JC_1,IC_2,JC_2,maxload,dosum); + varout1.ptr=IC_1; + varout1.cols=JC_1; + varout1.tsize=[l,n1,n2]; + varout2.IC_1=IC_1; + varout2.IC_2=IC_2; + varout2.JC_1=JC_1; + varout2.JC_2=JC_2; +end + +if isfield(A,'ptr2d') % if the pointer of A is 2D varout is also 2D + varout1.ptr2d=A.ptr2d; +end + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/contraction3.m b/105/replication_package/solution_methods/taylor_projection/Tensors/contraction3.m new file mode 100644 index 0000000000000000000000000000000000000000..ad4373811d37c7682b7b1cfcdb60d7d8655a667c --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/contraction3.m @@ -0,0 +1,195 @@ +function [varout1,varout2]=contraction3(A,B3,B2,B1,varargin) +%C=contraction3(A,B3,B2,B1) calculates C=A*kron(B3,B2,B1). +%[C,ind]=contraction3(A,B3,B2,B1,ind,1,maxload) calculates C using one precomputed +%index ind. If ind=[] the function returns ind. The option maxload controls +%the maximum number of flops performed in parallel by the simd. This is +%relevant only if A or B1,B2,B3 represent sets of s tensors. +%[C,ind]=contraction3(A,B3,B2,B1,ind,2,maxload) calculates C using two precomputed +%indices ind. +%[C,ind]=contraction3(A,B3,B2,B1,ind,1,maxload,'sum') sums across s if A +%or B1,B2 represent sets of s tensors. This option is useful for calculating +%expected value of C. +%[C,ind]=contraction3(A,B3,B2,B1,ind,2,maxload,'sum') is similar but uses two +%precomputed indices. +%ind=contraction3(A,B3,B2,B1,1) returns a structure ind with one field +%to speed up calculation. +%ind=contraction3(A,B3,B2,B1,2) returns a structure ind with two fields. Speedup +%is larger compared to one field, but requires more memory. +% +% � Copyright, Oren Levintal, June 13, 2016. + +varout1=[]; varout2=[]; + +if nargin<4 || nargin>8 + error('wrong number of input arguments') +end + +if A.tsize(2)~=B1.tsize(1) || A.tsize(3)~=B2.tsize(1) || A.tsize(4)~=B3.tsize(1) + error('incompatible dimensions') +end +dosum=0; +if nargin==8 + if strcmp(varargin{4},'sum') + dosum=1; + elseif ~strcmp(varargin{4},'vec') + error(['eighth argument must be charater ' '''' 'sum' '''' ' or ' '''' 'vec' '''']) + end +end +if nargin==4 + type=0; % index is not available + maxload=intarray(1); +end +if nargin==5 + if varargin{1}==1 + type=1; + elseif varargin{1}==2 + type=2; + else + error('number of precomputed indices should be 1 or 2') + end +end +calculate_ind=0; +if nargin>=6 + if varargin{2}==1 + type=3; + elseif varargin{2}==2 + type=4; + else + error('number of precomputed indices should be 1 or 2') + end + if isempty(varargin{1}) + calculate_ind=1; + else + ind=varargin{1}; + if ~isa(ind,'struct') + error('index variable incorrectly defined') + end + if ~isfield(ind,'IC_1') + error('index variable incorrectly defined') + end + if varargin{2}==2 + if ~isfield(ind,'JC_1') + error('index variable incorrectly defined') + end + end + end +end +if nargin==6 + maxload=intarray(1); +elseif nargin>=6 + maxload=intarray(varargin{3}); +end + +l=A.tsize(1); +m1=A.tsize(2); +m2=A.tsize(3); +n1=B1.tsize(2); +n2=B2.tsize(2); +n3=B3.tsize(2); +IA=A.ptr; +JA=A.cols; +IB1=B1.ptr; +JB1=B1.cols; +IB2=B2.ptr; +JB2=B2.cols; +IB3=B3.ptr; +JB3=B3.cols; +if type==0 % calculate A*kron(B3,B2,B1) without precomputed index + varout1=sptensor; + [IC_1,IC_2,IC_3] = contraction3IC_mex(l,m1,m2,n1,n2,n3,IA,JA,IB1,JB1,IB2,JB2,IB3,JB3); + JCrows_1=IC_1(end)-1; + NA=A.vals; + NB1=B1.vals; + NB2=B2.vals; + NB3=B3.vals; + if ~isreal(NA) || ~isreal(NB1) || ~isreal(NB2) || ~isreal(NB3) + error('complex numbers not supported') + end + [varout1.vals,JC_1] = contraction3vecI_mex(l,m1,m2,n1,n2,n3,IA,JA,NA,... + IB1,JB1,NB1,IB2,JB2,NB2,IB3,JB3,NB3,... + IC_1,IC_2,IC_3,JCrows_1,... + maxload,dosum); + varout1.ptr=IC_1; + varout1.cols=JC_1; + varout1.tsize=[l,n1,n2,n3]; +elseif type==1 % compute IC + [varout1.IC_1,varout1.IC_2,varout1.IC_3] = contraction3IC_mex(l,m1,m2,n1,n2,n3,IA,JA,IB1,JB1,IB2,JB2,IB3,JB3); +elseif type==2 % compute IC and JC + [IC_1,IC_2,IC_3] = contraction3IC_mex(l,m1,m2,n1,n2,n3,IA,JA,IB1,JB1,IB2,JB2,IB3,JB3); + JCrows_1=IC_1(end)-1; + JCrows_2=IC_2(end)-1; + JCrows_3=IC_3(end)-1; + [ varout1.JC_1,varout1.JC_2,varout1.JC_3 ] = contraction3JC_mex( l,m1,m2,n1,n2,n3,IA,JA,IB1,JB1,IB2,JB2,IB3,JB3,... + JCrows_1,JCrows_2,JCrows_3,IC_2,IC_3 ); + varout1.IC_1=IC_1; + varout1.IC_2=IC_2; + varout1.IC_3=IC_3; +elseif type==3 % compute A*kron(B3,B2,B1) with one precomputed index IC + varout1=sptensor; + if calculate_ind==1 + [IC_1,IC_2,IC_3] = contraction3IC_mex(l,m1,m2,n1,n2,n3,IA,JA,IB1,JB1,IB2,JB2,IB3,JB3); + else + IC_1=ind.IC_1; + IC_2=ind.IC_2; + IC_3=ind.IC_3; + end + JCrows_1=IC_1(end)-1; + NA=A.vals; + NB1=B1.vals; + NB2=B2.vals; + NB3=B3.vals; + if ~isreal(NA) || ~isreal(NB1) || ~isreal(NB2) || ~isreal(NB3) + error('complex numbers not supported') + end + [varout1.vals,JC_1] = contraction3vecI_mex(l,m1,m2,n1,n2,n3,IA,JA,NA,... + IB1,JB1,NB1,IB2,JB2,NB2,IB3,JB3,NB3,... + IC_1,IC_2,IC_3,JCrows_1,... + maxload,dosum); + varout1.ptr=IC_1; + varout1.cols=JC_1; + varout1.tsize=[l,n1,n2,n3]; + varout2.IC_1=IC_1; + varout2.IC_2=IC_2; + varout2.IC_3=IC_3; +elseif type==4 % compute A*kron(B3,B2,B1) with two precomputed indices IC,JC + varout1=sptensor; + if calculate_ind==1 + [IC_1,IC_2,IC_3] = contraction3IC_mex(l,m1,m2,n1,n2,n3,IA,JA,IB1,JB1,IB2,JB2,IB3,JB3); + JCrows_1=IC_1(end)-1; + JCrows_2=IC_2(end)-1; + JCrows_3=IC_3(end)-1; + [JC_1,JC_2,JC_3 ] = contraction3JC_mex( l,m1,m2,n1,n2,n3,IA,JA,IB1,JB1,IB2,JB2,IB3,JB3,... + JCrows_1,JCrows_2,JCrows_3,IC_2,IC_3 ); + else + IC_1=ind.IC_1; + IC_2=ind.IC_2; + IC_3=ind.IC_3; + JC_1=ind.JC_1; + JC_2=ind.JC_2; + JC_3=ind.JC_3; + end + NA=A.vals; + NB1=B1.vals; + NB2=B2.vals; + NB3=B3.vals; + if ~isreal(NA) || ~isreal(NB1) || ~isreal(NB2) || ~isreal(NB3) + error('complex numbers not supported') + end + varout1.vals = contraction3vec_mex(l,m1,m2,n1,n2,n3,IA,JA,NA,... + IB1,JB1,NB1,IB2,JB2,NB2,IB3,JB3,NB3,... + IC_1,JC_1,IC_2,JC_2,IC_3,JC_3,... + maxload,dosum); + varout1.ptr=IC_1; + varout1.cols=JC_1; + varout1.tsize=[l,n1,n2,n3]; + varout2.IC_1=IC_1; + varout2.IC_2=IC_2; + varout2.IC_3=IC_3; + varout2.JC_1=JC_1; + varout2.JC_2=JC_2; + varout2.JC_3=JC_3; +end +if isfield(A,'ptr2d') % if the pointer of A is 2D varout is also 2D + varout1.ptr2d=A.ptr2d; +end +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/contraction4.m b/105/replication_package/solution_methods/taylor_projection/Tensors/contraction4.m new file mode 100644 index 0000000000000000000000000000000000000000..20e3e555e33d4de6b86bf25d8639492963b3f521 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/contraction4.m @@ -0,0 +1,205 @@ +function [varout1,varout2]=contraction4(A,B4,B3,B2,B1,varargin) +%C=contraction4(A,B4,B3,B2,B1) calculates C=A*kron(B4,B3,B2,B1). +%[C,ind]=contraction4(A,B4,B3,B2,B1,ind,1,maxload) calculates C using one precomputed +%index ind. If ind=[] the function returns ind. The option maxload controls +%the maximum number of flops performed in parallel by the simd. This is +%relevant only if A or B1,B2,B3,B4 represent sets of s tensors. +%[C,ind]=contraction4(A,B4,B3,B2,B1,ind,2,maxload) calculates C using two precomputed +%indices ind. +%[C,ind]=contraction4(A,B4,B3,B2,B1,ind,1,maxload,'sum') sums across s if A +%or B1,B2 represent sets of s tensors. This option is useful for calculating +%expected value of C. +%[C,ind]=contraction4(A,B4,B3,B2,B1,ind,2,maxload,'sum') is similar but uses two +%precomputed indices. +%ind=contraction4(A,B4,B3,B2,B1,1) returns a structure ind with one field +%to speed up calculation. +%ind=contraction4(A,B4,B3,B2,B1,2) returns a structure ind with two fields. Speedup +%is larger compared to one field, but requires more memory. + +if nargin<5 || nargin>9 + error('wrong number of input arguments') +end + +if A.tsize(2)~=B1.tsize(1) || A.tsize(3)~=B2.tsize(1) || A.tsize(4)~=B3.tsize(1) + error('incompatible dimensions') +end +dosum=0; +if nargin==9 + if strcmp(varargin{4},'sum') + dosum=1; + elseif ~strcmp(varargin{4},'vec') + error(['ninth argument must be charater ' '''' 'sum' '''' ' or ' '''' 'vec' '''']) + end +end +if nargin==5 + type=0; % index is not available + maxload=intarray(1); +end +if nargin==6 + if varargin{1}==1 + type=1; + elseif varargin{1}==2 + type=2; + else + error('number of precomputed indices should be 1 or 2') + end +end +calculate_ind=0; +if nargin>=7 + if varargin{2}==1 + type=3; + elseif varargin{2}==2 + type=4; + else + error('number of precomputed indices should be 1 or 2') + end + if isempty(varargin{1}) + calculate_ind=1; + else + ind=varargin{1}; + if ~isa(ind,'struct') + error('index variable incorrectly defined') + end + if ~isfield(ind,'IC_1') + error('index variable incorrectly defined') + end + if varargin{2}==2 + if ~isfield(ind,'JC_1') + error('index variable incorrectly defined') + end + end + end +end +if nargin==7 + maxload=intarray(1); +elseif nargin>=7 + maxload=intarray(varargin{3}); +end + +l=A.tsize(1); +m1=A.tsize(2); +m2=A.tsize(3); +m3=A.tsize(4); +n1=B1.tsize(2); +n2=B2.tsize(2); +n3=B3.tsize(2); +n4=B4.tsize(2); +IA=A.ptr; +JA=A.cols; +IB1=B1.ptr; +JB1=B1.cols; +IB2=B2.ptr; +JB2=B2.cols; +IB3=B3.ptr; +JB3=B3.cols; +IB4=B4.ptr; +JB4=B4.cols; +if type==0 % calculate A*kron(B4,B3,B2,B1) without precomputed index + varout1=sptensor; + [IC_1,IC_2,IC_3,IC_4] = contraction4IC_mex(l,m1,m2,m3,n1,n2,n3,n4,IA,JA,IB1,JB1,IB2,JB2,IB3,JB3,IB4,JB4); + JCrows_1=IC_1(end)-1; + NA=A.vals; + NB1=B1.vals; + NB2=B2.vals; + NB3=B3.vals; + NB4=B4.vals; + if ~isreal(NA) || ~isreal(NB1) || ~isreal(NB2) || ~isreal(NB3) || ~isreal(NB4) + error('complex numbers not supported') + end + [varout1.vals,JC_1] = contraction4vecI_mex(l,m1,m2,m3,n1,n2,n3,n4,IA,JA,NA,... + IB1,JB1,NB1,IB2,JB2,NB2,IB3,JB3,NB3,IB4,JB4,NB4,... + IC_1,IC_2,IC_3,IC_4,JCrows_1,... + maxload,dosum); + varout1.ptr=IC_1; + varout1.cols=JC_1; + varout1.tsize=[l,n1,n2,n3,n4]; +elseif type==1 % compute IC + [varout1.IC_1,varout1.IC_2,varout1.IC_3,varout1.IC_4] = contraction4IC_mex(l,m1,m2,m3,n1,n2,n3,n4,IA,JA,IB1,JB1,IB2,JB2,IB3,JB3,IB4,JB4); +elseif type==2 % compute IC and JC + [IC_1,IC_2,IC_3,IC_4] = contraction4IC_mex(l,m1,m2,m3,n1,n2,n3,n4,IA,JA,IB1,JB1,IB2,JB2,IB3,JB3,IB4,JB4); + JCrows_1=IC_1(end)-1; + JCrows_2=IC_2(end)-1; + JCrows_3=IC_3(end)-1; + JCrows_4=IC_4(end)-1; + [ varout1.JC_1,varout1.JC_2,varout1.JC_3,varout1.JC_4 ] = contraction4JC_mex( l,m1,m2,m3,n1,n2,n3,n4,IA,JA,IB1,JB1,IB2,JB2,IB3,JB3,IB4,JB4,JCrows_1,JCrows_2,JCrows_3,JCrows_4,IC_2,IC_3,IC_4); + varout1.IC_1=IC_1; + varout1.IC_2=IC_2; + varout1.IC_3=IC_3; + varout1.IC_4=IC_4; +elseif type==3 % compute A*kron(B4,B3,B2,B1) with one precomputed index IC + varout1=sptensor; + if calculate_ind==1 + [IC_1,IC_2,IC_3,IC_4] = contraction4IC_mex(l,m1,m2,m3,n1,n2,n3,n4,IA,JA,IB1,JB1,IB2,JB2,IB3,JB3,IB4,JB4); + else + IC_1=ind.IC_1; + IC_2=ind.IC_2; + IC_3=ind.IC_3; + IC_4=ind.IC_4; + end + JCrows_1=IC_1(end)-1; + NA=A.vals; + NB1=B1.vals; + NB2=B2.vals; + NB3=B3.vals; + NB4=B4.vals; + if ~isreal(NA) || ~isreal(NB1) || ~isreal(NB2) || ~isreal(NB3) || ~isreal(NB4) + error('complex numbers not supported') + end + [varout1.vals,JC_1] = contraction4vecI_mex(l,m1,m2,m3,n1,n2,n3,n4,IA,JA,NA,... + IB1,JB1,NB1,IB2,JB2,NB2,IB3,JB3,NB3,IB4,JB4,NB4,... + IC_1,IC_2,IC_3,IC_4,JCrows_1,... + maxload,dosum); + varout1.ptr=IC_1; + varout1.cols=JC_1; + varout1.tsize=[l,n1,n2,n3,n4]; + varout2.IC_1=IC_1; + varout2.IC_2=IC_2; + varout2.IC_3=IC_3; + varout2.IC_4=IC_4; +elseif type==4 % compute A*kron(B4,B3,B2,B1) with two precomputed indices IC,JC + varout1=sptensor; + if calculate_ind==1 + [IC_1,IC_2,IC_3,IC_4] = contraction4IC_mex(l,m1,m2,m3,n1,n2,n3,n4,IA,JA,IB1,JB1,IB2,JB2,IB3,JB3,IB4,JB4); + JCrows_1=IC_1(end)-1; + JCrows_2=IC_2(end)-1; + JCrows_3=IC_3(end)-1; + JCrows_4=IC_4(end)-1; + [ JC_1,JC_2,JC_3,JC_4 ] = contraction4JC_mex( l,m1,m2,m3,n1,n2,n3,n4,IA,JA,IB1,JB1,IB2,JB2,IB3,JB3,IB4,JB4,JCrows_1,JCrows_2,JCrows_3,JCrows_4,IC_2,IC_3,IC_4); + else + IC_1=ind.IC_1; + IC_2=ind.IC_2; + IC_3=ind.IC_3; + IC_4=ind.IC_4; + JC_1=ind.JC_1; + JC_2=ind.JC_2; + JC_3=ind.JC_3; + JC_4=ind.JC_4; + end + NA=A.vals; + NB1=B1.vals; + NB2=B2.vals; + NB3=B3.vals; + NB4=B4.vals; + if ~isreal(NA) || ~isreal(NB1) || ~isreal(NB2) || ~isreal(NB3) || ~isreal(NB4) + error('complex numbers not supported') + end + varout1.vals = contraction4vec_mex(l,m1,m2,m3,n1,n2,n3,n4,IA,JA,NA,... + IB1,JB1,NB1,IB2,JB2,NB2,IB3,JB3,NB3,IB4,JB4,NB4,... + IC_1,JC_1,IC_2,JC_2,IC_3,JC_3,IC_4,JC_4,... + maxload,dosum); + varout1.ptr=IC_1; + varout1.cols=JC_1; + varout1.tsize=[l,n1,n2,n3,n4]; + varout2.IC_1=IC_1; + varout2.IC_2=IC_2; + varout2.IC_3=IC_3; + varout2.IC_4=IC_4; + varout2.JC_1=JC_1; + varout2.JC_2=JC_2; + varout2.JC_3=JC_3; + varout2.JC_4=JC_4; +end +if isfield(A,'ptr2d') % if the pointer of A is 2D varout is also 2D + varout1.ptr2d=A.ptr2d; +end +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/extract.m b/105/replication_package/solution_methods/taylor_projection/Tensors/extract.m new file mode 100644 index 0000000000000000000000000000000000000000..ddde7542f97e6725aac624816458641e1c2571b7 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/extract.m @@ -0,0 +1,28 @@ +function [ A,ind ] = extract(B,extractrows,extractcols,compress,ind) +%The function extract rows and columns from a tensor with symmetric column +%and returns a new sparse tensor. If compress=1 the output is in compressed +%form. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if isempty(ind) + [A,tempind1]=takerows(B,extractrows); + [A,tempind2]=takecols(A,extractcols); + if compress==1 + [A,tempind3]=takeunique(A); + tempind2=tempind2(tempind3); + end + tempind=tempind1(tempind2); + ind.ptr=A.ptr; + ind.cols=A.cols; + ind.tsize=A.tsize; + ind.ind=tempind; +else + A.vals=B.vals(:,ind.ind); + A.ptr=ind.ptr; + A.cols=ind.cols; + A.tsize=ind.tsize; +end + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/fold.m b/105/replication_package/solution_methods/taylor_projection/Tensors/fold.m new file mode 100644 index 0000000000000000000000000000000000000000..2072f5ac852e2ff6bb255ae7d4ebbaec88f24093 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/fold.m @@ -0,0 +1,48 @@ +function [R]=fold(A,varargin) +% reshape a sparse matrix of dimensions m,n1*...*n4 to a tensor of +% dimensions m,n1,...,n4 +% +% � Copyright, Oren Levintal, June 13, 2016. + +if length(A.tsize)>2 + A=unfold(A); +end +R=A; +if nargin==3 + n1=varargin{1}; + n2=varargin{2}; + [cols1,cols2]=ind2sub([n1,n2],A.cols); + R.cols=[cols1,cols2]; + R.tsize=[A.tsize(1),n1,n2]; +elseif nargin==4 + n1=varargin{1}; + n2=varargin{2}; + n3=varargin{3}; + [cols1,cols2,cols3]=ind2sub([n1,n2,n3],A.cols); + R.cols=[cols1,cols2,cols3]; + R.tsize=[A.tsize(1),n1,n2,n3]; +elseif nargin==5 + n1=varargin{1}; + n2=varargin{2}; + n3=varargin{3}; + n4=varargin{4}; + [cols1,cols2,cols3,cols4]=ind2sub([n1,n2,n3,n4],A.cols); + R.cols=[cols1,cols2,cols3,cols4]; + R.tsize=[A.tsize(1),n1,n2,n3,n4]; +elseif nargin==6 + n1=varargin{1}; + n2=varargin{2}; + n3=varargin{3}; + n4=varargin{4}; + n5=varargin{5}; + [cols1,cols2,cols3,cols4,cols5]=ind2sub([n1,n2,n3,n4,n5],A.cols); + R.cols=[cols1,cols2,cols3,cols4,cols5]; + R.tsize=[A.tsize(1),n1,n2,n3,n4,n5]; +elseif nargin>6 + error('tensor of rank higher than 6 not supported') +end + +R.cols=intarray(R.cols); +R.tsize=intarray(R.tsize); + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/foldj.m b/105/replication_package/solution_methods/taylor_projection/Tensors/foldj.m new file mode 100644 index 0000000000000000000000000000000000000000..41a959a5b917ca75f9d4b690c087f0de8f92622f --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/foldj.m @@ -0,0 +1,38 @@ +function [R]=foldj(A,j,dim) +% [R]=foldj(A,j,dim) reshapes the j'th col dimension of a sparse tensor A +% do new dimension dim. +% +% � Copyright, Oren Levintal, June 13, 2016. + +R=A; +ndim=length(dim); +dim=intarray(dim); +if ndim==2 + n1=dim(1); + n2=dim(2); + [cols1,cols2]=ind2sub([n1,n2],A.cols(:,j)); + R.cols=[A.cols(:,1:j-1),cols1,cols2,A.cols(:,j+1:end)]; + R.tsize=[A.tsize(1:j),n1,n2,A.tsize(j+2:end)]; +elseif ndim==3 + n1=dim(1); + n2=dim(2); + n3=dim(3); + [cols1,cols2,cols3]=ind2sub([n1,n2,n3],A.cols(:,j)); + R.cols=[A.cols(:,1:j-1),cols1,cols2,cols3,A.cols(:,j+1:end)]; + R.tsize=[A.tsize(1:j),n1,n2,n3,A.tsize(j+2:end)]; +elseif ndim==4 + n1=dim(1); + n2=dim(2); + n3=dim(3); + n4=dim(4); + [cols1,cols2,cols3,cols4]=ind2sub([n1,n2,n3,n4],A.cols(:,j)); + R.cols=[A.cols(:,1:j-1),cols1,cols2,cols3,cols4,A.cols(:,j+1:end)]; + R.tsize=[A.tsize(1:j),n1,n2,n3,n4,A.tsize(j+2:end)]; +elseif ndim>4 + error('tensor of rank higher than 5 not supported') +end + +R.cols=intarray(R.cols); +R.tsize=intarray(R.tsize); + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/intarray.m b/105/replication_package/solution_methods/taylor_projection/Tensors/intarray.m new file mode 100644 index 0000000000000000000000000000000000000000..7b61c224edb43bcac9532cdfdd5e488d1318ccb6 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/intarray.m @@ -0,0 +1,15 @@ +function [ y ] = intarray( x ) +%Convert to int32 or int64, depending on the operating system. +% +% � Copyright, Oren Levintal, June 13, 2016. + +archstr = computer('arch'); +if strcmp(archstr(end-1:end),'32') + y=int32(x); +elseif strcmp(archstr(end-1:end),'64') + y=int64(x); +else + error('cannot find if MATLAB runs on 32-bit or 64-bit operating system.') +end +end + diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/multscalar.m b/105/replication_package/solution_methods/taylor_projection/Tensors/multscalar.m new file mode 100644 index 0000000000000000000000000000000000000000..b38a6160e8778dab6387fad40cbb784b5d5a3e06 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/multscalar.m @@ -0,0 +1,9 @@ +function ten=multscalar(ten,n) +% multiply sparse tensor ten by scalar n +% +% � Copyright, Oren Levintal, June 13, 2016. + +ten.vals=ten.vals*n; + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/permutecols.m b/105/replication_package/solution_methods/taylor_projection/Tensors/permutecols.m new file mode 100644 index 0000000000000000000000000000000000000000..779aff47fc3156b89cc0838894a0562861efb065 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/permutecols.m @@ -0,0 +1,10 @@ +function ten=permutecols(ten,ind) +% permute columns of a sparse sptensor +% +% � Copyright, Oren Levintal, June 13, 2016. + +ind=ind(:)'; +ten.cols=ten.cols(:,ind); +ten.tsize=ten.tsize([1,1+ind]); +end + diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/permuterows.m b/105/replication_package/solution_methods/taylor_projection/Tensors/permuterows.m new file mode 100644 index 0000000000000000000000000000000000000000..6df4e8d59e295821eae8e901a71e17fef575cf45 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/permuterows.m @@ -0,0 +1,14 @@ +function [A]=permuterows(A,newrows) +%Permute the rows of tensor A by newrows. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if isfield(A,'ptr2d') + error('2D pointer not supported') +end + +newrows=intarray(newrows); + +[A.ptr,A.cols,A.vals] = perm_rows(A.ptr,A.cols,A.vals,A.tsize(1),newrows); + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/ptr1d.m b/105/replication_package/solution_methods/taylor_projection/Tensors/ptr1d.m new file mode 100644 index 0000000000000000000000000000000000000000..7fa4f9c59641ff5154bf19667adbfed9ceee04fc --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/ptr1d.m @@ -0,0 +1,14 @@ +function [ A ] = ptr1d( A ) +%convert the 2-D pointer to 1-D +% +% � Copyright, Oren Levintal, June 13, 2016. + +if size(A.ptr,2)>1 + tempptr=A.ptr(:,1:end-1); + tempptr=tempptr'; + A.ptr=[tempptr(:);A.ptr(end)]; + A.tsize=[prod(A.tsize(1:2)),A.tsize(3:end)]; +end + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/ptr2col.m b/105/replication_package/solution_methods/taylor_projection/Tensors/ptr2col.m new file mode 100644 index 0000000000000000000000000000000000000000..8dcded14c0a3fa74d44db54803baffe80b7157f1 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/ptr2col.m @@ -0,0 +1,21 @@ +function [ R ] = ptr2col( ten,coli ) +%A=ptr2col(A,j) converts a 2D pointer to 1D pointer. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if coli>length(ten.tsize) + error('column dimension too large') +end + +l1=ten.ptr2d(1); +l2=ten.ptr2d(2); +[ newcol ] = ptr2col_mex( ten.ptr,ten.ptr(end)-1 ); +R=sptensor; +R.vals=ten.vals; +R.ptr=[ten.ptr(:,1);ten.ptr(end)]; +R.cols=[ten.cols(:,1:coli-1),newcol,ten.cols(:,coli:end)]; +R.tsize=[l1,ten.tsize(3:coli+1),l2,ten.tsize(coli+2:end)]; + + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/ptr2d.m b/105/replication_package/solution_methods/taylor_projection/Tensors/ptr2d.m new file mode 100644 index 0000000000000000000000000000000000000000..0bcd1579b992b38d7ecc7754e0be57f0faa3ec5c --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/ptr2d.m @@ -0,0 +1,38 @@ +function [ A ] = ptr2d( A,l1,l2 ) +%Convert the pointer to 2-D. If the original pointer was obtained from a +%2-D pointer then rows are assumed to be indexed l2,l1. Otherwis, rows +%are assumed to be indexed l1,l2. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if size(A.ptr,2)==1 + if isfield(A,'ptr2d') + if A.ptr2d(1)~=l1 || A.ptr2d(2)~=l2 + error('dimensions of 2D pointer are wrong') + else + A=ptr2d_sub(A,l1,l2); + end + else % convert to 1,l1,l2 and move l1 to pointer + A=ptr2d_sub(A,1,l1*l2); + A.ptr2d=intarray([1,l1*l2]); % the size of the 2D pointer + A=ptr2col(A,1); + A=foldj(A,1,[l1,l2]); + A=col2ptr(A,1); + A=ptr1d(A); + A=rmfield(A,'ptr2d'); + A=col2ptr(A,1); + + end +end + +end + +function A=ptr2d_sub(A,l1,l2) + +tempptr=zeros(l1,l2+1); +tempptr(:,1:l2)=reshape(A.ptr(1:end-1),l2,l1)'; +tempptr(:,end)=[tempptr(2:end,1);A.ptr(end)]; +A.ptr=intarray(tempptr); +A.tsize=intarray([l1,l2,A.tsize(2:end)]); + +end diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/spmat2sptensor.m b/105/replication_package/solution_methods/taylor_projection/Tensors/spmat2sptensor.m new file mode 100644 index 0000000000000000000000000000000000000000..6bfc196877a755e7ced72a1ec96fab8ce9308d93 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/spmat2sptensor.m @@ -0,0 +1,12 @@ +function [ A ] = spmat2sptensor( spmat ) +%convert sparse matrix to sparse tensor +%can be improved by mexing (its basically a transpose) +% +% � Copyright, Oren Levintal, June 13, 2016. +% bug fixed on January 20, 2017 (a row vector produced an error) +[i,j,vals]=find(spmat); +[l,m]=size(spmat); +A=sptensor(i(:),j(:),vals(:)',l,m); + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/sptensor.m b/105/replication_package/solution_methods/taylor_projection/Tensors/sptensor.m new file mode 100644 index 0000000000000000000000000000000000000000..5df45ec69540da295d773ee220af1a733a4dbe71 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/sptensor.m @@ -0,0 +1,157 @@ +function obj=sptensor(varargin) +% sptensor constructs a sparse tensor. +% T=sptensor(row,cols,vals,rowdim,colsdim) constructs a sparse tensor T. +% The first index of nnz values is stored in vector row. The other indices +% are stored in matrix cols, where size(cols,1)=length(row) and +% size(cols,2) is the number of the other indices. Total number of indices +% (tensor rank) is size(cols,2)+1. The nnz values are stored in vals, where +% size(vals,2)=size(cols,1)=length(row). It is possible to store a set of s +% tensors with the same sparse structure but different nnz values, by +% storing the nnz values of these tensors as different rows in vals. +% Namely, size(vals,1)=s. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if nargin==0 % empty tensor + obj.vals=[]; + obj.ptr=[]; + obj.cols=[]; + obj.tsize=[]; +elseif nargin==1 % convert a matrix to a sparse tensor. if matrix is sparse better use spmat2sptensor + T=full(varargin{1}); + if length(size(T))==2 + vals=T'; + obj.vals=vals(:)'; + [m,n]=size(T); + obj.ptr=(1:n:m*n+1)'; + obj.cols=repmat((1:n)',m,1); + obj.tsize=[m,n]; + % convert integers to int32 or int64, depending on the + archstr = computer('arch'); + if strcmp(archstr(end-1:end),'32') + sys=32; + elseif strcmp(archstr(end-1:end),'64') + sys=64; + else + error('cannot determine if MATLAB runs on 32-bit or 64-bit platform.') + end + if sys==32 + obj.ptr=int32(obj.ptr); + obj.cols=int32(obj.cols); + obj.tsize=int32(obj.tsize); + elseif sys==64 + obj.ptr=int64(obj.ptr); + obj.cols=int64(obj.cols); + obj.tsize=int64(obj.tsize); + end + else + error('full tensor not supported') + end +elseif nargin==2 || nargin==3 % create a sparse tensor of zeros + rowdim=varargin{1}; + colsdim=varargin{2}; + if nargin==3 + n_s=varargin{3}; + else + n_s=1; + end + + obj.vals=zeros(n_s,0); + obj.cols=zeros(0,length(colsdim)); + obj.ptr=ones(rowdim+1,1); + obj.tsize=[rowdim,colsdim(:)']; + + % convert integers to int32 or int64, depending on the + archstr = computer('arch'); + if strcmp(archstr(end-1:end),'32') + sys=32; + elseif strcmp(archstr(end-1:end),'64') + sys=64; + else + error('cannot determine if MATLAB runs on 32-bit or 64-bit platform.') + end + if sys==32 + obj.ptr=int32(obj.ptr); + obj.cols=int32(obj.cols); + obj.tsize=int32(obj.tsize); + elseif sys==64 + obj.ptr=int64(obj.ptr); + obj.cols=int64(obj.cols); + obj.tsize=int64(obj.tsize); + end +elseif nargin==5 + row=varargin{1}; + cols=varargin{2}; + vals=varargin{3}; + rowdim=varargin{4}; + colsdim=varargin{5}; + if size(row,1)~=1 && size(row,2)~=1 + error('first argument must be a vector') + end + n_vals=size(vals,2); + if n_vals~=length(row) + error('length of row index must equal the number of nnz values') + end + if size(cols,1)~=n_vals + error('length of col indices must equal the number of nnz values') + end + if ~isa(vals,'double') + error('nnz values should be of class double') + end + % check indices for nonzero tensors + if n_vals>0 + % check row index + if ~isequal(round(row),row) + error('Index into tensor must be an integer.') + end + if max(row)>rowdim + error('Index exceeds tensor dimensions') + end + if min(row)<1 + error('Index into tensor must be positive.') + end + % check cols indices + if size(cols,2)~=length(colsdim) + error('incompatible column dimensions') + end + if ~isequal(round(cols),cols) + error('Index into tensor must be an integer.') + end + if max(cols(:))>colsdim + error('Index exceeds tensor dimensions') + end + if min(cols(:))<1 + error('Index into tensor must be positive.') + end + end + % convert integers to int32 or int64, depending on the + archstr = computer('arch'); + if strcmp(archstr(end-1:end),'32') + sys=32; + elseif strcmp(archstr(end-1:end),'64') + sys=64; + else + error('cannot determine if MATLAB runs on 32-bit or 64-bit platform.') + end + if sys==32 + row=int32(row); + cols=int32(cols); + rowdim=int32(rowdim); + n_vals=int32(n_vals); + elseif sys==64 + row=int64(row); + cols=int64(cols); + rowdim=int64(rowdim); + n_vals=int64(n_vals); + end + % store nnz values in CRS format +% [ obj.vals,obj.ptr,obj.cols ] = compress( vals,row,cols,rowdim,n_vals ); + [ obj.vals,obj.ptr,obj.cols ] = compress_mex( vals,row,cols,rowdim,n_vals ); + + obj.tsize=[rowdim,colsdim(:)']; +else + error('wrong number of arguments') +end + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/sptensor2spmat.m b/105/replication_package/solution_methods/taylor_projection/Tensors/sptensor2spmat.m new file mode 100644 index 0000000000000000000000000000000000000000..20f60545bf4cfb0f7c59316ddb8cf084db9d5112 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/sptensor2spmat.m @@ -0,0 +1,35 @@ +function [ A ] = sptensor2spmat( ten ) +%convert sparse tensor to sparse matrix +%can be improved by mexing +% +% � Copyright, Oren Levintal, June 13, 2016. +% extended to rank=5 on January 20, 2017 + +if isfield(ten,'ptr2d') % 2D pointer + ten=ptr2d(ten,ten.ptr2d(1),ten.ptr2d(2)); + ten=ptr2col(ten,1); +end + +[i,j,vals]=tfind(ten); + +colsdim=ten.tsize(2:end); +ncolsdim=length(colsdim); +if ncolsdim==1 + cols=j; +elseif ncolsdim==2 + cols=sub2ind(ten.tsize(2:end),j(:,1),j(:,2)); +elseif ncolsdim==3 + cols=sub2ind(ten.tsize(2:end),j(:,1),j(:,2),j(:,3)); +elseif ncolsdim==4 + cols=sub2ind(ten.tsize(2:end),j(:,1),j(:,2),j(:,3),j(:,4)); +elseif ncolsdim==5 + cols=sub2ind(ten.tsize(2:end),j(:,1),j(:,2),j(:,3),j(:,4),j(:,5)); +else + error('tensor rank larger than 6') +end + +ten.tsize=double(ten.tsize); +A=sparse(double(i),double(cols),vals',ten.tsize(1),prod(ten.tsize(2:end))); + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/spteye.m b/105/replication_package/solution_methods/taylor_projection/Tensors/spteye.m new file mode 100644 index 0000000000000000000000000000000000000000..6cade20cdb55655dea29f0d6188f4ef1c5726950 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/spteye.m @@ -0,0 +1,21 @@ +function T=spteye(n,varargin) +% +% � Copyright, Oren Levintal, June 13, 2016. + +if nargin==1 + n_s=1; +elseif nargin==2 + n_s=varargin{1}; +else + error('wrong number of arguments') +end +% creates eye(T) as sptensor +n=double(n); +T.vals=ones(n_s,n); +n=intarray(n); +T.cols=(1:n)'; +T.ptr=(1:n+1)'; +T.tsize=[n,n]; + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/takecols.m b/105/replication_package/solution_methods/taylor_projection/Tensors/takecols.m new file mode 100644 index 0000000000000000000000000000000000000000..d706c836677c89b19cc8aed3ad59abf0bcb8d49c --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/takecols.m @@ -0,0 +1,34 @@ +function [ A,ind ] = takecols( ten,cols ) +%extract cols from a tensor class ten with symmetric columns. +%improve by mex +% +% � Copyright, Oren Levintal, June 13, 2016. +% bug corrected on Jan 11, 2018 for the cases of one or zero nonzero values in ten + +m=length(cols); +temp=zeros(ten.tsize(2),1); +temp(cols)=1:m; +[i,j,vals]=tfind(ten); +j=temp(j); + +n_vals=numel(i); +if n_vals==1 + j=j(:)'; +end + +if n_vals>0 + prodj=prod(j,2); +else + prodj=0; +end + +if nnz(prodj)>0 + A=sptensor(i(prodj~=0),j(prodj~=0,:),vals(:,prodj~=0),ten.tsize(1),repmat(m,1,length(ten.tsize)-1)); +else + A=sptensor(ten.tsize(1),repmat(m,1,length(ten.tsize)-1),size(ten.vals,1)); +end + +ind=find(prodj); + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/takerows.m b/105/replication_package/solution_methods/taylor_projection/Tensors/takerows.m new file mode 100644 index 0000000000000000000000000000000000000000..f20a3453b0d023dc00f0967668bef0e3a694dafc --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/takerows.m @@ -0,0 +1,49 @@ +function [ A,ind ] = takerows( ten,rows ) +%extract rows from tensor ten. +% +% � Copyright, Oren Levintal, June 13, 2016. +% bug corrected on Jan 1, 2018 for the case of zero nonzero values in A +% bug corrected on Jan 29, 2018 for the case of an empty tensor + +if ten.tsize(1)==0 && ~isempty(rows) + error('trying to extract rows from an empty tensor') +elseif ten.tsize(1)==0 && isempty(rows) + if nargout==1 + A=ten; + else + A=ten; + ind=[]; + end +else + if nargout==1 %mex version + A=sptensor; + IA=ten.ptr; + JA=ten.cols; + NA=ten.vals; + l=ten.tsize(1); + takel=intarray(rows); + [IC,JC,NC] = takerows_mex(IA,JA,NA,l,takel); + newl=length(takel); + A.ptr=IC(1:newl+1); + A.cols=JC(1:A.ptr(end)-1,:); + A.vals=NC(:,1:A.ptr(end)-1); + A.tsize=ten.tsize; + A.tsize(1)=newl; + else + l=length(rows); + temp=zeros(ten.tsize(1),1); + temp(rows)=1:l; + [i,j,vals]=tfind(ten); + i=temp(i); + + if nnz(i)>0 + A=sptensor(i(i~=0),j(i~=0,:),vals(:,i~=0),l,ten.tsize(2:end)); + else + A=sptensor(l,ten.tsize(2:end),size(ten.vals,1)); + end + + ind=find(i); + end +end +end + diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/takeunique.m b/105/replication_package/solution_methods/taylor_projection/Tensors/takeunique.m new file mode 100644 index 0000000000000000000000000000000000000000..03c9dbe3b0e28c7898667f772befaf834bb8fc00 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/takeunique.m @@ -0,0 +1,21 @@ +function [ Ac,ind ] = takeunique( ten ) +%extract unique columns from a tensor with symmetric columns. +%improve by mex +% +% � Copyright, Oren Levintal, June 13, 2016. + +oldvals=ten.vals; +ten.vals=ten.vals(1,:); +[i,j,~]=tfind(ten); + +ij=[i,sort(j,2)]; % columns are sorted j1<=j2<=... below i use the function u2c which assumes j1>=j2>=.. so order of columns need to be reversed +[uniqueij,ind]=unique(ij,'rows'); + +Au=sptensor(uniqueij(:,1),uniqueij(:,end:-1:2),ind(:)',ten.tsize(1),ten.tsize(2:end)); % columns reversed + +Ac=u2c(Au); +ind=Ac.vals(:); +Ac.vals=oldvals(:,ind); + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/tfind.m b/105/replication_package/solution_methods/taylor_projection/Tensors/tfind.m new file mode 100644 index 0000000000000000000000000000000000000000..213bf2f3a6e86977327f83ad07f7eccaab691176 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/tfind.m @@ -0,0 +1,38 @@ +function [i,j,vals]=tfind(A) +% similar to the function find for sparse matrices. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if isempty(A.vals) + i=zeros(0,1); + j=zeros(0,length(A.tsize)-1); +else + if size(A.ptr,2)==1 + x=zeros(size(A.cols,1)+1,1); + rows=1:A.tsize(1); + x(A.ptr(1:end-1))=rows; + x=x(1:end-1); + x(x>0)=[x(1);diff(x(x>0))]; + x=cumsum(x); + i=x; + j=A.cols; + else +%convert the 2-D pointer to 1-D + tempptr=A.ptr(:,1:end-1); + tempptr=tempptr'; + tempptr=[tempptr(:);A.ptr(end)]; + tempsize=[prod(A.tsize(1:2)),A.tsize(3:end)]; + x=zeros(size(A.cols,1)+1,1); + rows=1:tempsize(1); + x(tempptr(1:end-1))=rows; + x=x(1:end-1); + x(x>0)=[x(1);diff(x(x>0))]; + x=cumsum(x); + i=x; + [i2,i1]=ind2sub(A.tsize(2:-1:1),i); + i=i1; + j=[i2,A.cols]; + end +end +vals=A.vals; +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/tkron.m b/105/replication_package/solution_methods/taylor_projection/Tensors/tkron.m new file mode 100644 index 0000000000000000000000000000000000000000..8d91338d35b6420620f3bc3e8d69c9ffd75566db --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/tkron.m @@ -0,0 +1,30 @@ +function [varout1,varout2]=tkron(B2,B1,varargin) +%C=tkron(B2,B1) calculates C=kron(B2,B1). +% +% � Copyright, Oren Levintal, June 13, 2016. + +sB1=size(B1.vals,1); +sB2=size(B2.vals,1); + +if sB1==1 + if sB2>1 + B1.vals=repmat(B1.vals,sB2,1); + end +elseif sB1>1 + if sB2==1 + B2.vals=repmat(B2.vals,sB1,1); + elseif sB2>1 && sB1~=sB2 + error('incompatible states') + end +end + +l1=B1.tsize(1); +l2=B2.tsize(1); +A=fold(spteye(l1*l2),l1,l2); +if nargin>2 + [varout1,varout2]=contraction2(A,B2,B1,varargin{:}); +elseif nargin==2 + [varout1,varout2]=contraction2(A,B2,B1); +end + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/tkron3.m b/105/replication_package/solution_methods/taylor_projection/Tensors/tkron3.m new file mode 100644 index 0000000000000000000000000000000000000000..442eb75c81e30f5f223e5f3267c21b08422e0b08 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/tkron3.m @@ -0,0 +1,48 @@ +function [varout1,varout2]=tkron3(B3,B2,B1,varargin) +%C=tkron(B3,B2,B1) calculates C=kron(B3,B2,B1). +% +% � Copyright, Oren Levintal, June 13, 2016. + +sB1=size(B1.vals,1); +sB2=size(B2.vals,1); +sB3=size(B3.vals,1); + +if sB1==1 + if sB2>1 + B1.vals=repmat(B1.vals,sB2,1); + end +elseif sB1>1 + if sB2==1 + B2.vals=repmat(B2.vals,sB1,1); + elseif sB2>1 && sB1~=sB2 + error('incompatible states') + end +end + +sB=max(sB1,sB2); + +if sB3==1 + if sB>1 + B3.vals=repmat(B3.vals,sB,1); + end +elseif sB3>1 + if sB==1 + B2.vals=repmat(B2.vals,sB3,1); + B1.vals=repmat(B1.vals,sB3,1); + elseif sB>1 && sB3~=sB + error('incompatible states') + end +end + +l1=B1.tsize(1); +l2=B2.tsize(1); +l3=B3.tsize(1); + +A=fold(spteye(l1*l2*l3),l1,l2,l3); +if nargin>3 + [varout1,varout2]=contraction3(A,B3,B2,B1,varargin{:}); +elseif nargin==3 + [varout1,varout2]=contraction3(A,B3,B2,B1); +end + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/tkron3_d1.m b/105/replication_package/solution_methods/taylor_projection/Tensors/tkron3_d1.m new file mode 100644 index 0000000000000000000000000000000000000000..a3ac422e42d6a2cb9014b91da656a855fc644f7a --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/tkron3_d1.m @@ -0,0 +1,52 @@ +function R=tkron3_d1(A,B,C,Ax,Bx,Cx) +% Compute first derivative of kron(A,B,C) w.r.t x +% A is m1-by-1 +% Ax is m1-by-n_x +% B is m2-by-1 +% Bx is m2-by-n_x +% C is m3-by-1 +% Cx is m3-by-n_x +% +% � Copyright, Oren Levintal, June 13, 2016. + +m1=A.tsize(1); +m2=B.tsize(1); +m3=C.tsize(1); + +if m1~=prod(A.tsize) + error('A must be a vector') +end +if m2~=prod(B.tsize) + error('B must be a vector') +end +if m3~=prod(C.tsize) + error('C must be a vector') +end + +if Ax.tsize(1)~=m1 + error('Incompatible dimensions') +end +if Bx.tsize(1)~=m2 + error('Incompatible dimensions') +end +if Cx.tsize(1)~=m3 + error('Incompatible dimensions') +end + +if Ax.tsize(2)~=Bx.tsize(2) + error('Incompatible dimensions') +elseif Ax.tsize(2)~=Cx.tsize(2) + error('Incompatible dimensions') +end + +term1=tkron3(Ax,B,C); %m3*m2*m1,n_x + +term2=tkron3(A,Bx,C); %m3*m2*m1,n_x + +term3=trkron3(A,B,Cx); %m3*m2*m1,n_x + +R=tplus(term1,term2); + +R=tplus(R,term3); + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/tkron3_d2.m b/105/replication_package/solution_methods/taylor_projection/Tensors/tkron3_d2.m new file mode 100644 index 0000000000000000000000000000000000000000..c3c6c65c77d701f37126f60f2c60e6c7928bd846 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/tkron3_d2.m @@ -0,0 +1,76 @@ +function R=tkron3_d2(A,B,C,Ax,Bx,Cx,Axx,Bxx,Cxx) +% Compute first derivative of kron(A,B,C) +% A is m1-by-1 +% Ax is m1-by-n_x +% Axx is m1-by-n_x-by-n_x +% B is m2-by-1 +% Bx is m2-by-n_x +% Bxx is m2-by-n_x-by-n_x +% C is m3-by-1 +% Cx is m3-by-n_x +% Cxx is m3-by-n_x-by-n_x +% +% � Copyright, Oren Levintal, June 13, 2016. + +m1=A.tsize(1); +m2=B.tsize(1); +m3=C.tsize(1); + +if m1~=prod(A.tsize) + error('A must be a vector') +end +if m2~=prod(B.tsize) + error('B must be a vector') +end +if m3~=prod(C.tsize) + error('C must be a vector') +end + +if Ax.tsize(1)~=m1 + error('Incompatible dimensions') +end +if Bx.tsize(1)~=m2 + error('Incompatible dimensions') +end +if Cx.tsize(1)~=m3 + error('Incompatible dimensions') +end + +if Ax.tsize(2)~=Bx.tsize(2) + error('Incompatible dimensions') +elseif Ax.tsize(2)~=Cx.tsize(2) + error('Incompatible dimensions') +end + +Axx=ptr1d(col2ptr(Axx,1)); +Bxx=ptr1d(col2ptr(Bxx,1)); +Cxx=ptr1d(col2ptr(Cxx,1)); + + +term1=tkron3_d1(tvec(Ax),B,C,Axx,Bx,Cx); %m3*m2*m1*n_x,n_x + +term1=ptr2d(term1,m3*m2*m1,n_x); +term1=ptr2col(term1,1); %m3*m2*m1,n_x,n_x + + +term2=tkron3_d1(A,tvec(Bx),C,Ax,Bxx,Cx); %m3*m2*n_x*m1,n_x + +term2=ptr2d(term2,m3*m2,n_x*m1); +term2=ptr2col(term2,1); %m3*m2,n_x*m1,n_x +term2=fold(term2,n_x,m1,n_x);%m3*m2,n_x,m1,n_x +term2=col2ptr(term2,2); +term2=ptr1d(term2);%m3*m2*m1,n_x,n_x + +term3=trkron3_d1(A,B,Cx,Ax,Bx,Cxx); %m3*n_x*m2*m1,n_x + +term3=ptr2d(term3,m3,n_x*m2*m1); +term3=ptr2col(term3,1); %m3,n_x*m2*m1,n_x +term3=fold(term3,n_x,m2*m1,n_x);%m3,n_x,m2*m1,n_x +term3=col2ptr(term3,2); +term3=ptr1d(term3);%m3*m2*m1,n_x,n_x + +R=tplus(term1,term2); + +R=tplus(R,term3); + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/tkron3_x.m b/105/replication_package/solution_methods/taylor_projection/Tensors/tkron3_x.m new file mode 100644 index 0000000000000000000000000000000000000000..597dbb205753e66971cc9a162628475b7f77e163 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/tkron3_x.m @@ -0,0 +1,52 @@ +function R=tkron3_x(A,B,C,Ax,Bx,Cx) +% Compute first derivative of kron(A,B,C) w.r.t x +% A is m1-by-1 +% Ax is m1-by-n_x +% B is m2-by-1 +% Bx is m2-by-n_x +% C is m3-by-1 +% Cx is m3-by-n_x +% +% � Copyright, Oren Levintal, June 13, 2016. + +m1=A.tsize(1); +m2=B.tsize(1); +m3=C.tsize(1); + +if m1~=prod(A.tsize) + error('A must be a vector') +end +if m2~=prod(B.tsize) + error('B must be a vector') +end +if m3~=prod(C.tsize) + error('C must be a vector') +end + +if Ax.tsize(1)~=m1 + error('Incompatible dimensions') +end +if Bx.tsize(1)~=m2 + error('Incompatible dimensions') +end +if Cx.tsize(1)~=m3 + error('Incompatible dimensions') +end + +if Ax.tsize(2)~=Bx.tsize(2) + error('Incompatible dimensions') +elseif Ax.tsize(2)~=Cx.tsize(2) + error('Incompatible dimensions') +end + +term1=tkron3(Ax,B,C); %m3*m2*m1,n_x + +term2=tkron3(A,Bx,C); %m3*m2*m1,n_x + +term3=trkron3(A,B,Cx); %m3*m2*m1,n_x + +R=tplus(term1,term2); + +R=tplus(R,term3); + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/tplus.m b/105/replication_package/solution_methods/taylor_projection/Tensors/tplus.m new file mode 100644 index 0000000000000000000000000000000000000000..c26244f42a3f39b96d1730b268c468aa38b61e66 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/tplus.m @@ -0,0 +1,83 @@ +function [ A ] = tplus( B1,B2,varargin ) +%adds two tensors +% +% � Copyright, Oren Levintal, June 13, 2016. + +sB1=size(B1.vals,1); +sB2=size(B2.vals,1); + +if sB1==1 + if sB2>1 + B1.vals=repmat(B1.vals,sB2,1); + end +elseif sB1>1 + if sB2==1 + B2.vals=repmat(B2.vals,sB1,1); + elseif sB2>1 && sB1~=sB2 + error('incompatible states') + end +end + + +if size(B1.ptr,2)>1 % 2D pointers + if nargin==2 + maxload=intarray(1); + elseif nargin==3 + maxload=intarray(varargin{1}); + end + [ A ] = tplus2d( B1,B2,maxload ); +else + + rank1=length(B1.tsize); + rank2=length(B2.tsize); + if ~isequal(rank1,rank2) + error('incompatible dimensions') + end + + + A=sptensor; + A.tsize=B1.tsize; + + l=B1.tsize(1); + m=B1.tsize(2:end); + IB1=B1.ptr; + IB2=B2.ptr; + JB1=B1.cols; + JB2=B2.cols; + NB1=B1.vals; + NB2=B2.vals; + if ~isreal(NB1) || ~isreal(NB2) + error('complex numbers not supported') + end + + if nargin==2 + maxload=intarray(1); + elseif nargin==3 + maxload=intarray(varargin{1}); + end + + if rank1==2 + % A=tplus1(B1,B2); + [A.vals,A.ptr,A.cols] = tplus1_mex(l,m,IB1,JB1,NB1,IB2,JB2,NB2,maxload); + A.vals=A.vals(:,1:A.ptr(end)-1); + A.cols=A.cols(1:A.ptr(end)-1,:); + elseif rank1==3 + [A.vals,A.ptr,A.cols] = tplus2_mex(l,m,IB1,JB1,NB1,IB2,JB2,NB2,maxload); + A.vals=A.vals(:,1:A.ptr(end)-1); + A.cols=A.cols(1:A.ptr(end)-1,:); + elseif rank1==4 + [A.vals,A.ptr,A.cols] = tplus3_mex(l,m,IB1,JB1,NB1,IB2,JB2,NB2,maxload); + A.vals=A.vals(:,1:A.ptr(end)-1); + A.cols=A.cols(1:A.ptr(end)-1,:); + elseif rank1==5 + [A.vals,A.ptr,A.cols] = tplus4_mex(l,m,IB1,JB1,NB1,IB2,JB2,NB2,maxload); + A.vals=A.vals(:,1:A.ptr(end)-1); + A.cols=A.cols(1:A.ptr(end)-1,:); + else + error('tensors of rank larger than 5 not supported') + end + +end + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/tplus2d.m b/105/replication_package/solution_methods/taylor_projection/Tensors/tplus2d.m new file mode 100644 index 0000000000000000000000000000000000000000..0bd770c5af43c00ce8871d58db4aefad065ef71c --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/tplus2d.m @@ -0,0 +1,83 @@ +function [ A ] = tplus2d( B1,B2,varargin ) +%adds two tensors with two dimensional pointers +% +% � Copyright, Oren Levintal, June 13, 2016. + +if size(B1.ptr,2)==1 + error('pointer should be 2-D') +end +rank1=length(B1.tsize); +rank2=length(B2.tsize); +if ~isequal(rank1,rank2) + error('incompatible dimensions') +end + + +A=sptensor; +A.ptr2d=B1.ptr2d; +A.tsize=B1.tsize; + +if nargin==2 + maxload=intarray(1); +elseif nargin==3 + maxload=intarray(varargin{1}); +end + +if rank1==3 + % A=tplus1(B1,B2); + l1=B1.tsize(1); + l2=B1.tsize(2); + m1=B1.tsize(3); + IB1=B1.ptr; + IB2=B2.ptr; + JB1=B1.cols; + JB2=B2.cols; + NB1=B1.vals; + NB2=B2.vals; + [A.vals,A.ptr,A.cols] = tplus1_2D_mex(l1,l2,m1,IB1,JB1,NB1,IB2,JB2,NB2,maxload); + A.vals=A.vals(:,1:A.ptr(end)-1); + A.cols=A.cols(1:A.ptr(end)-1,:); +% A.ptr2d=1; +% elseif rank1==3 +% l=B1.tsize(1); +% m=B1.tsize(2:end); +% IB1=B1.ptr; +% IB2=B2.ptr; +% JB1=B1.cols; +% JB2=B2.cols; +% NB1=B1.vals; +% NB2=B2.vals; +% [A.vals,A.ptr,A.cols] = tplus2_mex(l,m,IB1,JB1,NB1,IB2,JB2,NB2,maxload); +% A.vals=A.vals(:,1:A.ptr(end)-1); +% A.cols=A.cols(1:A.ptr(end)-1,:); +% elseif rank1==4 +% l=B1.tsize(1); +% m=B1.tsize(2:end); +% IB1=B1.ptr; +% IB2=B2.ptr; +% JB1=B1.cols; +% JB2=B2.cols; +% NB1=B1.vals; +% NB2=B2.vals; +% [A.vals,A.ptr,A.cols] = tplus3_mex(l,m,IB1,JB1,NB1,IB2,JB2,NB2,maxload); +% A.vals=A.vals(:,1:A.ptr(end)-1); +% A.cols=A.cols(1:A.ptr(end)-1,:); +% elseif rank1==5 +% l=B1.tsize(1); +% m=B1.tsize(2:end); +% IB1=B1.ptr; +% IB2=B2.ptr; +% JB1=B1.cols; +% JB2=B2.cols; +% NB1=B1.vals; +% NB2=B2.vals; +% [A.vals,A.ptr,A.cols] = tplus4_mex(l,m,IB1,JB1,NB1,IB2,JB2,NB2,maxload); +% A.vals=A.vals(:,1:A.ptr(end)-1); +% A.cols=A.cols(1:A.ptr(end)-1,:); +else + error('tensors of rank larger than 3 not supported') +end + + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/tscalar.m b/105/replication_package/solution_methods/taylor_projection/Tensors/tscalar.m new file mode 100644 index 0000000000000000000000000000000000000000..5a9dab520729132d7c48f739837311ec73c7bbda --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/tscalar.m @@ -0,0 +1,17 @@ +function [R]=tscalar(A) +% returns a scalar tensor. +% +% � Copyright, Oren Levintal, June 13, 2016. + +A=tvec(A); + +[i,j,vals]=tfind(A); + +Rvals=zeros([A.tsize(1),size(A.vals,1)]); +Rvals(i,:)=vals'; + +R=sptensor(1); + +R.vals=Rvals(:); + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/ttranspose.m b/105/replication_package/solution_methods/taylor_projection/Tensors/ttranspose.m new file mode 100644 index 0000000000000000000000000000000000000000..600dd582e80bbbf74557c812725ee6fc330ed555 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/ttranspose.m @@ -0,0 +1,22 @@ +function [ A ] = ttranspose( A ) +%transpose a 2D sparse tensor +% +% � Copyright, Oren Levintal, June 13, 2016. + +if length(A.tsize)>2 + error('tensors or rank higher than 2 are not supported') +end + +m=A.tsize(1); +n=A.tsize(2); + +A.ptr2d=intarray([1,m]); +A=ptr2d(A,1,m); +A=ptr2col(A,1); +A=col2ptr(A,2); +A=ptr1d(A); + +A=rmfield(A,'ptr2d'); + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/tvec.m b/105/replication_package/solution_methods/taylor_projection/Tensors/tvec.m new file mode 100644 index 0000000000000000000000000000000000000000..0d36135d8fd71732da8fe9f649dad921a8ca8565 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/tvec.m @@ -0,0 +1,16 @@ +function [R]=tvec(A) +% vectorize a sparse tensor of dimensions m,n1,...,n4 to dimensions +% m*n1*...*n4,1. +% +% � Copyright, Oren Levintal, June 13, 2016. + +A=unfold(A); + +A=ptr2d(A,1,A.tsize(1)); +A=ptr2col(A,1); +A=fold(A,prod(A.tsize),1); +A=col2ptr(A,1); +A=ptr1d(A); +R=rmfield(A,'ptr2d'); + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/u2c.m b/105/replication_package/solution_methods/taylor_projection/Tensors/u2c.m new file mode 100644 index 0000000000000000000000000000000000000000..e8ac1e8d2962d98908701b0c43ddbdb37c6a6c69 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/u2c.m @@ -0,0 +1,28 @@ +function [ A ] = u2c( ten ) +%convert a tensor with symmetric column from unique form to compress form. +%improve by mex +% +% � Copyright, Oren Levintal, June 13, 2016. + +n=double(ten.tsize(2)); +k=double(length(ten.tsize)-1); + +n_unique=double(ten.ptr(end)-1); +sortM=double(ten.cols(:,end:-1:1)); % the formula below assumes indices a1<=a2<=a3, so i have to change location of indices because i use the convention a3>=a2>=a1 + +tempmat=repmat(n+k:-1:n+1,n_unique,1); +loc=(repmat(prod(n+k-1:-1:n),n_unique,1)-prod(tempmat-repmat(sortM(:,1),1,k),2))/factorial(k)+1; + +for j=2:k-1 + tempmat=repmat(n+k-j+1:-1:n+1,n_unique,1); + loc=loc+(prod(tempmat-repmat(sortM(:,j-1),1,k-j+1),2)-prod(tempmat-repmat(sortM(:,j),1,k-j+1),2))/factorial(k-j+1); +end +loc=loc+sortM(:,k)-sortM(:,k-1); + +A=ten; +A.cols=intarray(loc); +A.tsize=[ten.tsize(1),intarray(nchoosek(n+k-1,k))]; + + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/unfold.m b/105/replication_package/solution_methods/taylor_projection/Tensors/unfold.m new file mode 100644 index 0000000000000000000000000000000000000000..ba5da36455c18731f9ad9cb046bc5e4f5559dc68 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/unfold.m @@ -0,0 +1,40 @@ +function [R]=unfold(A) +% unfold a sparse tensor of dimensions m,n1,...,n4 to a matrix of +% dimensions m,n1*...*n4 +% the pointer can be 1D or 2D +% +% � Copyright, Oren Levintal, June 13, 2016. + +if size(A.ptr,2)==1 %1D pointer + rowdim=A.tsize(1); + coldim=A.tsize(2:end); + rank=length(A.tsize); + +else % 2D pointer + rowdim=A.tsize(1:2); + coldim=A.tsize(3:end); + rank=length(A.tsize)-1; +end +% check overflow on 32-bit system +n=prod(int64(coldim)); +if intarray(n)==intarray(n-1) + error('integer overflow') +end + +R=A; +R.tsize=intarray([rowdim,n]); + +if rank==3 + R.cols=sub2ind(coldim,A.cols(:,1),A.cols(:,2)); +elseif rank==4 + R.cols=sub2ind(coldim,A.cols(:,1),A.cols(:,2),A.cols(:,3)); +elseif rank==5 + R.cols=sub2ind(coldim,A.cols(:,1),A.cols(:,2),A.cols(:,3),A.cols(:,4)); +elseif rank==6 + R.cols=sub2ind(coldim,A.cols(:,1),A.cols(:,2),A.cols(:,3),A.cols(:,4),A.cols(:,5)); +elseif rank>6 + error('tensor of rank higher than 6 not supported') +end +R.cols=intarray(R.cols); + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/uniquecols2ind.m b/105/replication_package/solution_methods/taylor_projection/Tensors/uniquecols2ind.m new file mode 100644 index 0000000000000000000000000000000000000000..bf3758329590b5e2377b8577f23602c2278d9142 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/uniquecols2ind.m @@ -0,0 +1,25 @@ +function [ loc ] = uniquecols2ind( cols,n ) +%convert unique columns to index (like u2c). Columns are assumed to satisfy +%a1>=a2>=a3 +% +% � Copyright, Oren Levintal, June 13, 2016. + +[n_unique,k]=size(cols); + +if k>1 + sortM=double(cols(:,end:-1:1)); % the formula below assumes indices a1<=a2<=a3, so i have to change location of indices because i use the convention a3>=a2>=a1 + + tempmat=repmat(n+k:-1:n+1,n_unique,1); + loc=(repmat(prod(n+k-1:-1:n),n_unique,1)-prod(tempmat-repmat(sortM(:,1),1,k),2))/factorial(k)+1; + + for j=2:k-1 + tempmat=repmat(n+k-j+1:-1:n+1,n_unique,1); + loc=loc+(prod(tempmat-repmat(sortM(:,j-1),1,k-j+1),2)-prod(tempmat-repmat(sortM(:,j),1,k-j+1),2))/factorial(k-j+1); + end + loc=loc+sortM(:,k)-sortM(:,k-1); +else + loc=cols; +end + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/Tensors/vconcat.m b/105/replication_package/solution_methods/taylor_projection/Tensors/vconcat.m new file mode 100644 index 0000000000000000000000000000000000000000..51da2450ed0e497b38231facf621815e4c8efc4a --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/Tensors/vconcat.m @@ -0,0 +1,21 @@ +function ten=vconcat(ten1,ten2) +% vertical concatenation of two tensors of same column size. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if ~isequal(ten1.tsize(2:end),ten2.tsize(2:end)) + error('incompatible dimensions') +elseif size(ten1.vals,1)~=size(ten2.vals,1) + error('incompatible states') +else + ten=sptensor; + ten.tsize=ten1.tsize; + ten.tsize(1)=ten1.tsize(1)+ten2.tsize(1); + ten.ptr=[ten1.ptr;ten2.ptr(2:end)+ten1.ptr(end)-1]; + ten.cols=[ten1.cols;ten2.cols]; + ten.vals=[ten1.vals,ten2.vals]; +end + + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/chain0_theta_tensor.m b/105/replication_package/solution_methods/taylor_projection/chain0_theta_tensor.m new file mode 100644 index 0000000000000000000000000000000000000000..ad85bae7ea0ea86fd969b41b7bad628b3360a4f1 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/chain0_theta_tensor.m @@ -0,0 +1,9 @@ +function [ R,ind ] = chain0_theta_tensor( fv,vtheta,ind,n_ind,maxload,sum ) +% +% � Copyright, Oren Levintal, June 13, 2016. + + +[R,ind]=contraction1(fv,vtheta,ind,n_ind,maxload,sum); + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/chain1_tensor.m b/105/replication_package/solution_methods/taylor_projection/chain1_tensor.m new file mode 100644 index 0000000000000000000000000000000000000000..afca203fa9de6903c1f8b42ff58f9bcdc05b3d20 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/chain1_tensor.m @@ -0,0 +1,9 @@ +function [ R,ind ] = chain1_tensor(fv,vx,ind,n_ind,maxload,sum) +%1st order chain rule. +% +% � Copyright, Oren Levintal, June 13, 2016. + +[R,ind]=contraction1(fv,vx,ind,n_ind,maxload,sum); + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/chain1_theta_tensor.m b/105/replication_package/solution_methods/taylor_projection/chain1_theta_tensor.m new file mode 100644 index 0000000000000000000000000000000000000000..e910b1721325f498729003969db0215e6077a133 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/chain1_theta_tensor.m @@ -0,0 +1,28 @@ +function [ R,ind,term1,term2 ] = chain1_theta_tensor( fv,fvv,vx,vtheta,vxtheta,ind,n_ind,maxload,sum ) +% +% � Copyright, Oren Levintal, June 13, 2016. + +if isempty(ind) + ind=cell(2,1); +end + +n_f=fv.tsize(1); + +n_x=vx.tsize(2); +n_theta=vtheta.tsize(2); +n_s=max([size(fv.vals,1),size(vx.vals,1),size(vtheta.vals,1)]); + +if ~isempty(fvv.vals) + [term1,ind{1}]=contraction2(fvv,vx,vtheta,ind{1},n_ind,maxload,sum); + term1=permutecols(term1,[2,1]); +else + term1=sptensor(n_f,[n_x,n_theta],n_s); +end + +[term2,ind{2}]=contraction1(fv,vxtheta,ind{2},n_ind,maxload,sum); + +R=tplus(term1,fold(term2,n_x,n_theta),maxload); + + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/chain2c_tensor.m b/105/replication_package/solution_methods/taylor_projection/chain2c_tensor.m new file mode 100644 index 0000000000000000000000000000000000000000..2cb7d1deeae48a7b3e96b2673905940433622d73 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/chain2c_tensor.m @@ -0,0 +1,23 @@ +function [ fxxc,ind ] = chain2c_tensor(fv,fvv,vx,vxxc,ind,n_ind,maxload,sum) +%chain2c is compressed. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if isempty(ind) + ind=cell(2,1); +end + +%fvv*kron(vx,vx)*U2 +[term1,ind{1}]=AkronBU2(fvv,vx,ind{1},n_ind,maxload,sum); + +%fv*vxxc +[term2,ind{2}]=contraction1(fv,vxxc,ind{2},n_ind,maxload,sum); + +fxxc=tplus(term1,term2,maxload); + +if isfield(fv,'ptr2d') + fxxc.ptr2d=fv.ptr2d; +end + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/chain2c_theta_tensor.m b/105/replication_package/solution_methods/taylor_projection/chain2c_theta_tensor.m new file mode 100644 index 0000000000000000000000000000000000000000..d227831ba4f400f166615c6d3e80514e4c9a89d2 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/chain2c_theta_tensor.m @@ -0,0 +1,59 @@ +function [ R,ind] = chain2c_theta_tensor(fv,fvv,fvvv,vx,vxxc,vtheta,vxtheta,vxxctheta,M2,ind,n_ind,maxload,sum ) +% +% � Copyright, Oren Levintal, June 13, 2016. + +if isempty(ind) + ind=cell(5,1); +end + +n_f=fv.tsize(1); + +n_x=vx.tsize(2); +n_theta=vtheta.tsize(2); +unique2=nchoosek(n_x+1,2); +n_s=max([size(fv.vals,1),size(vx.vals,1),size(vtheta.vals,1)]); + + +if ~isempty(fvvv.vals) + + [term1,ind{1}]=AkronB1U2B2(fvvv,vx,vtheta,ind{1},n_ind,maxload,sum); + term1=fold(term1,n_theta,unique2); + + term1=col2ptr(term1,2); + +else + term1=sptensor(n_f,[unique2,n_theta],n_s); + term1=col2ptr(term1,1); +end + +[term2,ind{2}]=contraction2(fvv,vx,vxtheta,ind{2},n_ind,maxload,sum); +term2=foldj(term2,1,[n_x,n_theta]); + +term2=ptr1d(unfold(col2ptr(term2,2))); + +[term2,ind{3}]=contraction1(term2,M2,ind{3},n_ind,maxload,sum); +term2=ptr2d(term2,n_f,n_theta); +term2=ptr2col(term2,2); % tsize=[n_f*n_theta,unique2] +term2=col2ptr(term2,1); + + +sumterm=tplus(term1,term2,maxload); + +[term3,ind{4}]=contraction2(fvv,vxxc,vtheta,ind{4},n_ind,maxload,sum); + +term3=col2ptr(term3,2); +sumterm=tplus(sumterm,term3,maxload); + + +[term4,ind{5}]=contraction1(fv,vxxctheta,ind{5},n_ind,maxload,sum); +term4=fold(term4,unique2,n_theta); +term4=col2ptr(term4,1); + + + +R=tplus(sumterm,term4,maxload); + +R=ptr2col(R,1); + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/chain3c_tensor.m b/105/replication_package/solution_methods/taylor_projection/chain3c_tensor.m new file mode 100644 index 0000000000000000000000000000000000000000..0faa37cdc9a3415d42c489a18382e557e23165b6 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/chain3c_tensor.m @@ -0,0 +1,30 @@ +function [ fxxxc,ind ] = chain3c_tensor(fv,fvv,fvvv,vx,vxxc,vxxxc,M2,ind,n_ind,maxload,sum) +%chain3c is compressed. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if isempty(ind) + ind=cell(4,1); +end + +%fvvv*kron(vx,vx,vx)*U3 + +[term1,ind{1}]=AkronBU3(fvvv,vx,ind{1},n_ind,maxload,sum); + +[term2,ind{2}]=contraction2(fvv,vx,vxxc,ind{2},n_ind,maxload,sum); + +[term2,ind{3}]=contraction1(unfold(term2),M2,ind{3},n_ind,maxload,sum); + +sumterm=tplus(term1,term2,maxload); clear term1 term2 + +[term3,ind{4}]=contraction1(fv,vxxxc,ind{4},n_ind,maxload,sum); + +fxxxc=tplus(sumterm,term3,maxload); + +if isfield(fv,'ptr2d') + fxxxc.ptr2d=fv.ptr2d; +end + + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/chain3c_theta_tensor.m b/105/replication_package/solution_methods/taylor_projection/chain3c_theta_tensor.m new file mode 100644 index 0000000000000000000000000000000000000000..50af2df921d5be06262fbdd4ab205f402c0220e1 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/chain3c_theta_tensor.m @@ -0,0 +1,138 @@ +function [ R ,ind] = chain3c_theta_tensor(fv,fvv,fvvv,fvvvv,... + vx,vxxc,vxxxc,vtheta,vxtheta,vxxctheta,vxxxctheta,... + M2,M3,M4,M5,ind,n_ind,maxload,sum ) +% +% � Copyright, Oren Levintal, June 13, 2016. + +if isempty(ind) + ind=cell(15,1); +end + +n_f=fv.tsize(1); +n_v=fv.tsize(2); +n_x=vx.tsize(2); +n_theta=vtheta.tsize(2); +unique2=nchoosek(n_x+1,2); +unique3=nchoosek(n_x+2,3); + +n_s=max([size(fv.vals,1),size(vx.vals,1),size(vtheta.vals,1)]); + +if ~isempty(fvvvv.vals) + [term1,ind{1}]=AkronB1U3B2(fvvvv,vx,vtheta,ind{1},n_ind,maxload,sum); + term1=fold(term1,n_theta,unique3); + term1=col2ptr(term1,2); +else + term1=sptensor(n_f,[unique3,n_theta],n_s); + term1=col2ptr(term1,1); +end + +[term2,ind{2}]=AkronB1U2B2(fvvv,vx,vxtheta,ind{2},n_ind,maxload,sum); + +term2=fold(term2,n_x,n_theta,unique2); + +term2=ptr1d(unfold(col2ptr(term2,2))); + +[term2,ind{3}]=contraction1(term2,M2,ind{3},n_ind,maxload,sum); +term2=ptr2d(term2,n_f,n_theta);% tsize=[n_f*n_theta,unique3] +term2=ptr2col(term2,2);% tsize=[n_f,unique3,n_theta] +term2=col2ptr(term2,1);% tsize=[n_f*unique3,n_theta] + +sumterm=tplus(term1,term2,maxload); + + +fvvv=col2ptr(fvvv,1); %n_f*n_v,n_v,n_v +fvvv=ptr1d(fvvv); %n_f*n_v,n_v,n_v +[term3,ind{4}]=contraction2(fvvv,vx,vxxc,ind{4},n_ind,maxload,'vec'); %n_f*n_v,unique2,n_x +term3=ptr2d(term3,n_f,n_v); %n_f*n_v,unique2,n_x +term3=ptr2col(term3,1); %n_f,n_v,unique2,n_x + +term3=fold(term3,n_v,unique2*n_x); +term3=col2ptr(term3,2); +term3=ptr1d(term3); +[term3,ind{12}]=contraction1(term3,vtheta,ind{12},n_ind,maxload,sum); +term3=fold(ptr2col(ptr2d(term3,n_f,unique2*n_x),2),n_theta,unique2,n_x); + +term3=col2ptr(term3,1); %n_f*n_theta,unique2,n_x +term3=ptr1d(unfold(term3)); %n_f*n_theta,unique2*n_x +[term3,ind{5}]=contraction1(term3,M3,ind{5},n_ind,maxload,sum); +term3=ptr2d(term3,n_f,n_theta); %n_f*n_theta,unique3 +term3=ptr2col(term3,2);%n_f,unique3,n_theta +term3=col2ptr(term3,1);%n_f*unique3,n_theta + +sumterm=tplus(sumterm,term3,maxload); + +% term4 + +rfvv=col2ptr(fvv,1); %n_f*n_v,n_v +rfvv=ptr1d(rfvv); %n_f*n_v,n_v +[term4,ind{6}]=contraction1(rfvv,vx,ind{6},n_ind,maxload,'vec'); %n_f*n_v,n_x +term4=ptr2d(term4,n_f,n_v); %n_f*n_v,n_x +term4=ptr2col(term4,1); %n_f,n_v,n_x + +term4=col2ptr(term4,2); %n_f*n_x,n_v +term4=ptr1d(term4); +[term4,ind{13}]=contraction1(term4,col2ptr(fold(vxxctheta,unique2,n_theta),1),ind{13},n_ind,maxload,sum); + +% this is special because term4 ptr has 3D +term4.ptr2d=intarray([n_f*n_x,unique2]); +term4=ptr2col(term4,1); %n_f*n_x,unique2,n_theta +term4.ptr2d=intarray([n_f,n_x]); +term4=ptr2d(term4,n_f,n_x); +term4=ptr2col(term4,2); %n_f,unique2,n_x,n_theta +term4=col2ptr(term4,3); %n_f*n_theta,unique2,n_x + +term4=ptr1d(unfold(term4)); %n_f*n_theta,unique2*n_x +[term4,ind{7}]=contraction1(term4,M4,ind{7},n_ind,maxload,sum); +term4=ptr2d(term4,n_f,n_theta); %n_f*n_theta,unique3 +term4=ptr2col(term4,2);%n_f,unique3,n_theta +term4=col2ptr(term4,1);%n_f*unique3,n_theta + +sumterm=tplus(sumterm,term4,maxload); + + +% term5 + +[term5,ind{8}]=contraction1(rfvv,vxxc,ind{8},n_ind,maxload,'vec'); %n_f*n_v,unique2 +term5=ptr2d(term5,n_f,n_v); %n_f*n_v,unique2 +term5=ptr2col(term5,1); %n_f,n_v,unique2 +term5=col2ptr(term5,2); %n_f*unique2,n_v +term5=ptr1d(term5); +[term5,ind{14}]=contraction1(term5,col2ptr(fold(vxtheta,n_x,n_theta),1),ind{14},n_ind,maxload,sum); + +% this is special because term5 ptr has 3D +term5.ptr2d=intarray([n_f*unique2,n_x]); +term5=ptr2col(term5,1); %n_f*unique2,n_x,n_theta +term5.ptr2d=intarray([n_f,unique2]); +term5=ptr2d(term5,n_f,unique2); +term5=ptr2col(term5,2); %n_f,n_x,unique2,n_theta +term5=col2ptr(term5,3); %n_f*n_theta,n_x,unique2 + +term5=ptr1d(unfold(term5)); %n_f*n_theta,n_x*unique2 +[term5,ind{9}]=contraction1(term5,M5,ind{9},n_ind,maxload,sum); +term5=ptr2d(term5,n_f,n_theta); %n_f*n_theta,unique3 +term5=ptr2col(term5,2);%n_f,unique3,n_theta +term5=col2ptr(term5,1);%n_f*unique3,n_theta + +sumterm=tplus(sumterm,term5,maxload); + +% term6 + +[term6,ind{10}]=contraction1(rfvv,vxxxc,ind{10},n_ind,maxload,'vec'); %n_f*n_v,unique3 +term6=ptr2d(term6,n_f,n_v); %n_f*n_v,unique3 +term6=ptr2col(term6,1); %n_f,n_v,unique3 +term6=col2ptr(term6,2); %n_f*unique3,n_v +term6=ptr1d(term6); +[term6,ind{15}]=contraction1(term6,vtheta,ind{15},n_ind,maxload,sum); +term6=ptr2d(term6,n_f,unique3); %n_f*unique3,n_theta + +sumterm=tplus(sumterm,term6,maxload); + +[term7,ind{11}]=contraction1(fv,col2ptr(fold(vxxxctheta,unique3,n_theta),1),ind{11},n_ind,maxload,sum); + + +R=tplus(sumterm,term7,maxload); + +R=ptr2col(R,1); + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/chain4c_tensor.m b/105/replication_package/solution_methods/taylor_projection/chain4c_tensor.m new file mode 100644 index 0000000000000000000000000000000000000000..804ab99c26ee3ed298d1e77bfe163ae8a51a0988 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/chain4c_tensor.m @@ -0,0 +1,53 @@ +function [ fxxxxc,ind ] = chain4c_tensor(fv,fvv,fvvv,fvvvv,vx,vxxc,vxxxc,vxxxxc,M2,M3,M4,ind,n_ind,maxload,sum,varargin) +%chain4c is compressed. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if ~isempty(varargin) + convertind=varargin{1}; + maxind=varargin{2}; + doi=1; +else + doi=0; +end + +if isempty(ind) + ind=cell(8,1); +end + +%fvvvv*kron(vx,vx,vx,vx)*U4 +if doi==0 + [term1,ind{1}]=AkronBU4(fvvvv,vx,ind{1},n_ind,maxload,sum); +else + [term1,ind{1}]=AkronBU4i(fvvvv,vx,ind{1},n_ind,maxload,sum,convertind,maxind); +end + + +%fvvv*kron(kron(vx,vx)*U,vxxc)*kron(W2,W2)*OMEGA2*U4 +[term2,ind{2}]=AkronB1U2B2(fvvv,vx,vxxc,ind{2},n_ind,maxload,sum); +[term2,ind{3}]=contraction1(term2,M2,ind{3},n_ind,maxload,sum); + + +sumterm=tplus(term1,term2); clear term1 term2 + +%fvv*kron(vx,vxxxc)*kron(I,W3)*OMEGA3*U4 +[term3,ind{4}]=contraction2(fvv,vx,vxxxc,ind{4},n_ind,maxload,sum); +[term3,ind{5}]=contraction1(unfold(term3),M3,ind{5},n_ind,maxload,sum); +sumterm=tplus(sumterm,term3); clear term3 + +%fvv*kron(vxxc,vxxc)*U*W*kron(W2,W2)*OMEGA4*U4 +[term4,ind{6}]=AkronBU2(fvv,vxxc,ind{6},n_ind,maxload,sum); + +[term4,ind{7}]=contraction1(unfold(term4),M4,ind{7},n_ind,maxload,sum); +sumterm=tplus(sumterm,term4); clear term4 + +[term5,ind{8}]=contraction1(fv,vxxxxc,ind{8},n_ind,maxload,sum); + +fxxxxc=tplus(sumterm,term5); + +if isfield(fv,'ptr2d') + fxxxxc.ptr2d=fv.ptr2d; +end + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/chain4c_theta_tensor.m b/105/replication_package/solution_methods/taylor_projection/chain4c_theta_tensor.m new file mode 100644 index 0000000000000000000000000000000000000000..59433d16612c9ee0b2b929c6adb4888f85d0e0fe --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/chain4c_theta_tensor.m @@ -0,0 +1,209 @@ +function [ R ,ind] = chain4c_theta_tensor(fv,fvv,fvvv,fvvvv,fvvvvv,... + vx,vxxc,vxxxc,vxxxxc,vtheta,vxtheta,vxxctheta,vxxxctheta,vxxxxctheta,... + M2,M3,M5,M6,M9,M10,ind,n_ind,maxload,sum ) +% +% � Copyright, Oren Levintal, January 23, 2017. + +if isempty(ind) + ind=cell(21,1); +end + +n_f=fv.tsize(1); +n_v=fv.tsize(2); +n_x=vx.tsize(2); +n_theta=vtheta.tsize(2); +unique2=nchoosek(n_x+1,2); +unique3=nchoosek(n_x+2,3); +unique4=nchoosek(n_x+3,4); + +n_s=max([size(fv.vals,1),size(vx.vals,1),size(vtheta.vals,1)]); + +vxtheta=unfold(vxtheta); +vxxctheta=unfold(vxxctheta); +vxxxctheta=unfold(vxxxctheta); +vxxxxctheta=unfold(vxxxxctheta); + +%fvvvvv*kron(vtheta,kron(vx,vx,vx,vx)*U4) + +if ~isempty(fvvvvv.vals) + fv_vvvv=col2ptr(fvvvvv,1); %n_vn_f,n_v,n_v,n_v,n_v + fv_vvvv=ptr1d(fv_vvvv); %n_vn_f,n_v,n_v,n_v,n_v + [term1,ind{1}]=AkronBU4(fv_vvvv,vx,ind{1},n_ind,maxload,sum); % n_vn_f,unique4 + term1.ptr2d=fv_vvvv.ptr2d; + term1=ptr2d(term1,n_f,n_v); + term1=ptr2col(term1,2); %n_f,unique4,n_v + term1=col2ptr(term1,1); %unique4 n_f,n_v + term1=ptr1d(term1); + [term1,ind{2}]=contraction1(term1,vtheta,ind{2},n_ind,maxload,sum); %unique4 n_f,n_theta + term1=ptr2d(term1,n_f,unique4); +else + term1=sptensor(n_f,[unique4,n_theta],n_s); + term1=col2ptr(term1,1); +end + +[term2,ind{3}]=AkronB1U3B2(fvvvv,vx,vxtheta,ind{3},n_ind,maxload,sum); %n_f,n_x,n_theta,unique3 + +term2=fold(term2,n_x,n_theta,unique3); + +term2=ptr1d(unfold(col2ptr(term2,2))); %n_thetan_f,n_x,unique3 + + +[term2,ind{4}]=contraction1(term2,M2,ind{4},n_ind,maxload,sum); +term2=ptr2d(term2,n_f,n_theta);% tsize=[n_f*n_theta,unique4] +term2=ptr2col(term2,2);% tsize=[n_f,unique4,n_theta] +term2=col2ptr(term2,1);% tsize=[n_f*unique4,n_theta] + +sumterm=tplus(term1,term2,maxload); + + +clear term1 term2 + +% term3 + +fv_vvv=col2ptr(fvvvv,1); %n_f*n_v,n_v,n_v,n_v +fv_vvv=ptr1d(fv_vvv); %n_f*n_v,n_v,n_v,n_v +[term3,ind{5}]=AkronB1U2B2(fv_vvv,vx,vxxc,ind{5},n_ind,maxload,sum); %n_f*n_v,unique2,unique2 +term3.ptr2d=fv_vvv.ptr2d; +term3=ptr2d(term3,n_f,n_v); %n_f*n_v,unique2*unique2 +term3=ptr2col(term3,1); %n_f,n_v,unique2*unique2 + +term3=fold(term3,n_v,unique2*unique2); +term3=col2ptr(term3,2); +term3=ptr1d(term3); +[term3,ind{6}]=contraction1(term3,vtheta,ind{6},n_ind,maxload,sum); +term3=fold(ptr2col(ptr2d(term3,n_f,unique2*unique2),2),n_theta,unique2,unique2); + +term3=col2ptr(term3,1); %n_f*n_theta,unique2,unique2 +term3=ptr1d(unfold(term3)); %n_f*n_theta,unique2*unique2 +[term3,ind{7}]=contraction1(term3,M3,ind{7},n_ind,maxload,sum); +term3=ptr2d(term3,n_f,n_theta); %n_f*n_theta,unique4 +term3=ptr2col(term3,2);%n_f,unique4,n_theta +term3=col2ptr(term3,1);%n_f*unique4,n_theta + +sumterm=tplus(sumterm,term3,maxload); + +clear term3 + +% term4 + +[term4,ind{8}]=AkronB1U2B2(fvvv,vx,vxxctheta,ind{8},n_ind,maxload,sum); %n_f,unique2,n_theta,unique2 +term4=fold(term4,unique2,n_theta,unique2); +term4=col2ptr(term4,2); %n_thetan_f,unique2,unique2 +term4=ptr1d(unfold(term4)); %n_thetan_f,unique2*unique2 +[term4,ind{9}]=contraction1(term4,M3,ind{9},n_ind,maxload,sum); +term4=ptr2d(term4,n_f,n_theta); %n_f*n_theta,unique4 +term4=ptr2col(term4,2);%n_f,unique4,n_theta +term4=col2ptr(term4,1);%n_f*unique4,n_theta + +sumterm=tplus(sumterm,term4,maxload); + + + +clear term4 + +% term5 + +[term5,ind{10}]=contraction3(fvvv,vx,vxtheta,vxxc,ind{10},n_ind,maxload,sum); %n_f,unique2,n_x,n_theta,n_x +term5=fold(term5,unique2,n_x,n_theta,n_x); +term5=col2ptr(term5,3); %n_thetan_f,unique2,n_x,n_x +term5=ptr1d(unfold(term5)); %n_thetan_f,unique2*n_x*n_x +[term5,ind{11}]=contraction1(term5,M5,ind{11},n_ind,maxload,sum); +term5=ptr2d(term5,n_f,n_theta); %n_f*n_theta,unique4 +term5=ptr2col(term5,2);%n_f,unique4,n_theta +term5=col2ptr(term5,1);%n_f*unique4,n_theta + +sumterm=tplus(sumterm,term5,maxload); + + +clear term5 + +% term6 + +[term6,ind{12}]=contraction3(fvvv,vx,vxxxc,vtheta,ind{12},n_ind,maxload,sum); %n_f,n_theta,unique3,n_x +term6=fold(term6,n_theta,unique3,n_x); +term6=col2ptr(term6,1); %n_thetan_f,unique3,n_x + + +% term7 + +[term7,ind{13}]=contraction2(fvv,vx,vxxxctheta,ind{13},n_ind,maxload,sum); %n_f,unique3,n_theta,n_x +term7=fold(term7,unique3,n_theta,n_x); +term7=col2ptr(term7,2); %n_thetan_f,unique3,n_x + +term6_7_8=tplus(unfold(term6),unfold(term7),maxload); + +clear term6 term7 + +[term8,ind{14}]=contraction2(fvv,vxtheta,vxxxc,ind{14},n_ind,maxload,sum); %n_f,unique3,n_x,n_theta +term8=fold(term8,unique3,n_x,n_theta); +term8=col2ptr(term8,3); %n_thetan_f,unique3,n_x + +term6_7_8=tplus(term6_7_8,unfold(term8),maxload); %n_thetan_f,unique3,n_x + +clear term8 + +term6_7_8=unfold(term6_7_8); %n_thetan_f,unique3,n_x +term6_7_8=ptr1d(term6_7_8); +[term6_7_8,ind{15}]=contraction1(term6_7_8,M6,ind{15},n_ind,maxload,sum); +term6_7_8=ptr2d(term6_7_8,n_f,n_theta); %n_f*n_theta,unique4 +term6_7_8=ptr2col(term6_7_8,2);%n_f,unique4,n_theta +term6_7_8=col2ptr(term6_7_8,1);%n_f*unique4,n_theta + +sumterm=tplus(sumterm,term6_7_8,maxload); + + +clear term6_7_8 + +% term9 +unique2new=nchoosek(unique2+1,2); +[term9,ind{16}]=AkronB1U2B2(fvvv,vxxc,vtheta,ind{16},n_ind,maxload,sum); %n_f,n_theta,unique2new +term9=fold(term9,n_theta,unique2new); +term9=col2ptr(term9,1); %n_thetan_f,unique2new +term9=ptr1d(unfold(term9)); %n_thetan_f,unique2new +[term9,ind{17}]=contraction1(term9,M9,ind{17},n_ind,maxload,sum); +term9=ptr2d(term9,n_f,n_theta); %n_f*n_theta,unique4 +term9=ptr2col(term9,2);%n_f,unique4,n_theta +term9=col2ptr(term9,1);%n_f*unique4,n_theta + +sumterm=tplus(sumterm,term9,maxload); + +clear term9 + +% term10 + +[term10,ind{18}]=contraction2(fvv,vxxc,vxxctheta,ind{18},n_ind,maxload,sum); %n_f,unique2,n_theta,unique2 +term10=fold(term10,unique2,n_theta,unique2); +term10=col2ptr(term10,2); %n_thetan_f,unique2,unique2 +term10=ptr1d(unfold(term10)); %n_thetan_f,unique2*unique2 +[term10,ind{19}]=contraction1(term10,M10,ind{19},n_ind,maxload,sum); +term10=ptr2d(term10,n_f,n_theta); %n_f*n_theta,unique4 +term10=ptr2col(term10,2);%n_f,unique4,n_theta +term10=col2ptr(term10,1);%n_f*unique4,n_theta + +sumterm=tplus(sumterm,term10,maxload); + + +clear term10 + +% term11 + +[term11,ind{20}]=contraction2(fvv,vtheta,vxxxxc,ind{20},n_ind,maxload,sum); % n_f,unique4,n_theta +term11=col2ptr(term11,1);%n_f*unique4,n_theta + +sumterm=tplus(sumterm,term11,maxload); + + +clear term11 + +% term12 + +[term12,ind{21}]=contraction1(fv,vxxxxctheta,ind{21},n_ind,maxload,sum); % n_f,unique4,n_theta +term12=fold(term12,unique4,n_theta); +term12=col2ptr(term12,1);%n_f*unique4,n_theta + +R=tplus(sumterm,term12,maxload); + +R=ptr2col(R,1); + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/chain5c_tensor.m b/105/replication_package/solution_methods/taylor_projection/chain5c_tensor.m new file mode 100644 index 0000000000000000000000000000000000000000..35a6df044e6c55a9895a2458140b3b317bc07f57 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/chain5c_tensor.m @@ -0,0 +1,189 @@ +function [ fxxxxxc,ind ] = chain5c_tensor(fv,fvv,fvvv,fvvvv,fvvvvv,vx,vxxc,vxxxc,vxxxxc,vxxxxxc... + ,M1,M2,M3,M4,M5,M6,ind,n_ind,maxload,sum,varargin) +%chain5c is compressed. +% +% � Copyright, Oren Levintal, January 18, 2017. + +if ~isempty(varargin) + convertind=varargin{1}; + maxind=varargin{2}; + doi=1; +else + doi=0; +end + +if isempty(ind) + ind=cell(14,1); +end + +n_f=fv.tsize(1); +n_v=fv.tsize(2); +n_x=vx.tsize(2); +%fvvvvv*kron(vx,vx,vx,vx,vx)*U5 + +%fvvvvv*kron(kron(vx,vx,vx,vx)U4W4,vx))*U5 +%fvvvvv*kron(kron(vx,vx,vx,vx)U4,vx))*kron(W4,I)*U5 +fv_vvvv=col2ptr(fvvvvv,1); %n_vn_f,n_v,n_v,n_v,n_v +fv_vvvv=ptr1d(fv_vvvv); %n_vn_f,n_v,n_v,n_v,n_v +if doi==0 + [term1,ind{1}]=AkronBU4(fv_vvvv,vx,ind{1},n_ind,maxload,sum); %n_vn_f,unique4 +else + [term1,ind{1}]=AkronBU4i(fv_vvvv,vx,ind{1},n_ind,maxload,sum,reshape(repmat(convertind(:)',n_v,1),n_v*n_f,n_v),maxind); %n_vn_f,unique4 +end +term1.ptr2d=fv_vvvv.ptr2d; +term1=ptr2d(term1,n_f,n_v); +term1=ptr2col(term1,2); %n_f,unique4,n_v +term1=col2ptr(term1,1); %unique4 n_f,n_v +term1=ptr1d(term1); +[term1b,ind{2}]=contraction1(term1,vx,ind{2},n_ind,maxload,sum); %unique4 n_f,n_x +term1b.ptr2d=term1.ptr2d; +term1b=ptr2d(term1b,term1b.ptr2d(1),term1b.ptr2d(2)); +term1=ptr2col(term1b,2); % n_f,n_x,unique4 +clear term1b +[term1,ind{3}]=contraction1(unfold(term1),M1,ind{3},n_ind,maxload,sum); %n_f,unique5 + + % test +% fvvvvv1=fvvvvv; +% fvvvvv1.vals=fvvvvv1.vals(1,:); +% vx1=vx; +% vx1.vals=vx1.vals(1,:); +% sfvvvvv=sptensor2spmat(unfold(fvvvvv1)); +% svx=sptensor2spmat(vx1); +% sfv_vvvv=reshape(sfvvvvv,n_f*n_v,[]); +% n_x=vx.tsize(2); +% [U4,W4]=create_UW(n_x,4); +% temp1=sfv_vvvv*kron(kron(svx,svx),kron(svx,svx))*U4; +% temp1=reshape(full(temp1),n_f,n_v,[]); +% temp1=permute(temp1,[2,1,3]); +% temp1=sparse(reshape(temp1,n_v*n_f,[])); %n_v,n_f,unique4 +% +% temp1=reshape(temp1,n_v,[])'*svx; % n_f,unique4,n_x +% unique4=nchoosek(n_x+3,4); +% temp1=reshape(full(temp1),n_f,unique4,n_x); +% temp1=permute(temp1,[1,3,2]); +% temp1=sparse(reshape(temp1,n_f,unique4*n_x)); +% U5=create_UW(n_x,5); +% term1_1=term1; +% term1_1.vals=term1_1.vals(1,:); +% temp1=sfvvvvv*kron(svx,kron(kron(svx,svx),kron(svx,svx)))*U5; +% oren=sptensor2spmat(unfold(term1_1))-temp1; +% max(abs(oren(:))) + + +%fvvvv*kron(kron(vx,vx,vx)*U3,vxxc)*kron(W3,W2)*OMEGA5*U5 +[term2,ind{4}]=AkronB1U3B2(fvvvv,vx,vxxc,ind{4},n_ind,maxload,sum); +[term2,ind{5}]=contraction1(term2,M2,ind{5},n_ind,maxload,sum); + +% test + +% fvvvv1=fvvvv; +% fvvvv1.vals=fvvvv1.vals(1,:); +% vx1=vx; +% vx1.vals=vx1.vals(1,:); +% vxxc1=vxxc; +% vxxc1.vals=vxxc1.vals(1,:); +% sfvvvv=sptensor2spmat(unfold(fvvvv1)); +% svx=sptensor2spmat(vx1); +% svxxc=sptensor2spmat(vxxc1); +% +% n_x=vx.tsize(2); +% [U2,W2]=create_UW(n_x,2); +% [U5]=create_UW(n_x,5); +% +% OMEGA=create_OMEGA(n_x,5); +% temp2=sfvvvv*kron(kron(svx,svx),kron(svx,svxxc*W2))*OMEGA.OMEGA5*U5; +% temp2=sparse(temp2); +% term2_1=term2; +% term2_1.vals=term2_1.vals(1,:); +% oren=sptensor2spmat(unfold(term2_1))-temp2; +% max(abs(oren(:))) + +sumterm=tplus(term1,term2); clear term1 term2 + +%fvvv*kron(kron(vx,vx)*U2,vxxxc)*kron(W2,W3)*OMEGA6*U5 +[term3,ind{6}]=AkronB1U2B2(fvvv,vx,vxxxc,ind{6},n_ind,maxload,sum); +[term3,ind{7}]=contraction1(term3,M3,ind{7},n_ind,maxload,sum); + +% test + +% fvvv1=fvvv; +% fvvv1.vals=fvvv1.vals(1,:); +% vx1=vx; +% vx1.vals=vx1.vals(1,:); +% vxxxc1=vxxxc; +% vxxxc1.vals=vxxxc1.vals(1,:); +% sfvvv=sptensor2spmat(unfold(fvvv1)); +% svx=sptensor2spmat(vx1); +% svxxxc=sptensor2spmat(vxxxc1); +% +% n_x=vx.tsize(2); +% [U2,W2]=create_UW(n_x,2); +% [U3,W3]=create_UW(n_x,3); +% [U5]=create_UW(n_x,5); +% +% OMEGA=create_OMEGA(n_x,5); +% temp3=sfvvv*kron(kron(svx,svx),svxxxc*W3)*OMEGA.OMEGA6*U5; +% temp3=sparse(temp3); +% term3_1=term3; +% term3_1.vals=term3_1.vals(1,:); +% oren=sptensor2spmat(unfold(term3_1))-temp3; +% max(abs(oren(:))) + +sumterm=tplus(sumterm,term3); clear term3 + +%fvvv*kron(vx,kron(vxxc*W2,vxxc*W2))*OMEGA7*U5 +%fvvv*kron(vx,kron(vxxc,vxxc))*kron(I,W2,W2)*OMEGA7*U5 +%fvvv*kron(vx,kron(vxxc,vxxc)UW)*kron(I,W2,W2)*OMEGA7*U5 +%fvvv*kron(vx,kron(vxxc,vxxc)U)*kron(I,W)*kron(I,W2,W2)*OMEGA7*U5 +[term4,ind{8}]=AkronB1U2B2(fvvv,vxxc,vx,ind{8},n_ind,maxload,sum); +term4=permutecols(fold(term4,n_x,term4.tsize(2)/n_x),[2,1]); +[term4,ind{9}]=contraction1(unfold(term4),M4,ind{9},n_ind,maxload,sum); + +% test + +% fvvv1=fvvv; +% fvvv1.vals=fvvv1.vals(1,:); +% vx1=vx; +% vx1.vals=vx1.vals(1,:); +% vxxc1=vxxc; +% vxxc1.vals=vxxc1.vals(1,:); +% sfvvv=sptensor2spmat(unfold(fvvv1)); +% svx=sptensor2spmat(vx1); +% svxxc=sptensor2spmat(vxxc1); +% +% n_x=vx.tsize(2); +% [U2,W2]=create_UW(n_x,2); +% [U3,W3]=create_UW(n_x,3); +% [U5]=create_UW(n_x,5); +% +% OMEGA=create_OMEGA(n_x,5); +% temp4=sfvvv*kron(svx,kron(svxxc*W2,svxxc*W2))*OMEGA.OMEGA7*U5; +% temp4=sparse(temp4); +% term4_1=term4; +% term4_1.vals=term4_1.vals(1,:); +% oren=sptensor2spmat(unfold(term4_1))-temp4; +% max(abs(oren(:))) + +sumterm=tplus(sumterm,term4); clear term4 + +%fvv*kron(vx,vxxxxc)*kron(I,W4)*OMEGA8*U5 +[term5,ind{10}]=contraction2(fvv,vx,vxxxxc,ind{10},n_ind,maxload,sum); +[term5,ind{11}]=contraction1(unfold(term5),M5,ind{11},n_ind,maxload,sum); +sumterm=tplus(sumterm,term5); clear term5 + +%fvv*kron(vxxc,vxxxc)*kron(W2,W3)*OMEGA9*U5 +[term6,ind{12}]=contraction2(fvv,vxxc,vxxxc,ind{12},n_ind,maxload,sum); +[term6,ind{13}]=contraction1(unfold(term6),M6,ind{13},n_ind,maxload,sum); +sumterm=tplus(sumterm,term6); clear term6 + +%fv*vxxxxxc +[term7,ind{14}]=contraction1(fv,vxxxxxc,ind{14},n_ind,maxload,sum); + +fxxxxxc=tplus(sumterm,term7); + +if isfield(fv,'ptr2d') + fxxxxxc.ptr2d=fv.ptr2d; +end + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/chainsM.m b/105/replication_package/solution_methods/taylor_projection/chainsM.m new file mode 100644 index 0000000000000000000000000000000000000000..f7c36b83dccf84f59c31e50f7c2be3d38f9eae19 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/chainsM.m @@ -0,0 +1,61 @@ +function [ M ] = chainsM( n,order,varargin ) +%calculate coefficient matrices for compressed chain rules. +% +% � Copyright, Oren Levintal, June 13, 2016. + +compress=1; +if ~isempty(varargin) + compress=0; +end + +if order==3 + M=cell(2,1); + [~,W2]=create_UW(n,2); + [U3,~]=create_UW(n,3); + OMEGA=create_OMEGA(n,3); + M{2}=spmat2sptensor(kron(speye(n),W2)*OMEGA.OMEGA1*U3); +elseif order==4 + M=cell(4,1); + [~,W2]=create_UW(n,2); + [~,W3]=create_UW(n,3); + [U4,~]=create_UW(n,4); + OMEGA=create_OMEGA(n,4); + if compress==1 + M{2}=spmat2sptensor(kron(W2,W2)*(OMEGA.OMEGA2*U4)); OMEGA=rmfield(OMEGA,'OMEGA2'); + M{3}=spmat2sptensor(kron(speye(n),W3)*(OMEGA.OMEGA3*U4)); OMEGA=rmfield(OMEGA,'OMEGA3'); + [~,tempW]=create_UW(nchoosek(n+1,2),2); + M{4}=spmat2sptensor(tempW*kron(W2,W2)*(OMEGA.OMEGA4*U4)); + elseif compress==0 + M{2}=spmat2sptensor(kron(W2,W2)*(OMEGA.OMEGA2)); OMEGA=rmfield(OMEGA,'OMEGA2'); + M{3}=spmat2sptensor(kron(speye(n),W3)*(OMEGA.OMEGA3)); OMEGA=rmfield(OMEGA,'OMEGA3'); + [~,tempW]=create_UW(nchoosek(n+1,2),2); + M{4}=spmat2sptensor(tempW*kron(W2,W2)*(OMEGA.OMEGA4)); + end +elseif order==5 + M=cell(6,1); + [~,W2]=create_UW(n,2); + [~,W3]=create_UW(n,3); + [U4,W4]=create_UW(n,4); + [U5,W5]=create_UW(n,5); + OMEGA=create_OMEGA(n,5); + if compress==1 + M{1}=spmat2sptensor(kron(W4,speye(n))*U5); + M{2}=spmat2sptensor(kron(W3,W2)*OMEGA.OMEGA5*U5); OMEGA=rmfield(OMEGA,'OMEGA5'); + M{3}=spmat2sptensor(kron(W2,W3)*OMEGA.OMEGA6*U5); OMEGA=rmfield(OMEGA,'OMEGA6'); + [~,tempW]=create_UW(nchoosek(n+1,2),2); + M{4}=spmat2sptensor(kron(speye(n),tempW)*kron(kron(speye(n),W2),W2)*OMEGA.OMEGA7*U5); OMEGA=rmfield(OMEGA,'OMEGA7'); + M{5}=spmat2sptensor(kron(speye(n),W4)*OMEGA.OMEGA8*U5); OMEGA=rmfield(OMEGA,'OMEGA8'); + M{6}=spmat2sptensor(kron(W2,W3)*OMEGA.OMEGA9*U5); OMEGA=rmfield(OMEGA,'OMEGA9'); + + % elseif compress==0 +% M{2}=spmat2sptensor(kron(W2,W2)*(OMEGA.OMEGA2)); OMEGA=rmfield(OMEGA,'OMEGA2'); +% M{3}=spmat2sptensor(kron(speye(n),W3)*(OMEGA.OMEGA3)); OMEGA=rmfield(OMEGA,'OMEGA3'); +% [~,tempW]=create_UW(nchoosek(n+1,2),2); +% M{4}=spmat2sptensor(tempW*kron(W2,W2)*(OMEGA.OMEGA4)); + end +else + error('order is 3 or 4 or 5'); +end + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/coeffs2derivs.m b/105/replication_package/solution_methods/taylor_projection/coeffs2derivs.m new file mode 100644 index 0000000000000000000000000000000000000000..a2f4001de44b3614448f5da77e6b2910fa45bc20 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/coeffs2derivs.m @@ -0,0 +1,71 @@ +function [ derivs0,derivs1,derivs2,derivs3,derivs4,derivs5 ] = coeffs2derivs( coeffs,c0,x0,model ) +%The function transforms the vector of unique polynomial coefficients (coeffs) into +%derivatives at x0. + +derivs0=[]; +derivs1=[]; +derivs2=[]; +derivs3=[]; +derivs4=[]; +derivs5=[]; + +n_b=model.n_b; +n_x=model.n_x; +order=model.order(1); + +W=model.W; + +coeffs=reshape(coeffs,[],n_b); +newc0=x0; +GH0=coeffs(:,1); +if order==1 + GH1=coeffs(:,2:1+n_x); + [ GH0,GH1 ] = shiftpoly( newc0,c0,[],GH0,GH1 ); + derivs0=GH0; + derivs1=GH1; +elseif order==2 + GH1=coeffs(:,2:1+n_x); + GH2=coeffs(:,2+n_x:1+n_x+model.unique2)*W{2}; + [ GH0,GH1,GH2 ] = shiftpoly( newc0,c0,[],GH0,GH1,GH2 ); + derivs0=GH0; + derivs1=GH1; + derivs2=reshape(GH2*2,[],n_x,n_x); +elseif order==3 + GH1=coeffs(:,2:1+n_x); + GH2=coeffs(:,2+n_x:1+n_x+model.unique2)*W{2}; + GH3=coeffs(:,2+n_x+model.unique2:1+n_x+model.unique2+model.unique3)*W{3}; + [ GH0,GH1,GH2,GH3 ] = shiftpoly( newc0,c0,[],GH0,GH1,GH2,GH3 ); + derivs0=GH0; + derivs1=GH1; + derivs2=reshape(GH2*2,[],n_x,n_x); + derivs3=reshape(GH3*6,[],n_x,n_x,n_x); +elseif order==4 + GH1=coeffs(:,2:1+n_x); + GH2=coeffs(:,2+n_x:1+n_x+model.unique2)*W{2}; + GH3=coeffs(:,2+n_x+model.unique2:1+n_x+model.unique2+model.unique3)*W{3}; + GH4=coeffs(:,2+n_x+model.unique2+model.unique3:1+n_x+model.unique2+model.unique3+model.unique4)*W{4}; + [ GH0,GH1,GH2,GH3,GH4 ] = shiftpoly( newc0,c0,[],GH0,GH1,GH2,GH3,GH4 ); + derivs0=GH0; + derivs1=GH1; + derivs2=reshape(GH2*2,[],n_x,n_x); + derivs3=reshape(GH3*6,[],n_x,n_x,n_x); + derivs4=reshape(GH4*24,[],n_x,n_x,n_x,n_x); +elseif order==5 + GH1=coeffs(:,2:1+n_x); + GH2=coeffs(:,nchoosek(n_x+1,1)+(1:nchoosek(n_x+1,2)))*W{2}; + GH3=coeffs(:,nchoosek(n_x+2,2)+(1:nchoosek(n_x+2,3)))*W{3}; + GH4=coeffs(:,nchoosek(n_x+3,3)+(1:nchoosek(n_x+3,4)))*W{4}; + GH5=coeffs(:,nchoosek(n_x+4,4)+(1:nchoosek(n_x+4,5)))*W{5}; + [ GH0,GH1,GH2,GH3,GH4,GH5 ] = shiftpoly( newc0,c0,[],GH0,GH1,GH2,GH3,GH4,GH5 ); + derivs0=GH0; + derivs1=GH1; + derivs2=reshape(GH2*2,[],n_x,n_x); + derivs3=reshape(GH3*6,[],n_x,n_x,n_x); + derivs4=reshape(GH4*24,[],n_x,n_x,n_x,n_x); + derivs5=reshape(GH5*120,[],n_x,n_x,n_x,n_x,n_x); +else + error('order must not be larger than 5') +end + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/compderivs.m b/105/replication_package/solution_methods/taylor_projection/compderivs.m new file mode 100644 index 0000000000000000000000000000000000000000..16136099e082fe8daff30c56aff20573bbbbbfd2 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/compderivs.m @@ -0,0 +1,157 @@ +function [derivs,uncomp]=compderivs(f,x,order) + +% [derivs,uncomp,U,W]=compderivs(f,x,order) differentiates f with respect to x +% serveral times (given by order). The differentiation is done in +% a compressed manner, by exploiting sparsity and symmetry of mixed derivatives. +% The function returns two cell arrays. The first output contains the +% nonzero unique derivatives up to the order defined by the user. The +% second array contains matrices that uncompress the nonzero unique derivatives +% into the full arrays of derivatives. U and W are compress/uncompress +% matrices to unique elements. +% +% For details on the compressed differentiation routine see: +% Levintal, Oren, "Fifth Order Perturbation Solution to DSGE Models". +% +% Input arguments: +% f - a symbolic scalar. +% x - a symbolic vector. +% order - the maximum order of derivatives. For example, order=3 returns +% the first, second and third derivatives. +% +% Output arguments: +% derivs - a cell array of the nonzero unique derivatives. For example, +% derivs{1} is a symbolic vector of the nonzero first derivatives, derivs{2} is a +% symbolic vector of the nonzero unique second derivatives and so on. +% uncomp - a cell array of sparse matrices that are used to uncompress the +% compressed derivatives. For example, the full array of second order +% derivatives is obtained by uncomp{2}*derivs{2}. +% +% Example: f=x1^3*x2^4, and x=[x1,x2], both are symbolic variables. +% [derivs,uncomp]=compderivs(f,x,3) returns the first, second and third +% compressed derivatives. The full array of third derivatives is obtained +% by uncomp{3}*derivs{3}. This array can be reshaped into a 2-by-2-by-2 +% array by the reshape function. +% The i,j,l element of this array is the third derivative of f +% w.r.t xi, xj and xl. +% +% This code can be used freely for non commercial purposes. +% +% � Copyright, Oren Levintal, June 13, 2016. + +n_x=length(x); +derivs=cell(order,1); +uncomp=cell(order,1); + +if n_x==1 + tempderiv=f; + for k=1:order + tempderiv=jacobian(tempderiv,x); + derivs{k}=tempderiv; + if logical(tempderiv==0) + uncomp{k}=sparse(0); + else + uncomp{k}=sparse(1); + end + end +else + tempderiv=jacobian(f,x); + tempderiv=tempderiv(:); + + nnztempderiv=1-logical(tempderiv==0); + tempind=find(nnztempderiv); + countdf=sparse(tempind,ones(length(tempind),1),ones(length(tempind),1),numel(tempderiv),1); % counts nonzero derivatives. + N1=sparse(tempind,1:sum(countdf),ones(1,sum(countdf)),n_x,sum(countdf)); + uncomp{1}=N1; + derivs{1}=tempderiv(countdf==1); + + for k=2:order + tempderiv=jacobian(derivs{k-1}, x); + + nnztempderiv=1-logical(tempderiv==0); + [i,j]=find(nnztempderiv); + + countdf_short=sparse(i,j,ones(length(i),1),size(tempderiv,1),size(tempderiv,2)); + countdf=uncomp{k-1}*countdf_short; + countdf=countdf(:); + if nnz(countdf)>0 + [U,W]=create_UW(n_x,k,countdf); + N=sparse(find(countdf),1:sum(countdf),ones(1,sum(countdf)),n_x^k,sum(countdf)); + tempmat=[U'*(N'*kron(speye(n_x),uncomp{k-1}))]; + [i,j]=find(tempmat'); + tempderiv=tempderiv(i); + [colM,rowM]=find(N); + [rowW,colW]=find(W); + tempuncomp=sparse(size(N,1),size(W,1)); + tempeye=speye(size(W,1)); + tempuncomp(colM,:)=tempeye(rowW,:); + else + tempderiv=sym(0); + tempuncomp=sparse(n_x^k,1); + end + derivs{k}=tempderiv; + uncomp{k}=tempuncomp; + end +end + +end + +function [U,W]=create_UW(n,k,varargin) +% [U,W]=create_UW(n,k) creates two sparse matrices, U and W, that compress and +% uncompress a symmetric array A with k dimensions and n^k elements. +% A(:)'*U is a row vector that contains the unique elements of A, +% and A(:)'=(A(:)'*U)*W. +% [U,W]=create_UW(n,k,N) creates matrices U and W of a sparse symmetric +% array A with k dimensions and n^k elements. N is a vector of size n^k, +% where N(j)=1 if A(j)~=0 and zero otherwise. If B is a row +% vector with the nonzero elements of the row vector A(:)', then B*U +% is a row vector of the unique nonzero elements of A, and B=(B*U)*W. +% +% This code can be used freely for non commercial purposes, provided that +% it is not altered. +% +% (c) Oren Levintal, December 20, 2013 + +if isempty(varargin) +% nonzero=ones(n^k,1); + I=[1:n^k]; +else + nonzero=varargin{1}; + I=find(nonzero); +end + +if isempty(I) + error('The symmetric array is all zero') +end + +I=I(:); +% nonzero(nonzero~=0)=1; nonzero=nonzero(:); +sizeM='n'; +subind='I1'; +for i=2:k + sizeM=[sizeM ' n']; + subind=[subind ',I' num2str(i) ]; +end + +eval(['[' subind ']=ind2sub([' sizeM '],I);']); % I is a linear index of all nonzero elements. +eval(['M=[' subind '];']); + +M=sort(M,2); % sort columns +[M,I]=sortrows(M); % sort rows +if size(M,1)==1 + DM=1; +else + DM=[1;(sum(abs(diff(M)),2)~=0)]; +end +group=cumsum(DM); +minI=accumarray(group,I,[],@min); +newi=minI(group); + +unique=newi(DM>0); % index of unique nonzero elements + +n_unique=length(unique); + +U= sparse(unique,[1:n_unique]',ones(n_unique,1),length(I),n_unique); + +W= sparse(group,I,ones(length(I),1),n_unique,length(I)); + +end diff --git a/105/replication_package/solution_methods/taylor_projection/compderivs_u.m b/105/replication_package/solution_methods/taylor_projection/compderivs_u.m new file mode 100644 index 0000000000000000000000000000000000000000..b87d0c1bc8cbb13d80162c7e7d40d31d8a6321ba --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/compderivs_u.m @@ -0,0 +1,126 @@ +function [derivs,uncomp]=compderivs_u(f,x,order) +% This is like compderivs except that the uncompression matrix returns a +% column vector of the full derivative matrix where non-unique derivatives +% are zeroed. +% +% +% � Copyright, Oren Levintal, June 13, 2016. +% Changed on July 31, 2016 by Oren Levintal (corrected mistake for all zero +% derivatives for the case n_x=1) +n_x=length(x); +derivs=cell(order,1); +uncomp=cell(order,1); + +if n_x==1 + tempderiv=f; + for k=1:order + tempderiv=jacobian(tempderiv,x); + derivs{k}=tempderiv; + if logical(tempderiv==0) + uncomp{k}=sparse(0); + else + uncomp{k}=sparse(1); + end + end +else + tempderiv=jacobian(f,x); + tempderiv=tempderiv(:); + + nnztempderiv=1-logical(tempderiv==0); + tempind=find(nnztempderiv); + countdf=sparse(tempind,ones(length(tempind),1),ones(length(tempind),1),numel(tempderiv),1); % counts nonzero derivatives. + N1=sparse(tempind,1:sum(countdf),ones(1,sum(countdf)),n_x,sum(countdf)); + uncomp{1}=N1; + derivs{1}=tempderiv(countdf==1); + + for k=2:order + tempderiv=jacobian(derivs{k-1}, x); + + nnztempderiv=1-logical(tempderiv==0); + [i,j]=find(nnztempderiv); + + countdf_short=sparse(i,j,ones(length(i),1),size(tempderiv,1),size(tempderiv,2)); + countdf=uncomp{k-1}*countdf_short; + countdf=countdf(:); + if nnz(countdf)>0 + [U,W]=create_UW(n_x,k,countdf); + N=sparse(find(countdf),1:sum(countdf),ones(1,sum(countdf)),n_x^k,sum(countdf)); + tempmat=[U'*(N'*kron(speye(n_x),uncomp{k-1}))]; + [i,j]=find(tempmat'); + tempderiv=tempderiv(i); + [colM,rowM]=find(N); + [rowW,colW]=find(W); + tempuncomp=sparse(size(N,1),size(W,1)); + tempeye=speye(size(W,1)); + tempuncomp(colM,:)=(U*U')*tempeye(rowW,:); + else + tempderiv=sym(0); + tempuncomp=sparse(n_x^k,1); + end + derivs{k}=tempderiv; + uncomp{k}=tempuncomp; + end +end + +end + +function [U,W]=create_UW(n,k,varargin) +% [U,W]=create_UW(n,k) creates two sparse matrices, U and W, that compress and +% uncompress a symmetric array A with k dimensions and n^k elements. +% A(:)'*U is a row vector that contains the unique elements of A, +% and A(:)'=(A(:)'*U)*W. +% [U,W]=create_UW(n,k,N) creates matrices U and W of a sparse symmetric +% array A with k dimensions and n^k elements. N is a vector of size n^k, +% where N(j)=1 if A(j)~=0 and zero otherwise. If B is a row +% vector with the nonzero elements of the row vector A(:)', then B*U +% is a row vector of the unique nonzero elements of A, and B=(B*U)*W. +% +% This code can be used freely for non commercial purposes, provided that +% it is not altered. +% +% (c) Oren Levintal, December 20, 2013 + +if isempty(varargin) +% nonzero=ones(n^k,1); + I=[1:n^k]; +else + nonzero=varargin{1}; + I=find(nonzero); +end + +if isempty(I) + error('The symmetric array is all zero') +end + +I=I(:); +% nonzero(nonzero~=0)=1; nonzero=nonzero(:); +sizeM='n'; +subind='I1'; +for i=2:k + sizeM=[sizeM ' n']; + subind=[subind ',I' num2str(i) ]; +end + +eval(['[' subind ']=ind2sub([' sizeM '],I);']); % I is a linear index of all nonzero elements. +eval(['M=[' subind '];']); + +M=sort(M,2); % sort columns +[M,I]=sortrows(M); % sort rows +if size(M,1)==1 + DM=1; +else + DM=[1;(sum(abs(diff(M)),2)~=0)]; +end +group=cumsum(DM); +minI=accumarray(group,I,[],@min); +newi=minI(group); + +unique=newi(DM>0); % index of unique nonzero elements + +n_unique=length(unique); + +U= sparse(unique,[1:n_unique]',ones(n_unique,1),length(I),n_unique); + +W= sparse(group,I,ones(length(I),1),n_unique,length(I)); + +end diff --git a/105/replication_package/solution_methods/taylor_projection/convert_to_matrices.m b/105/replication_package/solution_methods/taylor_projection/convert_to_matrices.m new file mode 100644 index 0000000000000000000000000000000000000000..19c5165e4c84aa0977ba6636954149c22f3db618 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/convert_to_matrices.m @@ -0,0 +1,280 @@ +if ~isempty(model.prefrows) + + if approx>=1 + prefv=changecols(prefv,model.prefvars,n_v_tp,1); + tempv=1:n_v; + tempv(2*n_y+n_x)=[]; + tempv(end)=[]; + prefv=changecols(prefv,tempv,n_v,1); + prefv=changerows(prefv,model.prefrows,n_f); + + stochfv_vec=changecols(stochfv_vec,model.stochfvars,n_v_tp,1); + stochfv_vec=changecols(stochfv_vec,tempv,n_v,1); + stochfv_vec=changerows(stochfv_vec,model.stochfrows,n_f); + + Phiv_vec=changecols(Phiv_vec,model.Phivars,n_v_tp,1); + Phiv_vec=changecols(Phiv_vec,tempv,n_v,1); + + [prei,prej,prevals]=tfind(unfold(prefv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfv_vec)); + [Phii,Phij,Phivals]=tfind(unfold(Phiv_vec)); + Phii=Phii+n_f-n_x2; + + fv=sparse(double([prei;stochi;Phii]),double([prej;stochj;Phij]),double([prevals(:);stochvals(:);Phivals(:)]),n_f,n_v); + end + if approx>=2 + prefvv=changecols(prefvv,model.prefvars,n_v_tp,1); + prefvv=changecols(prefvv,model.prefvars,n_v_tp,2); + prefvv=changecols(prefvv,tempv,n_v,1); + prefvv=changecols(prefvv,tempv,n_v,2); + prefvv=changerows(prefvv,model.prefrows,n_f); + + stochfvv_vec=changecols(stochfvv_vec,model.stochfvars,n_v_tp,1); + stochfvv_vec=changecols(stochfvv_vec,model.stochfvars,n_v_tp,2); + stochfvv_vec=changecols(stochfvv_vec,tempv,n_v,1); + stochfvv_vec=changecols(stochfvv_vec,tempv,n_v,2); + stochfvv_vec=changerows(stochfvv_vec,model.stochfrows,n_f); + + Phivv_vec=changecols(Phivv_vec,model.Phivars,n_v_tp,1); + Phivv_vec=changecols(Phivv_vec,model.Phivars,n_v_tp,2); + Phivv_vec=changecols(Phivv_vec,tempv,n_v,1); + Phivv_vec=changecols(Phivv_vec,tempv,n_v,2); + + [prei,prej,prevals]=tfind(unfold(prefvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvv_vec)); + [Phii,Phij,Phivals]=tfind(unfold(Phivv_vec)); + Phii=Phii+n_f-n_x2; + + alli=double([prei;stochi;Phii]); + allj=double([prej;stochj;Phij]); + allvals=double([prevals(:);stochvals(:);Phivals(:)]); + + newi=sub2ind([n_f,n_v^2],alli,allj); + newj=ones(size(newi)); + + fvv=sparse(newi,newj,allvals,n_f*n_v^2,1); + end + if approx>=3 + prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,1); + prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,2); + prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,3); + prefvvv=changecols(prefvvv,tempv,n_v,1); + prefvvv=changecols(prefvvv,tempv,n_v,2); + prefvvv=changecols(prefvvv,tempv,n_v,3); + prefvvv=changerows(prefvvv,model.prefrows,n_f); + + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,1); + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,2); + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,3); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,1); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,2); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,3); + stochfvvv_vec=changerows(stochfvvv_vec,model.stochfrows,n_f); + + Phivvv_vec=changecols(Phivvv_vec,model.Phivars,n_v_tp,1); + Phivvv_vec=changecols(Phivvv_vec,model.Phivars,n_v_tp,2); + Phivvv_vec=changecols(Phivvv_vec,model.Phivars,n_v_tp,3); + Phivvv_vec=changecols(Phivvv_vec,tempv,n_v,1); + Phivvv_vec=changecols(Phivvv_vec,tempv,n_v,2); + Phivvv_vec=changecols(Phivvv_vec,tempv,n_v,3); + + [prei,prej,prevals]=tfind(unfold(prefvvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvvv_vec)); + [Phii,Phij,Phivals]=tfind(unfold(Phivvv_vec)); + Phii=Phii+n_f-n_x2; + + alli=double([prei;stochi;Phii]); + allj=double([prej;stochj;Phij]); + allvals=double([prevals(:);stochvals(:);Phivals(:)]); + + newi=sub2ind([n_f,n_v^3],alli,allj); + newj=ones(size(newi)); + + fvvv=sparse(newi,newj,allvals,n_f*n_v^3,1); + end + if approx>=4 + prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,1); + prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,2); + prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,3); + prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,4); + prefvvvv=changecols(prefvvvv,tempv,n_v,1); + prefvvvv=changecols(prefvvvv,tempv,n_v,2); + prefvvvv=changecols(prefvvvv,tempv,n_v,3); + prefvvvv=changecols(prefvvvv,tempv,n_v,4); + prefvvvv=changerows(prefvvvv,model.prefrows,n_f); + + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,1); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,2); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,3); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,4); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,1); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,2); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,3); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,4); + stochfvvvv_vec=changerows(stochfvvvv_vec,model.stochfrows,n_f); + + Phivvvv_vec=changecols(Phivvvv_vec,model.Phivars,n_v_tp,1); + Phivvvv_vec=changecols(Phivvvv_vec,model.Phivars,n_v_tp,2); + Phivvvv_vec=changecols(Phivvvv_vec,model.Phivars,n_v_tp,3); + Phivvvv_vec=changecols(Phivvvv_vec,model.Phivars,n_v_tp,4); + Phivvvv_vec=changecols(Phivvvv_vec,tempv,n_v,1); + Phivvvv_vec=changecols(Phivvvv_vec,tempv,n_v,2); + Phivvvv_vec=changecols(Phivvvv_vec,tempv,n_v,3); + Phivvvv_vec=changecols(Phivvvv_vec,tempv,n_v,4); + + [prei,prej,prevals]=tfind(unfold(prefvvvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvvvv_vec)); + [Phii,Phij,Phivals]=tfind(unfold(Phivvvv_vec)); + Phii=Phii+n_f-n_x2; + + alli=double([prei;stochi;Phii]); + allj=double([prej;stochj;Phij]); + allvals=double([prevals(:);stochvals(:);Phivals(:)]); + + newi=sub2ind([n_f,n_v^4],alli,allj); + newj=ones(size(newi)); + + fvvvv=sparse(newi,newj,allvals,n_f*n_v^4,1); + end +else + if approx>=1 +% prefv=changecols(prefv,model.prefvars,n_v_tp,1); + tempv=1:n_v; + tempv(2*n_y+n_x)=[]; + tempv(end)=[]; +% prefv=changecols(prefv,tempv,n_v,1); +% prefv=changerows(prefv,model.prefrows,n_f); + + stochfv_vec=changecols(stochfv_vec,model.stochfvars,n_v_tp,1); + stochfv_vec=changecols(stochfv_vec,tempv,n_v,1); + stochfv_vec=changerows(stochfv_vec,model.stochfrows,n_f); + + Phiv_vec=changecols(Phiv_vec,model.Phivars,n_v_tp,1); + Phiv_vec=changecols(Phiv_vec,tempv,n_v,1); + +% [prei,prej,prevals]=tfind(unfold(prefv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfv_vec)); + [Phii,Phij,Phivals]=tfind(unfold(Phiv_vec)); + Phii=Phii+n_f-n_x2; + +% fv=sparse(double([prei;stochi]),double([prej;stochj]),double([prevals(:);stochvals(:)]),n_f,n_v); + fv=sparse(double([stochi;Phii]),double([stochj;Phij]),double([stochvals(:);Phivals(:)]),n_f,n_v); + end + if approx>=2 +% prefvv=changecols(prefvv,model.prefvars,n_v_tp,1); +% prefvv=changecols(prefvv,model.prefvars,n_v_tp,2); +% prefvv=changecols(prefvv,tempv,n_v,1); +% prefvv=changecols(prefvv,tempv,n_v,2); +% prefvv=changerows(prefvv,model.prefrows,n_f); + + stochfvv_vec=changecols(stochfvv_vec,model.stochfvars,n_v_tp,1); + stochfvv_vec=changecols(stochfvv_vec,model.stochfvars,n_v_tp,2); + stochfvv_vec=changecols(stochfvv_vec,tempv,n_v,1); + stochfvv_vec=changecols(stochfvv_vec,tempv,n_v,2); + stochfvv_vec=changerows(stochfvv_vec,model.stochfrows,n_f); + + Phivv_vec=changecols(Phivv_vec,model.Phivars,n_v_tp,1); + Phivv_vec=changecols(Phivv_vec,model.Phivars,n_v_tp,2); + Phivv_vec=changecols(Phivv_vec,tempv,n_v,1); + Phivv_vec=changecols(Phivv_vec,tempv,n_v,2); + + +% [prei,prej,prevals]=tfind(unfold(prefvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvv_vec)); + [Phii,Phij,Phivals]=tfind(unfold(Phivv_vec)); + Phii=Phii+n_f-n_x2; + + alli=double([stochi;Phii]); + allj=double([stochj;Phij]); + allvals=double([stochvals(:);Phivals(:)]); + + newi=sub2ind([n_f,n_v^2],alli,allj); + newj=ones(size(newi)); + + fvv=sparse(newi,newj,allvals,n_f*n_v^2,1); + end + if approx>=3 +% prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,1); +% prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,2); +% prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,3); +% prefvvv=changecols(prefvvv,tempv,n_v,1); +% prefvvv=changecols(prefvvv,tempv,n_v,2); +% prefvvv=changecols(prefvvv,tempv,n_v,3); +% prefvvv=changerows(prefvvv,model.prefrows,n_f); + + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,1); + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,2); + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,3); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,1); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,2); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,3); + stochfvvv_vec=changerows(stochfvvv_vec,model.stochfrows,n_f); + + Phivvv_vec=changecols(Phivvv_vec,model.Phivars,n_v_tp,1); + Phivvv_vec=changecols(Phivvv_vec,model.Phivars,n_v_tp,2); + Phivvv_vec=changecols(Phivvv_vec,model.Phivars,n_v_tp,3); + Phivvv_vec=changecols(Phivvv_vec,tempv,n_v,1); + Phivvv_vec=changecols(Phivvv_vec,tempv,n_v,2); + Phivvv_vec=changecols(Phivvv_vec,tempv,n_v,3); + + +% [prei,prej,prevals]=tfind(unfold(prefvvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvvv_vec)); + [Phii,Phij,Phivals]=tfind(unfold(Phivvv_vec)); + Phii=Phii+n_f-n_x2; + + alli=double([stochi;Phii]); + allj=double([stochj;Phij]); + allvals=double([stochvals(:);Phivals(:)]); + + newi=sub2ind([n_f,n_v^3],alli,allj); + newj=ones(size(newi)); + + fvvv=sparse(newi,newj,allvals,n_f*n_v^3,1); + end + if approx>=4 +% prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,1); +% prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,2); +% prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,3); +% prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,4); +% prefvvvv=changecols(prefvvvv,tempv,n_v,1); +% prefvvvv=changecols(prefvvvv,tempv,n_v,2); +% prefvvvv=changecols(prefvvvv,tempv,n_v,3); +% prefvvvv=changecols(prefvvvv,tempv,n_v,4); +% prefvvvv=changerows(prefvvvv,model.prefrows,n_f); + + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,1); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,2); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,3); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,4); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,1); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,2); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,3); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,4); + stochfvvvv_vec=changerows(stochfvvvv_vec,model.stochfrows,n_f); + + Phivvvv_vec=changecols(Phivvvv_vec,model.Phivars,n_v_tp,1); + Phivvvv_vec=changecols(Phivvvv_vec,model.Phivars,n_v_tp,2); + Phivvvv_vec=changecols(Phivvvv_vec,model.Phivars,n_v_tp,3); + Phivvvv_vec=changecols(Phivvvv_vec,model.Phivars,n_v_tp,4); + Phivvvv_vec=changecols(Phivvvv_vec,tempv,n_v,1); + Phivvvv_vec=changecols(Phivvvv_vec,tempv,n_v,2); + Phivvvv_vec=changecols(Phivvvv_vec,tempv,n_v,3); + Phivvvv_vec=changecols(Phivvvv_vec,tempv,n_v,4); + + +% [prei,prej,prevals]=tfind(unfold(prefvvvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvvvv_vec)); + [Phii,Phij,Phivals]=tfind(unfold(Phivvvv_vec)); + Phii=Phii+n_f-n_x2; + + alli=double([stochi;Phii]); + allj=double([stochj;Phij]); + allvals=double([stochvals(:);Phivals(:)]); + + newi=sub2ind([n_f,n_v^4],alli,allj); + newj=ones(size(newi)); + + fvvvv=sparse(newi,newj,allvals,n_f*n_v^4,1); + end +end diff --git a/105/replication_package/solution_methods/taylor_projection/convert_to_matrices_i.m b/105/replication_package/solution_methods/taylor_projection/convert_to_matrices_i.m new file mode 100644 index 0000000000000000000000000000000000000000..3db7a9a9723b00f9b6346d2aae155f9450d9e4ac --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/convert_to_matrices_i.m @@ -0,0 +1,370 @@ +if ~isempty(model.prefrows) + + if approx>=1 + prefv=changecols(prefv,model.prefvars,n_v_tp,1); + tempv=1:n_v; + tempv(2*n_y+n_x)=[]; + tempv(end)=[]; + prefv=changecols(prefv,tempv,n_v,1); + prefv=changerows(prefv,model.prefrows,n_f); + + stochfv_vec=changecols(stochfv_vec,model.stochfvars,n_v_tp,1); + stochfv_vec=changecols(stochfv_vec,tempv,n_v,1); + stochfv_vec=changerows(stochfv_vec,model.stochfrows,n_f); + + Phiv_vec=changecols(Phiv_vec,model.Phivars,n_v_tp,1); + Phiv_vec=changecols(Phiv_vec,tempv,n_v,1); + + [prei,prej,prevals]=tfind(unfold(prefv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfv_vec)); + [Phii,Phij,Phivals]=tfind(unfold(Phiv_vec)); + + temp=repmat((0:n_s-1)*double(prefv.tsize(1)),numel(prei),1); + prei=repmat(prei,n_s,1)+temp(:); + prej=repmat(prej,n_s,1); + prevals=prevals'; + prevals=prevals(:); + + temp=repmat((0:n_s-1)*double(stochfv_vec.tsize(1)),numel(stochi),1); + stochi=repmat(stochi,n_s,1)+temp(:); + stochj=repmat(stochj,n_s,1); + stochvals=stochvals'; + stochvals=stochvals(:); + + Phivals=Phivals(1,:); + + Phii=Phii+n_f_all-n_x2; + + fv=sparse(double([prei;stochi;Phii]),double([prej;stochj;Phij]),double([prevals(:);stochvals(:);Phivals(:)]),n_f_all,n_v); + end + if approx>=2 + prefvv=changecols(prefvv,model.prefvars,n_v_tp,1); + prefvv=changecols(prefvv,model.prefvars,n_v_tp,2); + prefvv=changecols(prefvv,tempv,n_v,1); + prefvv=changecols(prefvv,tempv,n_v,2); + prefvv=changerows(prefvv,model.prefrows,n_f); + + stochfvv_vec=changecols(stochfvv_vec,model.stochfvars,n_v_tp,1); + stochfvv_vec=changecols(stochfvv_vec,model.stochfvars,n_v_tp,2); + stochfvv_vec=changecols(stochfvv_vec,tempv,n_v,1); + stochfvv_vec=changecols(stochfvv_vec,tempv,n_v,2); + stochfvv_vec=changerows(stochfvv_vec,model.stochfrows,n_f); + + Phivv_vec=changecols(Phivv_vec,model.Phivars,n_v_tp,1); + Phivv_vec=changecols(Phivv_vec,model.Phivars,n_v_tp,2); + Phivv_vec=changecols(Phivv_vec,tempv,n_v,1); + Phivv_vec=changecols(Phivv_vec,tempv,n_v,2); + + [prei,prej,prevals]=tfind(unfold(prefvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvv_vec)); + [Phii,Phij,Phivals]=tfind(unfold(Phivv_vec)); + + temp=repmat((0:n_s-1)*double(prefvv.tsize(1)),numel(prei),1); + prei=repmat(prei,n_s,1)+temp(:); + prej=repmat(prej,n_s,1); + prevals=prevals'; + prevals=prevals(:); + + temp=repmat((0:n_s-1)*double(stochfvv_vec.tsize(1)),numel(stochi),1); + stochi=repmat(stochi,n_s,1)+temp(:); + stochj=repmat(stochj,n_s,1); + stochvals=stochvals'; + stochvals=stochvals(:); + + Phivals=Phivals(1,:); + + Phii=Phii+n_f_all-n_x2; + + alli=double([prei;stochi;Phii]); + allj=double([prej;stochj;Phij]); + allvals=double([prevals(:);stochvals(:);Phivals(:)]); + + newi=sub2ind([n_f_all,n_v^2],alli,allj); + newj=ones(size(newi)); + + fvv=sparse(newi,newj,allvals,n_f_all*n_v^2,1); + end + if approx>=3 + prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,1); + prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,2); + prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,3); + prefvvv=changecols(prefvvv,tempv,n_v,1); + prefvvv=changecols(prefvvv,tempv,n_v,2); + prefvvv=changecols(prefvvv,tempv,n_v,3); + prefvvv=changerows(prefvvv,model.prefrows,n_f); + + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,1); + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,2); + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,3); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,1); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,2); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,3); + stochfvvv_vec=changerows(stochfvvv_vec,model.stochfrows,n_f); + + Phivvv_vec=changecols(Phivvv_vec,model.Phivars,n_v_tp,1); + Phivvv_vec=changecols(Phivvv_vec,model.Phivars,n_v_tp,2); + Phivvv_vec=changecols(Phivvv_vec,model.Phivars,n_v_tp,3); + Phivvv_vec=changecols(Phivvv_vec,tempv,n_v,1); + Phivvv_vec=changecols(Phivvv_vec,tempv,n_v,2); + Phivvv_vec=changecols(Phivvv_vec,tempv,n_v,3); + + [prei,prej,prevals]=tfind(unfold(prefvvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvvv_vec)); + [Phii,Phij,Phivals]=tfind(unfold(Phivvv_vec)); + + temp=repmat((0:n_s-1)*double(prefvvv.tsize(1)),numel(prei),1); + prei=repmat(prei,n_s,1)+temp(:); + prej=repmat(prej,n_s,1); + prevals=prevals'; + prevals=prevals(:); + + temp=repmat((0:n_s-1)*double(stochfvvv_vec.tsize(1)),numel(stochi),1); + stochi=repmat(stochi,n_s,1)+temp(:); + stochj=repmat(stochj,n_s,1); + stochvals=stochvals'; + stochvals=stochvals(:); + + Phivals=Phivals(1,:); + Phii=Phii+n_f_all-n_x2; + + alli=double([prei;stochi;Phii]); + allj=double([prej;stochj;Phij]); + allvals=double([prevals(:);stochvals(:);Phivals(:)]); + + newi=sub2ind([n_f_all,n_v^3],alli,allj); + newj=ones(size(newi)); + + fvvv=sparse(newi,newj,allvals,n_f_all*n_v^3,1); + end + if approx>=4 + prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,1); + prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,2); + prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,3); + prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,4); + prefvvvv=changecols(prefvvvv,tempv,n_v,1); + prefvvvv=changecols(prefvvvv,tempv,n_v,2); + prefvvvv=changecols(prefvvvv,tempv,n_v,3); + prefvvvv=changecols(prefvvvv,tempv,n_v,4); + prefvvvv=changerows(prefvvvv,model.prefrows,n_f); + + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,1); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,2); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,3); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,4); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,1); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,2); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,3); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,4); + stochfvvvv_vec=changerows(stochfvvvv_vec,model.stochfrows,n_f); + + Phivvvv_vec=changecols(Phivvvv_vec,model.Phivars,n_v_tp,1); + Phivvvv_vec=changecols(Phivvvv_vec,model.Phivars,n_v_tp,2); + Phivvvv_vec=changecols(Phivvvv_vec,model.Phivars,n_v_tp,3); + Phivvvv_vec=changecols(Phivvvv_vec,model.Phivars,n_v_tp,4); + Phivvvv_vec=changecols(Phivvvv_vec,tempv,n_v,1); + Phivvvv_vec=changecols(Phivvvv_vec,tempv,n_v,2); + Phivvvv_vec=changecols(Phivvvv_vec,tempv,n_v,3); + Phivvvv_vec=changecols(Phivvvv_vec,tempv,n_v,4); + + [prei,prej,prevals]=tfind(unfold(prefvvvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvvvv_vec)); + [Phii,Phij,Phivals]=tfind(unfold(Phivvvv_vec)); + temp=repmat((0:n_s-1)*double(prefvvvv.tsize(1)),numel(prei),1); + prei=repmat(prei,n_s,1)+temp(:); + prej=repmat(prej,n_s,1); + prevals=prevals'; + prevals=prevals(:); + + temp=repmat((0:n_s-1)*double(stochfvvvv_vec.tsize(1)),numel(stochi),1); + stochi=repmat(stochi,n_s,1)+temp(:); + stochj=repmat(stochj,n_s,1); + stochvals=stochvals'; + stochvals=stochvals(:); + + Phivals=Phivals(1,:); + Phii=Phii+n_f_all-n_x2; + + alli=double([prei;stochi;Phii]); + allj=double([prej;stochj;Phij]); + allvals=double([prevals(:);stochvals(:);Phivals(:)]); + + newi=sub2ind([n_f_all,n_v^4],alli,allj); + newj=ones(size(newi)); + + fvvvv=sparse(newi,newj,allvals,n_f_all*n_v^4,1); + end +else + if approx>=1 +% prefv=changecols(prefv,model.prefvars,n_v_tp,1); + tempv=1:n_v; + tempv(2*n_y+n_x)=[]; + tempv(end)=[]; +% prefv=changecols(prefv,tempv,n_v,1); +% prefv=changerows(prefv,model.prefrows,n_f); + + stochfv_vec=changecols(stochfv_vec,model.stochfvars,n_v_tp,1); + stochfv_vec=changecols(stochfv_vec,tempv,n_v,1); + stochfv_vec=changerows(stochfv_vec,model.stochfrows,n_f); + + Phiv_vec=changecols(Phiv_vec,model.Phivars,n_v_tp,1); + Phiv_vec=changecols(Phiv_vec,tempv,n_v,1); + +% [prei,prej,prevals]=tfind(unfold(prefv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfv_vec)); + + temp=repmat((0:n_s-1)*double(stochfv_vec.tsize(1)),numel(stochi),1); + stochi=repmat(stochi,n_s,1)+temp(:); + stochj=repmat(stochj,n_s,1); + stochvals=stochvals'; + stochvals=stochvals(:); + + Phiv_vec.vals=Phiv_vec.vals(1,:); + + [Phii,Phij,Phivals]=tfind(unfold(Phiv_vec)); + Phii=Phii+n_f_all-n_x2; + +% fv=sparse(double([prei;stochi]),double([prej;stochj]),double([prevals(:);stochvals(:)]),n_f,n_v); + fv=sparse(double([stochi;Phii]),double([stochj;Phij]),double([stochvals(:);Phivals(:)]),n_f_all,n_v); + end + if approx>=2 +% prefvv=changecols(prefvv,model.prefvars,n_v_tp,1); +% prefvv=changecols(prefvv,model.prefvars,n_v_tp,2); +% prefvv=changecols(prefvv,tempv,n_v,1); +% prefvv=changecols(prefvv,tempv,n_v,2); +% prefvv=changerows(prefvv,model.prefrows,n_f); + + stochfvv_vec=changecols(stochfvv_vec,model.stochfvars,n_v_tp,1); + stochfvv_vec=changecols(stochfvv_vec,model.stochfvars,n_v_tp,2); + stochfvv_vec=changecols(stochfvv_vec,tempv,n_v,1); + stochfvv_vec=changecols(stochfvv_vec,tempv,n_v,2); + stochfvv_vec=changerows(stochfvv_vec,model.stochfrows,n_f); + + Phivv_vec=changecols(Phivv_vec,model.Phivars,n_v_tp,1); + Phivv_vec=changecols(Phivv_vec,model.Phivars,n_v_tp,2); + Phivv_vec=changecols(Phivv_vec,tempv,n_v,1); + Phivv_vec=changecols(Phivv_vec,tempv,n_v,2); + + +% [prei,prej,prevals]=tfind(unfold(prefvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvv_vec)); + + temp=repmat((0:n_s-1)*double(stochfvv_vec.tsize(1)),numel(stochi),1); + stochi=repmat(stochi,n_s,1)+temp(:); + stochj=repmat(stochj,n_s,1); + stochvals=stochvals'; + stochvals=stochvals(:); + + Phivv_vec.vals=Phivv_vec.vals(1,:); + + [Phii,Phij,Phivals]=tfind(unfold(Phivv_vec)); + Phii=Phii+n_f_all-n_x2; + + alli=double([stochi;Phii]); + allj=double([stochj;Phij]); + allvals=double([stochvals(:);Phivals(:)]); + + newi=sub2ind([n_f_all,n_v^2],alli,allj); + newj=ones(size(newi)); + + fvv=sparse(newi,newj,allvals,n_f_all*n_v^2,1); + end + if approx>=3 +% prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,1); +% prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,2); +% prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,3); +% prefvvv=changecols(prefvvv,tempv,n_v,1); +% prefvvv=changecols(prefvvv,tempv,n_v,2); +% prefvvv=changecols(prefvvv,tempv,n_v,3); +% prefvvv=changerows(prefvvv,model.prefrows,n_f); + + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,1); + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,2); + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,3); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,1); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,2); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,3); + stochfvvv_vec=changerows(stochfvvv_vec,model.stochfrows,n_f); + + Phivvv_vec=changecols(Phivvv_vec,model.Phivars,n_v_tp,1); + Phivvv_vec=changecols(Phivvv_vec,model.Phivars,n_v_tp,2); + Phivvv_vec=changecols(Phivvv_vec,model.Phivars,n_v_tp,3); + Phivvv_vec=changecols(Phivvv_vec,tempv,n_v,1); + Phivvv_vec=changecols(Phivvv_vec,tempv,n_v,2); + Phivvv_vec=changecols(Phivvv_vec,tempv,n_v,3); + + +% [prei,prej,prevals]=tfind(unfold(prefvvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvvv_vec)); + temp=repmat((0:n_s-1)*double(stochfvvv_vec.tsize(1)),numel(stochi),1); + stochi=repmat(stochi,n_s,1)+temp(:); + stochj=repmat(stochj,n_s,1); + stochvals=stochvals'; + stochvals=stochvals(:); + + Phivvv_vec.vals=Phivvv_vec.vals(1,:); + [Phii,Phij,Phivals]=tfind(unfold(Phivvv_vec)); + Phii=Phii+n_f_all-n_x2; + + alli=double([stochi;Phii]); + allj=double([stochj;Phij]); + allvals=double([stochvals(:);Phivals(:)]); + + newi=sub2ind([n_f_all,n_v^3],alli,allj); + newj=ones(size(newi)); + + fvvv=sparse(newi,newj,allvals,n_f_all*n_v^3,1); + end + if approx>=4 +% prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,1); +% prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,2); +% prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,3); +% prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,4); +% prefvvvv=changecols(prefvvvv,tempv,n_v,1); +% prefvvvv=changecols(prefvvvv,tempv,n_v,2); +% prefvvvv=changecols(prefvvvv,tempv,n_v,3); +% prefvvvv=changecols(prefvvvv,tempv,n_v,4); +% prefvvvv=changerows(prefvvvv,model.prefrows,n_f); + + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,1); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,2); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,3); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,4); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,1); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,2); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,3); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,4); + stochfvvvv_vec=changerows(stochfvvvv_vec,model.stochfrows,n_f); + + Phivvvv_vec=changecols(Phivvvv_vec,model.Phivars,n_v_tp,1); + Phivvvv_vec=changecols(Phivvvv_vec,model.Phivars,n_v_tp,2); + Phivvvv_vec=changecols(Phivvvv_vec,model.Phivars,n_v_tp,3); + Phivvvv_vec=changecols(Phivvvv_vec,model.Phivars,n_v_tp,4); + Phivvvv_vec=changecols(Phivvvv_vec,tempv,n_v,1); + Phivvvv_vec=changecols(Phivvvv_vec,tempv,n_v,2); + Phivvvv_vec=changecols(Phivvvv_vec,tempv,n_v,3); + Phivvvv_vec=changecols(Phivvvv_vec,tempv,n_v,4); + + +% [prei,prej,prevals]=tfind(unfold(prefvvvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvvvv_vec)); + temp=repmat((0:n_s-1)*double(stochfvvvv_vec.tsize(1)),numel(stochi),1); + stochi=repmat(stochi,n_s,1)+temp(:); + stochj=repmat(stochj,n_s,1); + stochvals=stochvals'; + stochvals=stochvals(:); + + Phivvvv_vec.vals=Phivvvv_vec.vals(1,:); + + [Phii,Phij,Phivals]=tfind(unfold(Phivvvv_vec)); + Phii=Phii+n_f_all-n_x2; + + alli=double([stochi;Phii]); + allj=double([stochj;Phij]); + allvals=double([stochvals(:);Phivals(:)]); + + newi=sub2ind([n_f_all,n_v^4],alli,allj); + newj=ones(size(newi)); + + fvvvv=sparse(newi,newj,allvals,n_f_all*n_v^4,1); + end +end diff --git a/105/replication_package/solution_methods/taylor_projection/create_GAMMA.m b/105/replication_package/solution_methods/taylor_projection/create_GAMMA.m new file mode 100644 index 0000000000000000000000000000000000000000..65022ab16a8ba242d5e72e16756ec4ab40fb1a80 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/create_GAMMA.m @@ -0,0 +1,61 @@ +function [ GAMMA ] = create_GAMMA( n_x,n_theta,varargin ) +%The function creates sparse matrices GAMMA1, GAMMA2, ... +% +% � Copyright, Oren Levintal, June 13, 2016. + +if length(varargin)==1 + order_vec=varargin{1}; % do only specified order +else + order_vec=2:3; % do all orders +end + +for order=order_vec + + if order==2 + ind=1:n_x*n_x; + M=reshape(ind,n_x,n_x); + Ix=speye(n_x*n_x); + GAMMA.GAMMA1=Ix(:,ipermute(M,[2,1]))+Ix(:,ipermute(M,[1,2])); + end + + if order==3 + ind=1:n_x^3; + M=reshape(ind,n_x,n_x,n_x); + Ix=speye(n_x^3); + GAMMA.GAMMA2=Ix(:,ipermute(M,[3,2,1]))+Ix(:,ipermute(M,[2,3,1]))+Ix(:,ipermute(M,[1,3,2])); + + GAMMA.GAMMA3=Ix(:,ipermute(M,[2,3,1]))+Ix(:,ipermute(M,[1,3,2]))+Ix(:,ipermute(M,[1,2,3])); + + GAMMA.GAMMA4=Ix(:,ipermute(M,[2,3,1]))+Ix(:,ipermute(M,[1,3,2]))+Ix(:,ipermute(M,[1,2,3])); + + GAMMA.GAMMA5=Ix(:,ipermute(M,[ 2,3,1 ]))+Ix(:,ipermute(M,[ 1,3,2 ]))+Ix(:,ipermute(M,[ 1,2,3 ])); + end + if order==4 + ind=1:n_x^4; + M=reshape(ind,n_x,n_x,n_x,n_x); + Ix=speye(n_x^4); + GAMMA.GAMMA16=Ix+Ix(:,ipermute(M,[4,3,5,6]-2))+Ix(:,ipermute(M,[5,3,4,6]-2))+Ix(:,ipermute(M,[6,3,4,5]-2)); + + GAMMA.GAMMA2=Ix+Ix(:,ipermute(M,[5,4,3,6]-2))+Ix(:,ipermute(M,[6,4,3,5]-2))+Ix(:,ipermute(M,[5,3,4,6]-2))+Ix(:,ipermute(M,[6,3,4,5]-2))+Ix(:,ipermute(M,[6,5,4,3]-2)); + + GAMMA.GAMMA17=Ix+Ix(:,ipermute(M,[3,4,6,5]-2)); + + GAMMA.GAMMA3=Ix+Ix(:,ipermute(M,[ 6 4 5 3]-2))+Ix(:,ipermute(M,[ 6 3 5 4]-2))+Ix(:,ipermute(M,[ 6 3 4 5]-2)); + + GAMMA.GAMMA4=Ix+Ix(:,ipermute(M,[5,4,3,6]-2))+Ix(:,ipermute(M,[5,3,4,6]-2)); + + GAMMA.GAMMA18=Ix+Ix(:,ipermute(M,[5,6,3,4]-2)); + + +% GAMMA.GAMMA3=1(:,ipermute(M,[2,3,1]))+Ix(:,ipermute(M,[1,3,2]))+Ix(:,ipermute(M,[1,2,3])); +% +% GAMMA.GAMMA4=Ix(:,ipermute(M,[2,3,1]))+Ix(:,ipermute(M,[1,3,2]))+Ix(:,ipermute(M,[1,2,3])); +% +% GAMMA.GAMMA5=Ix(:,ipermute(M,[ 2,3,1 ]))+Ix(:,ipermute(M,[ 1,3,2 ]))+Ix(:,ipermute(M,[ 1,2,3 ])); + end + +end + +end + + diff --git a/105/replication_package/solution_methods/taylor_projection/create_OMEGA.m b/105/replication_package/solution_methods/taylor_projection/create_OMEGA.m new file mode 100644 index 0000000000000000000000000000000000000000..5d52e9f9310d08448e201238c59af2041fccb56c --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/create_OMEGA.m @@ -0,0 +1,53 @@ +function [ OMEGA ] = create_OMEGA( n_x,varargin ) +%The function creates sparse matrices OMEGA1,..,OMEGA9, that are used for +%the high-order multivariate chain rules described in Levintal, Oren, +%"Fifth Order Perturbation Solution to DSGE Models", 2014. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if length(varargin)==1 + order=varargin{1}; % do only specified order +else + order=0; % do orders 3,4,5 +end + +if order==3 || order==0 + ind=[1:n_x^3]; + M=reshape(ind,1,n_x,n_x,n_x); + Ix=speye(n_x^3); + OMEGA.OMEGA1=Ix(:,ipermute(M,[1,3,4,2]))+Ix(:,ipermute(M,[1,2,4,3]))+Ix(:,ipermute(M,[1,2,3,4])); +end + +if order==4 || order==0 + ind=[1:n_x^4]; + M=reshape(ind,1,n_x,n_x,n_x,n_x); + Ix=speye(n_x^4); + OMEGA.OMEGA2=Ix(:,ipermute(M,[1,4,5,3,2]))+Ix(:,ipermute(M,[1,3,5,4,2]))+Ix(:,ipermute(M,[1,2,5,4,3]))... + +Ix(:,ipermute(M,[1,3,4,5,2]))+Ix(:,ipermute(M,[1,2,4,5,3]))+Ix(:,ipermute(M,[1,2,3,5,4])); + OMEGA.OMEGA3=Ix(:,ipermute(M,[1,3,4,5,2]))+Ix(:,ipermute(M,[1,2,4,5,3]))+Ix(:,ipermute(M,[1,2,3,5,4]))+Ix(:,ipermute(M,[1,2,3,4,5])); + OMEGA.OMEGA4=Ix(:,ipermute(M,[1,3,4,2,5]))+Ix(:,ipermute(M,[1,2,4,3,5]))+Ix(:,ipermute(M,[1,2,3,4,5])); +end + +if order==5 || order==0 + ind=[1:n_x^5]; + M=reshape(ind,1,n_x,n_x,n_x,n_x,n_x); + Ix=speye(n_x^5); + OMEGA.OMEGA5=Ix(:,ipermute(M,[1,5,6,4,3,2]))+Ix(:,ipermute(M,[1,4,6,5,3,2]))+Ix(:,ipermute(M,[1,3,6,5,4,2]))+Ix(:,ipermute(M,[1,2,6,5,4,3]))... + +Ix(:,ipermute(M,[1,4,5,6,3,2]))+Ix(:,ipermute(M,[1,3,5,6,4,2]))... + +Ix(:,ipermute(M,[1,2,5,6,4,3]))+Ix(:,ipermute(M,[1,3,4,6,5,2]))+Ix(:,ipermute(M,[1,2,4,6,5,3]))+Ix(:,ipermute(M,[1,2,3,6,5,4])); + OMEGA.OMEGA6=Ix(:,ipermute(M,[1,4,5,6,3,2]))+Ix(:,ipermute(M,[1,3,5,6,4,2]))+Ix(:,ipermute(M,[1,2,5,6,4,3]))+Ix(:,ipermute(M,[1,3,4,6,5,2]))... + +Ix(:,ipermute(M,[1,2,4,6,5,3]))+Ix(:,ipermute(M,[1,2,3,6,5,4]))+Ix(:,ipermute(M,[1,3,4,5,6,2]))... + +Ix(:,ipermute(M,[1,2,4,5,6,3]))+Ix(:,ipermute(M,[1,2,3,5,6,4]))+Ix(:,ipermute(M,[1,2,3,4,6,5])); + OMEGA.OMEGA7=Ix(:,ipermute(M,[1,4,5,3,6,2]))+Ix(:,ipermute(M,[1,3,5,4,6,2]))+Ix(:,ipermute(M,[1,2,5,4,6,3]))... + +Ix(:,ipermute(M,[1,3,4,5,6,2]))+Ix(:,ipermute(M,[1,2,4,5,6,3]))+Ix(:,ipermute(M,[1,2,3,5,6,4]))... + +Ix(:,ipermute(M,[1,4,5,2,6,3]))+Ix(:,ipermute(M,[1,3,5,2,6,4]))+Ix(:,ipermute(M,[1,2,5,3,6,4]))... + +Ix(:,ipermute(M,[1,3,4,2,6,5]))+Ix(:,ipermute(M,[1,2,4,3,6,5]))+Ix(:,ipermute(M,[1,2,3,4,6,5]))... + +Ix(:,ipermute(M,[1,3,4,2,5,6]))+Ix(:,ipermute(M,[1,2,4,3,5,6]))+Ix(:,ipermute(M,[1,2,3,4,5,6])); + OMEGA.OMEGA8=Ix(:,ipermute(M,[1,3,4,5,6,2]))+Ix(:,ipermute(M,[1,2,4,5,6,3]))+Ix(:,ipermute(M,[1,2,3,5,6,4]))+Ix(:,ipermute(M,[1,2,3,4,6,5]))+Ix(:,ipermute(M,[1,2,3,4,5,6])); + OMEGA.OMEGA9=Ix(:,ipermute(M,[1,3,4,5,2,6]))+Ix(:,ipermute(M,[1,2,4,5,3,6]))+Ix(:,ipermute(M,[1,2,3,5,4,6]))+Ix(:,ipermute(M,[1,2,3,4,5,6]))... + +Ix(:,ipermute(M,[1,3,4,6,2,5]))+Ix(:,ipermute(M,[1,2,4,6,3,5]))+Ix(:,ipermute(M,[1,2,3,6,4,5]))... + +Ix(:,ipermute(M,[1,2,5,6,3,4]))+Ix(:,ipermute(M,[1,3,5,6,2,4]))+Ix(:,ipermute(M,[1,4,5,6,2,3])); +end + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/create_OMEGA_x.m b/105/replication_package/solution_methods/taylor_projection/create_OMEGA_x.m new file mode 100644 index 0000000000000000000000000000000000000000..467868e50ad9ddc14fd930528bce1bcd3b074574 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/create_OMEGA_x.m @@ -0,0 +1,22 @@ +% +% � Copyright, Oren Levintal, June 13, 2016. +OMEGA_x=[]; +if approx>=3 + tempOMEGA = create_OMEGA( n_x,3 ); + OMEGA_x.OMEGA1=tempOMEGA.OMEGA1; +end + +if approx>=4 + tempOMEGA = create_OMEGA( n_x,4 ); + OMEGA_x.OMEGA2=tempOMEGA.OMEGA2; + OMEGA_x.OMEGA3=tempOMEGA.OMEGA3; + OMEGA_x.OMEGA4=tempOMEGA.OMEGA4; +end +if approx>=5 + tempOMEGA = create_OMEGA( n_x,5 ); + OMEGA_x.OMEGA5=tempOMEGA.OMEGA5; + OMEGA_x.OMEGA6=tempOMEGA.OMEGA6; + OMEGA_x.OMEGA7=tempOMEGA.OMEGA7; + OMEGA_x.OMEGA8=tempOMEGA.OMEGA8; + OMEGA_x.OMEGA9=tempOMEGA.OMEGA9; +end diff --git a/105/replication_package/solution_methods/taylor_projection/create_UW.m b/105/replication_package/solution_methods/taylor_projection/create_UW.m new file mode 100644 index 0000000000000000000000000000000000000000..0560026cde9504572ee1e2a37619c85cea3f2563 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/create_UW.m @@ -0,0 +1,59 @@ +function [U,W]=create_UW(n,k,varargin) +% [U,W]=create_UW(n,k) creates two sparse matrices, U and W, that compress and +% uncompress a symmetric array A with k dimensions and n^k elements. +% A(:)'*U is a row vector that contains the unique elements of A, +% and A(:)'=(A(:)'*U)*W. +% [U,W]=create_UW(n,k,N) creates matrices U and W of a sparse symmetric +% array A with k dimensions and n^k elements. N is a vector of size n^k, +% where N(j)=1 if A(j)~=0 and zero otherwise. If B is a row +% vector with the nonzero elements of the row vector A(:)', then B*U +% is a row vector of the unique nonzero elements of A, and B=(B*U)*W. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if isempty(varargin) +% nonzero=ones(n^k,1); + I=[1:n^k]; +else + nonzero=varargin{1}; + I=find(nonzero); +end + +if isempty(I) + error('The symmetric array is all zero') +end + +I=I(:); +% nonzero(nonzero~=0)=1; nonzero=nonzero(:); +sizeM='n'; +subind='I1'; +for i=2:k + sizeM=[sizeM ' n']; + subind=[subind ',I' num2str(i) ]; +end + +eval(['[' subind ']=ind2sub([' sizeM '],I);']); % I is a linear index of all nonzero elements. +eval(['M=[' subind '];']); + +M=sort(M,2); % sort columns +[M,I]=sortrows(M); % sort rows +if size(M,1)==1 + DM=1; +else + DM=[1;(sum(abs(diff(M)),2)~=0)]; +end +group=cumsum(DM); +minI=accumarray(group,I,[],@min); +newi=minI(group); + +unique=newi(DM>0); % index of unique nonzero elements + +n_unique=length(unique); + +U= sparse(unique,[1:n_unique]',ones(n_unique,1),length(I),n_unique); + +W= sparse(group,I,ones(length(I),1),n_unique,length(I)); + +end + + diff --git a/105/replication_package/solution_methods/taylor_projection/create_X.m b/105/replication_package/solution_methods/taylor_projection/create_X.m new file mode 100644 index 0000000000000000000000000000000000000000..df1172f62163c91f578fafb07244cd8ce8a3b5c4 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/create_X.m @@ -0,0 +1,52 @@ +function [X,Xx,Xxx,Xxxx,Xxxxx,Xxxxxx]=create_X(N,n_x,x,c0,W2,unique2,W3,unique3,W4,unique4) +% compute the basis function and its derivatives +% +% � Copyright, Oren Levintal, June 13, 2016. +% extended to 4th order on January 19, 2017. + +Xx=[];Xxx=[]; Xxxx=[]; Xxxxx=[]; Xxxxxx=[]; +if N==0 + X=1; + Xx=sparse(1,n_x); +elseif N>=1 + x_c0=sparse(x-c0); + X=[1;x_c0]; + Xx=[sparse(1,n_x);speye(n_x)]; +end +if N==1 + Xxx=sparse(1+n_x,n_x^2); +elseif N>=2 + tempx=reshape(reshape(W2,unique2*n_x,n_x)*x_c0,unique2,n_x); + temp=tempx*x_c0; + X=[X;temp]; + Xx=[Xx;2*tempx]; + Xxx=[sparse(1+n_x,n_x^2);2*W2]; +end +if N==2 + Xxxx=sparse(1+n_x+unique2,n_x^3); +elseif N>=3 + tempxx=reshape(reshape(W3,unique3*n_x^2,n_x)*x_c0,unique3,n_x^2); + tempx=reshape(reshape(tempxx,unique3*n_x,n_x)*x_c0,unique3,n_x); + temp=tempx*x_c0; + X=[X;temp]; + Xx=[Xx;3*tempx]; + Xxx=[Xxx;6*tempxx]; + Xxxx=[sparse(1+n_x+unique2,n_x^3);6*W3]; +end +if N==3 + Xxxxx=sparse(1+n_x+unique2+unique3,n_x^4); +elseif N>=4 + tempxxx=reshape(reshape(W4,unique4*n_x^3,n_x)*x_c0,unique4,n_x^3); + tempxx=reshape(reshape(tempxxx,unique4*n_x^2,n_x)*x_c0,unique4,n_x^2); + tempx=reshape(reshape(tempxx,unique4*n_x,n_x)*x_c0,unique4,n_x); + temp=tempx*x_c0; + X=[X;temp]; + Xx=[Xx;4*tempx]; + Xxx=[Xxx;12*tempxx]; + Xxxx=[Xxxx;24*tempxxx]; + Xxxxx=[sparse(1+n_x+unique2+unique3,n_x^4);24*W4]; +end +if N==4 + Xxxxxx=sparse(1+n_x+unique2+unique3+unique4,n_x^5); +end +end diff --git a/105/replication_package/solution_methods/taylor_projection/create_X_no_derivs.m b/105/replication_package/solution_methods/taylor_projection/create_X_no_derivs.m new file mode 100644 index 0000000000000000000000000000000000000000..3df79da6c226da099cde0fa742f37c44c5204145 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/create_X_no_derivs.m @@ -0,0 +1,28 @@ +function [X]=create_X_no_derivs(N,n_x,x,c0,W2,unique2,W3,unique3,W4,unique4) +% compute the basis function and its derivatives +% +% � Copyright, Oren Levintal, April 25, 2017. + + +x_c0=sparse(x-c0); +X=[1;x_c0]; +if N>=2 + tempx=reshape(reshape(W2,unique2*n_x,n_x)*x_c0,unique2,n_x); + temp=tempx*x_c0; + X=[X;temp]; +end +if N>=3 + tempxx=reshape(reshape(W3,unique3*n_x^2,n_x)*x_c0,unique3,n_x^2); + tempx=reshape(reshape(tempxx,unique3*n_x,n_x)*x_c0,unique3,n_x); + temp=tempx*x_c0; + X=[X;temp]; +end +if N>=4 + tempxxx=reshape(reshape(W4,unique4*n_x^3,n_x)*x_c0,unique4,n_x^3); + tempxx=reshape(reshape(tempxxx,unique4*n_x^2,n_x)*x_c0,unique4,n_x^2); + tempx=reshape(reshape(tempxx,unique4*n_x,n_x)*x_c0,unique4,n_x); + temp=tempx*x_c0; + X=[X;temp]; +end + +end diff --git a/105/replication_package/solution_methods/taylor_projection/create_X_tensor.m b/105/replication_package/solution_methods/taylor_projection/create_X_tensor.m new file mode 100644 index 0000000000000000000000000000000000000000..c82d72f01d99995c2bdd01e802b57985f6c32121 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/create_X_tensor.m @@ -0,0 +1,65 @@ +function [X,Xx,Xxx,Xxxx,Xxxxx,Xxxxxx,ind]=create_X_tensor(N,x_c0,M2,M3,M3x,W2,W3,M4,M4x,M4xx,M4xxx,unique2,unique3,unique4,ind,n_ind,maxload,sum) +% +% � Copyright, Oren Levintal, June 13, 2016. +% changed on January 23, 2017 - extended to 4th order +if isempty(ind) + ind=cell(9,1); +end +n_x=x_c0.tsize(1); + +Xx=[];Xxx=[]; Xxxx=[]; Xxxxx=[]; Xxxxxx=[]; +n_s=size(x_c0.vals,1); +temp=sptensor(1); +temp.vals=repmat(temp.vals,n_s,1); +X=temp; +if N==0 + Xx=sptensor(1,n_x,n_s); +elseif N>=1 + X=vconcat(X,x_c0); + + Ix=spteye(n_x,n_s); + Xx=vconcat(sptensor(1,n_x,n_s),Ix); +end +if N==1 + Xxx=sptensor(1+n_x,n_x^2,n_s); +elseif N>=2 + [temp,ind{1}]=contraction2(M2,x_c0,x_c0,ind{1},n_ind,maxload,sum); + X=vconcat(X,unfold(temp)); + twoW2=multscalar(W2,2); + twoW2.vals=repmat(twoW2.vals,n_s,1); + [tempx,ind{2}]=contraction2(twoW2,x_c0,Ix,ind{2},n_ind,maxload,sum); + Xx=vconcat(Xx,unfold(tempx)); + Xxx=vconcat(sptensor(1+n_x,n_x^2,n_s),unfold(twoW2)); +end +if N==2 + Xxxx=sptensor(1+n_x+unique2,n_x^3,n_s); +elseif N>=3 + [temp,ind{3}]=contraction3(M3,x_c0,x_c0,x_c0,ind{3},n_ind,maxload,sum); + X=vconcat(X,unfold(temp)); + [tempx,ind{4}]=contraction3(M3x,x_c0,x_c0,Ix,ind{4},n_ind,maxload,sum); + Xx=vconcat(Xx,unfold(tempx)); + Ix6=multscalar(Ix,6); + [tempxx,ind{5}]=contraction3(W3,x_c0,Ix,Ix6,ind{5},n_ind,maxload,sum); + + Xxx=vconcat(Xxx,unfold(tempxx)); + sixW3=multscalar(W3,6); + sixW3.vals=repmat(sixW3.vals,n_s,1); + Xxxx=vconcat(sptensor(1+n_x+unique2,n_x^3,n_s),unfold(sixW3)); +end +if N==3 + Xxxxx=sptensor(1+n_x+unique2+unique3,n_x^4,n_s); +elseif N>=4 + [temp,ind{6}]=contraction4(M4,x_c0,x_c0,x_c0,x_c0,ind{6},n_ind,maxload,sum); + X=vconcat(X,unfold(temp)); + [tempx,ind{7}]=contraction4(M4x,x_c0,x_c0,x_c0,Ix,ind{7},n_ind,maxload,sum); + Xx=vconcat(Xx,unfold(tempx)); + [tempxx,ind{8}]=contraction4(M4xx,x_c0,x_c0,Ix,Ix,ind{8},n_ind,maxload,sum); + Xxx=vconcat(Xxx,unfold(tempxx)); + [tempxxx,ind{9}]=contraction4(M4xxx,x_c0,Ix,Ix,Ix,ind{9},n_ind,maxload,sum); + Xxxx=vconcat(Xxxx,unfold(tempxxx)); + M4xxx.vals=repmat(M4xxx.vals,n_s,1); + Xxxxx=vconcat(sptensor(1+n_x+unique2+unique3,n_x^4,n_s),unfold(M4xxx)); +end +if N==4 + Xxxxxx=sptensor(1+n_x+unique2+unique3+unique4,n_x^5,n_s); +end diff --git a/105/replication_package/solution_methods/taylor_projection/create_X_tensor_no_derivs.m b/105/replication_package/solution_methods/taylor_projection/create_X_tensor_no_derivs.m new file mode 100644 index 0000000000000000000000000000000000000000..94f316bad34f375b1c76ae0ff77e6a2b908700cd --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/create_X_tensor_no_derivs.m @@ -0,0 +1,32 @@ +function [X,ind]=create_X_tensor_no_derivs(N,x_c0,M2,M3,M4,ind,n_ind,maxload,sum) +% +% � Copyright, Oren Levintal, June 13, 2016. + +if isempty(ind) + ind=cell(5,1); +end +n_x=x_c0.tsize(1); + +n_s=size(x_c0.vals,1); +temp=sptensor(1); +temp.vals=repmat(temp.vals,n_s,1); +X=temp; + +if N>=1 + X=vconcat(X,x_c0); +end + +if N>=2 + [temp,ind{1}]=contraction2(M2,x_c0,x_c0,ind{1},n_ind,maxload,sum); + X=vconcat(X,unfold(temp)); +end + +if N>=3 + [temp,ind{3}]=contraction3(M3,x_c0,x_c0,x_c0,ind{3},n_ind,maxload,sum); + X=vconcat(X,unfold(temp)); +end + +if N>=4 + [temp,ind{4}]=contraction4(M4,x_c0,x_c0,x_c0,x_c0,ind{4},n_ind,maxload,sum); + X=vconcat(X,unfold(temp)); +end diff --git a/105/replication_package/solution_methods/taylor_projection/create_compression_matrices_nonzero2.m b/105/replication_package/solution_methods/taylor_projection/create_compression_matrices_nonzero2.m new file mode 100644 index 0000000000000000000000000000000000000000..0cdec71d9d0d1c647fa4e6fb8066c48d52ed50b5 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/create_compression_matrices_nonzero2.m @@ -0,0 +1,77 @@ +function [UW]=create_compression_matrices_nonzero2(approx,n_x) +% +% � Copyright, Oren Levintal, June 13, 2016. + +if approx>=2 + k=2; + nonzero=reshape(ones(1,n_x^k),n_x,n_x); + nonzero(end,1:end-1)=0; + nonzero(1:end-1,end)=0; + [U2,W2]=create_UW(n_x,k,nonzero(:)); + nnz=find(nonzero); + N2=sparse(nnz,1:length(nnz),ones(1,length(nnz)),n_x^k,length(nnz)); + U2=N2*U2; + W2=W2*N2'; +end + +if approx>=3 + k=3; + nonzero=reshape(ones(1,n_x^k),n_x,n_x,n_x); + nonzero(end,1:end-1,1:end-1)=0; + nonzero(1:end-1,end,1:end-1)=0; + nonzero(1:end-1,1:end-1,end)=0; + [U3,W3]=create_UW(n_x,k,nonzero(:)); + nnz=find(nonzero); + N3=sparse(nnz,1:length(nnz),ones(1,length(nnz)),n_x^k,length(nnz)); + U3=N3*U3; + W3=W3*N3'; +end + +if approx>=4 + k=4; + nonzero=reshape(ones(1,n_x^k),n_x,n_x,n_x,n_x); + nonzero(end,1:end-1,1:end-1,1:end-1)=0; + nonzero(1:end-1,end,1:end-1,1:end-1)=0; + nonzero(1:end-1,1:end-1,end,1:end-1)=0; + nonzero(1:end-1,1:end-1,1:end-1,end)=0; + [U4,W4]=create_UW(n_x,k,nonzero(:)); + nnz=find(nonzero); + N4=sparse(nnz,1:length(nnz),ones(1,length(nnz)),n_x^k,length(nnz)); + U4=N4*U4; + W4=W4*N4'; +end + +if approx>=5 + k=5; + nonzero=reshape(ones(1,n_x^k),n_x,n_x,n_x,n_x,n_x); + nonzero(end,1:end-1,1:end-1,1:end-1,1:end-1)=0; + nonzero(1:end-1,end,1:end-1,1:end-1,1:end-1)=0; + nonzero(1:end-1,1:end-1,end,1:end-1,1:end-1)=0; + nonzero(1:end-1,1:end-1,1:end-1,end,1:end-1)=0; + nonzero(1:end-1,1:end-1,1:end-1,1:end-1,end)=0; + [U5,W5]=create_UW(n_x,k,nonzero(:)); + nnz=find(nonzero); + N5=sparse(nnz,1:length(nnz),ones(1,length(nnz)),n_x^k,length(nnz)); + U5=N5*U5; + W5=W5*N5'; +end + +if approx==1 + UW=struct([]); +elseif approx==2 + UW.U2=U2; UW.W2=W2; +elseif approx==3 + UW.U2=U2; UW.W2=W2; + UW.U3=U3; UW.W3=W3; +elseif approx==4 + UW.U2=U2; UW.W2=W2; + UW.U3=U3; UW.W3=W3; + UW.U4=U4; UW.W4=W4; +elseif approx==5 + UW.U2=U2; UW.W2=W2; + UW.U3=U3; UW.W3=W3; + UW.U4=U4; UW.W4=W4; + UW.U5=U5; UW.W5=W5; +end + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/derivs2coeffs.m b/105/replication_package/solution_methods/taylor_projection/derivs2coeffs.m new file mode 100644 index 0000000000000000000000000000000000000000..d0b549a13f8ea7bdf56edfcef48b7a9876f7a406 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/derivs2coeffs.m @@ -0,0 +1,26 @@ +function [ coeffs ] = derivs2coeffs( model,G0,varargin ) +%The function converts derivatives into a column of unique Taylor +%coefficients. +% +% � Copyright, Oren Levintal, June 13, 2016. + +order=length(varargin); +coeffs=G0(:); +n_y=length(coeffs); + +if order>=1 + temp=reshape(varargin{1},n_y,[]); + n_x=size(temp,2); + coeffs=[coeffs,temp]; +end + +for k=2:order + U=model.U{k}; + temp=reshape(varargin{k},n_y,[])*U/factorial(k); + coeffs=[coeffs,temp]; +end + +coeffs=coeffs(:); + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/diff_fun.m b/105/replication_package/solution_methods/taylor_projection/diff_fun.m new file mode 100644 index 0000000000000000000000000000000000000000..8a2e0b7e7a36f9efefa57d87fec057387c318241 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/diff_fun.m @@ -0,0 +1,204 @@ +function model=diff_fun(f,x,symparams,order,varargin) + +% This file differentiates the symbolic function f w.r.t +% the symbolic vector x up to order and returns data used to compute those +% derivatives. +% +% � Copyright, Oren Levintal, September 8, 2017. + +model.n_params=numel(symparams); + +f=sym(f(:)); + +x=sym(x(:)); + + +% SIZE VARIABLES +n_f=length(f); n_x=length(x); +v=x(:); +n_v=length(v); + +if order>5 + error('differentiation is allowed up to fifth order') +end +model.order=order; + +% fname + +if nargin>4 + fname=varargin{3}; + if ~ischar(fname) + error('function name must be a string') + end +else + fname=''; +end + +model.fname=fname; + +% DEFINE pi_ and u +if isempty(varargin) + pi_=sym([]); + u=sym([]); +elseif isempty(varargin{1}) + warning('no substitutions assumed') + pi_=sym([]); + u=sym([]); +else + pi_=varargin{1}; % pi_ is the function pi(v,u) + pi_=pi_(:); + u=varargin{2}; % auxiliary variables that are eventually substituted out + u=u(:); + if ~isequal(sort(u),unique(u)) + error('substituted variables are not uniquely determined') + end +end + +% check that all symbolic variables/parameters are defined +actualsymvars=symvar([f;pi_]); +for i=1:length(actualsymvars) + if isempty(v(v==actualsymvars(i))) && isempty(u(u==actualsymvars(i))) && isempty(symparams(symparams==actualsymvars(i))) + error([char(actualsymvars(i)) ' is not defined']) + end +end + +n_u=length(u); +model.n_u=n_u; +tilf=f; % tilf(v,u) is a function of v and u +n=find_n(pi_,u); % number of substitutions needed to eliminate u + +% Identify variables that affect u +u_v=u; %u_v which is u as a function of v only u(v) +uu=eye(n_u); % matrix to store which of u affect u +uv=zeros(n_u,n_v); +for k=1:n + u_v=subs(u_v,u,pi_); % substitute pi_ into itself n times + uu=uu+logical(jacobian(u_v,u)~=0); % uu is a n_u-by-n_u matrix. the ij element is zero only if ui is independent of uj through all substitutions + uv=uv+logical(jacobian(u_v,v)~=0); % uv is a n_u-by-n_v matrix. the ij element is zero only if ui is independent of vj through all substitutions +end + +fv=logical(logical(jacobian(tilf,v)~=0)+logical(jacobian(tilf,u)~=0)*uv~=0); % logical Jacobian of f w.r.t v +fvars=find(sum(1-logical(fv==0),1)); + +currentFolder=pwd; +if ~exist([pwd '\fun_' fname], 'dir') + mkdir(['fun_' fname]); +end + +cd(['fun_' fname]) + +% Create an m file for u +gen_fun_vec(u_v,symparams,v,'u','row'); + +% build z and find the Jacobian of z +z=[v;u]; +n_z=n_v+n_u; +zz=[eye(n_v),zeros(n_v,n_u);uv,uu]; +for i=1:n_z + temp=zz(i,:); + temp(temp~=0)=1:nnz(temp); + zz(i,:)=temp; +end +zz=intarray(zz); +model.maxzz=intarray(max(zz(:))); + +% build fv similar to zz +fv=double(fv); +for i=1:n_f + temp=fv(i,:); + temp(temp~=0)=1:nnz(temp); + fv(i,:)=temp; +end +model.fv=fv; + +tilfz=jacobian(tilf,z); + +% build tilfz +tilfz=double(logical(tilfz~=0)); % only direct effects +for i=1:n_f + temp=tilfz(i,:); + temp(temp~=0)=1:nnz(temp); + tilfz(i,:)=temp; +end +model.tilfz=tilfz; +model.maxtilfz=intarray(max(tilfz(:))); + +% Create an m file for tilf +tilfzvars=find(sum(1-logical(tilfz==0),1)); +model.tilfzvars=tilfzvars; % variables in z that affect tilf +gen_fun_vec(tilf,symparams,z(tilfzvars),['tilf' fname],'row'); + +% Differentiate PI and create m files + +PI=[v;pi_]; + +[model.PI_ind_u]=getderivs_tensor(PI,z,order,symparams,'PI'); + +fuvars=find(sum(uu(logical(sum(logical(jacobian(tilf,u)~=0),1)~=0),:),1)); +model.fuvars=fuvars; + +fzvars=[fvars,n_v+fuvars]; +model.n_fzvars=length(fzvars); + +[model.tilf_ind_u,model.pre_n]=gen_chainderivs_tensor(tilf,v,u,pi_,order,symparams,['tilf' fname]); + +% Store variables in struct model +model.fvars=fvars; +model.fzvars=fzvars; + +model.n_f=n_f; +model.n_x=n_x; + +model.n_v=n_v; +model.n_z=n_z; +model.n_u=n_u; + +model.n_ind=1; + +% calculate some big matrices now + +if order>=3 + save('tempfile') + n_fvars=length(fvars); + clearvars -except n_fvars + + if n_fvars>0 + [ tempM ] = chainsM( n_fvars,4 ); + else + tempM=cell(4,1); + end + load('tempfile') + model.fvars_chain4c_M2=tempM{2}; + model.fvars_chain4c_M3=tempM{3}; + model.fvars_chain4c_M4=tempM{4}; + clear tempM + delete('tempfile.mat') +end + +if order>=4 + save('tempfile') + n_fvars=length(fvars); + clearvars -except n_fvars + + if n_fvars>0 + [ tempM ] = chainsM( n_efvars,5 ); + else + tempM=cell(6,1); + end + load('tempfile') + model.fvars_chain5c_M1=tempM{1}; + model.fvars_chain5c_M2=tempM{2}; + model.fvars_chain5c_M3=tempM{3}; + model.fvars_chain5c_M4=tempM{4}; + model.fvars_chain5c_M5=tempM{5}; + model.fvars_chain5c_M6=tempM{6}; + + clear tempM + + delete('tempfile.mat') +end + +rehash; + + +cd(currentFolder) \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/diff_fun2.m b/105/replication_package/solution_methods/taylor_projection/diff_fun2.m new file mode 100644 index 0000000000000000000000000000000000000000..f1725461595b2edfcffbec8f8bf2a1b859359e3e --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/diff_fun2.m @@ -0,0 +1,349 @@ +function model=diff_fun2(f,x,symparams,order,varargin) + +model.n_params=numel(symparams); + +f=sym(f(:)); +x=sym(x(:)); + +% SIZE VARIABLES +n_f=length(f); n_x=length(x); +v=[x(:)]; +n_v=length(v); + +model.order=[order]; + +% fname + +if nargin==7 + fname=varargin{3}; + if ~ischar(fname) + error('function name must be a string') + end +else + fname='new'; +end +model.fname=fname; + +% DEFINE pi_ and u +if isempty(varargin) + pi_=sym([]); + u=sym([]); +elseif isempty(varargin{1}) + warning('no substitutions assumed') + pi_=sym([]); + u=sym([]); +else + pi_=varargin{1}; % pi_ is the function pi(v,u) + pi_=pi_(:); + u=varargin{2}; % auxiliary variables that are eventually substituted out + u=u(:); + if length(pi_)~=length(u) + error('wrong size of substituted variables or functions') + end + if ~isequal(sort(u),unique(u)) + error('substituted variables are not uniquely determined') + end +end + +% check that all symbolic variables/parameters are defined +actualsymvars=symvar([f;pi_]); +for i=1:length(actualsymvars) + if isempty(v(v==actualsymvars(i))) && isempty(u(u==actualsymvars(i))) && isempty(symparams(symparams==actualsymvars(i))) + error([char(actualsymvars(i)) ' is not defined']) + end +end + +n_u=length(u); +model.n_u=n_u; +tilf=f; % tilf(v,u) is a function of v and u +% [n,u_v]=find_n(pi_,u); % number of substitutions needed to eliminate u +n=find_n_new(pi_,u); + +% Identify variables that affect u +uu=eye(n_u); % matrix to store which of u affect u +uv=zeros(n_u,n_v); + +piu0=double(logical(jacobian(pi_,u)~=0)); +piv0=double(logical(jacobian(pi_,v)~=0)); +piu=piu0; +piv=piv0; + +for k=1:n + uu=uu+piu; + uv=uv+piv; + piv=piu*piv0; + piu=piu*piu0; +end +% uu_=uu; +% uv_=uv; +% % older version +% u_v=u; %u_v which is u as a function of v only u(v) +% uu=eye(n_u); % matrix to store which of u affect u +% uv=zeros(n_u,n_v); +% for k=1:n +% u_v=subs(u_v,u,pi_); % substitute pi_ into itself n times +% uu=uu+logical(jacobian(u_v,u)~=0); % uu is a n_u-by-n_u matrix. the ij element is zero only if ui is independent of uj through all substitutions +% uv=uv+logical(jacobian(u_v,v)~=0); % uv is a n_u-by-n_v matrix. the ij element is zero only if ui is independent of vj through all substitutions +% end + +% Identify stochasic and predetermined functions and variables +% if n_x2>0 +% stochexog=find(sum(1-logical(eta(n_x1+1:end,:)==0),2)); % stochastic exogenous variables +% else +% stochexog=[]; +% end +% preexog=1:n_x2; +% preexog(stochexog)=[]; % predetermined exogenous variables +% +% stochvars=[1:n_y,2*n_y+n_x1+stochexog']; % all stochastic variables +fv=ones(n_f,n_v); +% fv=logical(logical(jacobian(tilf,v)~=0)+logical(jacobian(tilf,u)~=0)*uv~=0); % logical Jacobian of f w.r.t v + +% stochfrows=find(sum( 1-logical(fv(:,stochvars)==0),2)); % stochastic rows of f +prefrows=1:n_f; +% prefrows(stochfrows)=[]; % predetermined rows of f + +% variables that affect the predetermined and stochastic rows of f + +prefvars=find(sum(1-logical(fv(prefrows,:)==0),1)); +% stochfvars=find(sum(1-logical(fv(stochfrows,:)==0),1)); + + +currentFolder=pwd; +if ~exist([pwd '\files'], 'dir') + mkdir('files'); +end + +cd 'files' + +% generate a function that computes eta +% gen_fun_vec(eta(:),[],symparams,'eta','row'); + + +% Create an m file for Phi and its derivatives w.r.t x +% gen_fun_vec(Phi,symparams,x,'Phi','row'); +% if order>=1 +% model.Phi_indc=getderivs_c(Phi,x,max(order,pert_order),symparams,'Phi'); +% end + +% Create an m file for u +% newuv=jacobian(u_v,v); % calculate uv again +newuv=uv; +% stochurows=find(sum( 1-logical(newuv(:,stochvars)==0),2)); % stochastic rows of u +% model.stochurows=stochurows; +preurows=1:n_u; +% preurows(stochurows)=[]; % predetermined rows of u +model.preurows=preurows; +preuvars=find(sum( logical(newuv(preurows,:)~=0),1)); % variables of predetermined rows of u +% stochuvars=find(sum( logical(newuv(stochurows,:)~=0),1)); % variables of stochastic rows of u +gen_fun_vec_subs(u(preurows),symparams,v(preuvars),pi_,u,[fname 'u'],'row'); +% gen_fun_vec(u_v(stochurows),symparams,v(stochuvars),'stochu','row'); +model.preuvars=preuvars; +% model.stochuvars=stochuvars; + +% build z and find the Jacobian of z +z=[v;u]; +n_z=n_v+n_u; +zz=[eye(n_v),zeros(n_v,n_u);uv,uu]; +for i=1:n_z + temp=zz(i,:); + temp(temp~=0)=1:nnz(temp); + zz(i,:)=temp; +end +zz=intarray(zz); +model.maxzz=intarray(max(zz(:))); + +% build fv similar to zz +fv=double(fv); +for i=1:n_f + temp=fv(i,:); + temp(temp~=0)=1:nnz(temp); + fv(i,:)=temp; +end +model.fv=fv; + +tilfz=jacobian(tilf,z); + +% build tilfz +tilfz=double(logical(tilfz~=0)); % only direct effects +for i=1:n_f + temp=tilfz(i,:); + temp(temp~=0)=1:nnz(temp); + tilfz(i,:)=temp; +end +model.tilfz=tilfz; +model.maxtilfz=intarray(max(tilfz(:))); + +% Create an m file for tilf +pretilfzvars=find(sum(1-logical(tilfz(prefrows,:)==0),1)); +model.pretilfzvars=pretilfzvars; % variables in z that affect pretilf +gen_fun_vec(tilf(prefrows),symparams,z(pretilfzvars),[fname 'f'],'row'); + +% stochtilfzvars=find(sum(1-logical(tilfz(stochfrows,:)==0),1)); +% model.stochtilfzvars=stochtilfzvars; % variables in z that affect stochtilf +% gen_fun_vec(tilf(stochfrows),symparams,z(stochtilfzvars),['stochtilf' fname],'row'); + +% Differentiate PI and create m files + +PI=[v;pi_]; +prePI=PI; +% prePI(n_v+stochurows)=0; % stochastic rows of PI are set to zero. Note: the first n_v rows include stochastic variables but their derivatives w.r.t are ones or zeros. +% stochPI=PI; +% stochPI([1:n_v,n_v+preurows])=0; % nonstochastic rows are set to zero. See the note above. + +[model.prePI_ind_u]=getderivs_tensor(prePI,z,order,symparams,[fname 'PI']); +% [model.stochPI_ind_u]=getderivs_tensor(stochPI,z,max(order+1,pert_order),symparams,'stochPI'); + +prefuvars=find(sum(uu(logical(sum(logical(jacobian(tilf(prefrows),u)~=0),1)~=0),:),1)); +% stochfuvars=find(sum(uu(logical(sum(logical(jacobian(tilf(stochfrows),u)~=0),1)~=0),:),1)); +model.prefuvars=prefuvars; +% model.stochfuvars=stochfuvars; + +prefzvars=[prefvars,n_v+prefuvars]; +% stochfzvars=[stochfvars,n_v+stochfuvars]; +model.n_prefzvars=length(prefzvars); +% model.n_stochfzvars=length(stochfzvars); + +% [model.stochtilf_ind_u,model.stoch_n]=gen_chainderivs_tensor(tilf(stochfrows),v(stochfvars),u(stochfuvars),pi_(stochfuvars),max(order+1,pert_order),symparams,['stochtilf' fname]); +[model.pretilf_ind_u,model.pre_n]=gen_chainderivs_tensor(tilf(prefrows),v(prefvars),u(prefuvars),pi_(prefuvars),order,symparams,[fname 'tilf']); + + +% Store variables in struct model +model.prefrows=prefrows; +% model.stochfrows=stochfrows; +model.prefvars=prefvars; +% model.stochfvars=stochfvars; +% model.stochexog=stochexog; +% model.preexog=preexog; +% model.n_stochexog=length(stochexog); +% model.n_preexog=length(preexog); +% model.stochfzvars=stochfzvars; +model.prefzvars=prefzvars; + +% model.n_theta=n_theta; +% model.n_b=n_b; + +model.n_f=n_f; +model.n_x=n_x; +% model.n_y=n_y; +% model.n_x1=n_x1; +% model.n_x2=n_x2; + +model.n_v=n_v; +model.n_z=n_z; +model.n_u=n_u; + +model.n_ind=1; + +% model.U=cell(4,1); +% model.W=cell(4,1); +% for i=2:order+1 +% [model.U{i},model.W{i}]=create_UW(n_x,i); +% end + +% model.stochzz=zz(model.stochfzvars,model.stochfzvars); +model.prezz=zz(model.prefzvars,model.prefzvars); + +% model.stochtilfz=tilfz(model.stochfrows,model.stochfzvars); +model.pretilfz=tilfz(model.prefrows,model.prefzvars); + +% calculate some big matrices now + +if order>=4 + save('tempfile') + n_prefvars=length(prefvars); + clearvars -except n_prefvars + + if n_prefvars>0 + [ tempM ] = chainsM( n_prefvars,4 ); + else + tempM=cell(4,1); + end + load('tempfile') + model.prefvars_chain4c_M2=tempM{2}; + model.prefvars_chain4c_M3=tempM{3}; + model.prefvars_chain4c_M4=tempM{4}; + clear tempM +% save('tempfile') +% +% +% +% n_stochfvars=length(stochfvars); +% clearvars -except n_stochfvars +% +% if n_stochfvars>0 +% [ tempM ] = chainsM( n_stochfvars,4 ); +% else +% tempM=cell(4,1); +% end +% load('tempfile') +% model.stochfvars_chain4c_M2=tempM{2}; +% model.stochfvars_chain4c_M3=tempM{3}; +% model.stochfvars_chain4c_M4=tempM{4}; +% clear tempM + delete('tempfile.mat') +end + +if order>=5 + save('tempfile') + n_prefvars=length(prefvars); + clearvars -except n_prefvars + + if n_prefvars>0 + [ tempM ] = chainsM( n_prefvars,5 ); + else + tempM=cell(6,1); + end + load('tempfile') + model.prefvars_chain5c_M1=tempM{1}; + model.prefvars_chain5c_M2=tempM{2}; + model.prefvars_chain5c_M3=tempM{3}; + model.prefvars_chain5c_M4=tempM{4}; + model.prefvars_chain5c_M5=tempM{5}; + model.prefvars_chain5c_M6=tempM{6}; + + clear tempM +% save('tempfile') +% +% +% +% n_stochfvars=length(stochfvars); +% clearvars -except n_stochfvars +% +% if n_stochfvars>0 +% [ tempM ] = chainsM( n_stochfvars,5 ); +% else +% tempM=cell(6,1); +% end +% load('tempfile') +% model.stochfvars_chain5c_M1=tempM{1}; +% model.stochfvars_chain5c_M2=tempM{2}; +% model.stochfvars_chain5c_M3=tempM{3}; +% model.stochfvars_chain5c_M4=tempM{4}; +% model.stochfvars_chain5c_M5=tempM{5}; +% model.stochfvars_chain5c_M6=tempM{6}; +% +% clear tempM + delete('tempfile.mat') +end + +% totindi=5+8; +% totindi=totindi+(model.pre_n-1)*(1+3+4+6)+1+4+6+9; +% totindi=totindi+3; +% totindi=totindi+4; +% totindi=totindi+2; +% totindi=totindi+2; +% totindi=totindi+1; +% totindi=totindi+9; +% totindi=totindi+8; +% totindi=totindi+8+(model.stoch_n-1)*(1+3+4+6)+1+4+6+9; +% totindi=totindi+2; +% totindi=totindi+9; +% totindi=totindi+7; +% +% model.totindi=totindi; + +rehash; + + +cd(currentFolder) \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/disp_fun_vec.m b/105/replication_package/solution_methods/taylor_projection/disp_fun_vec.m new file mode 100644 index 0000000000000000000000000000000000000000..ea03df6b4ca4d040da6886846aac3a1cba960697 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/disp_fun_vec.m @@ -0,0 +1,49 @@ +function R=disp_fun_vec(fun_string,fun_sym,i,fid) +%disp_fun breaks a function into several lines if the length of the function is +%larger than 1000 characters. +% +% � Copyright, Oren Levintal, June 13, 2016. + +texp=char(fun_sym); + +texp=strrep(texp,'*','.*'); +texp=strrep(texp,'/','./'); +texp=strrep(texp,'^','.^'); +if length(texp)<1000 + R=[fun_string '(' num2str(i) ',:)=' texp ';']; + fprintf(fid,'%s\n',R); + texp=''; +else + itexp=1000; + while strcmp(texp(itexp),'+')+strcmp(texp(itexp),'-')+strcmp(texp(itexp),'*')+strcmp(texp(itexp),'/')==0 && itexp1 + error('only 1 regime is allowed') + end + + msparams=msparams'; + + paramsvec=repmat(params(:)',model.n_regimes,1); % n_regimes*n_regimes,[] + + s=repmat(regime,model.n_regimes,1); + sp=(1:model.n_regimes)'; + paramsvec=[paramsvec,msparams(s,:),msparams(sp,:)]; %n_s,n_sp,n_params + + paramsvec=[paramsvec,zeros(model.n_regimes,model.n_logicalparams)]; + + coeffs=reshape(full(coeffs),model.n_theta,model.n_regimes); + coeffsvec=coeffs(:,s)'; + coeffspvec=coeffs(:,sp)'; + + x0vec=repmat(x0(:)',model.n_regimes,1); + c0vec=repmat(c0(:)',model.n_regimes,1); + + nep=full(nep); + P=full(P); + + [R0,g,h1,nPhi,nu_vec,model]=eval_model_vec(coeffsvec,x0vec,model,paramsvec,c0vec,nep,P,coeffspvec); + + ny=reshape(g.vals,1,model.n_regimes,[]); + ny=ny(:,1,:); + g=squeeze(ny); + + nx1=reshape(h1.vals,1,model.n_regimes,[]); + nx1=nx1(:,1,:); + h1=squeeze(nx1); + + if model.hybrid==0 + nPhi=reshape(nPhi,1,model.n_regimes,[]); + nPhi=nPhi(:,1,:); + nPhi=squeeze(nPhi); + else + nPhi=permute(reshape(nPhi,model.n_regimes,model.n_x2,n_nodes),[2,1,3]); +% nPhi=nPhi(:,1,:); + nPhi=reshape(nPhi,model.n_x2,model.n_regimes,n_nodes); + end + + n_nodes=length(P); + nu_vec=reshape(nu_vec,n_nodes,model.n_regimes,model.n_u); % n_nodes,sp,n_u + nu_vec=permute(nu_vec,[3,2,1]); + % sum across sp + R0=reshape(R0,1,model.n_regimes,[]); + R0=R0.*reshape(repmat(transition(regime,:),1,size(R0,3)),1,model.n_regimes,size(R0,3)); + + R0=reshape(sum(R0,2),1,[]); + + R0=R0(:); + +end + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/eval_modelMS_vec.m b/105/replication_package/solution_methods/taylor_projection/eval_modelMS_vec.m new file mode 100644 index 0000000000000000000000000000000000000000..b2f9010b3de6e17801a383173de02c8598bdabe6 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/eval_modelMS_vec.m @@ -0,0 +1,181 @@ +function [R0,g,h1,nPhi,nu_vec,model]=eval_modelMS_vec(coeffs,x0,model,params,msparams,transition,c0,nep,P,varargin) + +% INPUTS: +% coeffs (n_s,n_endog*n_b*n_regimes,n_regimes) +% x0 (n_s,n_x) +% params (n_s,n_params) +% msparams (n_msparams,n_regimes) + +% if size(coeffs,1)~=model.n_theta || size(coeffs,2)~=model.n_regimes +% message=sprintf(['The first argument is wrong. The initial guess should be a ' num2str(model.n_theta) '-by-' num2str(model.n_regimes) ' matrix. \nThe number of polynomial coefficients per regime is ' num2str(model.n_theta) ' and the number of regimes is ' num2str(model.n_regimes)'.']); +% error(message); +% end +% x0=x0(:); +% if length(x0)~=model.n_x +% error(['The second argument is wrong. The approximation point should be a vector of' num2str(model.n_x) ' elements (=the number of state variables).']) +% end +% if ~isstruct(model) +% error('The third argument is wrong. It should be a structure generated by prepare_tpMS.') +% elseif ~isfield(model,'n_x') +% error('The third argument is wrong. It should be a structure generated by prepare_tpMS.') +% end +% params=params(:); +% if length(params)~=model.n_params_no_ms +% error(['The fourth argument is wrong. The number of model parameters should be ' num2str(model.n_params_no_ms) '.']) +% end +% if isempty(msparams) +% msparams=zeros(0,model.n_regimes); +% end +% if size(msparams,1)~=model.n_msparams || size(msparams,2)~=model.n_regimes +% error(sprintf(['The fifth argument is wrong. It should be a ' num2str(model.n_msparams) '-by-' num2str(model.n_regimes) ' matrix. \nThe number of Markov switching parameters is ' num2str(model.n_msparams) ' and the number of regimes is ' num2str(model.n_regimes) '.'])) +% end +% if size(transition,1)~=model.n_regimes || size(transition,2)~=model.n_regimes +% error(['The sixth argument is wrong. The transition matrix should have ' num2str(model.n_regimes) ' rows and columns.']) +% end +% c0=c0(:); +% if length(c0)~=model.n_x +% error(['The seventh argument is wrong. The center of the approximating polynomial should be a vector of' num2str(model.n_x) ' elements (=the number of state variables).']) +% end +% if size(nep,1)~=model.n_e +% error(['The eighth argument is wrong. It should be a matrix with ' num2str(model.n_e) ' rows (=the number of shocks).']) +% end +% P=P(:); +% if size(nep,2)~=length(P) +% error('The eighth or ninth arguments are wrong. The number of columns in the eighth argument should be equal to the number of elements in the ninth argument.') +% end + +% if isempty(varargin) + +if numel(x0)==model.n_x && numel(coeffs)==model.n_theta*model.n_regimes && numel(params)==model.n_params + n_s=1; +else % x0,coeffs,params have a row dimension of 1 or n_s + temp=[size(x0,1),size(coeffs,1),size(params,1),size(c0,1)]; + n_s=max(temp); + if min(temp)~=n_s + error('incompatible s dimension') + end +end + +% if ~isequal(x0,c0) +% error('x0 must be equal to c0') +% end + +% msparams should have n_regimes columns + +if size(msparams,2)~=model.n_regimes + error('msparams should have n_regimes columns') +end + +msparams=msparams'; %n_regimes,n_msparams + +paramsvec=reshape(repmat(params(:)',model.n_regimes^2,1),model.n_regimes^2*n_s,[]); % n_regimes*n_regimes,n_s*n_params + +[s,sp]=ndgrid([1:model.n_regimes],[1:model.n_regimes]); +s=s(:); +sp=sp(:); +paramsvec=[paramsvec,repmat([msparams(s,:),msparams(sp,:)],n_s,1)]; + +coeffs=reshape(full(coeffs),n_s*model.n_theta,model.n_regimes); +coeffsvec=coeffs(:,s); +coeffsvec=reshape(coeffsvec,n_s,model.n_theta,model.n_regimes^2); +coeffsvec=permute(coeffsvec,[3,1,2]); +coeffsvec=reshape(coeffsvec,model.n_regimes^2*n_s,[]); + +coeffspvec=coeffs(:,sp); +coeffspvec=reshape(coeffspvec,n_s,model.n_theta,model.n_regimes^2); +coeffspvec=permute(coeffspvec,[3,1,2]); +coeffspvec=reshape(coeffspvec,model.n_regimes^2*n_s,[]); + + +x0vec=repmat(x0(:)',model.n_regimes^2,1); %n_regimes^2,n_s*n_x +x0vec=reshape(x0vec,model.n_regimes^2*n_s,[]); %n_regimes^2*n_s,n_x +c0vec=repmat(c0(:)',model.n_regimes^2,1); %n_regimes^2,n_s*n_x +c0vec=reshape(c0vec,model.n_regimes^2*n_s,[]); %n_regimes^2*n_s,n_x + +nep=full(nep); +P=full(P); +% row dimensions should be n_regimes*n_regimes*n_s + + [R0,g,h1,nPhi,nu_vec,model]=eval_model_vec(coeffsvec,x0vec,model,paramsvec,c0vec,nep,P,coeffspvec); + + ny=reshape(g.vals,model.n_regimes,model.n_regimes,n_s,[]); + ny=ny(:,1,:,:); + g=reshape(ny,model.n_regimes,n_s,model.n_y); + g=permute(g,[2,3,1]); %n_s,n_y,n_regimes + + nx1=reshape(h1.vals,model.n_regimes,model.n_regimes,n_s,[]); + nx1=nx1(:,1,:,:); + h1=reshape(nx1,model.n_regimes,n_s,model.n_x1); + h1=permute(h1,[2,3,1]); + + nPhi=reshape(nPhi,model.n_regimes,model.n_regimes,n_s,[]); + nPhi=nPhi(:,1,:,:); + nPhi=reshape(nPhi,model.n_regimes,n_s,model.n_x2); + nPhi=permute(nPhi,[2,3,1]); + + n_nodes=length(P); + nu_vec=reshape(nu_vec,n_nodes,model.n_regimes,model.n_regimes,n_s,model.n_u); % n_nodes,s,sp,n_s,n_u + nu_vec=permute(nu_vec,[4,5,1,2,3]); + + % sum across sp + R0=reshape(R0,model.n_regimes,model.n_regimes,[]); + R0=R0.*reshape(repmat(transition,1,size(R0,3)),model.n_regimes,model.n_regimes,size(R0,3)); + R0=reshape(sum(R0,2),model.n_regimes,n_s,[]); + R0=permute(R0,[2,3,1]); + R0=reshape(R0,n_s,[]); + +% R0=R0(:); + +% else +% +% regime=varargin{1}; +% if numel(regime)>1 +% error('only 1 regime is allowed') +% end +% +% msparams=msparams'; +% +% paramsvec=repmat(params(:)',model.n_regimes,1); % n_regimes*n_regimes,[] +% +% s=repmat(regime,model.n_regimes,1); +% sp=(1:model.n_regimes)'; +% paramsvec=[paramsvec,msparams(s,:),msparams(sp,:)]; %n_s,n_sp,n_params +% +% coeffs=reshape(full(coeffs),model.n_theta,model.n_regimes); +% coeffsvec=coeffs(:,s)'; +% coeffspvec=coeffs(:,sp)'; +% +% x0vec=repmat(x0(:)',model.n_regimes,1); +% c0vec=repmat(c0(:)',model.n_regimes,1); +% +% nep=full(nep); +% P=full(P); +% +% [R0,g,h1,nPhi,nu_vec,model]=eval_model_vec(coeffsvec,x0vec,model,paramsvec,c0vec,nep,P,coeffspvec); +% +% ny=reshape(g.vals,1,model.n_regimes,[]); +% ny=ny(:,1,:); +% g=squeeze(ny); +% +% nx1=reshape(h1.vals,1,model.n_regimes,[]); +% nx1=nx1(:,1,:); +% h1=squeeze(nx1); +% +% nPhi=reshape(nPhi,1,model.n_regimes,[]); +% nPhi=nPhi(:,1,:); +% nPhi=squeeze(nPhi); +% +% n_nodes=length(P); +% nu_vec=reshape(nu_vec,n_nodes,model.n_regimes,model.n_u); % n_nodes,sp,n_u +% nu_vec=permute(nu_vec,[3,2,1]); +% % sum across sp +% R0=reshape(R0,1,model.n_regimes,[]); +% R0=R0.*reshape(repmat(transition(regime,:),1,size(R0,3)),1,model.n_regimes,size(R0,3)); +% +% R0=reshape(sum(R0,2),1,[]); +% +% R0=R0(:); +% +% end + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/eval_model_vec.m b/105/replication_package/solution_methods/taylor_projection/eval_model_vec.m new file mode 100644 index 0000000000000000000000000000000000000000..83e2d9ebce9b967823d9bdc3245d8bbdc3dca586 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/eval_model_vec.m @@ -0,0 +1,293 @@ +function [R0,g,h1,nPhi,nu_vec,model]=eval_model_vec(coeffs,x0,model,params,c0,nep,P,varargin) +% The function evaluates the model residuals of tpvec. +% +% � Copyright, Oren Levintal, October 21, 2016. + +order=model.order(1); + +ms=0; % no Markov Switching +if ~isempty(varargin) + coeffsp=varargin{1}; + if ~isempty(coeffsp) + ms=1; % Markov Switching model + end +end + +if numel(x0)==model.n_x && numel(coeffs)==model.n_theta && numel(params)==model.n_params + n_s=1; +else % x0,coeffs,params have a row dimension of 1 or n_s + temp=[size(x0,1),size(coeffs,1),size(params,1),size(c0,1)]; + n_s=max(temp); + if min(temp)~=n_s + error('incompatible s dimension') + end +end + +% make sure all inputs are full +coeffsvec=full(reshape(coeffs,n_s,model.n_theta)); +x0vec=full(reshape(x0,n_s,model.n_x)); + +paramsvec=full(reshape(params,n_s,model.n_params)); + +if model.hybrid==1 || model.hybrid==3 + paramsvec=[zeros(n_s,model.n_e),paramsvec]; +end + +% eta=full(eta); +if model.hybrid==0 || model.hybrid==1 + etavec=eta_fun(paramsvec,[]); +else + etavec=zeros(n_s,model.n_x*model.n_e); +end +etavec=reshape(full(etavec),n_s*model.n_x,[]); + +c0vec=full(reshape(c0,n_s,model.n_x)); +nep=full(nep); +P=full(P); + +params=paramsvec; +P=P(:); + +n_f=model.n_f; % no. of model conditions +n_x=model.n_x; % no. of state variables +n_y=model.n_y; % no. of control variables +n_x2=model.n_x2; % no. of exogenous state variables +n_x1=model.n_x1; % no. of endogenous state variabels +n_v=model.n_v; % total no. of variables v=(yp,y,xp,x) +n_theta=model.n_theta; % no. of Polynomial coefficients +n_b=model.n_b; % no. of terms in the basis function +n_nodes=size(nep,2); % no. nodes in the discrete shocks +n_z=model.n_z; % no. of auxiliary variables +n_e=model.n_e; + +n_prefrows=length(model.prefrows); +n_stochfrows=length(model.stochfrows); + +n_params=model.n_params; + +if model.hybrid==1 || model.hybrid==3 + n_params=n_params+n_e; % shocks are treated as parameters +end + +coeffs=reshape(coeffsvec,n_s,[],n_b); + +% current state +nx=x0vec; + +nx_c0_vec=x0vec-c0vec; +nx_c0=sptensor(nx_c0_vec(1,:)'); % convert to 1D tensor +nx_c0.vals=nx_c0_vec; % assign the correct values in vals. + +if ~isfield(model,'M2') + model.M2=[]; + model.M3=[]; + model.M3x=[]; + model.TW2=[]; + model.TW3=[]; + model.M4=[]; + model.M4x=[]; + model.M4xx=[]; + model.M4xxx=[]; + if order>=2 + model.M2=fold(spmat2sptensor(model.W{2}*model.W{2}'*model.U{2}'),n_x,n_x); + model.TW2=fold(spmat2sptensor(model.W{2}),n_x,n_x); + model.TW2U2=spmat2sptensor(model.W{2}*model.U{2}); + end + if order>=3 + model.M3=fold(spmat2sptensor(model.W{3}*model.W{3}'*model.U{3}'),n_x,n_x,n_x); + model.M3x=fold(spmat2sptensor(3*model.W{3}*kron(model.W{2}'*model.U{2}',speye(n_x))),n_x,n_x,n_x); + model.TW3=fold(spmat2sptensor(model.W{3}),n_x,n_x,n_x); + model.TW3U3=spmat2sptensor(model.W{3}*model.U{3}); + end + if order>=4 + model.M4=fold(spmat2sptensor(model.W{4}*model.W{4}'*model.U{4}'),n_x,n_x,n_x,n_x); + model.M4x=fold(spmat2sptensor(4*model.W{4}*kron(model.W{3}'*model.U{3}',speye(n_x))),n_x,n_x,n_x,n_x); + model.M4xx=fold(spmat2sptensor(12*model.W{4}*kron(model.W{2}'*model.U{2}',speye(n_x^2))),n_x,n_x,n_x,n_x); + model.M4xxx=fold(spmat2sptensor(24*model.W{4}),n_x,n_x,n_x,n_x); + end +end + +[X_vecT]=create_X_tensor_no_derivs(order,nx_c0,... +model.M2,model.M3,model.M4,[],model.n_ind,n_s,'vec'); + +gh_coeffs=reshape(coeffs,n_s,(n_y+n_x1),n_b); +% g_coeffs=reshape(gh_coeffs(:,1:n_y,:),n_s*n_y,n_b); + +gh_coeffsT=sptensor(ones(n_y+n_x1,n_b)); +tempvals=gh_coeffs; %n_s,n_y+n_x1,n_b +tempvals=permute(tempvals,[1,3,2]); % n_s,n_b,n_y+n_x1 +tempvals=reshape(tempvals,n_s,n_b*(n_y+n_x1)); +gh_coeffsT.vals=tempvals; + +[gh1]=contraction1(gh_coeffsT,X_vecT,[],model.n_ind,n_s,'vec'); + +g=takerows(gh1,1:n_y); +h1=takerows(gh1,n_y+(1:n_x1)); + +% control vars +ny=g.vals; + +% expected values: + +% The residual function R is calculated in two steps. The first step +% calculates the nonstochastic (predetermined) rows of f (pref). The second step calculates +% the expected value of the stochastic rows of f (stochf). + +% Step 1. predetermined equations (pref) + +% preallocate +h=zeros(n_s,n_x); + +% build h(x) + +h(:,1:n_x1)=h1.vals; % predetermined endogenous state vars + +if model.hybrid==0 + nPhi=Phi_fun(nx,params); + h(:,n_x1+1:end)=nPhi; % expected value of exogenous state vars. shocks are added later +end + +% next period state +nxp=h; + +% evaluate residuals R0 +nv=[zeros(n_s,n_y),ny,nxp,nx]; % all variables with zeros for the stochastic vars. + +n_u=model.n_u; +nu=zeros(n_s,n_u); +npreu=preu_fun(nv(:,model.preuvars),params); % all predetermined u +nu(:,model.preurows)=npreu; +nz=[nv,nu]; +params(:,model.logical_params_loc)=double(logical(nz(:,model.logical_zvars)>=0)); + +fname=['pretilf' model.fname '_fun']; +pref=feval(fname,nz(:,model.pretilfzvars),params); % since i already have z, i use pretilf to evaluate f. + +preR0=pref; + +% Step 2. expected value of stochastic equations (stochf) + +% vectorized expressions +%create stochy: index of future control variables that affect stochastic equations +if isempty(model.stochfrows) + EstochR0=zeros(n_s,0); + nu_vec=reshape(repmat(nu(:)',n_nodes,1),n_nodes*n_s,[]); + +else + nx_vec=repmat(nx(:)',n_nodes,1); % n_nodes=the number of nodes of the discrete shocks. + nx_vec=reshape(nx_vec,n_nodes*n_s,[]); + + % next period state + % next period state + if model.hybrid==0 + nxp_vec=repmat(h(:),1,n_nodes)+reshape(etavec,[],n_e)*nep; %n_s*n_x,n_nodes + elseif model.hybrid==1 + h_vec=repmat(h(:),1,n_nodes); %n_s*n_x,n_nodes + + params_vec=[repmat(nep',n_s,1),reshape(repmat(reshape(params(:,n_e+1:end),1,[]),n_nodes,1),n_nodes*n_s,[])]; %n_nodes*n_s,n_params + uname=['Phi' model.uname '_fun']; + tempvars=[nx,ny,nu(:,model.preurows)]; %n_s,n_x+n_y + tempvars=reshape(repmat(tempvars(:)',n_nodes,1),n_nodes*n_s,[]); %n_s*n_nodes,n_x+n_y+n_preurows + Phi_vec=feval(uname,tempvars,params_vec); %n_s*n_nodes,n_x2 + Phi_vec=permute(reshape(Phi_vec,n_s,n_nodes,n_x2),[1,3,2]); %n_s,n_x2,n_nodes + nPhi=Phi_vec; + h_vec=reshape(h_vec,n_s,n_x,n_nodes); + h_vec(:,n_x1+1:end,:)=Phi_vec; % expected value of exogenous state vars. shocks are added later + h_vec=reshape(h_vec,n_s*n_x,n_nodes); + nxp_vec=h_vec+reshape(etavec,[],n_e)*nep; %n_s*n_x,n_nodes + elseif model.hybrid==3 + h_vec=repmat(h(:),1,n_nodes); %n_s*n_x,n_nodes + + params_vec=[repmat(nep',n_s,1),reshape(repmat(reshape(params(:,n_e+1:end),1,[]),n_nodes,1),n_nodes*n_s,[])]; %n_nodes*n_s,n_params + uname=['Phi' model.uname '_fun']; + tempvars=nz(:,model.Phizvars); %n_s,n_x+n_y + tempvars=reshape(repmat(tempvars(:)',n_nodes,1),n_nodes*n_s,[]); %n_nodes*n_s,n_x+n_y+n_preurows + Phi_vec=feval(uname,tempvars,params_vec); %n_nodes*n_s,n_x2 + Phi_vec=permute(reshape(Phi_vec,n_nodes,n_s,n_x2),[2,3,1]); %n_s,n_x2,n_nodes + nPhi=Phi_vec; + h_vec=reshape(h_vec,n_s,n_x,n_nodes); + h_vec(:,n_x1+1:end,:)=Phi_vec; + h_vec=reshape(h_vec,n_s*n_x,n_nodes); + nxp_vec=h_vec+reshape(etavec,[],n_e)*nep; %n_s*n_x,n_nodes + end + + nxp_c0_vec=nxp_vec-reshape(repmat(c0vec,1,n_nodes),n_s*n_x,n_nodes); + + nxp_vec_permuted=reshape(permute(reshape(nxp_vec,n_s,n_x,n_nodes),[3,1,2]),n_nodes*n_s,n_x); + + tempxp=1:n_x; + tempxp=tempxp(:); + nxp_c0=sptensor(tempxp); % convert to 1D tensor + tempvals=reshape(nxp_c0_vec,n_s,n_x,n_nodes); + tempvals=permute(tempvals,[3,1,2]); + tempvals=reshape(tempvals,n_nodes*n_s,n_x); + nxp_c0.vals=tempvals; % assign the correct values in vals. + + +[Xp_vecT]=create_X_tensor_no_derivs(order,nxp_c0,... + model.M2,model.M3,model.M4,[],model.n_ind,n_s*n_nodes,'vec'); + +tempv=zeros(n_v,1); +tempv(model.stochfvars)=model.stochfvars; +tempv(n_y+1:end)=0; +stochy=nonzeros(tempv); +n_stochy=length(stochy); +% stochg_coeffs=coeffs(:,stochy,:); +if ms==0 + stochg_coeffs=coeffs(:,stochy,:); +else + coeffspvec=full(reshape(coeffsp,n_s,[],n_b)); + stochg_coeffs=coeffspvec(:,stochy,:); +end + stochg_coeffsT=sptensor(ones(n_stochy,n_b)); + tempvals=stochg_coeffs; %n_s,n_stochy,n_b + tempvals=permute(tempvals,[1,3,2]); % n_s,n_b,n_stochy + tempvals=repmat(tempvals(:)',n_nodes,1); % n_nodes,n_s*n_b*n_stochy + tempvals=reshape(tempvals,n_nodes*n_s,n_b*n_stochy); + stochg_coeffsT.vals=tempvals; + + [stochgp_vecT]=contraction1(stochg_coeffsT,Xp_vecT,[],model.n_ind,n_s*n_nodes,'vec'); + + gp_vec=changerows(stochgp_vecT,stochy,n_y); + temp=zeros(n_nodes*n_s,n_y); + temp(:,stochy)=gp_vec.vals; + gp_vec=temp; % n_nodes*n_s,n_y + +% control vars in t+1 +nyp_vec=gp_vec; + +% evaluate residuals R0 + nv_vec=[nyp_vec,reshape(repmat(ny(:)',n_nodes,1),n_nodes*n_s,[]),nxp_vec_permuted,nx_vec]; + +% nstochv_vec=nv_vec(stochfvars,:); % stochastic vars. + + if model.hybrid==0 + params_vec=reshape(repmat(params(:)',n_nodes,1),n_nodes*n_s,n_params); + end + + nstochu_vec=stochu_fun(nv_vec(:,model.stochuvars),params_vec); % all stochastic u vars + nu_vec=reshape(repmat(nu(:)',n_nodes,1),n_nodes*n_s,[]); + + nu_vec(:,model.stochurows)=nstochu_vec; + nz_vec=[nv_vec,nu_vec]; + params_vec(:,model.logical_params_loc)=double(logical(nz_vec(:,model.logical_zvars)>=0)); + + fname=['stochtilf' model.fname '_fun']; + stochf_vec=feval(fname,nz_vec(:,model.stochtilfzvars),params_vec); + + + EstochR0=P'*reshape(stochf_vec,n_nodes,[]); %expected value of stochR0 + EstochR0=reshape(EstochR0,n_s,[]); +end +% tempT=sptensor(zeros(n_stochfrows,1)); +% tempT.vals=full(EstochR0); +% EstochR0=tempT; + + R0=zeros(n_s,n_f); +R0(:,model.prefrows)=preR0; +R0(:,model.stochfrows)=EstochR0; + +nu_vec=reshape(nu_vec,n_nodes,n_s,[]); +model.coeffs=coeffs; +model.nv=nv; + diff --git a/105/replication_package/solution_methods/taylor_projection/find_n.m b/105/replication_package/solution_methods/taylor_projection/find_n.m new file mode 100644 index 0000000000000000000000000000000000000000..d7824be843e36089c31e4499f2234f39b68ace95 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/find_n.m @@ -0,0 +1,24 @@ +function [n]=find_n(pi_,u) +% Given u=pi_(v,u), how many compositions of type pi_(v,pi_(v,u)) are needed to get a +% function of v only. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if isempty(pi_) + n=0; + subspi_=[]; +else + check=0; + subspi_=pi_; + n=0; + while check==0 + n=n+1; + newsubspi_=subs(subspi_,u,pi_); +% check=nnz(1-logical(jacobian(subspi_,u)==0)); + check=isequal(newsubspi_,subspi_); + subspi_=newsubspi_; + + end +end + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/find_n_new.m b/105/replication_package/solution_methods/taylor_projection/find_n_new.m new file mode 100644 index 0000000000000000000000000000000000000000..4e1c501b9c2aadb70e2857325e6909aa394e1d56 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/find_n_new.m @@ -0,0 +1,30 @@ +function [n,uu0]=find_n_new(pi_,u) +% Given u=pi_(v,u), how many compositions of type pi_(v,pi_(v,u)) are needed to get a +% function of v only. +% +% � Copyright, Oren Levintal, September 12, 2017. + +if isempty(pi_) + n=0; + uu0=zeros(0,0); +else + n_u=length(u); + if length(pi_)~=n_u + error('wrong size of function') + end + pi_=pi_(:); + uu0=double(logical(jacobian(pi_,u)~=0)); + if max(abs(real(eig(uu0))))>=1-2*eps + error('Auxiliary functions are not defined properly.') + end + n=1; + uu=uu0; + nuu=uu*uu0; + while ~isequal(logical(nuu),logical(uu)) + n=n+1; + uu=nuu; + nuu=uu*uu0; + end +end + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/gen_chainderivs_tensor.m b/105/replication_package/solution_methods/taylor_projection/gen_chainderivs_tensor.m new file mode 100644 index 0000000000000000000000000000000000000000..dc83a01172ac3a73950f659c44af00280dfb496c --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/gen_chainderivs_tensor.m @@ -0,0 +1,20 @@ +function [index,n]=gen_chainderivs_tensor(tilf,v,u,pi_,order,symparams,fname) +% +% � Copyright, Oren Levintal, June 13, 2016. + +if order>5 + error('Differentiation order must not exceed 5') +end + +n=find_n_new(pi_,u); % number of substitutions needed to eliminate u + +z=[v(:);u(:)]; + +% Differentiate with chain rules + +[index]=getderivs_tensor(tilf,z,order,symparams,[fname '_tilf']); + + + + + diff --git a/105/replication_package/solution_methods/taylor_projection/gen_fun_vec.m b/105/replication_package/solution_methods/taylor_projection/gen_fun_vec.m new file mode 100644 index 0000000000000000000000000000000000000000..8364c8d071340e40b69ee8687c99f655e6860ee0 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/gen_fun_vec.m @@ -0,0 +1,61 @@ +function gen_fun_vec(f,symparams,v,fname,varargin) +% +% � Copyright, Oren Levintal, June 13, 2016. + +rowformat=0; % function returns a column vector (number of columns>1 in vectorized form) +if ~isempty(varargin) + if strcmp(varargin{1},'row') + rowformat=1; % function returns a row vector (number of rows>1 in vectorized form) + end +end + +f=f(:); +if numel(f)>1 + nnzf=1-logical(f==0); + index=find(nnzf); +else + index=1; +end +fid = fopen([fname '_fun.m'], 'w'); +fprintf(fid,'%s\n', ['function function_f=' fname '_fun(variables_v,parameters)']); +for i=1:length(symparams) + if strcmp(char(symparams(i)),'function_f') || strcmp(char(symparams(i)),'variables_v') || strcmp(char(symparams(i)),'parameters') + error([char(symparams(i)) 'is reserved. Change variable/parameter name.']); + end + if rowformat==0 + fprintf(fid,'%s\n', [char(symparams(i)) '=parameters(' num2str(i) ',:);']); + elseif rowformat==1 + fprintf(fid,'%s\n', [char(symparams(i)) '=parameters(:,' num2str(i) ');']); + end +end +for i=1:length(v) + if strcmp(char(v(i)),'function_f') || strcmp(char(v(i)),'variables_v') || strcmp(char(v(i)),'parameters') + error([char(v(i)) 'is reserved. Change variable/parameter name.']); + end + if rowformat==0 + fprintf(fid,'%s\n', [char(v(i)) '=variables_v(' num2str(i) ',:);']); + elseif rowformat==1 + fprintf(fid,'%s\n', [char(v(i)) '=variables_v(:,' num2str(i) ');']); + end +end +if isempty(f) + if rowformat==0 + fprintf(fid,'%s\n', ['function_f=zeros(0,size(variables_v,2));']); + elseif rowformat==1 + fprintf(fid,'%s\n', ['function_f=zeros(size(variables_v,1),0);']); + end +else + if rowformat==0 + fprintf(fid,'%s\n', ['function_f=zeros(' num2str(numel(f)) ',size(variables_v,2));']); + elseif rowformat==1 + fprintf(fid,'%s\n', ['function_f=zeros(size(variables_v,1),' num2str(numel(f)) ');']); + end + for i=index(:)' + if rowformat==0 + disp_fun_vec('function_f',f(i),i,fid); + elseif rowformat==1 + disp_fun_vec_row('function_f',f(i),i,fid); + end + end +end +fclose(fid); diff --git a/105/replication_package/solution_methods/taylor_projection/gen_fun_vec_subs.m b/105/replication_package/solution_methods/taylor_projection/gen_fun_vec_subs.m new file mode 100644 index 0000000000000000000000000000000000000000..38ee5c35fc583ce488a3b4ac06fca614ead87c2f --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/gen_fun_vec_subs.m @@ -0,0 +1,137 @@ +function gen_fun_vec_subs(f,symparams,v,ufun,u,fname,varargin) +% +% � Copyright, Oren Levintal, September 11, 2017. + +rowformat=0; % function returns a column vector (number of columns>1 in vectorized form) +if ~isempty(varargin) + if strcmp(varargin{1},'row') + rowformat=1; % function returns a row vector (number of rows>1 in vectorized form) + end +end +if nargin==8 + uu0=varargin{2}; +end + +f=f(:); +if numel(f)>1 + nnzf=1-logical(f==0); + index=find(nnzf); +else + index=1; +end +fid = fopen([fname '_fun.m'], 'w'); +fprintf(fid,'%s\n', ['function function_f=' fname '_fun(variables_v,parameters)']); +for i=1:length(symparams) + if strcmp(char(symparams(i)),'function_f') || strcmp(char(symparams(i)),'variables_v') || strcmp(char(symparams(i)),'parameters') + error([char(symparams(i)) 'is reserved. Change variable/parameter name.']); + end + if rowformat==0 + fprintf(fid,'%s\n', [char(symparams(i)) '=parameters(' num2str(i) ',:);']); + elseif rowformat==1 + fprintf(fid,'%s\n', [char(symparams(i)) '=parameters(:,' num2str(i) ');']); + end +end +for i=1:length(v) + if strcmp(char(v(i)),'function_f') || strcmp(char(v(i)),'variables_v') || strcmp(char(v(i)),'parameters') + error([char(v(i)) 'is reserved. Change variable/parameter name.']); + end + if rowformat==0 + fprintf(fid,'%s\n', [char(v(i)) '=variables_v(' num2str(i) ',:);']); + elseif rowformat==1 + fprintf(fid,'%s\n', [char(v(i)) '=variables_v(:,' num2str(i) ');']); + end +end + +%%%%%%% substituted vars - version 1 + +% subsu=ufun; +% newsubsu=subs(subsu,u,ufun); +% +% n_u=length(u); +% A=cell(n_u,1); +% l=1; +% uind=1:n_u; +% while ~isequal(subsu,newsubsu) +% for i=uind(logical(newsubsu==subsu)) +% texp=char(ufun(i)); +% texp=strrep(texp,'*','.*'); +% texp=strrep(texp,'/','./'); +% texp=strrep(texp,'^','.^'); +% A{l}=[char(u(i)) '=' texp ';'];l=l+1; +% end +% uind=uind(logical(newsubsu~=subsu)); +% subsu=newsubsu(logical(newsubsu~=subsu)); +% newsubsu=subs(subsu,u,ufun); +% end +% for i=uind +% texp=char(ufun(i)); +% texp=strrep(texp,'*','.*'); +% texp=strrep(texp,'/','./'); +% texp=strrep(texp,'^','.^'); +% A{l}=[char(u(i)) '=' texp ';'];l=l+1; +% end +% +% for i=1:l-1 +% fprintf(fid,'%s\n', A{i}); +% end + +%%%%%%% substituted vars - version 2 + +if nargin~=8 + uu0=double(logical(jacobian(ufun(:),u)~=0)); +end + +uu=uu0; + +n_u=length(u); +A=cell(n_u,1); +l=1; +uind=1:n_u; +while nnz(uu)~=0 + for i=uind(logical(sum(uu,2)==0)) + texp=char(ufun(i)); + texp=strrep(texp,'*','.*'); + texp=strrep(texp,'/','./'); + texp=strrep(texp,'^','.^'); + A{l}=[char(u(i)) '=' texp ';'];l=l+1; + end + uind=uind(logical(sum(uu,2)~=0)); + uu=uu(logical(sum(uu,2)~=0),:); + uu=uu*uu0; +end +for i=uind + texp=char(ufun(i)); + texp=strrep(texp,'*','.*'); + texp=strrep(texp,'/','./'); + texp=strrep(texp,'^','.^'); + A{l}=[char(u(i)) '=' texp ';'];l=l+1; +end + +for i=1:l-1 + fprintf(fid,'%s\n', A{i}); +end + +%%%%%%%%%%% + + +if isempty(f) + if rowformat==0 + fprintf(fid,'%s\n', ['function_f=zeros(0,size(variables_v,2));']); + elseif rowformat==1 + fprintf(fid,'%s\n', ['function_f=zeros(size(variables_v,1),0);']); + end +else + if rowformat==0 + fprintf(fid,'%s\n', ['function_f=zeros(' num2str(numel(f)) ',size(variables_v,2));']); + elseif rowformat==1 + fprintf(fid,'%s\n', ['function_f=zeros(size(variables_v,1),' num2str(numel(f)) ');']); + end + for i=index(:)' + if rowformat==0 + disp_fun_vec('function_f',f(i),i,fid); + elseif rowformat==1 + disp_fun_vec_row('function_f',f(i),i,fid); + end + end +end +fclose(fid); diff --git a/105/replication_package/solution_methods/taylor_projection/get_Phi_derivs.m b/105/replication_package/solution_methods/taylor_projection/get_Phi_derivs.m new file mode 100644 index 0000000000000000000000000000000000000000..1a3a7aca7721542077d61cfb40fbe52afd935267 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/get_Phi_derivs.m @@ -0,0 +1,33 @@ +% +% � Copyright, Oren Levintal, June 13, 2016. +% changed on November 28, 2016: the matrix nnzmat was wrong. Consequently, +% uncompression of high-order derivatives was wrong. Now it's the right +% matrix. +params=params(:)'; +if approx>=1 + nPhix=Phi_d_c1(nx(:)',params,model.Phi_indc); + nPhix.tsize=[n_x2,repmat(n_x,1,1)]; % change size to account for the perturbation parameter + nPhix=sptensor2spmat(unfold(nPhix)); +end +if approx>=2 + nPhixxc=Phi_d_c2(nx(:)',params,model.Phi_indc); + nnzmat=repmat(1:n_x_tp,n_x2,1); + [nPhixx,model.pertind{pertindi}]=uncompressderivs( nPhixxc,2,n_x_tp,nnzmat,model.pertind{pertindi} ); + pertindi=pertindi+1; + nPhixx.tsize=[n_x2,repmat(n_x,1,2)]; % change size to account for the perturbation parameter + nPhixx=sptensor2spmat(unfold(nPhixx)); +end +if approx>=3 + nPhixxxc=Phi_d_c3(nx(:)',params,model.Phi_indc); + [nPhixxx,model.pertind{pertindi}]=uncompressderivs( nPhixxxc,3,n_x_tp,nnzmat,model.pertind{pertindi} ); + pertindi=pertindi+1; + nPhixxx.tsize=[n_x2,repmat(n_x,1,3)]; % change size to account for the perturbation parameter + nPhixxx=sptensor2spmat(unfold(nPhixxx)); +end +if approx>=4 + nPhixxxxc=Phi_d_c4(nx(:)',params,model.Phi_indc); + [nPhixxxx,model.pertind{pertindi}]=uncompressderivs( nPhixxxxc,4,n_x_tp,nnzmat,model.pertind{pertindi} ); + pertindi=pertindi+1; + nPhixxxx.tsize=[n_x2,repmat(n_x,1,4)]; % change size to account for the perturbation parameter + nPhixxxx=sptensor2spmat(unfold(nPhixxxx)); +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/get_f_derivs.m b/105/replication_package/solution_methods/taylor_projection/get_f_derivs.m new file mode 100644 index 0000000000000000000000000000000000000000..805aaf4836553a6f9cbedb616d915f36770c00d7 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/get_f_derivs.m @@ -0,0 +1,526 @@ +%%%%%%%%%%%%% code from tp to compute fv,fvv,fvvv,fvvvv, where v is the +%%%%%%%%%%%%% vector of variables of the tp system (the pert system has a +%%%%%%%%%%%%% larger v). +% +% � Copyright, Oren Levintal, June 13, 2016. + +nv=[zeros(n_y,1);nyss;nxss;nxss]'; % variables of tp + +n_u=model.n_u; +nu=zeros(n_u,1)'; +npreu=preu_fun(nv(model.preuvars),params); % all predetermined u +nu(model.preurows)=npreu; +nz=[nv,nu]; % auxiliary variables +params(:,model.logical_params_loc)=double(logical(nz(:,model.logical_zvars)>=0)); + +pref=pretilf_fun(nz(model.pretilfzvars),params); % since i already have z, i use pretilf to evaluate f. + +% compute derivatives of prePI and pretilf w.r.t z (prePI=nonstochastic rows of PI, pretilf=nonstochastic rows of f) + +prePIz_full=prePI_d1(nz,params,model.prePI_ind_u); +prefvars=model.prefvars; +n_prefvars=length(prefvars); +pretilfz=pretilf_tilf_d1([nv(prefvars),nu(model.prefuvars)],params,model.pretilf_ind_u); +if approx>=2 + prePIzz_full=prePI_d2(nz,params,model.prePI_ind_u); + pretilfzz=pretilf_tilf_d2([nv(prefvars),nu(model.prefuvars)],params,model.pretilf_ind_u); +end +if approx>=3 + prePIzzz_full=prePI_d3(nz,params,model.prePI_ind_u); + pretilfzzz=pretilf_tilf_d3([nv(prefvars),nu(model.prefuvars)],params,model.pretilf_ind_u); +end +if approx>=4 + prePIzzzz_full=prePI_d4(nz,params,model.prePI_ind_u); + pretilfzzzz=pretilf_tilf_d4([nv(prefvars),nu(model.prefuvars)],params,model.pretilf_ind_u); +end + +% extract derivatives of prePI w.r.t v from prePIz, prePIzz, ... +if ~isfield(model,'ind') + model.ind=cell(model.totindi,1); +end +indi=5; + +if approx>=1 + [prePIz,model.ind{indi}]=extract(prePIz_full,model.prefzvars,model.prefzvars,0,model.ind{indi}); + indi=indi+1; + [prePIv,model.ind{indi}]=extract(prePIz_full,model.prefzvars,model.prefvars,0,model.ind{indi}); + indi=indi+1; +end +if approx>=2 + [prePIzz,model.ind{indi}]=extract(prePIzz_full,model.prefzvars,model.prefzvars,0,model.ind{indi}); + indi=indi+1; + [prePIvvc,model.ind{indi}]=extract(prePIzz_full,model.prefzvars,model.prefvars,1,model.ind{indi}); + indi=indi+1; +end +if approx>=3 + [prePIzzz,model.ind{indi}]=extract(prePIzzz_full,model.prefzvars,model.prefzvars,0,model.ind{indi}); + indi=indi+1; + [prePIvvvc,model.ind{indi}]=extract(prePIzzz_full,model.prefzvars,model.prefvars,1,model.ind{indi}); + indi=indi+1; + if ~isfield(model,'prefvars_chain3c_M2') + [ tempM ] = chainsM( n_prefvars,3 ); + model.prefvars_chain3c_M2=tempM{2}; + clear tempM + end +end +if approx>=4 + [prePIzzzz,model.ind{indi}]=extract(prePIzzzz_full,model.prefzvars,model.prefzvars,0,model.ind{indi}); + indi=indi+1; + [prePIvvvvc,model.ind{indi}]=extract(prePIzzzz_full,model.prefzvars,model.prefvars,1,model.ind{indi}); + indi=indi+1; + if ~isfield(model,'prefvars_chain4c_M2') + [ tempM ] = chainsM( n_prefvars,4 ); + model.prefvars_chain4c_M2=tempM{2}; + model.prefvars_chain4c_M3=tempM{3}; + model.prefvars_chain4c_M4=tempM{4}; + clear tempM + end +end + + +% Use high order chain rules to compute derivatives of prePI w.r.t v +totindi=5+8; +if approx==1 + indi=totindi; + for i=2:model.pre_n + [prePIv,model.ind{indi}]=chain1_tensor(prePIz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [prefv,model.ind{indi}]=chain1_tensor(pretilfz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; +elseif approx==2 + indi=totindi+(model.pre_n-1)*(1)+1; + for i=2:model.pre_n + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + [prePIvvc,model.ind{indi}]=chain2c_tensor(prePIz,prePIzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIv,model.ind{indi}]=chain1_tensor(prePIz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + + [prefv,model.ind{indi}]=chain1_tensor(pretilfz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvc,model.ind{indi}]=chain2c_tensor(pretilfz,pretilfzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [ prefvv,model.ind{indi} ] = uncompressderivs( prefvvc,2,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + +elseif approx==3 + indi=totindi+(model.pre_n-1)*(1+3)+1+4; + for i=2:model.pre_n + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + [prePIvvvc,model.ind{indi}]=chain3c_tensor(prePIz,prePIzz,prePIzzz,... + prePIv,prePIvvc,prePIvvvc,model.prefvars_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIvvc,model.ind{indi}]=chain2c_tensor(prePIz,prePIzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIv,model.ind{indi}]=chain1_tensor(prePIz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + + [prefv,model.ind{indi}]=chain1_tensor(pretilfz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvc,model.ind{indi}]=chain2c_tensor(pretilfz,pretilfzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvvc,model.ind{indi}]=chain3c_tensor(pretilfz,pretilfzz,pretilfzzz,... + prePIv,prePIvvc,prePIvvvc,... + model.prefvars_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [ prefvv,model.ind{indi} ] = uncompressderivs( prefvvc,2,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + + [ prefvvv,model.ind{indi} ] = uncompressderivs( prefvvvc,3,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + +elseif approx==4 + indi=totindi+(model.pre_n-1)*(1+3+4)+1+4+6; + for i=2:model.pre_n + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + [prePIvvc,model.ind{indi}]=colsort(prePIvvc,model.ind{indi}); + indi=indi+1; + [prePIvvvvc,model.ind{indi}]=chain4c_tensor(prePIz,prePIzz,prePIzzz,prePIzzzz,... + prePIv,prePIvvc,prePIvvvc,prePIvvvvc,... + model.prefvars_chain4c_M2,model.prefvars_chain4c_M3,model.prefvars_chain4c_M4,... + model.ind{indi},n_ind,maxload,'vec',model.prezz,model.maxzz); + indi=indi+1; + [prePIvvvc,model.ind{indi}]=chain3c_tensor(prePIz,prePIzz,prePIzzz,... + prePIv,prePIvvc,prePIvvvc,model.prefvars_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIvvc,model.ind{indi}]=chain2c_tensor(prePIz,prePIzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIv,model.ind{indi}]=chain1_tensor(prePIz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + [prePIvvc,model.ind{indi}]=colsort(prePIvvc,model.ind{indi}); + indi=indi+1; + + [prefv,model.ind{indi}]=chain1_tensor(pretilfz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [prefvvc,model.ind{indi}]=chain2c_tensor(pretilfz,pretilfzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvvc,model.ind{indi}]=chain3c_tensor(pretilfz,pretilfzz,pretilfzzz,... + prePIv,prePIvvc,prePIvvvc,... + model.prefvars_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvvvc,model.ind{indi}]=chain4c_tensor(pretilfz,pretilfzz,pretilfzzz,pretilfzzzz,... + prePIv,prePIvvc,prePIvvvc,prePIvvvvc,... + model.prefvars_chain4c_M2,model.prefvars_chain4c_M3,model.prefvars_chain4c_M4,... + model.ind{indi},n_ind,maxload,'vec',model.pretilfz,model.maxtilfz); + indi=indi+1; + + [ prefvv,model.ind{indi} ] = uncompressderivs( prefvvc,2,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + + [ prefvvv,model.ind{indi} ] = uncompressderivs( prefvvvc,3,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + + [ prefvvvv,model.ind{indi} ] = uncompressderivs( prefvvvvc,4,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; +end +totindi=totindi+(model.pre_n-1)*(1+3+4+6)+1+4+6+9; + +%%%%%%%%%%%%% now stochastic equations +n_nodes=1; +nv_vec=[nyss;nyss;nxss;nxss]'; +stochfvars=model.stochfvars; +n_stochfvars=length(stochfvars); +nstochv_vec=nv_vec(:,stochfvars); % stochastic vars. + +nstochu_vec=stochu_fun(nv_vec(:,model.stochuvars),params); % all stochastic u vars +nu_vec=repmat(nu,n_nodes,1); +nu_vec(:,model.stochurows)=nstochu_vec; +nz_vec=[nv_vec,nu_vec]; +params(model.logical_params_loc)=double(logical(nz_vec(model.logical_zvars)>=0)); + +stochf_vec=stochtilf_fun(nz_vec(:,model.stochtilfzvars),params); + +% compute derivatives of stochPI and stochtilf w.r.t z + +stochPIz_vec=stochPI_d1(nz_vec,params,model.stochPI_ind_u); +prePIz_full.vals=repmat(prePIz_full.vals,n_nodes,1); + +i1=tfind(prePIz_full); +i2=tfind(stochPIz_vec); +PIz_vec=sptensor([i1;i2],[prePIz_full.cols;stochPIz_vec.cols],[prePIz_full.vals,stochPIz_vec.vals],n_z,[n_z]); +stochtilfz_vec=stochtilf_tilf_d1([nv_vec(:,stochfvars),nu_vec(:,model.stochfuvars)],params,model.stochtilf_ind_u); + +if approx>=2 + stochPIzz_vec=stochPI_d2(nz_vec,params,model.stochPI_ind_u); + prePIzz_full.vals=repmat(prePIzz_full.vals,n_nodes,1); + + i1=tfind(prePIzz_full); + i2=tfind(stochPIzz_vec); + PIzz_vec=sptensor([i1;i2],[prePIzz_full.cols;stochPIzz_vec.cols],[prePIzz_full.vals,stochPIzz_vec.vals],n_z,[n_z,n_z]); + stochtilfzz_vec=stochtilf_tilf_d2([nv_vec(:,stochfvars),nu_vec(:,model.stochfuvars)],params,model.stochtilf_ind_u); +end +if approx>=3 + stochPIzzz_vec=stochPI_d3(nz_vec,params,model.stochPI_ind_u); + prePIzzz_full.vals=repmat(prePIzzz_full.vals,n_nodes,1); + + i1=tfind(prePIzzz_full); + i2=tfind(stochPIzzz_vec); + PIzzz_vec=sptensor([i1;i2],[prePIzzz_full.cols;stochPIzzz_vec.cols],[prePIzzz_full.vals,stochPIzzz_vec.vals],n_z,[n_z,n_z,n_z]); + stochtilfzzz_vec=stochtilf_tilf_d3([nv_vec(:,stochfvars),nu_vec(:,model.stochfuvars)],params,model.stochtilf_ind_u); +end +if approx>=4 + stochPIzzzz_vec=stochPI_d4(nz_vec,params,model.stochPI_ind_u); + prePIzzzz_full.vals=repmat(prePIzzzz_full.vals,n_nodes,1); + + i1=tfind(prePIzzzz_full); + i2=tfind(stochPIzzzz_vec); + PIzzzz_vec=sptensor([i1;i2],[prePIzzzz_full.cols;stochPIzzzz_vec.cols],[prePIzzzz_full.vals,stochPIzzzz_vec.vals],n_z,[n_z,n_z,n_z,n_z]); + stochtilfzzzz_vec=stochtilf_tilf_d4([nv_vec(:,stochfvars),nu_vec(:,model.stochfuvars)],params,model.stochtilf_ind_u); +end + +% extract PIv,Pivv,... from PIz,PIzz,... + +totindi=totindi+3; +totindi=totindi+4; +totindi=totindi+2; +totindi=totindi+2; +totindi=totindi+1; +totindi=totindi+9; + + +indi=totindi; +if approx>=1 + [stochPIz_vec,model.ind{indi}]=extract(PIz_vec,model.stochfzvars,model.stochfzvars,0,model.ind{indi}); + indi=indi+1; + [stochPIv_vec,model.ind{indi}]=extract(PIz_vec,model.stochfzvars,model.stochfvars,0,model.ind{indi}); + indi=indi+1; +end +if approx>=2 + [stochPIzz_vec,model.ind{indi}]=extract(PIzz_vec,model.stochfzvars,model.stochfzvars,0,model.ind{indi}); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=extract(PIzz_vec,model.stochfzvars,model.stochfvars,1,model.ind{indi}); + indi=indi+1; +end +if approx>=3 + [stochPIzzz_vec,model.ind{indi}]=extract(PIzzz_vec,model.stochfzvars,model.stochfzvars,0,model.ind{indi}); + indi=indi+1; + [stochPIvvvc_vec,model.ind{indi}]=extract(PIzzz_vec,model.stochfzvars,model.stochfvars,1,model.ind{indi}); + indi=indi+1; + if ~isfield(model,'stochfvars_chain3c_M2') + [ tempM ] = chainsM( n_stochfvars,3 ); + model.stochfvars_chain3c_M2=tempM{2}; + clear tempM + end +end +if approx>=4 + [stochPIzzzz_vec,model.ind{indi}]=extract(PIzzzz_vec,model.stochfzvars,model.stochfzvars,0,model.ind{indi}); + indi=indi+1; + [stochPIvvvvc_vec,model.ind{indi}]=extract(PIzzzz_vec,model.stochfzvars,model.stochfvars,1,model.ind{indi}); + indi=indi+1; + if ~isfield(model,'stochfvars_chain4c_M2') + [ tempM ] = chainsM( n_stochfvars,4 ); + model.stochfvars_chain4c_M2=tempM{2}; + model.stochfvars_chain4c_M3=tempM{3}; + model.stochfvars_chain4c_M4=tempM{4}; + clear tempM + end +end + +totindi=totindi+8; + +% compute derivatives of stochf w.r.t v by high order chain rules + +if approx==1 + indi=totindi; + for i=2:model.stoch_n + [stochPIv_vec,model.ind{indi}]=chain1_tensor(stochPIz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [stochfv_vec,model.ind{indi}]=chain1_tensor(stochtilfz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + +elseif approx==2 + indi=totindi+(model.stoch_n-1)*(1)+1; + for i=2:model.stoch_n + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=chain2c_tensor(stochPIz_vec,stochPIzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIv_vec,model.ind{indi}]=chain1_tensor(stochPIz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + + [stochfv_vec,model.ind{indi}]=chain1_tensor(stochtilfz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvc_vec,model.ind{indi}]=chain2c_tensor(stochtilfz_vec,stochtilfzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [ stochfvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvc_vec,2,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvc_vec + +elseif approx==3 + indi=totindi+(model.stoch_n-1)*(1+3)+1+4; + for i=2:model.stoch_n + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvvc_vec,model.ind{indi}]=chain3c_tensor(stochPIz_vec,stochPIzz_vec,stochPIzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,model.stochfvars_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=chain2c_tensor(stochPIz_vec,stochPIzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIv_vec,model.ind{indi}]=chain1_tensor(stochPIz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + + [stochfv_vec,model.ind{indi}]=chain1_tensor(stochtilfz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvc_vec,model.ind{indi}]=chain2c_tensor(stochtilfz_vec,stochtilfzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvvc_vec,model.ind{indi}]=chain3c_tensor(stochtilfz_vec,stochtilfzz_vec,stochtilfzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,... + model.stochfvars_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [ stochfvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvc_vec,2,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvc_vec + + [ stochfvvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvvc_vec,3,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvvc_vec + +elseif approx==4 + indi=totindi+(model.stoch_n-1)*(1+3+4)+1+4+6; + for i=2:model.stoch_n + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=colsort(stochPIvvc_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvvvc_vec,model.ind{indi}]=chain4c_tensor(stochPIz_vec,stochPIzz_vec,stochPIzzz_vec,stochPIzzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,stochPIvvvvc_vec,... + model.stochfvars_chain4c_M2,model.stochfvars_chain4c_M3,model.stochfvars_chain4c_M4,... + model.ind{indi},n_ind,maxload,'vec',model.stochzz,model.maxzz); + indi=indi+1; + [stochPIvvvc_vec,model.ind{indi}]=chain3c_tensor(stochPIz_vec,stochPIzz_vec,stochPIzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,model.stochfvars_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=chain2c_tensor(stochPIz_vec,stochPIzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIv_vec,model.ind{indi}]=chain1_tensor(stochPIz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=colsort(stochPIvvc_vec,model.ind{indi}); + indi=indi+1; + + [stochfv_vec,model.ind{indi}]=chain1_tensor(stochtilfz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [stochfvvc_vec,model.ind{indi}]=chain2c_tensor(stochtilfz_vec,stochtilfzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvvc_vec,model.ind{indi}]=chain3c_tensor(stochtilfz_vec,stochtilfzz_vec,stochtilfzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,... + model.stochfvars_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvvvc_vec,model.ind{indi}]=chain4c_tensor(stochtilfz_vec,stochtilfzz_vec,stochtilfzzz_vec,stochtilfzzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,stochPIvvvvc_vec,... + model.stochfvars_chain4c_M2,model.stochfvars_chain4c_M3,model.stochfvars_chain4c_M4,... + model.ind{indi},n_ind,maxload,'vec',model.stochtilfz,model.maxtilfz); + indi=indi+1; + + [ stochfvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvc_vec,2,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvc_vec + + [ stochfvvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvvc_vec,3,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvvc_vec + + [ stochfvvvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvvvc_vec,4,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvvvc_vec + +end + +%%%%%%%%%%%%% convert to sparse matrices + +if approx>=1 + prefv=changecols(prefv,model.prefvars,n_v_tp,1); + tempv=1:n_v; + tempv(2*n_y+n_x)=[]; + tempv(end)=[]; + prefv=changecols(prefv,tempv,n_v,1); + prefv=changerows(prefv,model.prefrows,n_f); + + stochfv_vec=changecols(stochfv_vec,model.stochfvars,n_v_tp,1); + stochfv_vec=changecols(stochfv_vec,tempv,n_v,1); + stochfv_vec=changerows(stochfv_vec,model.stochfrows,n_f); + + [prei,prej,prevals]=tfind(unfold(prefv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfv_vec)); + + fv=sparse(double([prei;stochi]),double([prej;stochj]),double([prevals(:);stochvals(:)]),n_f,n_v); +end +if approx>=2 + prefvv=changecols(prefvv,model.prefvars,n_v_tp,1); + prefvv=changecols(prefvv,model.prefvars,n_v_tp,2); + prefvv=changecols(prefvv,tempv,n_v,1); + prefvv=changecols(prefvv,tempv,n_v,2); + prefvv=changerows(prefvv,model.prefrows,n_f); + + stochfvv_vec=changecols(stochfvv_vec,model.stochfvars,n_v_tp,1); + stochfvv_vec=changecols(stochfvv_vec,model.stochfvars,n_v_tp,2); + stochfvv_vec=changecols(stochfvv_vec,tempv,n_v,1); + stochfvv_vec=changecols(stochfvv_vec,tempv,n_v,2); + stochfvv_vec=changerows(stochfvv_vec,model.stochfrows,n_f); + + [prei,prej,prevals]=tfind(unfold(prefvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvv_vec)); + + alli=double([prei;stochi]); + allj=double([prej;stochj]); + allvals=double([prevals(:);stochvals(:)]); + + newi=sub2ind([n_f,n_v^2],alli,allj); + newj=ones(size(newi)); + + fvv=sparse(newi,newj,allvals,n_f*n_v^2,1); +end +if approx>=3 + prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,1); + prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,2); + prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,3); + prefvvv=changecols(prefvvv,tempv,n_v,1); + prefvvv=changecols(prefvvv,tempv,n_v,2); + prefvvv=changecols(prefvvv,tempv,n_v,3); + prefvvv=changerows(prefvvv,model.prefrows,n_f); + + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,1); + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,2); + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,3); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,1); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,2); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,3); + stochfvvv_vec=changerows(stochfvvv_vec,model.stochfrows,n_f); + + [prei,prej,prevals]=tfind(unfold(prefvvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvvv_vec)); + + alli=double([prei;stochi]); + allj=double([prej;stochj]); + allvals=double([prevals(:);stochvals(:)]); + + newi=sub2ind([n_f,n_v^3],alli,allj); + newj=ones(size(newi)); + + fvvv=sparse(newi,newj,allvals,n_f*n_v^3,1); +end +if approx>=4 + prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,1); + prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,2); + prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,3); + prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,4); + prefvvvv=changecols(prefvvvv,tempv,n_v,1); + prefvvvv=changecols(prefvvvv,tempv,n_v,2); + prefvvvv=changecols(prefvvvv,tempv,n_v,3); + prefvvvv=changecols(prefvvvv,tempv,n_v,4); + prefvvvv=changerows(prefvvvv,model.prefrows,n_f); + + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,1); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,2); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,3); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,4); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,1); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,2); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,3); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,4); + stochfvvvv_vec=changerows(stochfvvvv_vec,model.stochfrows,n_f); + + [prei,prej,prevals]=tfind(unfold(prefvvvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvvvv_vec)); + + alli=double([prei;stochi]); + allj=double([prej;stochj]); + allvals=double([prevals(:);stochvals(:)]); + + newi=sub2ind([n_f,n_v^4],alli,allj); + newj=ones(size(newi)); + + fvvvv=sparse(newi,newj,allvals,n_f*n_v^4,1); +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/get_f_derivs_fname.m b/105/replication_package/solution_methods/taylor_projection/get_f_derivs_fname.m new file mode 100644 index 0000000000000000000000000000000000000000..e5e44cc220495ba6e56a62cff7d0e1130976ef7c --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/get_f_derivs_fname.m @@ -0,0 +1,686 @@ +%%%%%%%%%%%%% code from tp to compute fv,fvv,fvvv,fvvvv, where v is the +%%%%%%%%%%%%% vector of variables of the tp system (the pert system has a +%%%%%%%%%%%%% larger v). +% +% � Copyright, Oren Levintal, June 13, 2016. + +nv=[zeros(model.n_y,1);nyss(:);nxss(:);nxss(:)]'; % variables of tp +nv=repmat(nv,n_s,1); + +n_u=model.n_u; +nu=zeros(n_s,n_u); +npreu=preu_fun(nv(:,model.preuvars),params); % all predetermined u +nu(:,model.preurows)=npreu; +nz=[nv,nu]; + +params(:,model.logical_params_loc)=double(logical(nz(:,model.logical_zvars)>=0)); +if isempty(model.prefrows) + % compute derivatives of prePI w.r.t z (prePI=nonstochastic rows of PI) + + prePIz_full=prePI_d1(nz,params,model.prePI_ind_u); + + if approx>=2 + prePIzz_full=prePI_d2(nz,params,model.prePI_ind_u); + end + if approx>=3 + prePIzzz_full=prePI_d3(nz,params,model.prePI_ind_u); + end + if approx>=4 + prePIzzzz_full=prePI_d4(nz,params,model.prePI_ind_u); + end + if ~isfield(model,'ind') + model.ind=cell(model.totindi,1); + end + totindi=5+8; + totindi=totindi+model.count_pre_n*(1+3+4+6)+1+4+6+9; +else + fname=['pretilf' model.fname '_fun']; + pref=feval(fname,nz(:,model.pretilfzvars),params); % since i already have z, i use pretilf to evaluate f. + + % compute derivatives of prePI and pretilf w.r.t z (prePI=nonstochastic rows of PI, pretilf=nonstochastic rows of f) + + prePIz_full=prePI_d1(nz,params,model.prePI_ind_u); + prefvars=model.prefvars; + n_prefvars=length(prefvars); + + fname=['pretilf' model.fname '_tilf_d1']; + pretilfz=feval(fname,[nv(:,prefvars),nu(:,model.prefuvars)],params,model.pretilf_ind_u); + if approx>=2 + prePIzz_full=prePI_d2(nz,params,model.prePI_ind_u); + fname=['pretilf' model.fname '_tilf_d2']; + pretilfzz=feval(fname,[nv(:,prefvars),nu(:,model.prefuvars)],params,model.pretilf_ind_u); + end + if approx>=3 + prePIzzz_full=prePI_d3(nz,params,model.prePI_ind_u); + fname=['pretilf' model.fname '_tilf_d3']; + pretilfzzz=feval(fname,[nv(:,prefvars),nu(:,model.prefuvars)],params,model.pretilf_ind_u); + end + if approx>=4 + prePIzzzz_full=prePI_d4(nz,params,model.prePI_ind_u); + fname=['pretilf' model.fname '_tilf_d4']; + pretilfzzzz=feval(fname,[nv(:,prefvars),nu(:,model.prefuvars)],params,model.pretilf_ind_u); + end + + % extract derivatives of prePI w.r.t v from prePIz, prePIzz, ... + if ~isfield(model,'ind') + model.ind=cell(model.totindi,1); + end + indi=5; + + if approx>=1 + [prePIz,model.ind{indi}]=extract(prePIz_full,model.prefzvars,model.prefzvars,0,model.ind{indi}); + indi=indi+1; + [prePIv,model.ind{indi}]=extract(prePIz_full,model.prefzvars,model.prefvars,0,model.ind{indi}); + indi=indi+1; + end + if approx>=2 + [prePIzz,model.ind{indi}]=extract(prePIzz_full,model.prefzvars,model.prefzvars,0,model.ind{indi}); + indi=indi+1; + [prePIvvc,model.ind{indi}]=extract(prePIzz_full,model.prefzvars,model.prefvars,1,model.ind{indi}); + indi=indi+1; + end + if approx>=3 + [prePIzzz,model.ind{indi}]=extract(prePIzzz_full,model.prefzvars,model.prefzvars,0,model.ind{indi}); + indi=indi+1; + [prePIvvvc,model.ind{indi}]=extract(prePIzzz_full,model.prefzvars,model.prefvars,1,model.ind{indi}); + indi=indi+1; + if ~isfield(model,'prefvars_chain3c_M2') + [ tempM ] = chainsM( n_prefvars,3 ); + model.prefvars_chain3c_M2=tempM{2}; + clear tempM + end + end + if approx>=4 + [prePIzzzz,model.ind{indi}]=extract(prePIzzzz_full,model.prefzvars,model.prefzvars,0,model.ind{indi}); + indi=indi+1; + [prePIvvvvc,model.ind{indi}]=extract(prePIzzzz_full,model.prefzvars,model.prefvars,1,model.ind{indi}); + indi=indi+1; + if ~isfield(model,'prefvars_chain4c_M2') + [ tempM ] = chainsM( n_prefvars,4 ); + model.prefvars_chain4c_M2=tempM{2}; + model.prefvars_chain4c_M3=tempM{3}; + model.prefvars_chain4c_M4=tempM{4}; + clear tempM + end + end + + + % Use high order chain rules to compute derivatives of prePI w.r.t v + totindi=5+8; + if approx==1 + indi=totindi; + for i=2:model.pre_n + [prePIv,model.ind{indi}]=chain1_tensor(prePIz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [prefv,model.ind{indi}]=chain1_tensor(pretilfz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + elseif approx==2 + indi=totindi+model.count_pre_n*(1)+1; + for i=2:model.pre_n + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + [prePIvvc,model.ind{indi}]=chain2c_tensor(prePIz,prePIzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIv,model.ind{indi}]=chain1_tensor(prePIz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + + [prefv,model.ind{indi}]=chain1_tensor(pretilfz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvc,model.ind{indi}]=chain2c_tensor(pretilfz,pretilfzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [ prefvv,model.ind{indi} ] = uncompressderivs( prefvvc,2,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + + elseif approx==3 + indi=totindi+model.count_pre_n*(1+3)+1+4; + for i=2:model.pre_n + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + [prePIvvvc,model.ind{indi}]=chain3c_tensor(prePIz,prePIzz,prePIzzz,... + prePIv,prePIvvc,prePIvvvc,model.prefvars_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIvvc,model.ind{indi}]=chain2c_tensor(prePIz,prePIzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIv,model.ind{indi}]=chain1_tensor(prePIz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + + [prefv,model.ind{indi}]=chain1_tensor(pretilfz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvc,model.ind{indi}]=chain2c_tensor(pretilfz,pretilfzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvvc,model.ind{indi}]=chain3c_tensor(pretilfz,pretilfzz,pretilfzzz,... + prePIv,prePIvvc,prePIvvvc,... + model.prefvars_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [ prefvv,model.ind{indi} ] = uncompressderivs( prefvvc,2,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + + [ prefvvv,model.ind{indi} ] = uncompressderivs( prefvvvc,3,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + + elseif approx==4 + indi=totindi+model.count_pre_n*(1+3+4)+1+4+6; + for i=2:model.pre_n + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + [prePIvvc,model.ind{indi}]=colsort(prePIvvc,model.ind{indi}); + indi=indi+1; + [prePIvvvvc,model.ind{indi}]=chain4c_tensor(prePIz,prePIzz,prePIzzz,prePIzzzz,... + prePIv,prePIvvc,prePIvvvc,prePIvvvvc,... + model.prefvars_chain4c_M2,model.prefvars_chain4c_M3,model.prefvars_chain4c_M4,... + model.ind{indi},n_ind,maxload,'vec',model.prezz,model.maxzz); + indi=indi+1; + [prePIvvvc,model.ind{indi}]=chain3c_tensor(prePIz,prePIzz,prePIzzz,... + prePIv,prePIvvc,prePIvvvc,model.prefvars_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIvvc,model.ind{indi}]=chain2c_tensor(prePIz,prePIzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIv,model.ind{indi}]=chain1_tensor(prePIz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + [prePIvvc,model.ind{indi}]=colsort(prePIvvc,model.ind{indi}); + indi=indi+1; + + [prefv,model.ind{indi}]=chain1_tensor(pretilfz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [prefvvc,model.ind{indi}]=chain2c_tensor(pretilfz,pretilfzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvvc,model.ind{indi}]=chain3c_tensor(pretilfz,pretilfzz,pretilfzzz,... + prePIv,prePIvvc,prePIvvvc,... + model.prefvars_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvvvc,model.ind{indi}]=chain4c_tensor(pretilfz,pretilfzz,pretilfzzz,pretilfzzzz,... + prePIv,prePIvvc,prePIvvvc,prePIvvvvc,... + model.prefvars_chain4c_M2,model.prefvars_chain4c_M3,model.prefvars_chain4c_M4,... + model.ind{indi},n_ind,maxload,'vec',model.pretilfz,model.maxtilfz); + indi=indi+1; + + [ prefvv,model.ind{indi} ] = uncompressderivs( prefvvc,2,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + + [ prefvvv,model.ind{indi} ] = uncompressderivs( prefvvvc,3,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + + [ prefvvvv,model.ind{indi} ] = uncompressderivs( prefvvvvc,4,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + end + totindi=totindi+model.count_pre_n*(1+3+4+6)+1+4+6+9; +end + +%%%%%%%%%%%%% now stochastic equations +n_nodes=1; +nv_vec=repmat([nyss;nyss;nxss;nxss]',n_s,1); +stochfvars=model.stochfvars; +n_stochfvars=length(stochfvars); +nstochv_vec=nv_vec(:,stochfvars); % stochastic vars. + +nstochu_vec=stochu_fun(nv_vec(:,model.stochuvars),params); % all stochastic u vars +nu_vec=repmat(nu,n_nodes,1); +nu_vec(:,model.stochurows)=nstochu_vec; +nz_vec=[nv_vec,nu_vec]; + +params(:,model.logical_params_loc)=double(logical(nz_vec(:,model.logical_zvars)>=0)); + +% stochf_vec=stochtilf_fun(nz_vec(:,model.stochtilfzvars),params); +fname=['stochtilf' model.fname '_fun']; +stochf_vec=feval(fname,nz_vec(:,model.stochtilfzvars),params); + +% compute derivatives of stochPI and stochtilf w.r.t z + +stochPIz_vec=stochPI_d1(nz_vec,params,model.stochPI_ind_u); +prePIz_full.vals=repmat(prePIz_full.vals,n_nodes,1); + +i1=tfind(prePIz_full); +i2=tfind(stochPIz_vec); +PIz_vec=sptensor([i1;i2],[prePIz_full.cols;stochPIz_vec.cols],[prePIz_full.vals,stochPIz_vec.vals],n_z,[n_z]); + +% stochtilfz_vec=stochtilf_tilf_d1([nv_vec(:,stochfvars),nu_vec(:,model.stochfuvars)],params,model.stochtilf_ind_u); +fname=['stochtilf' model.fname '_tilf_d1']; +stochtilfz_vec=feval(fname,[nv_vec(:,stochfvars),nu_vec(:,model.stochfuvars)],params,model.stochtilf_ind_u); + +if approx>=2 + stochPIzz_vec=stochPI_d2(nz_vec,params,model.stochPI_ind_u); + prePIzz_full.vals=repmat(prePIzz_full.vals,n_nodes,1); + + i1=tfind(prePIzz_full); + i2=tfind(stochPIzz_vec); + PIzz_vec=sptensor([i1;i2],[prePIzz_full.cols;stochPIzz_vec.cols],[prePIzz_full.vals,stochPIzz_vec.vals],n_z,[n_z,n_z]); +% stochtilfzz_vec=stochtilf_tilf_d2([nv_vec(:,stochfvars),nu_vec(:,model.stochfuvars)],params,model.stochtilf_ind_u); + fname=['stochtilf' model.fname '_tilf_d2']; + stochtilfzz_vec=feval(fname,[nv_vec(:,stochfvars),nu_vec(:,model.stochfuvars)],params,model.stochtilf_ind_u); + +end +if approx>=3 + stochPIzzz_vec=stochPI_d3(nz_vec,params,model.stochPI_ind_u); + prePIzzz_full.vals=repmat(prePIzzz_full.vals,n_nodes,1); + + i1=tfind(prePIzzz_full); + i2=tfind(stochPIzzz_vec); + PIzzz_vec=sptensor([i1;i2],[prePIzzz_full.cols;stochPIzzz_vec.cols],[prePIzzz_full.vals,stochPIzzz_vec.vals],n_z,[n_z,n_z,n_z]); +% stochtilfzzz_vec=stochtilf_tilf_d3([nv_vec(:,stochfvars),nu_vec(:,model.stochfuvars)],params,model.stochtilf_ind_u); + fname=['stochtilf' model.fname '_tilf_d3']; + stochtilfzzz_vec=feval(fname,[nv_vec(:,stochfvars),nu_vec(:,model.stochfuvars)],params,model.stochtilf_ind_u); +end +if approx>=4 + stochPIzzzz_vec=stochPI_d4(nz_vec,params,model.stochPI_ind_u); + prePIzzzz_full.vals=repmat(prePIzzzz_full.vals,n_nodes,1); + + i1=tfind(prePIzzzz_full); + i2=tfind(stochPIzzzz_vec); + PIzzzz_vec=sptensor([i1;i2],[prePIzzzz_full.cols;stochPIzzzz_vec.cols],[prePIzzzz_full.vals,stochPIzzzz_vec.vals],n_z,[n_z,n_z,n_z,n_z]); +% stochtilfzzzz_vec=stochtilf_tilf_d4([nv_vec(:,stochfvars),nu_vec(:,model.stochfuvars)],params,model.stochtilf_ind_u); + fname=['stochtilf' model.fname '_tilf_d4']; + stochtilfzzzz_vec=feval(fname,[nv_vec(:,stochfvars),nu_vec(:,model.stochfuvars)],params,model.stochtilf_ind_u); +end + +% extract PIv,Pivv,... from PIz,PIzz,... + +totindi=totindi+3; +totindi=totindi+4; +totindi=totindi+2; +totindi=totindi+2; +totindi=totindi+1; +totindi=totindi+9; + + +indi=totindi; +if approx>=1 + [stochPIz_vec,model.ind{indi}]=extract(PIz_vec,model.stochfzvars,model.stochfzvars,0,model.ind{indi}); + indi=indi+1; + [stochPIv_vec,model.ind{indi}]=extract(PIz_vec,model.stochfzvars,model.stochfvars,0,model.ind{indi}); + indi=indi+1; +end +if approx>=2 + [stochPIzz_vec,model.ind{indi}]=extract(PIzz_vec,model.stochfzvars,model.stochfzvars,0,model.ind{indi}); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=extract(PIzz_vec,model.stochfzvars,model.stochfvars,1,model.ind{indi}); + indi=indi+1; +end +if approx>=3 + [stochPIzzz_vec,model.ind{indi}]=extract(PIzzz_vec,model.stochfzvars,model.stochfzvars,0,model.ind{indi}); + indi=indi+1; + [stochPIvvvc_vec,model.ind{indi}]=extract(PIzzz_vec,model.stochfzvars,model.stochfvars,1,model.ind{indi}); + indi=indi+1; + if ~isfield(model,'stochfvars_chain3c_M2') + [ tempM ] = chainsM( n_stochfvars,3 ); + model.stochfvars_chain3c_M2=tempM{2}; + clear tempM + end +end +if approx>=4 + [stochPIzzzz_vec,model.ind{indi}]=extract(PIzzzz_vec,model.stochfzvars,model.stochfzvars,0,model.ind{indi}); + indi=indi+1; + [stochPIvvvvc_vec,model.ind{indi}]=extract(PIzzzz_vec,model.stochfzvars,model.stochfvars,1,model.ind{indi}); + indi=indi+1; + if ~isfield(model,'stochfvars_chain4c_M2') + [ tempM ] = chainsM( n_stochfvars,4 ); + model.stochfvars_chain4c_M2=tempM{2}; + model.stochfvars_chain4c_M3=tempM{3}; + model.stochfvars_chain4c_M4=tempM{4}; + clear tempM + end +end + +totindi=totindi+8; + +% compute derivatives of stochf w.r.t v by high order chain rules + +if approx==1 + indi=totindi; + for i=2:model.stoch_n + [stochPIv_vec,model.ind{indi}]=chain1_tensor(stochPIz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [stochfv_vec,model.ind{indi}]=chain1_tensor(stochtilfz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + +elseif approx==2 + indi=totindi+model.count_stoch_n*(1)+1; + for i=2:model.stoch_n + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=chain2c_tensor(stochPIz_vec,stochPIzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIv_vec,model.ind{indi}]=chain1_tensor(stochPIz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + + [stochfv_vec,model.ind{indi}]=chain1_tensor(stochtilfz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvc_vec,model.ind{indi}]=chain2c_tensor(stochtilfz_vec,stochtilfzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [ stochfvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvc_vec,2,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvc_vec + +elseif approx==3 + indi=totindi+model.count_stoch_n*(1+3)+1+4; + for i=2:model.stoch_n + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvvc_vec,model.ind{indi}]=chain3c_tensor(stochPIz_vec,stochPIzz_vec,stochPIzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,model.stochfvars_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=chain2c_tensor(stochPIz_vec,stochPIzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIv_vec,model.ind{indi}]=chain1_tensor(stochPIz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + + [stochfv_vec,model.ind{indi}]=chain1_tensor(stochtilfz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvc_vec,model.ind{indi}]=chain2c_tensor(stochtilfz_vec,stochtilfzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvvc_vec,model.ind{indi}]=chain3c_tensor(stochtilfz_vec,stochtilfzz_vec,stochtilfzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,... + model.stochfvars_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [ stochfvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvc_vec,2,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvc_vec + + [ stochfvvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvvc_vec,3,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvvc_vec + +elseif approx==4 + indi=totindi+model.count_stoch_n*(1+3+4)+1+4+6; + for i=2:model.stoch_n + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=colsort(stochPIvvc_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvvvc_vec,model.ind{indi}]=chain4c_tensor(stochPIz_vec,stochPIzz_vec,stochPIzzz_vec,stochPIzzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,stochPIvvvvc_vec,... + model.stochfvars_chain4c_M2,model.stochfvars_chain4c_M3,model.stochfvars_chain4c_M4,... + model.ind{indi},n_ind,maxload,'vec',model.stochzz,model.maxzz); + indi=indi+1; + [stochPIvvvc_vec,model.ind{indi}]=chain3c_tensor(stochPIz_vec,stochPIzz_vec,stochPIzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,model.stochfvars_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=chain2c_tensor(stochPIz_vec,stochPIzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIv_vec,model.ind{indi}]=chain1_tensor(stochPIz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=colsort(stochPIvvc_vec,model.ind{indi}); + indi=indi+1; + + [stochfv_vec,model.ind{indi}]=chain1_tensor(stochtilfz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [stochfvvc_vec,model.ind{indi}]=chain2c_tensor(stochtilfz_vec,stochtilfzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvvc_vec,model.ind{indi}]=chain3c_tensor(stochtilfz_vec,stochtilfzz_vec,stochtilfzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,... + model.stochfvars_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvvvc_vec,model.ind{indi}]=chain4c_tensor(stochtilfz_vec,stochtilfzz_vec,stochtilfzzz_vec,stochtilfzzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,stochPIvvvvc_vec,... + model.stochfvars_chain4c_M2,model.stochfvars_chain4c_M3,model.stochfvars_chain4c_M4,... + model.ind{indi},n_ind,maxload,'vec',model.stochtilfz,model.maxtilfz); + indi=indi+1; + + [ stochfvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvc_vec,2,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvc_vec + + [ stochfvvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvvc_vec,3,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvvc_vec + + [ stochfvvvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvvvc_vec,4,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvvvc_vec + +end + +%%%%%%%%%%%%% convert to sparse matrices +if model.hybrid==0 + if ~isempty(model.prefrows) + + if approx>=1 + prefv=changecols(prefv,model.prefvars,n_v_tp,1); + tempv=1:n_v; + tempv(2*n_y+n_x)=[]; + tempv(end)=[]; + prefv=changecols(prefv,tempv,n_v,1); + prefv=changerows(prefv,model.prefrows,n_f); + + stochfv_vec=changecols(stochfv_vec,model.stochfvars,n_v_tp,1); + stochfv_vec=changecols(stochfv_vec,tempv,n_v,1); + stochfv_vec=changerows(stochfv_vec,model.stochfrows,n_f); + + [prei,prej,prevals]=tfind(unfold(prefv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfv_vec)); + + fv=sparse(double([prei;stochi]),double([prej;stochj]),double([prevals(:);stochvals(:)]),n_f,n_v); + end + if approx>=2 + prefvv=changecols(prefvv,model.prefvars,n_v_tp,1); + prefvv=changecols(prefvv,model.prefvars,n_v_tp,2); + prefvv=changecols(prefvv,tempv,n_v,1); + prefvv=changecols(prefvv,tempv,n_v,2); + prefvv=changerows(prefvv,model.prefrows,n_f); + + stochfvv_vec=changecols(stochfvv_vec,model.stochfvars,n_v_tp,1); + stochfvv_vec=changecols(stochfvv_vec,model.stochfvars,n_v_tp,2); + stochfvv_vec=changecols(stochfvv_vec,tempv,n_v,1); + stochfvv_vec=changecols(stochfvv_vec,tempv,n_v,2); + stochfvv_vec=changerows(stochfvv_vec,model.stochfrows,n_f); + + [prei,prej,prevals]=tfind(unfold(prefvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvv_vec)); + + alli=double([prei;stochi]); + allj=double([prej;stochj]); + allvals=double([prevals(:);stochvals(:)]); + + newi=sub2ind([n_f,n_v^2],alli,allj); + newj=ones(size(newi)); + + fvv=sparse(newi,newj,allvals,n_f*n_v^2,1); + end + if approx>=3 + prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,1); + prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,2); + prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,3); + prefvvv=changecols(prefvvv,tempv,n_v,1); + prefvvv=changecols(prefvvv,tempv,n_v,2); + prefvvv=changecols(prefvvv,tempv,n_v,3); + prefvvv=changerows(prefvvv,model.prefrows,n_f); + + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,1); + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,2); + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,3); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,1); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,2); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,3); + stochfvvv_vec=changerows(stochfvvv_vec,model.stochfrows,n_f); + + [prei,prej,prevals]=tfind(unfold(prefvvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvvv_vec)); + + alli=double([prei;stochi]); + allj=double([prej;stochj]); + allvals=double([prevals(:);stochvals(:)]); + + newi=sub2ind([n_f,n_v^3],alli,allj); + newj=ones(size(newi)); + + fvvv=sparse(newi,newj,allvals,n_f*n_v^3,1); + end + if approx>=4 + prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,1); + prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,2); + prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,3); + prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,4); + prefvvvv=changecols(prefvvvv,tempv,n_v,1); + prefvvvv=changecols(prefvvvv,tempv,n_v,2); + prefvvvv=changecols(prefvvvv,tempv,n_v,3); + prefvvvv=changecols(prefvvvv,tempv,n_v,4); + prefvvvv=changerows(prefvvvv,model.prefrows,n_f); + + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,1); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,2); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,3); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,4); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,1); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,2); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,3); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,4); + stochfvvvv_vec=changerows(stochfvvvv_vec,model.stochfrows,n_f); + + [prei,prej,prevals]=tfind(unfold(prefvvvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvvvv_vec)); + + alli=double([prei;stochi]); + allj=double([prej;stochj]); + allvals=double([prevals(:);stochvals(:)]); + + newi=sub2ind([n_f,n_v^4],alli,allj); + newj=ones(size(newi)); + + fvvvv=sparse(newi,newj,allvals,n_f*n_v^4,1); + end + else + if approx>=1 + % prefv=changecols(prefv,model.prefvars,n_v_tp,1); + tempv=1:n_v; + tempv(2*n_y+n_x)=[]; + tempv(end)=[]; + % prefv=changecols(prefv,tempv,n_v,1); + % prefv=changerows(prefv,model.prefrows,n_f); + + stochfv_vec=changecols(stochfv_vec,model.stochfvars,n_v_tp,1); + stochfv_vec=changecols(stochfv_vec,tempv,n_v,1); + stochfv_vec=changerows(stochfv_vec,model.stochfrows,n_f); + + % [prei,prej,prevals]=tfind(unfold(prefv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfv_vec)); + + % fv=sparse(double([prei;stochi]),double([prej;stochj]),double([prevals(:);stochvals(:)]),n_f,n_v); + fv=sparse(double([stochi]),double([stochj]),double([stochvals(:)]),n_f,n_v); + end + if approx>=2 + % prefvv=changecols(prefvv,model.prefvars,n_v_tp,1); + % prefvv=changecols(prefvv,model.prefvars,n_v_tp,2); + % prefvv=changecols(prefvv,tempv,n_v,1); + % prefvv=changecols(prefvv,tempv,n_v,2); + % prefvv=changerows(prefvv,model.prefrows,n_f); + + stochfvv_vec=changecols(stochfvv_vec,model.stochfvars,n_v_tp,1); + stochfvv_vec=changecols(stochfvv_vec,model.stochfvars,n_v_tp,2); + stochfvv_vec=changecols(stochfvv_vec,tempv,n_v,1); + stochfvv_vec=changecols(stochfvv_vec,tempv,n_v,2); + stochfvv_vec=changerows(stochfvv_vec,model.stochfrows,n_f); + + % [prei,prej,prevals]=tfind(unfold(prefvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvv_vec)); + + % alli=double([prei;stochi]); + % allj=double([prej;stochj]); + % allvals=double([prevals(:);stochvals(:)]); + alli=double([stochi]); + allj=double([stochj]); + allvals=double([stochvals(:)]); + + newi=sub2ind([n_f,n_v^2],alli,allj); + newj=ones(size(newi)); + + fvv=sparse(newi,newj,allvals,n_f*n_v^2,1); + end + if approx>=3 + % prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,1); + % prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,2); + % prefvvv=changecols(prefvvv,model.prefvars,n_v_tp,3); + % prefvvv=changecols(prefvvv,tempv,n_v,1); + % prefvvv=changecols(prefvvv,tempv,n_v,2); + % prefvvv=changecols(prefvvv,tempv,n_v,3); + % prefvvv=changerows(prefvvv,model.prefrows,n_f); + + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,1); + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,2); + stochfvvv_vec=changecols(stochfvvv_vec,model.stochfvars,n_v_tp,3); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,1); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,2); + stochfvvv_vec=changecols(stochfvvv_vec,tempv,n_v,3); + stochfvvv_vec=changerows(stochfvvv_vec,model.stochfrows,n_f); + + % [prei,prej,prevals]=tfind(unfold(prefvvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvvv_vec)); + + % alli=double([prei;stochi]); + % allj=double([prej;stochj]); + % allvals=double([prevals(:);stochvals(:)]); + alli=double([stochi]); + allj=double([stochj]); + allvals=double([stochvals(:)]); + + newi=sub2ind([n_f,n_v^3],alli,allj); + newj=ones(size(newi)); + + fvvv=sparse(newi,newj,allvals,n_f*n_v^3,1); + end + if approx>=4 + % prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,1); + % prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,2); + % prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,3); + % prefvvvv=changecols(prefvvvv,model.prefvars,n_v_tp,4); + % prefvvvv=changecols(prefvvvv,tempv,n_v,1); + % prefvvvv=changecols(prefvvvv,tempv,n_v,2); + % prefvvvv=changecols(prefvvvv,tempv,n_v,3); + % prefvvvv=changecols(prefvvvv,tempv,n_v,4); + % prefvvvv=changerows(prefvvvv,model.prefrows,n_f); + + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,1); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,2); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,3); + stochfvvvv_vec=changecols(stochfvvvv_vec,model.stochfvars,n_v_tp,4); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,1); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,2); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,3); + stochfvvvv_vec=changecols(stochfvvvv_vec,tempv,n_v,4); + stochfvvvv_vec=changerows(stochfvvvv_vec,model.stochfrows,n_f); + + % [prei,prej,prevals]=tfind(unfold(prefvvvv)); + [stochi,stochj,stochvals]=tfind(unfold(stochfvvvv_vec)); + + % alli=double([prei;stochi]); + % allj=double([prej;stochj]); + % allvals=double([prevals(:);stochvals(:)]); + alli=double([stochi]); + allj=double([stochj]); + allvals=double([stochvals(:)]); + + newi=sub2ind([n_f,n_v^4],alli,allj); + newj=ones(size(newi)); + + fvvvv=sparse(newi,newj,allvals,n_f*n_v^4,1); + end + end +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/get_hybridPhi_derivs_v.m b/105/replication_package/solution_methods/taylor_projection/get_hybridPhi_derivs_v.m new file mode 100644 index 0000000000000000000000000000000000000000..83d7e184f41f244be8a32d2255cab5b97a9c1a7f --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/get_hybridPhi_derivs_v.m @@ -0,0 +1,289 @@ +% compute derivatives of Phi w.r.t v by high order chain rules. +n_Phivars=length(model.Phivars); +Phivars=model.Phivars; + +count_Phi_n=model.Phi_n-1; +if count_Phi_n<0 + count_Phi_n=0; +end + +if ~isfield(model,'hind') + model.hind=cell(100+1+8+8+count_Phi_n*(1+3+4+6)+1+4+6+9,1); + model.hind4=cell(100+count_Phi_n,1); +end + + +hindi=1; +hindi4=1; +tothindi=1; + +% extract PhiPIv,PhiPivv,... from PIz,PIzz,... +if order>=0 + [PhiPIz_vec,model.hind{hindi}]=extract(PIz_vec,model.Phizvars,model.Phizvars,0,model.hind{hindi}); + hindi=hindi+1; + [PhiPIv_vec,model.hind{hindi}]=extract(PIz_vec,model.Phizvars,model.Phivars,0,model.hind{hindi}); + hindi=hindi+1; + fname=['Phi' model.fname '_tilf_d1']; + Phiz_vec=feval(fname,[nv_vec(:,Phivars),nu_vec(:,model.Phiuvars)],params_vec,model.Phi_ind_u); +end +if order>=1 + [PhiPIzz_vec,model.hind{hindi}]=extract(PIzz_vec,model.Phizvars,model.Phizvars,0,model.hind{hindi}); + hindi=hindi+1; + [PhiPIvvc_vec,model.hind{hindi}]=extract(PIzz_vec,model.Phizvars,model.Phivars,1,model.hind{hindi}); + hindi=hindi+1; + fname=['Phi' model.fname '_tilf_d2']; + Phizz_vec=feval(fname,[nv_vec(:,Phivars),nu_vec(:,model.Phiuvars)],params_vec,model.Phi_ind_u); +end +if order>=2 + [PhiPIzzz_vec,model.hind{hindi}]=extract(PIzzz_vec,model.Phizvars,model.Phizvars,0,model.hind{hindi}); + hindi=hindi+1; + [PhiPIvvvc_vec,model.hind{hindi}]=extract(PIzzz_vec,model.Phizvars,model.Phivars,1,model.hind{hindi}); + hindi=hindi+1; + fname=['Phi' model.fname '_tilf_d3']; + Phizzz_vec=feval(fname,[nv_vec(:,Phivars),nu_vec(:,model.Phiuvars)],params_vec,model.Phi_ind_u); + + if ~isfield(model,'Phivars_chain3c_M2') + [ tempM ] = chainsM( n_Phivars,3 ); + model.Phivars_chain3c_M2=tempM{2}; + clear tempM + end +end +if order>=3 + [PhiPIzzzz_vec,model.hind{hindi}]=extract(PIzzzz_vec,model.Phizvars,model.Phizvars,0,model.hind{hindi}); + hindi=hindi+1; + [PhiPIvvvvc_vec,model.hind{hindi}]=extract(PIzzzz_vec,model.Phizvars,model.Phivars,1,model.hind{hindi}); + hindi=hindi+1; + fname=['Phi' model.fname '_tilf_d4']; + Phizzzz_vec=feval(fname,[nv_vec(:,Phivars),nu_vec(:,model.Phiuvars)],params_vec,model.Phi_ind_u); + if ~isfield(model,'Phivars_chain4c_M2') + [ tempM ] = chainsM( n_Phivars,4 ); + model.Phivars_chain4c_M2=tempM{2}; + model.Phivars_chain4c_M3=tempM{3}; + model.Phivars_chain4c_M4=tempM{4}; + clear tempM + end +end +if order>=4 + [PhiPIzzzzz_vec,model.hind4{hindi4}]=extract(PIzzzzz_vec,model.Phizvars,model.Phizvars,0,model.hind4{hindi4}); + hindi4=hindi4+1; + [PhiPIvvvvvc_vec,model.hind4{hindi4}]=extract(PIzzzzz_vec,model.Phizvars,model.Phivars,1,model.hind4{hindi4}); + hindi4=hindi4+1; + fname=['Phi' model.fname '_tilf_d5']; + Phizzzzz_vec=feval(fname,[nv_vec(:,Phivars),nu_vec(:,model.Phiuvars)],params_vec,model.Phi_ind_u); +end +tothindi=tothindi+8; +% hindi=tothindi; + + + +if order==0 + hindi=tothindi; + for i=2:model.Phi_n + [PhiPIv_vec,model.hind{hindi}]=chain1_tensor(PhiPIz_vec,PhiPIv_vec,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + end + [Phiv_vec,model.hind{hindi}]=chain1_tensor(Phiz_vec,PhiPIv_vec,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + +% stochfv_vec.vals=multcol(stochfv_vec.vals,Pvec); +% +% model.stochfv_vec=stochfv_vec; + +elseif order==1 + hindi=tothindi+count_Phi_n*(1)+1; + for i=2:model.Phi_n + [PhiPIv_vec,model.hind{hindi}]=colsort(PhiPIv_vec,model.hind{hindi}); + hindi=hindi+1; + [PhiPIvvc_vec,model.hind{hindi}]=chain2c_tensor(PhiPIz_vec,PhiPIzz_vec,PhiPIv_vec,PhiPIvvc_vec,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + [PhiPIv_vec,model.hind{hindi}]=chain1_tensor(PhiPIz_vec,PhiPIv_vec,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + end + [PhiPIv_vec,model.hind{hindi}]=colsort(PhiPIv_vec,model.hind{hindi}); + hindi=hindi+1; + + [Phiv_vec,model.hind{hindi}]=chain1_tensor(Phiz_vec,PhiPIv_vec,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + [Phivvc_vec,model.hind{hindi}]=chain2c_tensor(Phiz_vec,Phizz_vec,PhiPIv_vec,PhiPIvvc_vec,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + +% stochfv_vec.vals=multcol(stochfv_vec.vals,Pvec); +% stochfvvc_vec.vals=multcol(stochfvvc_vec.vals,Pvec); + + [ Phivv_vec,model.hind{hindi} ] = uncompressderivs( Phivvc_vec,2,n_Phivars,model.Phiv(:,Phivars),model.hind{hindi} ); + hindi=hindi+1; + clear Phivvc_vec + +elseif order==2 + hindi=tothindi+count_Phi_n*(1+3)+1+4; + for i=2:model.Phi_n + [PhiPIv_vec,model.hind{hindi}]=colsort(PhiPIv_vec,model.hind{hindi}); + hindi=hindi+1; + [PhiPIvvvc_vec,model.hind{hindi}]=chain3c_tensor(PhiPIz_vec,PhiPIzz_vec,PhiPIzzz_vec,... + PhiPIv_vec,PhiPIvvc_vec,PhiPIvvvc_vec,model.Phivars_chain3c_M2,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + [PhiPIvvc_vec,model.hind{hindi}]=chain2c_tensor(PhiPIz_vec,PhiPIzz_vec,PhiPIv_vec,PhiPIvvc_vec,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + [PhiPIv_vec,model.hind{hindi}]=chain1_tensor(PhiPIz_vec,PhiPIv_vec,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + end + [PhiPIv_vec,model.hind{hindi}]=colsort(PhiPIv_vec,model.hind{hindi}); + hindi=hindi+1; + + [Phiv_vec,model.hind{hindi}]=chain1_tensor(Phiz_vec,PhiPIv_vec,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + [Phivvc_vec,model.hind{hindi}]=chain2c_tensor(Phiz_vec,Phizz_vec,PhiPIv_vec,PhiPIvvc_vec,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + [Phivvvc_vec,model.hind{hindi}]=chain3c_tensor(Phiz_vec,Phizz_vec,Phizzz_vec,... + PhiPIv_vec,PhiPIvvc_vec,PhiPIvvvc_vec,... + model.Phivars_chain3c_M2,... + model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + +% stochfv_vec.vals=multcol(stochfv_vec.vals,Pvec); +% stochfvvc_vec.vals=multcol(stochfvvc_vec.vals,Pvec); +% stochfvvvc_vec.vals=multcol(stochfvvvc_vec.vals,Pvec); + + [ Phivv_vec,model.hind{hindi} ] = uncompressderivs( Phivvc_vec,2,n_Phivars,model.Phiv(:,Phivars),model.hind{hindi} ); + hindi=hindi+1; + clear Phivvc_vec + + [ Phivvv_vec,model.hind{hindi} ] = uncompressderivs( Phivvvc_vec,3,n_Phivars,model.Phiv(:,Phivars),model.hind{hindi} ); + hindi=hindi+1; + clear Phivvvc_vec + +elseif order==3 + hindi=tothindi+count_Phi_n*(1+3+4)+1+4+6; + for i=2:model.Phi_n + [PhiPIv_vec,model.hind{hindi}]=colsort(PhiPIv_vec,model.hind{hindi}); + hindi=hindi+1; + [PhiPIvvc_vec,model.hind{hindi}]=colsort(PhiPIvvc_vec,model.hind{hindi}); + hindi=hindi+1; + [PhiPIvvvvc_vec,model.hind{hindi}]=chain4c_tensor(PhiPIz_vec,PhiPIzz_vec,PhiPIzzz_vec,PhiPIzzzz_vec,... + PhiPIv_vec,PhiPIvvc_vec,PhiPIvvvc_vec,PhiPIvvvvc_vec,... + model.Phivars_chain4c_M2,model.Phivars_chain4c_M3,model.Phivars_chain4c_M4,... + model.hind{hindi},n_ind,maxload,'vec',model.Phizz,model.maxzz); + hindi=hindi+1; + [PhiPIvvvc_vec,model.hind{hindi}]=chain3c_tensor(PhiPIz_vec,PhiPIzz_vec,PhiPIzzz_vec,... + PhiPIv_vec,PhiPIvvc_vec,PhiPIvvvc_vec,model.Phivars_chain3c_M2,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + [PhiPIvvc_vec,model.hind{hindi}]=chain2c_tensor(PhiPIz_vec,PhiPIzz_vec,PhiPIv_vec,PhiPIvvc_vec,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + [PhiPIv_vec,model.hind{hindi}]=chain1_tensor(PhiPIz_vec,PhiPIv_vec,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + end + [PhiPIv_vec,model.hind{hindi}]=colsort(PhiPIv_vec,model.hind{hindi}); + hindi=hindi+1; + [PhiPIvvc_vec,model.hind{hindi}]=colsort(PhiPIvvc_vec,model.hind{hindi}); + hindi=hindi+1; + + [Phiv_vec,model.hind{hindi}]=chain1_tensor(Phiz_vec,PhiPIv_vec,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + [Phivvc_vec,model.hind{hindi}]=chain2c_tensor(Phiz_vec,Phizz_vec,PhiPIv_vec,PhiPIvvc_vec,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + [Phivvvc_vec,model.hind{hindi}]=chain3c_tensor(Phiz_vec,Phizz_vec,Phizzz_vec,... + PhiPIv_vec,PhiPIvvc_vec,PhiPIvvvc_vec,... + model.Phivars_chain3c_M2,... + model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + + [Phivvvvc_vec,model.hind{hindi}]=chain4c_tensor(Phiz_vec,Phizz_vec,Phizzz_vec,Phizzzz_vec,... + PhiPIv_vec,PhiPIvvc_vec,PhiPIvvvc_vec,PhiPIvvvvc_vec,... + model.Phivars_chain4c_M2,model.Phivars_chain4c_M3,model.Phivars_chain4c_M4,... + model.hind{hindi},n_ind,maxload,'vec',model.tilPhiz,model.maxtilPhiz); + hindi=hindi+1; + +% stochfv_vec.vals=multcol(stochfv_vec.vals,Pvec); +% stochfvvc_vec.vals=multcol(stochfvvc_vec.vals,Pvec); +% stochfvvvc_vec.vals=multcol(stochfvvvc_vec.vals,Pvec); +% stochfvvvvc_vec.vals=multcol(stochfvvvvc_vec.vals,Pvec); + + [ Phivv_vec,model.hind{hindi} ] = uncompressderivs( Phivvc_vec,2,n_Phivars,model.Phiv(:,Phivars),model.hind{hindi} ); + hindi=hindi+1; + clear Phivvc_vec + + [ Phivvv_vec,model.hind{hindi} ] = uncompressderivs( Phivvvc_vec,3,n_Phivars,model.Phiv(:,Phivars),model.hind{hindi} ); + hindi=hindi+1; + clear Phivvvc_vec + + [ Phivvvv_vec,model.hind{hindi} ] = uncompressderivs( Phivvvvc_vec,4,n_Phivars,model.Phiv(:,Phivars),model.hind{hindi} ); + hindi=hindi+1; + clear Phivvvvc_vec + +elseif order==4 + hindi=tothindi+count_Phi_n*(1+3+4)+1+4+6; + for i=2:model.Phi_n + [PhiPIv_vec,model.hind{hindi}]=colsort(PhiPIv_vec,model.hind{hindi}); + hindi=hindi+1; + [PhiPIvvc_vec,model.hind{hindi}]=colsort(PhiPIvvc_vec,model.hind{hindi}); + hindi=hindi+1; + [PhiPIvvvvvc_vec,model.hind4{hindi4}]=chain5c_tensor(PhiPIz_vec,PhiPIzz_vec,PhiPIzzz_vec,PhiPIzzzz_vec,PhiPIzzzzz_vec,... + PhiPIv_vec,PhiPIvvc_vec,PhiPIvvvc_vec,PhiPIvvvvc_vec,PhiPIvvvvvc_vec,... + model.Phivars_chain5c_M1,model.Phivars_chain5c_M2,model.Phivars_chain5c_M3,model.Phivars_chain5c_M4,model.Phivars_chain5c_M5,model.Phivars_chain5c_M6,... + model.hind4{hindi4},n_ind,maxload,'vec',model.Phizz,model.maxzz); + hindi4=hindi4+1; + [PhiPIvvvvc_vec,model.hind{hindi}]=chain4c_tensor(PhiPIz_vec,PhiPIzz_vec,PhiPIzzz_vec,PhiPIzzzz_vec,... + PhiPIv_vec,PhiPIvvc_vec,PhiPIvvvc_vec,PhiPIvvvvc_vec,... + model.Phivars_chain4c_M2,model.Phivars_chain4c_M3,model.Phivars_chain4c_M4,... + model.hind{hindi},n_ind,maxload,'vec',model.Phizz,model.maxzz); + hindi=hindi+1; + [PhiPIvvvc_vec,model.hind{hindi}]=chain3c_tensor(PhiPIz_vec,PhiPIzz_vec,PhiPIzzz_vec,... + PhiPIv_vec,PhiPIvvc_vec,PhiPIvvvc_vec,model.Phivars_chain3c_M2,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + [PhiPIvvc_vec,model.hind{hindi}]=chain2c_tensor(PhiPIz_vec,PhiPIzz_vec,PhiPIv_vec,PhiPIvvc_vec,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + [PhiPIv_vec,model.hind{hindi}]=chain1_tensor(PhiPIz_vec,PhiPIv_vec,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + end + [PhiPIv_vec,model.hind{hindi}]=colsort(PhiPIv_vec,model.hind{hindi}); + hindi=hindi+1; + [PhiPIvvc_vec,model.hind{hindi}]=colsort(PhiPIvvc_vec,model.hind{hindi}); + hindi=hindi+1; + + [Phiv_vec,model.hind{hindi}]=chain1_tensor(Phiz_vec,PhiPIv_vec,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + [Phivvc_vec,model.hind{hindi}]=chain2c_tensor(Phiz_vec,Phizz_vec,PhiPIv_vec,PhiPIvvc_vec,model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + [Phivvvc_vec,model.hind{hindi}]=chain3c_tensor(Phiz_vec,Phizz_vec,Phizzz_vec,... + PhiPIv_vec,PhiPIvvc_vec,PhiPIvvvc_vec,... + model.Phivars_chain3c_M2,... + model.hind{hindi},n_ind,maxload,'vec'); + hindi=hindi+1; + + [Phivvvvc_vec,model.hind{hindi}]=chain4c_tensor(Phiz_vec,Phizz_vec,Phizzz_vec,Phizzzz_vec,... + PhiPIv_vec,PhiPIvvc_vec,PhiPIvvvc_vec,PhiPIvvvvc_vec,... + model.Phivars_chain4c_M2,model.Phivars_chain4c_M3,model.Phivars_chain4c_M4,... + model.hind{hindi},n_ind,maxload,'vec',model.tilPhiz,model.maxtilPhiz); + hindi=hindi+1; + + [Phivvvvvc_vec,model.hind4{hindi4}]=chain5c_tensor(Phiz_vec,Phizz_vec,Phizzz_vec,Phizzzz_vec,Phizzzzz_vec,... + PhiPIv_vec,PhiPIvvc_vec,PhiPIvvvc_vec,PhiPIvvvvc_vec,PhiPIvvvvvc_vec,... + model.Phivars_chain5c_M1,model.Phivars_chain5c_M2,model.Phivars_chain5c_M3,model.Phivars_chain5c_M4,model.Phivars_chain5c_M5,model.Phivars_chain5c_M6,... + model.hind4{hindi4},n_ind,maxload,'vec',model.tilPhiz,model.maxtilPhiz); + hindi4=hindi4+1; + +% stochfv_vec.vals=multcol(stochfv_vec.vals,Pvec); +% stochfvvc_vec.vals=multcol(stochfvvc_vec.vals,Pvec); +% stochfvvvc_vec.vals=multcol(stochfvvvc_vec.vals,Pvec); +% stochfvvvvc_vec.vals=multcol(stochfvvvvc_vec.vals,Pvec); +% stochfvvvvvc_vec.vals=multcol(stochfvvvvvc_vec.vals,Pvec); + + [ Phivv_vec,model.hind{hindi} ] = uncompressderivs( Phivvc_vec,2,n_Phivars,model.Phiv(:,Phivars),model.hind{hindi} ); + hindi=hindi+1; + clear Phivvc_vec + + [ Phivvv_vec,model.hind{hindi} ] = uncompressderivs( Phivvvc_vec,3,n_Phivars,model.Phiv(:,Phivars),model.hind{hindi} ); + hindi=hindi+1; + clear Phivvvc_vec + + [ Phivvvv_vec,model.hind{hindi} ] = uncompressderivs( Phivvvvc_vec,4,n_Phivars,model.Phiv(:,Phivars),model.hind{hindi} ); + hindi=hindi+1; + clear Phivvvvc_vec + + [ Phivvvvv_vec,model.hind4{hindi4} ] = uncompressderivs( Phivvvvvc_vec,5,n_Phivars,model.Phiv(:,Phivars),model.hind4{hindi4} ); + hindi4=hindi4+1; + clear Phivvvvvc_vec + +end +tothindi=tothindi+8+count_Phi_n*(1+3+4+6)+1+4+6+9; +hindi=tothindi; \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/get_hybridPhi_derivs_x_theta.m b/105/replication_package/solution_methods/taylor_projection/get_hybridPhi_derivs_x_theta.m new file mode 100644 index 0000000000000000000000000000000000000000..281ccbc2ed56bbb1e0915eda13b5785dbec44c90 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/get_hybridPhi_derivs_x_theta.m @@ -0,0 +1,93 @@ +phiv_theta_vecT=takerows(v_theta,Phivars); +phiv_theta_vecT.vals=reshape(repmat(phiv_theta_vecT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + +[ Phitheta,model.hind{hindi} ] = chain0_theta_tensor( Phiv_vec,phiv_theta_vecT,model.hind{hindi},n_ind,maxload,'vec' ); +hindi=hindi+1; + +if order>=1 + phivxT=takerows(vx,Phivars); + phivxT.vals=reshape(repmat(phivxT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + phivx_theta_vecT=takerows(vx_theta,Phivars); + phivx_theta_vecT=unfold(phivx_theta_vecT); + phivx_theta_vecT.vals=reshape(repmat(phivx_theta_vecT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + [ Phix,model.hind{hindi} ] = chain1_tensor( Phiv_vec,phivxT,model.hind{hindi},n_ind,maxload,'vec' ); + hindi=hindi+1; + + [ Phixtheta,model.hind{hindi} ] = chain1_theta_tensor( Phiv_vec,Phivv_vec,... + phivxT,phiv_theta_vecT,phivx_theta_vecT,... + model.hind{hindi},n_ind,maxload,'vec' ); + hindi=hindi+1; + +end +if order>=2 + phivxxcT=takerows(vxxc,Phivars); + phivxxcT.vals=reshape(repmat(phivxxcT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + phivxxc_theta_vecT=takerows(vxxc_theta,Phivars); + phivxxc_theta_vecT=unfold(phivxxc_theta_vecT); + phivxxc_theta_vecT.vals=reshape(repmat(phivxxc_theta_vecT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + [phivxT,model.hind4{hindi4}]=colsort(phivxT,model.hind4{hindi4}); + hindi4=hindi4+1; + [ Phixxc,model.hind{hindi} ] = chain2c_tensor( Phiv_vec,Phivv_vec,... + phivxT,phivxxcT,model.hind{hindi},n_ind,maxload,'vec' ); + hindi=hindi+1; + + [ Phixxctheta,model.hind{hindi} ] = chain2c_theta_tensor( Phiv_vec,Phivv_vec,Phivvv_vec,... + phivxT,phivxxcT,... + phiv_theta_vecT,phivx_theta_vecT,phivxxc_theta_vecT,... + model.chain2c_theta_M2,... + model.hind{hindi},n_ind,maxload,'vec' ); + hindi=hindi+1; + +end +if order>=3 + phivxxxcT=takerows(vxxxc,Phivars); + phivxxxcT.vals=reshape(repmat(phivxxxcT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + phivxxxc_theta_vecT=takerows(vxxxc_theta,Phivars); + phivxxxc_theta_vecT=unfold(phivxxxc_theta_vecT); + phivxxxc_theta_vecT.vals=reshape(repmat(phivxxxc_theta_vecT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + [ Phixxxc,model.hind{hindi} ] = chain3c_tensor( Phiv_vec,Phivv_vec,Phivvv_vec,... + phivxT,phivxxcT,phivxxxcT,... + model.x_chain3c_M2,... + model.hind{hindi},n_ind,maxload,'vec' ); + hindi=hindi+1; + + [ Phixxxctheta,model.hind{hindi} ] = chain3c_theta_tensor( Phiv_vec,Phivv_vec,Phivvv_vec,Phivvvv_vec,... + phivxT,phivxxcT,phivxxxcT,... + phiv_theta_vecT,phivx_theta_vecT,phivxxc_theta_vecT,phivxxxc_theta_vecT,... + model.chain3c_theta_M2,model.chain3c_theta_M3,model.chain3c_theta_M4,model.chain3c_theta_M5,... + model.hind{hindi},n_ind,maxload,'vec' ); + hindi=hindi+1; + +end +if order>=4 + phivxxxxcT=takerows(vxxxxc,Phivars); + phivxxxxcT.vals=reshape(repmat(phivxxxxcT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + phivxxxxc_theta_vecT=takerows(vxxxxc_theta,Phivars); + phivxxxxc_theta_vecT=unfold(phivxxxxc_theta_vecT); + phivxxxxc_theta_vecT.vals=reshape(repmat(phivxxxxc_theta_vecT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + [phivxxcT,model.hind4{hindi4}]=colsort(phivxxcT,model.hind4{hindi4}); + hindi4=hindi4+1; + [ Phixxxxc,model.hind4{hindi4} ] = chain4c_tensor( Phiv_vec,Phivv_vec,Phivvv_vec,Phivvvv_vec,... + phivxT,phivxxcT,phivxxxcT,phivxxxxcT,... + model.x_chain4c_M2,model.x_chain4c_M3,model.x_chain4c_M4,... + model.hind4{hindi4},n_ind,maxload,'vec' ); + hindi4=hindi4+1; + + + [ Phixxxxctheta,model.hind4{hindi4} ] = chain4c_theta_tensor( Phiv_vec,Phivv_vec,Phivvv_vec,Phivvvv_vec,Phivvvvv_vec,... + phivxT,phivxxcT,phivxxxcT,phivxxxxcT,... + phiv_theta_vecT,phivx_theta_vecT,phivxxc_theta_vecT,phivxxxc_theta_vecT,phivxxxxc_theta_vecT,... + model.chain4c_theta_M2,model.chain4c_theta_M3,model.chain4c_theta_M5,model.chain4c_theta_M6,model.chain4c_theta_M9,model.chain4c_theta_M10,... + model.hind4{hindi4},n_ind,maxload,'vec' ); + hindi4=hindi4+1; + +end +tothindi=tothindi+7; \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/get_initial.m b/105/replication_package/solution_methods/taylor_projection/get_initial.m new file mode 100644 index 0000000000000000000000000000000000000000..aa99d125b30e57feecb0eddc9aa114ceec6ec45a --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/get_initial.m @@ -0,0 +1,92 @@ +function [ stoch_pert,nonstoch_pert ] = get_initial(model,order,derivs,nyss,nxss ) +%This function transforms a pertrubation solution to an initial guess for Taylor +%Projection. Two types of guess are available: stoch_pert includes +%correction for volatility. nonstoch_pert does not include correction for +%volatility. +% +% � Copyright, Oren Levintal, June 13, 2016. + +order=order(1); + +n_x=model.n_x; +n_x1=model.n_x1; +n_y=model.n_y; + +if order==1 + [GH0,GH1]=shiftpoly([nxss;1],[nxss;0],1:n_x,[nyss;nxss(1:n_x1,:)],[derivs.gx;derivs.hx(1:n_x1,:)]); + stoch_pert=[GH0,GH1]; + if nargout==2 + [GH0,GH1]=shiftpoly([nxss;0],[nxss;0],1:n_x,[nyss;nxss(1:n_x1,:)],[derivs.gx;derivs.hx(1:n_x1,:)]); + nonstoch_pert=[GH0,GH1]; + end +elseif order==2 + derivs.gxx=reshape(derivs.gxx,n_y,[]); + derivs.hxx=reshape(derivs.hxx(1:n_x1,:),n_x1,[]); + [GH0,GH1,GH2]=shiftpoly([nxss;1],[nxss;0],1:n_x,[nyss;nxss(1:n_x1,:)],[derivs.gx;derivs.hx(1:n_x1,:)],... + [derivs.gxx;derivs.hxx(1:n_x1,:)]/2); + [U2,~]=create_UW(n_x,2); + stoch_pert=[GH0,GH1,GH2*U2]; + if nargout==2 + [GH0,GH1,GH2]=shiftpoly([nxss;0],[nxss;0],1:n_x,[nyss;nxss(1:n_x1,:)],[derivs.gx;derivs.hx(1:n_x1,:)],... + [derivs.gxx;derivs.hxx(1:n_x1,:)]/2); + nonstoch_pert=[GH0,GH1,GH2*U2]; + end +elseif order==3 + derivs.gxx=reshape(derivs.gxx,n_y,[]); + derivs.hxx=reshape(derivs.hxx(1:n_x1,:),n_x1,[]); + derivs.gxxx=reshape(derivs.gxxx,n_y,[]); + derivs.hxxx=reshape(derivs.hxxx(1:n_x1,:),n_x1,[]); + [GH0,GH1,GH2,GH3]=shiftpoly([nxss;1],[nxss;0],1:n_x,[nyss;nxss(1:n_x1,:)],[derivs.gx;derivs.hx(1:n_x1,:)],... + [derivs.gxx;derivs.hxx(1:n_x1,:)]/2,[derivs.gxxx;derivs.hxxx(1:n_x1,:)]/factorial(3)); + [U2,~]=create_UW(n_x,2); + [U3,~]=create_UW(n_x,3); + stoch_pert=[GH0,GH1,GH2*U2,GH3*U3]; + if nargout==2 + [GH0,GH1,GH2,GH3]=shiftpoly([nxss;0],[nxss;0],1:n_x,[nyss;nxss(1:n_x1,:)],[derivs.gx;derivs.hx(1:n_x1,:)],... + [derivs.gxx;derivs.hxx(1:n_x1,:)]/2,[derivs.gxxx;derivs.hxxx(1:n_x1,:)]/factorial(3)); + nonstoch_pert=[GH0,GH1,GH2*U2,GH3*U3]; + end +elseif order==4 + derivs.gxx=reshape(derivs.gxx,n_y,[]); + derivs.hxx=reshape(derivs.hxx(1:n_x1,:),n_x1,[]); + derivs.gxxx=reshape(derivs.gxxx,n_y,[]); + derivs.hxxx=reshape(derivs.hxxx(1:n_x1,:),n_x1,[]); + derivs.gxxxx=reshape(derivs.gxxxx,n_y,[]); + derivs.hxxxx=reshape(derivs.hxxxx(1:n_x1,:),n_x1,[]); + [GH0,GH1,GH2,GH3,GH4]=shiftpoly([nxss;1],[nxss;0],1:n_x,[nyss;nxss(1:n_x1,:)],[derivs.gx;derivs.hx(1:n_x1,:)],... + [derivs.gxx;derivs.hxx(1:n_x1,:)]/2,[derivs.gxxx;derivs.hxxx(1:n_x1,:)]/factorial(3),... + [derivs.gxxxx;derivs.hxxxx(1:n_x1,:)]/factorial(4)); + [U2,~]=create_UW(n_x,2); + [U3,~]=create_UW(n_x,3); + [U4,~]=create_UW(n_x,4); + stoch_pert=[GH0,GH1,GH2*U2,GH3*U3,GH4*U4]; + if nargout==2 + [GH0,GH1,GH2,GH3,GH4]=shiftpoly([nxss;0],[nxss;0],1:n_x,[nyss;nxss(1:n_x1,:)],[derivs.gx;derivs.hx(1:n_x1,:)],... + [derivs.gxx;derivs.hxx(1:n_x1,:)]/2,[derivs.gxxx;derivs.hxxx(1:n_x1,:)]/factorial(3),... + [derivs.gxxxx;derivs.hxxxx(1:n_x1,:)]/factorial(4)); + nonstoch_pert=[GH0,GH1,GH2*U2,GH3*U3,GH4*U4]; + end +elseif order==5 + [GH0,GH1,GH2,GH3,GH4,GH5]=shiftpoly([nxss;1],[nxss;0],1:n_x,[nyss;nxss(1:n_x1,:)],[derivs.gx;derivs.hx(1:n_x1,:)],... + [derivs.gxx;derivs.hxx(1:n_x1,:)]/2,[derivs.gxxx;derivs.hxxx(1:n_x1,:)]/factorial(3),... + [derivs.gxxxx;derivs.hxxxx(1:n_x1,:)]/factorial(4),[derivs.gxxxxx;derivs.hxxxxx(1:n_x1,:)]/factorial(5)); + [U2,~]=create_UW(n_x,2); + [U3,~]=create_UW(n_x,3); + [U4,~]=create_UW(n_x,4); + [U5,~]=create_UW(n_x,5); + stoch_pert=[GH0,GH1,GH2*U2,GH3*U3,GH4*U4,GH5*U5]; + if nargout==2 + [GH0,GH1,GH2,GH3,GH4,GH5]=shiftpoly([nxss;0],[nxss;0],1:n_x,[nyss;nxss(1:n_x1,:)],[derivs.gx;derivs.hx(1:n_x1,:)],... + [derivs.gxx;derivs.hxx(1:n_x1,:)]/2,[derivs.gxxx;derivs.hxxx(1:n_x1,:)]/factorial(3),... + [derivs.gxxxx;derivs.hxxxx(1:n_x1,:)]/factorial(4),[derivs.gxxxxx;derivs.hxxxxx(1:n_x1,:)]/factorial(5)); + nonstoch_pert=[GH0,GH1,GH2*U2,GH3*U3,GH4*U4,GH5*U5]; + end +end +stoch_pert=stoch_pert(:); + +if nargout==2 + nonstoch_pert=nonstoch_pert(:); +end + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/get_moments.m b/105/replication_package/solution_methods/taylor_projection/get_moments.m new file mode 100644 index 0000000000000000000000000000000000000000..a047f7e86989553d0d032638ff9e85d791dd567c --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/get_moments.m @@ -0,0 +1,46 @@ +function M=get_moments(nep,P,order) +% +% � Copyright, Oren Levintal, June 13, 2016. + +order=order(1); +M2=0;M3=0;M4=0;M5=0; +for i=1:length(P) + if order>=2 + nep2=kron(nep(:,i),nep(:,i)); + M2=M2+nep2*P(i); + end + if order>=3 + nep3=kron(nep2,nep(:,i)); + M3=M3+nep3*P(i); + end + if order>=4 + nep4=kron(nep3,nep(:,i)); + M4=M4+nep4*P(i); + end + if order>=5 + nep5=kron(nep4,nep(:,i)); + M5=M5+nep5*P(i); + end +end + +if order==1 + M.M1=sparse(size(nep,1),1); +end +if order>=2 + M2(abs(M2)=3 + M3(abs(M3)=4 + M4(abs(M4)=5 + M5(abs(M5)4 + error('perturbation order cannot exceed 4') +end + +params=[params(:);zeros(model.n_logicalparams,1)]; + +if model.hybrid==0 + eta=eta_fun(params(:)',[]); + eta=reshape(full(eta),model.n_x,[]); +else + params=[zeros(1,model.n_e),params(:)']; + nv=[zeros(model.n_y,1);nyss(:);nxss(:);nxss(:)]'; % variables of tp + n_u=model.n_u; + nu=zeros(n_u,1)'; + npreu=preu_fun(nv(model.preuvars),params); % all predetermined u + nu(model.preurows)=npreu; + nz=[nv,nu]; + uname=['new_eta' model.uname '_fun']; + tempvars=nz(:,model.Phizvars); %n_s,n_x+n_y +% tempvars=reshape(repmat(tempvars(:)',n_nodes,1),n_nodes*n_s,[]); %n_s*n_nodes,n_x+n_y+n_preurows +% tempvars=reshape(repmat(tempvars(:)',n_nodes,1),n_nodes*n_s,[]); %n_s*n_nodes,n_x+n_y+n_preurows + eta=feval(uname,tempvars,params); %n_s*n_nodes,n_x2 + eta=reshape(full(eta),model.n_x,[]); +end + +tic +n_f=model.n_f; + +n_y=model.n_y; +n_x2=model.n_x2; +n_x1=model.n_x1; +n_z=model.n_z; % no. of auxiliary variables + +% note that pert system has one more state variable than tp system. +n_x_tp=model.n_x; +n_v_tp=model.n_v; +n_x=model.n_x+1; +n_v=model.n_v+2; + +if length(nyss)~=model.n_y + error('wrong size of steady state vector of control variables') +elseif length(nxss)~=model.n_x + error('wrong size of steady state vector of state variables') +end + +if isfield(model,'UW') + UW=model.UW; % IMPORTANT: THESE COMPRESSION MATRICES ASSUME A CERTAIN NONZERO PATTERN. +else + UW=create_compression_matrices_nonzero2(approx,n_x); % compression matrices for the perturbation solution. + model.UW=UW; +end + +if approx==2 + W2=UW.W2; U2=UW.U2; +elseif approx==3 + W2=UW.W2; U2=UW.U2; + W3=UW.W3; U3=UW.U3; +elseif approx==4 + W2=UW.W2; U2=UW.U2; + W3=UW.W3; U3=UW.U3; + W4=UW.W4; U4=UW.U4; +end + +if isfield(model,'OMEGA_x') + OMEGA_x=model.OMEGA_x; +else + create_OMEGA_x; + model.OMEGA_x=OMEGA_x; +end + + +n_e=size(eta,2); +eta=[eta;zeros(1,n_e)]; + +nx=nxss; +% nxss=[nxss(:);0]; % add steady state value of the perturbation variable. +nxss=nxss(:); +nyss=nyss(:); +% nuss=eval_u([nyss;nyss;nxss;nxss],params); +if ~isfield(model,'n_ind') + n_ind=1; +else + n_ind=model.n_ind; +end +if ~isfield(model,'maxload') + maxload=intarray(1); +else + maxload=intarray(model.maxload); +end +if ~isfield(model,'pertind') + model.pertind=cell(model.totindi,1); +end +pertindi=1; + +% nPhi=Phi_fun(nx,params); +if model.hybrid==0 + get_Phi_derivs; +end + + +if isfield(model,'fname') + get_f_derivs_fname; +else + get_f_derivs; +end + +if model.hybrid==1 || model.hybrid==3 + order=approx-1; + params_vec=params; + get_hybridPhi_derivs_v; + order=approx; + n_f=n_f+n_x2; + convert_to_matrices; + fv(n_y+n_x1+(1:n_x2),2*n_y+n_x1+(1:n_x2))=-eye(n_x2); + if approx>=1 + nPhix=zeros(0,n_x); + end + if approx>=2 + nPhixx=zeros(0,n_x^2); + end + if approx>=3 + nPhixxx=zeros(0,n_x^3); + end + if approx>=4 + nPhixxxx=zeros(0,n_x^4); + end + n_x2=0; + n_x1=n_x1+n_x2; +end +% numu_derivs=evalu_derivs(params,nxss,nyss,approx); +% call_evalf_derivs; +% +% sym2script_fv; + + + + +%%%%%%%%%%%%% +fyp=fv(:,1:n_y); fy=fv(:,n_y+1:2*n_y); fxp=fv(:,2*n_y+1:2*n_y+n_x); fx=fv(:,2*n_y+n_x+1:end); + +% First Order + +% use the function gx_hx of Schmitt-Grohe and Uribe (2004) to solve the +% first order solution + +% tic +if isfield(model,'stake') + stake=model.stake; +else + stake=1; +end +[gx,hx,exitflag]=gx_hx(full([fy;zeros(n_x2,n_y)]),full([fx(:,1:end-1);nPhix(:,1:end-1)]),full([fyp;zeros(n_x2,n_y)]),full([fxp(:,1:end-1);[zeros(n_x2,n_x1),-eye(n_x2)]]),stake); + +gx=[gx,zeros(n_y,1)]; +hx=[hx;zeros(1,n_x-1)]; +hx=[hx,zeros(n_x,1)]; +hx(end,end)=1; +% replace relevant rows of hx with nPhix which is more numerically accurate +hx(n_x1+1:n_x1+n_x2,:)=nPhix; + +% disp(['1st order completed in ' num2str(toc,'%15.2f') ' seconds']) + +hx=sparse(hx); +gx=sparse(gx); + +% Second Order +if approx>=2 +% tic + M2=M.M2; + eta2_M2=reshape([eta*reshape(M2,n_e,n_e)]',n_e,n_x); + eta2_M2=reshape([eta*eta2_M2]',n_x^2,1); + +% sym2script_fvv; + + unique=nchoosek(n_x+2-1,2); + unique=unique-nchoosek(n_x-1+1-1,1); + + Vx0=[gx*hx;gx;hx;speye(n_x)]; + Vx1=[gx;sparse(n_y,n_x);speye(n_x,n_x);sparse(n_x,n_x)]; + + Ezeta2=[ sparse(n_x^2,n_x^2-1) , eta2_M2 ]; + + A=innerkron(n_f,n_v,fvv,Vx0,Vx0)+innerkron(n_f,n_v,fvv,Vx1,Vx1)*Ezeta2; + + fy_fxp_fypgx=[fv(:,n_y+1:2*n_y) fv(:,2*n_y+1:2*n_y+n_x)+fv(:,1:n_y)*gx]; + + G=fy_fxp_fypgx(:,1:n_f); + H=fy_fxp_fypgx(:,n_f+1:n_f+n_x2); + + D=sparse(n_f,n_f); + D(:,1:n_y)=fv(:,1:n_y); + + + if strcmp(algo,'Kamenik') + if n_x2==0 + C=A; + else % do not solve exogenous state variables (see appendix A.6 in the paper). H is the last block of G. + C=A+H*(nPhixx); + end + %Block 1: xx + spx=sparse([ones(n_x-1,1);0]); + choosex2=kron(spx,spx); + choosex2=logical(choosex2==1); + tempeye=speye(n_x^2); + Z=tempeye(:,choosex2); + CZ=C*Z; + hx_hat=hx(1:end-1,1:end-1); + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-CZ,2 ); + time=toc; + else + G=full(G); + D=full(D); + hx_hat=full(hx_hat); + tic + [~,Xtemp]=gensylv( 2,G,D,hx_hat,full(-CZ) ); + time=toc; + end + acc=norm(full(CZ+AkronkC(D*Xtemp,hx_hat,2)+G*Xtemp)); + if acc>1e-8 + warning(['Second order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X=zeros(n_f,n_x^2); + X(:,choosex2)=full(Xtemp); + gxx_hat=Xtemp(1:n_y,:); + hat_eta2_M2=eta2_M2(choosex2,:); + %Block 2: ss + sps=sparse([zeros(n_x-1,1);1]); + choosex2=kron(sps,sps); + choosex2=logical(choosex2==1); + Z=tempeye(:,choosex2); + CZ=C*Z; + tic + Xtemp=-(D+G)\(CZ+(fyp*gxx_hat)*hat_eta2_M2); + time=toc; + + acc=norm(full(CZ+(fyp*gxx_hat)*hat_eta2_M2+(D+G)*Xtemp)); + if acc>1e-8 + warning(['Second order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex2)=full(Xtemp); clear Xtemp + else + if n_x2==0 + CU2=A*U2; + else % do not solve exogenous state variables (see appendix A.6 in the paper). H is the last block of G. + CU2=A*U2+H*(nPhixx*U2); + end + W2BU2=(innerkron(unique,n_x,W2,hx,hx)+W2*Ezeta2)*U2; + %Block 1: xx + spx=sparse([ones(n_x-1,1);0]); + choosex2=kron(spx,spx); + choosex2U=logical(U2'*choosex2==1); + tempeye=speye(size(U2,2)); + Z=tempeye(:,choosex2U); + CU2Z=CU2*Z; + ZTW2BU2Z=Z'*W2BU2*Z; + if strcmpi(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW2BU2Z',D)+kron(speye(size(Z,2)),G))\CU2Z(:),n_f,size(Z,2)); + elseif strcmpi(algo,'dlyap') + Xtemp=dlyap(ZTW2BU2Z',(-G\D)',(-G\CU2Z)'); + Xtemp=Xtemp'; + elseif strcmpi(algo,'slicot') + Xtemp=HessSchur(full(ZTW2BU2Z'),full((G\D)'),full((-G\CU2Z)')); + Xtemp=Xtemp'; + end + acc=norm(full(G*Xtemp+D*Xtemp*ZTW2BU2Z+CU2Z)); + if acc>1e-8 + warning(['Second order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X=zeros(n_f,size(U2,2)); + X(:,choosex2U)=full(Xtemp); clear Xtemp ZTW2BU2Z + %Block 2 + sps=sparse([zeros(n_x-1,1);1]); + choosex2=kron(sps,sps); + choosex2U=logical(U2'*choosex2==1); + tempeye=speye(size(U2,2)); + Z=tempeye(:,choosex2U); + W2BU2Z=W2BU2*Z; + CU2Z=CU2*Z+D*X*W2BU2Z; + ZTW2BU2Z=Z'*W2BU2*Z; + if strcmpi(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW2BU2Z',D)+kron(speye(size(Z,2)),G))\CU2Z(:),n_f,size(Z,2)); + elseif strcmpi(algo,'dlyap') + Xtemp=dlyap(ZTW2BU2Z',(-G\D)',(-G\CU2Z)'); + Xtemp=Xtemp'; + elseif strcmpi(algo,'slicot') + Xtemp=HessSchur(full(ZTW2BU2Z'),full((G\D)'),full((-G\CU2Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW2BU2Z+CU2Z); + if acc>1e-8 + warning(['Second order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex2U)=full(Xtemp); clear Xtemp W2BU2Z ZTW2BU2Z + X=X*W2; + end + gxx=X(1:n_y,:); + hxx=[X(n_y+1:end,:);nPhixx;zeros(1,n_x^2)]; +end + +% Third Order +if approx>=3 + Vxx0=[chain2(gx,gxx,hx,hxx);gxx;hxx;sparse(n_x,n_x^2)]; + Vxx1=[gxx;sparse(n_y+2*n_x,n_x^2)]; + + M3=M.M3(:); + + eta3_M3=reshape([eta*reshape(M3,n_e,n_e^2)]',n_e,n_e*n_x); + eta3_M3=reshape([eta*eta3_M3]',n_e,n_x^2); + eta3_M3=reshape([eta*eta3_M3]',n_x^3,1); + + Ezeta3=[ sparse(n_x^3,n_x^3-1) , eta3_M3 ]; + Ix=speye(n_x); + Ix_Ezeta2=kron(Ix,Ezeta2); + + unique=nchoosek(n_x+3-1,3); + unique=unique-nchoosek(n_x-1+2-1,2); + A_third_order; % create matrix A of a third order solution + + if strcmp(algo,'Kamenik') + if n_x2==0 + C=A; + else % do not solve exogenous state variables (see appendix A.6 in the paper). H is the last block of G. + C=A+H*(nPhixxx); + end + %Block 1:xxx + choosex3=kron(spx,kron(spx,spx)); + choosex3=logical(choosex3==1); + tempeye=speye(n_x^3); + Z=tempeye(:,choosex3); + CZ=C*Z; + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-CZ,3 ); + time=toc; + else + tic + [~,Xtemp]=gensylv( 3,G,D,hx_hat,full(-CZ)); + time=toc; + end + acc=norm(full(CZ+AkronkC(D*Xtemp,hx_hat,3)+G*Xtemp)); + if acc>1e-8 + warning(['Third order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X=zeros(n_f,n_x^3); + X(:,choosex3)=full(Xtemp); + gxxx_hat=Xtemp(1:n_y,:); + hat_eta3_M3=eta3_M3(choosex3,:); + %Block 2:xss + choosex3=kron(kron(sps,sps),spx); + choosex3=logical(choosex3==1); + Z=tempeye(:,choosex3); + CZ=C*Z; + term2=reshape(fyp*gxxx_hat,n_f*(n_x-1),(n_x-1)^2)*hat_eta2_M2; + term2=reshape(term2',n_f,n_x-1)*hx_hat; + cons=CZ+term2; + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-cons,1 ); + time=toc; + else + tic + [~,Xtemp]=gensylv( 1,G,D,hx_hat,full(-cons)); + time=toc; + end + acc=norm(full(cons+AkronkC(D*Xtemp,hx_hat,1)+G*Xtemp)); + if acc>1e-8 + warning(['Third order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex3)=full(Xtemp); clear Xtemp + %Block 2:sss + choosex3=kron(kron(sps,sps),sps); + choosex3=logical(choosex3==1); + Z=tempeye(:,choosex3); + CZ=C*Z; + term2=(fyp*gxxx_hat)*hat_eta3_M3; + cons=CZ+term2; + tic + Xtemp=-(D+G)\cons; + time=toc; + + acc=norm(full(cons+(D+G)*Xtemp)); + if acc>1e-8 + warning(['Third order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex3)=full(Xtemp); clear Xtemp + % add symmetric entries, but first permute the indices, because the + % compression matrices assume i1>=i2>=i3, while block xss has + % i11e-8 + warning(['Third order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X=zeros(n_f,size(U3,2)); + X(:,choosex3U)=full(Xtemp); clear Xtemp ZTW3BU3Z + %Block 2:xss + choosex3=kron(kron(sps,sps),spx); + choosex3=choosex3+kron(kron(sps,spx),sps); + choosex3=choosex3+kron(kron(spx,sps),sps); + choosex3U=logical(U3'*choosex3~=0); + Z=tempeye(:,choosex3U); + W3BU3Z=W3BU3*Z; + CU3Z=CU3*Z+D*X*W3BU3Z; + ZTW3BU3Z=Z'*W3BU3*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW3BU3Z',D)+kron(speye(size(Z,2)),G))\CU3Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW3BU3Z',(-G\D)',(-G\CU3Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW3BU3Z'),full((G\D)'),full((-G\CU3Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW3BU3Z+CU3Z); + if acc>1e-8 + warning(['Third order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex3U)=full(Xtemp); clear Xtemp ZTW3BU3Z + %Block 3:sss + choosex3=kron(kron(sps,sps),sps); + choosex3U=logical(U3'*choosex3~=0); + Z=tempeye(:,choosex3U); + W3BU3Z=W3BU3*Z; + CU3Z=CU3*Z+D*X*W3BU3Z; + ZTW3BU3Z=Z'*W3BU3*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW3BU3Z',D)+kron(speye(size(Z,2)),G))\CU3Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW3BU3Z',(-G\D)',(-G\CU3Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW3BU3Z'),full((G\D)'),full((-G\CU3Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW3BU3Z+CU3Z); + if acc>1e-8 + warning(['Third order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex3U)=full(Xtemp); clear Xtemp ZTW3BU3Z W3BU3 + X=X*W3; + end + + gxxx=X(1:n_y,:); + hxxx=[X(n_y+1:end,:);nPhixxx;zeros(1,n_x^3)]; +end + +% Fourth Order +if approx>=4 + Vxxx0=[chain3(gx,gxx,gxxx,hx,hxx,hxxx,OMEGA_x.OMEGA1);gxxx;hxxx;sparse(n_x,n_x^3)]; + Vxxx1=[gxxx;sparse(n_y+2*n_x,n_x^3)]; + + M4=M.M4(:); + + eta4_M4=reshape([eta*reshape(M4,n_e,n_e^3)]',n_e,n_e^2*n_x); + eta4_M4=reshape([eta*eta4_M4]',n_e,n_e*n_x^2); + eta4_M4=reshape([eta*eta4_M4]',n_e,n_x^3); + eta4_M4=reshape([eta*eta4_M4]',n_x^4,1); + + Ezeta4=[ sparse(n_x^4,n_x^4-1) , eta4_M4 ]; + Ix_Ezeta3=kron(Ix,Ezeta3); + Ix2=speye(n_x^2); + Ix2_Ezeta2=kron(Ix2,Ezeta2); + + hx2=kron(hx,hx); + hx_Ezeta2_hx=kron(kron(hx,Ezeta2),hx); + hx_Ezeta3=kron(hx,Ezeta3); + hx2_Ezeta2=kron(hx2,Ezeta2); + + unique=nchoosek(n_x+4-1,4); + unique=unique-nchoosek(n_x-1+3-1,3); + + clear result R + + A_fourth_order; % create matrix A of a fourth order solution + + if strcmp(algo,'Kamenik') + if n_x2==0 + C=A; + else % do not solve exogenous state variables (see appendix A.6 in the paper). H is the last block of G. + C=A+H*(nPhixxxx); + end + %Block 1:xxxx + choosex4=kron(kron(spx,spx),kron(spx,spx)); + choosex4=logical(choosex4==1); + tempeye=speye(n_x^4); + Z=tempeye(:,choosex4); + CZ=C*Z; + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-CZ,4 ); + time=toc; + else + tic + [~,Xtemp]=gensylv( 4,G,D,hx_hat,full(-CZ)); + time=toc; + end + acc=norm(full(CZ+AkronkC(D*Xtemp,hx_hat,4)+G*Xtemp)); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X=zeros(n_f,n_x^4); + X(:,choosex4)=full(Xtemp); + gxxxx_hat=Xtemp(1:n_y,:); + hat_eta4_M4=eta4_M4(choosex4,:); + %Block 2:xxss + choosex4=kron(kron(sps,sps),kron(spx,spx)); + choosex4=logical(choosex4==1); + Z=tempeye(:,choosex4); + CZ=C*Z; + term2=reshape(fyp*gxxxx_hat,n_f*(n_x-1)^2,(n_x-1)^2)*hat_eta2_M2; + term2=reshape(term2',n_f*(n_x-1),(n_x-1))*hx_hat; + term2=reshape(term2',(n_x-1)*n_f,(n_x-1))*hx_hat; + term2=reshape(term2',(n_x-1)^2,n_f); + term2=term2'; + cons=CZ+term2; + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-cons,2 ); + time=toc; + else + tic + [~,Xtemp]=gensylv( 2,G,D,hx_hat,full(-cons)); + time=toc; + end + + acc=norm(full(cons+AkronkC(D*Xtemp,hx_hat,2)+G*Xtemp)); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex4)=full(Xtemp); + gxxss_hat=Xtemp(1:n_y,:); + %Block 2:xsss + choosex4=kron(kron(sps,sps),kron(sps,spx)); + choosex4=logical(choosex4==1); + Z=tempeye(:,choosex4); + CZ=C*Z; + term2=reshape(fyp*gxxxx_hat,n_f*(n_x-1),(n_x-1)^3)*hat_eta3_M3; + term2=reshape(term2',n_f,(n_x-1))*hx_hat; + cons=CZ+term2; + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-cons,1 ); + time=toc; + else + tic + [~,Xtemp]=gensylv( 1,G,D,hx_hat,full(-cons)); + time=toc; + end + acc=norm(full(cons+AkronkC(D*Xtemp,hx_hat,1)+G*Xtemp)); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex4)=full(Xtemp); + %Block 2:ssss + choosex4=kron(kron(sps,sps),kron(sps,sps)); + choosex4=logical(choosex4==1); + Z=tempeye(:,choosex4); + CZ=C*Z; + term2=(6*fyp*gxxss_hat)*hat_eta2_M2; + term3=(fyp*gxxxx_hat)*hat_eta4_M4; + cons=CZ+term2+term3; + tic + Xtemp=-(D+G)\cons; + time=toc; + acc=norm(full(cons+(D+G)*Xtemp)); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex4)=full(Xtemp); clear Xtemp + % add symmetric entries, but first permute the indices. + X=reshape(permute(reshape(X,[],n_x,n_x,n_x,n_x),[1,5,4,3,2]),[],n_x^4)*U4*W4; + else + if n_x2==0 + CU4=A*U4; + else + CU4=A*U4+H*(nPhixxxx*U4); + end + kron_hx_hx=kron(hx,hx); + WBU_fourth_order; % create the matrix W4BU4 + %Block 1:xxxx + choosex4=kron(kron(spx,spx),kron(spx,spx)); + choosex4U=logical(U4'*choosex4~=0); + tempeye=speye(size(U4,2)); + Z=tempeye(:,choosex4U); + CU4Z=CU4*Z; + ZTW4BU4Z=Z'*W4BU4*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW4BU4Z',D)+kron(speye(size(Z,2)),G))\CU4Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW4BU4Z',(-G\D)',(-G\CU4Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW4BU4Z'),full((G\D)'),full((-G\CU4Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW4BU4Z+CU4Z); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X=zeros(n_f,size(U4,2)); + X(:,choosex4U)=full(Xtemp); clear Xtemp ZTW4BU4Z + %Block 2:xxss + choosex4=kron(kron(sps,sps),kron(spx,spx)); + choosex4=choosex4+kron(kron(sps,spx),kron(sps,spx)); + choosex4=choosex4+kron(kron(sps,spx),kron(spx,sps)); + choosex4=choosex4+kron(kron(spx,sps),kron(sps,spx)); + choosex4=choosex4+kron(kron(spx,sps),kron(spx,sps)); + choosex4=choosex4+kron(kron(spx,spx),kron(sps,sps)); + choosex4U=logical(U4'*choosex4~=0); + Z=tempeye(:,choosex4U); + W4BU4Z=W4BU4*Z; + CU4Z=CU4*Z+D*X*W4BU4Z; + ZTW4BU4Z=Z'*W4BU4*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW4BU4Z',D)+kron(speye(size(Z,2)),G))\CU4Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW4BU4Z',(-G\D)',(-G\CU4Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW4BU4Z'),full((G\D)'),full((-G\CU4Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW4BU4Z+CU4Z); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex4U)=full(Xtemp); clear Xtemp ZTW4BU4Z + %Block 3:xsss + choosex4=kron(kron(sps,sps),kron(sps,spx)); + choosex4=choosex4+kron(kron(sps,sps),kron(spx,sps)); + choosex4=choosex4+kron(kron(sps,spx),kron(sps,sps)); + choosex4=choosex4+kron(kron(spx,sps),kron(sps,sps)); + choosex4U=logical(U4'*choosex4~=0); + Z=tempeye(:,choosex4U); + W4BU4Z=W4BU4*Z; + CU4Z=CU4*Z+D*X*W4BU4Z; + ZTW4BU4Z=Z'*W4BU4*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW4BU4Z',D)+kron(speye(size(Z,2)),G))\CU4Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW4BU4Z',(-G\D)',(-G\CU4Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW4BU4Z'),full((G\D)'),full((-G\CU4Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW4BU4Z+CU4Z); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex4U)=full(Xtemp); clear Xtemp ZTW4BU4Z + %Block 4:ssss + choosex4=kron(kron(sps,sps),kron(sps,sps)); + choosex4U=logical(U4'*choosex4~=0); + Z=tempeye(:,choosex4U); + W4BU4Z=W4BU4*Z; + CU4Z=CU4*Z+D*X*W4BU4Z; + ZTW4BU4Z=Z'*W4BU4*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW4BU4Z',D)+kron(speye(size(Z,2)),G))\CU4Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW4BU4Z',(-G\D)',(-G\CU4Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW4BU4Z'),full((G\D)'),full((-G\CU4Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW4BU4Z+CU4Z); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex4U)=full(Xtemp); clear Xtemp ZTW4BU4Z + X=X*W4; + end + + gxxxx=X(1:n_y,:); + hxxxx=[X(n_y+1:end,:);nPhixxxx;zeros(1,n_x^4)]; +end + + + +clear derivs +derivs.gx=full(gx); +derivs.hx=full(hx(1:end-1,:)); +derivs.gxx=sparse(n_y,n_x^2); +derivs.hxx=sparse(n_x-1,n_x^2); +derivs.gxxx=sparse(n_y,n_x^3); +derivs.hxxx=sparse(n_x-1,n_x^3); + +if approx>=2 + derivs.gxx=reshape(full(gxx),n_y,n_x,n_x); + derivs.hxx=reshape(full(hxx(1:end-1,:)),n_x-1,n_x,n_x); +end +if approx>=3 + derivs.gxxx=reshape(full(gxxx),n_y,n_x,n_x,n_x); + derivs.hxxx=reshape(full(hxxx(1:end-1,:)),n_x-1,n_x,n_x,n_x); +end +if approx>=4 + derivs.gxxxx=reshape(full(gxxxx),n_y,n_x,n_x,n_x,n_x); + derivs.hxxxx=reshape(full(hxxxx(1:end-1,:)),n_x-1,n_x,n_x,n_x,n_x); +end + +[ stoch_pert, nonstoch_pert ] = get_initial( model,model.order(1),derivs,nyss,nxss ); + +stoch_pert=repmat(stoch_pert(:),1,model.n_regimes); % construct a matrix with n_regimes columns for the initial guess. +nonstoch_pert=repmat(nonstoch_pert(:),1,model.n_regimes); % construct a matrix with n_regimes columns for the initial guess. + + + + + + diff --git a/105/replication_package/solution_methods/taylor_projection/get_pertMS.m b/105/replication_package/solution_methods/taylor_projection/get_pertMS.m new file mode 100644 index 0000000000000000000000000000000000000000..f43568c3a658f1fd0e0589679f0ce3616787c5d4 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/get_pertMS.m @@ -0,0 +1,7 @@ +function [derivs,stoch_pert,nonstoch_pert,model]=get_pertMS(model,params,msparams_ss,M,nxss,nyss,algo) +%Get a standard perturbation solution for fixed parameters. + +[derivs,stoch_pert,nonstoch_pert,model]=get_pert(model,[params(:);msparams_ss(:);msparams_ss(:)],M,nxss,nyss,algo); + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/get_perti.m b/105/replication_package/solution_methods/taylor_projection/get_perti.m new file mode 100644 index 0000000000000000000000000000000000000000..0eced85c3fdbe1c8b06c44374192a03d2495d9aa --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/get_perti.m @@ -0,0 +1,776 @@ +function [derivs,stoch_pert,nonstoch_pert,model]=get_perti(model,params,paramsi,M,nxss,nyss,algo,varargin) +%get_pert(model,params,M,eta,nxss,nyss,algo) +%This function solves the model with perturbation up to fourth +%order. +%Input variables: +%model: a structure that is generated automatically by the function +%prepare_model.m +%params: a vector of all parameter values ordered in the same order of symparams. +%M: a structure that contains all the cross moments of the shocks. The fields of +%this structure should be M2,M3,M4. +%eta: The matrix eta as defined in Schmitt-Grohe and Uribe (2004). +%nxss,nyss: steady state values of x and y +%algo: algorithm type. 'dlyap' for dlyap or 'vectorize' for vectorization. +% +% � Copyright, Oren Levintal, June 13, 2016. + +if isempty(M) + M=gaussian_moments(1); +end + +if size(paramsi,1)~=model.n_paramsi + error('wrong size of varying parameters') +end + +n_s=size(paramsi,2); + +params=[repmat(params(:)',n_s,1),paramsi']; + + +if nargin==8 + msparams_ss=varargin{1}; + params=[params,repmar([msparams_ss(:);msparams_ss(:)]',n_s,1)]; +end + +if strcmpi(algo,'gensylv') + kamenik_type=2; + algo='Kamenik'; +elseif ~strcmpi(algo,'dlyap') && ~strcmpi(algo,'vectorize') + error('wrong algorithm') +end + +approx=model.order(2); + +if approx>4 + error('perturbation order cannot exceed 4') +end + +params=[params,zeros(n_s,model.n_logicalparams)]; + +if model.hybrid==0 + error('model must be hybrid') +% eta=eta_fun(params(:)',[]); +% eta=reshape(full(eta),model.n_x,[]); +else + params=[zeros(n_s,model.n_e),params]; + nv=[zeros(model.n_y,1);nyss(:);nxss(:);nxss(:)]'; % variables of tp + nv=repmat(nv,n_s,1); + n_u=model.n_u; + nu=zeros(n_s,n_u); + npreu=preu_fun(nv(:,model.preuvars),params); % all predetermined u + nu(:,model.preurows)=npreu; + nz=[nv,nu]; + uname=['new_eta' model.uname '_fun']; + tempvars=nz(:,model.Phizvars); %n_s,n_x+n_y +% tempvars=reshape(repmat(tempvars(:)',n_nodes,1),n_nodes*n_s,[]); %n_s*n_nodes,n_x+n_y+n_preurows +% tempvars=reshape(repmat(tempvars(:)',n_nodes,1),n_nodes*n_s,[]); %n_s*n_nodes,n_x+n_y+n_preurows + eta=feval(uname,tempvars,params); %n_s*n_nodes,n_x2 + eta=reshape(full(eta(1,:)),model.n_x,[]); + warning('I assume that law of motion of state variables is independent of varying parameters; otherwise, Blanchard-Khan method not applicable.'); +end + +tic +n_f=model.n_f; + +n_y=model.n_y; +n_x2=model.n_x2; +n_x1=model.n_x1; +n_z=model.n_z; % no. of auxiliary variables + +% note that pert system has one more state variable than tp system. +n_x_tp=model.n_x; +n_v_tp=model.n_v; +n_x=model.n_x+1; +n_v=model.n_v+2; + +if isfield(model,'UW') + UW=model.UW; % IMPORTANT: THESE COMPRESSION MATRICES ASSUME A CERTAIN NONZERO PATTERN. +else + UW=create_compression_matrices_nonzero2(approx,n_x); % compression matrices for the perturbation solution. + model.UW=UW; +end + +if approx==2 + W2=UW.W2; U2=UW.U2; +elseif approx==3 + W2=UW.W2; U2=UW.U2; + W3=UW.W3; U3=UW.U3; +elseif approx==4 + W2=UW.W2; U2=UW.U2; + W3=UW.W3; U3=UW.U3; + W4=UW.W4; U4=UW.U4; +end + +if isfield(model,'OMEGA_x') + OMEGA_x=model.OMEGA_x; +else + create_OMEGA_x; + model.OMEGA_x=OMEGA_x; +end + + +n_e=size(eta,2); +eta=[eta;zeros(1,n_e)]; + +nx=nxss; +% nxss=[nxss(:);0]; % add steady state value of the perturbation variable. +nxss=nxss(:); +nyss=nyss(:); +% nuss=eval_u([nyss;nyss;nxss;nxss],params); +if ~isfield(model,'n_ind') + n_ind=1; +else + n_ind=model.n_ind; +end +if ~isfield(model,'maxload') + maxload=intarray(1); +else + maxload=intarray(model.maxload); +end +if ~isfield(model,'pertind') + model.pertind=cell(model.totindi,1); +end +pertindi=1; + +% nPhi=Phi_fun(nx,params); +if model.hybrid==0 + get_Phi_derivs; +end + + +if isfield(model,'fname') + get_f_derivs_fname; +else + get_f_derivs; +end + +if model.hybrid==1 || model.hybrid==3 + order=approx-1; + params_vec=params; + get_hybridPhi_derivs_v; + order=approx; + + n_f_all=n_y+n_x1+n_x2; + convert_to_matrices_i; + n_f=n_f_all; + fv(n_y+n_x1+(1:n_x2),2*n_y+n_x1+(1:n_x2))=-eye(n_x2); + if approx>=1 + nPhix=zeros(0,n_x); + end + if approx>=2 + nPhixx=zeros(0,n_x^2); + end + if approx>=3 + nPhixxx=zeros(0,n_x^3); + end + if approx>=4 + nPhixxxx=zeros(0,n_x^4); + end + n_x2=0; + n_x1=n_x1+n_x2; +end +% numu_derivs=evalu_derivs(params,nxss,nyss,approx); +% call_evalf_derivs; +% +% sym2script_fv; + + + + +%%%%%%%%%%%%% +fyp=fv(:,1:n_y); fy=fv(:,n_y+1:2*n_y); fxp=fv(:,2*n_y+1:2*n_y+n_x); fx=fv(:,2*n_y+n_x+1:end); + +% First Order + +% use the function gx_hx of Schmitt-Grohe and Uribe (2004) to solve the +% first order solution + +% tic +[gx,hx,exitflag]=gx_hx(full([fy;zeros(n_x2,n_y)]),full([fx(:,1:end-1);nPhix(:,1:end-1)]),full([fyp;zeros(n_x2,n_y)]),full([fxp(:,1:end-1);[zeros(n_x2,n_x1),-eye(n_x2)]])); + +gx=[gx,zeros(n_y,1)]; +hx=[hx;zeros(1,n_x-1)]; +hx=[hx,zeros(n_x,1)]; +hx(end,end)=1; +% replace relevant rows of hx with nPhix which is more numerically accurate +hx(n_x1+1:n_x1+n_x2,:)=nPhix; + +% disp(['1st order completed in ' num2str(toc,'%15.2f') ' seconds']) + +hx=sparse(hx); +gx=sparse(gx); + +% Second Order +if approx>=2 +% tic + M2=M.M2; + eta2_M2=reshape([eta*reshape(M2,n_e,n_e)]',n_e,n_x); + eta2_M2=reshape([eta*eta2_M2]',n_x^2,1); + +% sym2script_fvv; + + unique=nchoosek(n_x+2-1,2); + unique=unique-nchoosek(n_x-1+1-1,1); + + Vx0=[gx*hx;gx;hx;speye(n_x)]; + Vx1=[gx;sparse(n_y,n_x);speye(n_x,n_x);sparse(n_x,n_x)]; + + Ezeta2=[ sparse(n_x^2,n_x^2-1) , eta2_M2 ]; + + A=innerkron(n_f,n_v,fvv,Vx0,Vx0)+innerkron(n_f,n_v,fvv,Vx1,Vx1)*Ezeta2; + + fy_fxp_fypgx=[fv(:,n_y+1:2*n_y) fv(:,2*n_y+1:2*n_y+n_x)+fv(:,1:n_y)*gx]; + + G=fy_fxp_fypgx(:,1:n_f); + H=fy_fxp_fypgx(:,n_f+1:n_f+n_x2); + + D=sparse(n_f,n_f); + D(:,1:n_y)=fv(:,1:n_y); + + + if strcmp(algo,'Kamenik') + if n_x2==0 + C=A; + else % do not solve exogenous state variables (see appendix A.6 in the paper). H is the last block of G. + C=A+H*(nPhixx); + end + %Block 1: xx + spx=sparse([ones(n_x-1,1);0]); + choosex2=kron(spx,spx); + choosex2=logical(choosex2==1); + tempeye=speye(n_x^2); + Z=tempeye(:,choosex2); + CZ=C*Z; + hx_hat=hx(1:end-1,1:end-1); + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-CZ,2 ); + time=toc; + else + G=full(G); + D=full(D); + hx_hat=full(hx_hat); + tic + [~,Xtemp]=gensylv( 2,G,D,hx_hat,full(-CZ) ); + time=toc; + end + acc=norm(full(CZ+AkronkC(D*Xtemp,hx_hat,2)+G*Xtemp)); + if acc>1e-8 + warning(['Second order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X=zeros(n_f,n_x^2); + X(:,choosex2)=full(Xtemp); + gxx_hat=Xtemp(1:n_y,:); + hat_eta2_M2=eta2_M2(choosex2,:); + %Block 2: ss + sps=sparse([zeros(n_x-1,1);1]); + choosex2=kron(sps,sps); + choosex2=logical(choosex2==1); + Z=tempeye(:,choosex2); + CZ=C*Z; + tic + Xtemp=-(D+G)\(CZ+(fyp*gxx_hat)*hat_eta2_M2); + time=toc; + + acc=norm(full(CZ+(fyp*gxx_hat)*hat_eta2_M2+(D+G)*Xtemp)); + if acc>1e-8 + warning(['Second order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex2)=full(Xtemp); clear Xtemp + else + if n_x2==0 + CU2=A*U2; + else % do not solve exogenous state variables (see appendix A.6 in the paper). H is the last block of G. + CU2=A*U2+H*(nPhixx*U2); + end + W2BU2=(innerkron(unique,n_x,W2,hx,hx)+W2*Ezeta2)*U2; + %Block 1: xx + spx=sparse([ones(n_x-1,1);0]); + choosex2=kron(spx,spx); + choosex2U=logical(U2'*choosex2==1); + tempeye=speye(size(U2,2)); + Z=tempeye(:,choosex2U); + CU2Z=CU2*Z; + ZTW2BU2Z=Z'*W2BU2*Z; + if strcmpi(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW2BU2Z',D)+kron(speye(size(Z,2)),G))\CU2Z(:),n_f,size(Z,2)); + elseif strcmpi(algo,'dlyap') + Xtemp=dlyap(ZTW2BU2Z',(-G\D)',(-G\CU2Z)'); + Xtemp=Xtemp'; + elseif strcmpi(algo,'slicot') + Xtemp=HessSchur(full(ZTW2BU2Z'),full((G\D)'),full((-G\CU2Z)')); + Xtemp=Xtemp'; + end + acc=norm(full(G*Xtemp+D*Xtemp*ZTW2BU2Z+CU2Z)); + if acc>1e-8 + warning(['Second order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X=zeros(n_f,size(U2,2)); + X(:,choosex2U)=full(Xtemp); clear Xtemp ZTW2BU2Z + %Block 2 + sps=sparse([zeros(n_x-1,1);1]); + choosex2=kron(sps,sps); + choosex2U=logical(U2'*choosex2==1); + tempeye=speye(size(U2,2)); + Z=tempeye(:,choosex2U); + W2BU2Z=W2BU2*Z; + CU2Z=CU2*Z+D*X*W2BU2Z; + ZTW2BU2Z=Z'*W2BU2*Z; + if strcmpi(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW2BU2Z',D)+kron(speye(size(Z,2)),G))\CU2Z(:),n_f,size(Z,2)); + elseif strcmpi(algo,'dlyap') + Xtemp=dlyap(ZTW2BU2Z',(-G\D)',(-G\CU2Z)'); + Xtemp=Xtemp'; + elseif strcmpi(algo,'slicot') + Xtemp=HessSchur(full(ZTW2BU2Z'),full((G\D)'),full((-G\CU2Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW2BU2Z+CU2Z); + if acc>1e-8 + warning(['Second order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex2U)=full(Xtemp); clear Xtemp W2BU2Z ZTW2BU2Z + X=X*W2; + end + gxx=X(1:n_y,:); + hxx=[X(n_y+1:end,:);nPhixx;zeros(1,n_x^2)]; +end + +% Third Order +if approx>=3 + Vxx0=[chain2(gx,gxx,hx,hxx);gxx;hxx;sparse(n_x,n_x^2)]; + Vxx1=[gxx;sparse(n_y+2*n_x,n_x^2)]; + + M3=M.M3(:); + + eta3_M3=reshape([eta*reshape(M3,n_e,n_e^2)]',n_e,n_e*n_x); + eta3_M3=reshape([eta*eta3_M3]',n_e,n_x^2); + eta3_M3=reshape([eta*eta3_M3]',n_x^3,1); + + Ezeta3=[ sparse(n_x^3,n_x^3-1) , eta3_M3 ]; + Ix=speye(n_x); + Ix_Ezeta2=kron(Ix,Ezeta2); + + unique=nchoosek(n_x+3-1,3); + unique=unique-nchoosek(n_x-1+2-1,2); + A_third_order; % create matrix A of a third order solution + + if strcmp(algo,'Kamenik') + if n_x2==0 + C=A; + else % do not solve exogenous state variables (see appendix A.6 in the paper). H is the last block of G. + C=A+H*(nPhixxx); + end + %Block 1:xxx + choosex3=kron(spx,kron(spx,spx)); + choosex3=logical(choosex3==1); + tempeye=speye(n_x^3); + Z=tempeye(:,choosex3); + CZ=C*Z; + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-CZ,3 ); + time=toc; + else + tic + [~,Xtemp]=gensylv( 3,G,D,hx_hat,full(-CZ)); + time=toc; + end + acc=norm(full(CZ+AkronkC(D*Xtemp,hx_hat,3)+G*Xtemp)); + if acc>1e-8 + warning(['Third order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X=zeros(n_f,n_x^3); + X(:,choosex3)=full(Xtemp); + gxxx_hat=Xtemp(1:n_y,:); + hat_eta3_M3=eta3_M3(choosex3,:); + %Block 2:xss + choosex3=kron(kron(sps,sps),spx); + choosex3=logical(choosex3==1); + Z=tempeye(:,choosex3); + CZ=C*Z; + term2=reshape(fyp*gxxx_hat,n_f*(n_x-1),(n_x-1)^2)*hat_eta2_M2; + term2=reshape(term2',n_f,n_x-1)*hx_hat; + cons=CZ+term2; + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-cons,1 ); + time=toc; + else + tic + [~,Xtemp]=gensylv( 1,G,D,hx_hat,full(-cons)); + time=toc; + end + acc=norm(full(cons+AkronkC(D*Xtemp,hx_hat,1)+G*Xtemp)); + if acc>1e-8 + warning(['Third order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex3)=full(Xtemp); clear Xtemp + %Block 2:sss + choosex3=kron(kron(sps,sps),sps); + choosex3=logical(choosex3==1); + Z=tempeye(:,choosex3); + CZ=C*Z; + term2=(fyp*gxxx_hat)*hat_eta3_M3; + cons=CZ+term2; + tic + Xtemp=-(D+G)\cons; + time=toc; + + acc=norm(full(cons+(D+G)*Xtemp)); + if acc>1e-8 + warning(['Third order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex3)=full(Xtemp); clear Xtemp + % add symmetric entries, but first permute the indices, because the + % compression matrices assume i1>=i2>=i3, while block xss has + % i11e-8 + warning(['Third order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X=zeros(n_f,size(U3,2)); + X(:,choosex3U)=full(Xtemp); clear Xtemp ZTW3BU3Z + %Block 2:xss + choosex3=kron(kron(sps,sps),spx); + choosex3=choosex3+kron(kron(sps,spx),sps); + choosex3=choosex3+kron(kron(spx,sps),sps); + choosex3U=logical(U3'*choosex3~=0); + Z=tempeye(:,choosex3U); + W3BU3Z=W3BU3*Z; + CU3Z=CU3*Z+D*X*W3BU3Z; + ZTW3BU3Z=Z'*W3BU3*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW3BU3Z',D)+kron(speye(size(Z,2)),G))\CU3Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW3BU3Z',(-G\D)',(-G\CU3Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW3BU3Z'),full((G\D)'),full((-G\CU3Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW3BU3Z+CU3Z); + if acc>1e-8 + warning(['Third order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex3U)=full(Xtemp); clear Xtemp ZTW3BU3Z + %Block 3:sss + choosex3=kron(kron(sps,sps),sps); + choosex3U=logical(U3'*choosex3~=0); + Z=tempeye(:,choosex3U); + W3BU3Z=W3BU3*Z; + CU3Z=CU3*Z+D*X*W3BU3Z; + ZTW3BU3Z=Z'*W3BU3*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW3BU3Z',D)+kron(speye(size(Z,2)),G))\CU3Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW3BU3Z',(-G\D)',(-G\CU3Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW3BU3Z'),full((G\D)'),full((-G\CU3Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW3BU3Z+CU3Z); + if acc>1e-8 + warning(['Third order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex3U)=full(Xtemp); clear Xtemp ZTW3BU3Z W3BU3 + X=X*W3; + end + + gxxx=X(1:n_y,:); + hxxx=[X(n_y+1:end,:);nPhixxx;zeros(1,n_x^3)]; +end + +% Fourth Order +if approx>=4 + Vxxx0=[chain3(gx,gxx,gxxx,hx,hxx,hxxx,OMEGA_x.OMEGA1);gxxx;hxxx;sparse(n_x,n_x^3)]; + Vxxx1=[gxxx;sparse(n_y+2*n_x,n_x^3)]; + + M4=M.M4(:); + + eta4_M4=reshape([eta*reshape(M4,n_e,n_e^3)]',n_e,n_e^2*n_x); + eta4_M4=reshape([eta*eta4_M4]',n_e,n_e*n_x^2); + eta4_M4=reshape([eta*eta4_M4]',n_e,n_x^3); + eta4_M4=reshape([eta*eta4_M4]',n_x^4,1); + + Ezeta4=[ sparse(n_x^4,n_x^4-1) , eta4_M4 ]; + Ix_Ezeta3=kron(Ix,Ezeta3); + Ix2=speye(n_x^2); + Ix2_Ezeta2=kron(Ix2,Ezeta2); + + hx2=kron(hx,hx); + hx_Ezeta2_hx=kron(kron(hx,Ezeta2),hx); + hx_Ezeta3=kron(hx,Ezeta3); + hx2_Ezeta2=kron(hx2,Ezeta2); + + unique=nchoosek(n_x+4-1,4); + unique=unique-nchoosek(n_x-1+3-1,3); + + clear result R + + A_fourth_order; % create matrix A of a fourth order solution + + if strcmp(algo,'Kamenik') + if n_x2==0 + C=A; + else % do not solve exogenous state variables (see appendix A.6 in the paper). H is the last block of G. + C=A+H*(nPhixxxx); + end + %Block 1:xxxx + choosex4=kron(kron(spx,spx),kron(spx,spx)); + choosex4=logical(choosex4==1); + tempeye=speye(n_x^4); + Z=tempeye(:,choosex4); + CZ=C*Z; + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-CZ,4 ); + time=toc; + else + tic + [~,Xtemp]=gensylv( 4,G,D,hx_hat,full(-CZ)); + time=toc; + end + acc=norm(full(CZ+AkronkC(D*Xtemp,hx_hat,4)+G*Xtemp)); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X=zeros(n_f,n_x^4); + X(:,choosex4)=full(Xtemp); + gxxxx_hat=Xtemp(1:n_y,:); + hat_eta4_M4=eta4_M4(choosex4,:); + %Block 2:xxss + choosex4=kron(kron(sps,sps),kron(spx,spx)); + choosex4=logical(choosex4==1); + Z=tempeye(:,choosex4); + CZ=C*Z; + term2=reshape(fyp*gxxxx_hat,n_f*(n_x-1)^2,(n_x-1)^2)*hat_eta2_M2; + term2=reshape(term2',n_f*(n_x-1),(n_x-1))*hx_hat; + term2=reshape(term2',(n_x-1)*n_f,(n_x-1))*hx_hat; + term2=reshape(term2',(n_x-1)^2,n_f); + term2=term2'; + cons=CZ+term2; + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-cons,2 ); + time=toc; + else + tic + [~,Xtemp]=gensylv( 2,G,D,hx_hat,full(-cons)); + time=toc; + end + + acc=norm(full(cons+AkronkC(D*Xtemp,hx_hat,2)+G*Xtemp)); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex4)=full(Xtemp); + gxxss_hat=Xtemp(1:n_y,:); + %Block 2:xsss + choosex4=kron(kron(sps,sps),kron(sps,spx)); + choosex4=logical(choosex4==1); + Z=tempeye(:,choosex4); + CZ=C*Z; + term2=reshape(fyp*gxxxx_hat,n_f*(n_x-1),(n_x-1)^3)*hat_eta3_M3; + term2=reshape(term2',n_f,(n_x-1))*hx_hat; + cons=CZ+term2; + if kamenik_type==1 + tic + Xtemp=kamenik( G,D,hx_hat,-cons,1 ); + time=toc; + else + tic + [~,Xtemp]=gensylv( 1,G,D,hx_hat,full(-cons)); + time=toc; + end + acc=norm(full(cons+AkronkC(D*Xtemp,hx_hat,1)+G*Xtemp)); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex4)=full(Xtemp); + %Block 2:ssss + choosex4=kron(kron(sps,sps),kron(sps,sps)); + choosex4=logical(choosex4==1); + Z=tempeye(:,choosex4); + CZ=C*Z; + term2=(6*fyp*gxxss_hat)*hat_eta2_M2; + term3=(fyp*gxxxx_hat)*hat_eta4_M4; + cons=CZ+term2+term3; + tic + Xtemp=-(D+G)\cons; + time=toc; + acc=norm(full(cons+(D+G)*Xtemp)); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + Xtemp=reshape(Xtemp,n_f,size(Z,2)); + X(:,choosex4)=full(Xtemp); clear Xtemp + % add symmetric entries, but first permute the indices. + X=reshape(permute(reshape(X,[],n_x,n_x,n_x,n_x),[1,5,4,3,2]),[],n_x^4)*U4*W4; + else + if n_x2==0 + CU4=A*U4; + else + CU4=A*U4+H*(nPhixxxx*U4); + end + kron_hx_hx=kron(hx,hx); + WBU_fourth_order; % create the matrix W4BU4 + %Block 1:xxxx + choosex4=kron(kron(spx,spx),kron(spx,spx)); + choosex4U=logical(U4'*choosex4~=0); + tempeye=speye(size(U4,2)); + Z=tempeye(:,choosex4U); + CU4Z=CU4*Z; + ZTW4BU4Z=Z'*W4BU4*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW4BU4Z',D)+kron(speye(size(Z,2)),G))\CU4Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW4BU4Z',(-G\D)',(-G\CU4Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW4BU4Z'),full((G\D)'),full((-G\CU4Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW4BU4Z+CU4Z); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X=zeros(n_f,size(U4,2)); + X(:,choosex4U)=full(Xtemp); clear Xtemp ZTW4BU4Z + %Block 2:xxss + choosex4=kron(kron(sps,sps),kron(spx,spx)); + choosex4=choosex4+kron(kron(sps,spx),kron(sps,spx)); + choosex4=choosex4+kron(kron(sps,spx),kron(spx,sps)); + choosex4=choosex4+kron(kron(spx,sps),kron(sps,spx)); + choosex4=choosex4+kron(kron(spx,sps),kron(spx,sps)); + choosex4=choosex4+kron(kron(spx,spx),kron(sps,sps)); + choosex4U=logical(U4'*choosex4~=0); + Z=tempeye(:,choosex4U); + W4BU4Z=W4BU4*Z; + CU4Z=CU4*Z+D*X*W4BU4Z; + ZTW4BU4Z=Z'*W4BU4*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW4BU4Z',D)+kron(speye(size(Z,2)),G))\CU4Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW4BU4Z',(-G\D)',(-G\CU4Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW4BU4Z'),full((G\D)'),full((-G\CU4Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW4BU4Z+CU4Z); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex4U)=full(Xtemp); clear Xtemp ZTW4BU4Z + %Block 3:xsss + choosex4=kron(kron(sps,sps),kron(sps,spx)); + choosex4=choosex4+kron(kron(sps,sps),kron(spx,sps)); + choosex4=choosex4+kron(kron(sps,spx),kron(sps,sps)); + choosex4=choosex4+kron(kron(spx,sps),kron(sps,sps)); + choosex4U=logical(U4'*choosex4~=0); + Z=tempeye(:,choosex4U); + W4BU4Z=W4BU4*Z; + CU4Z=CU4*Z+D*X*W4BU4Z; + ZTW4BU4Z=Z'*W4BU4*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW4BU4Z',D)+kron(speye(size(Z,2)),G))\CU4Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW4BU4Z',(-G\D)',(-G\CU4Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW4BU4Z'),full((G\D)'),full((-G\CU4Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW4BU4Z+CU4Z); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex4U)=full(Xtemp); clear Xtemp ZTW4BU4Z + %Block 4:ssss + choosex4=kron(kron(sps,sps),kron(sps,sps)); + choosex4U=logical(U4'*choosex4~=0); + Z=tempeye(:,choosex4U); + W4BU4Z=W4BU4*Z; + CU4Z=CU4*Z+D*X*W4BU4Z; + ZTW4BU4Z=Z'*W4BU4*Z; + if strcmp(algo,'vectorize') + Xtemp=reshape(-(kron(ZTW4BU4Z',D)+kron(speye(size(Z,2)),G))\CU4Z(:),n_f,size(Z,2)); + elseif strcmp(algo,'dlyap') + Xtemp=dlyap(ZTW4BU4Z',(-G\D)',(-G\CU4Z)'); + Xtemp=Xtemp'; + elseif strcmp(algo,'slicot') + Xtemp=HessSchur(full(ZTW4BU4Z'),full((G\D)'),full((-G\CU4Z)')); + Xtemp=Xtemp'; + end + acc=norm(G*Xtemp+D*Xtemp*ZTW4BU4Z+CU4Z); + if acc>1e-8 + warning(['Fourth order derivatives may be inaccurate, norm(error)=' num2str(acc) '. Try a different solver.']) + end + X(:,choosex4U)=full(Xtemp); clear Xtemp ZTW4BU4Z + X=X*W4; + end + + gxxxx=X(1:n_y,:); + hxxxx=[X(n_y+1:end,:);nPhixxxx;zeros(1,n_x^4)]; +end + + + +clear derivs +derivs.gx=full(gx); +derivs.hx=full(hx(1:end-1,:)); +derivs.gxx=sparse(n_y,n_x^2); +derivs.hxx=sparse(n_x-1,n_x^2); +derivs.gxxx=sparse(n_y,n_x^3); +derivs.hxxx=sparse(n_x-1,n_x^3); + +if approx>=2 + derivs.gxx=reshape(full(gxx),n_y,n_x,n_x); + derivs.hxx=reshape(full(hxx(1:end-1,:)),n_x-1,n_x,n_x); +end +if approx>=3 + derivs.gxxx=reshape(full(gxxx),n_y,n_x,n_x,n_x); + derivs.hxxx=reshape(full(hxxx(1:end-1,:)),n_x-1,n_x,n_x,n_x); +end +if approx>=4 + derivs.gxxxx=reshape(full(gxxxx),n_y,n_x,n_x,n_x,n_x); + derivs.hxxxx=reshape(full(hxxxx(1:end-1,:)),n_x-1,n_x,n_x,n_x,n_x); +end + +[ stoch_pert, nonstoch_pert ] = get_initial( model,model.order(1),derivs,nyss,nxss ); + + + + + diff --git a/105/replication_package/solution_methods/taylor_projection/getderivs_c.m b/105/replication_package/solution_methods/taylor_projection/getderivs_c.m new file mode 100644 index 0000000000000000000000000000000000000000..43fc65fa12b9d5bb8107ad1fa4eb4ea56603f4ea --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/getderivs_c.m @@ -0,0 +1,102 @@ +function [index]=getderivs_c(f,v,order,symparams,fname) +%This function is like getderivs, but only unique nonzero derivatives are +%returned. +% +% � Copyright, Oren Levintal, June 13, 2016. +% Changed on July 31, 2016 by Oren Levintal: conversion of relevant indices +% to full indices was wrong for the case of only one nonzero derivative. + +if order<1 + error('order must be at least 1') +end + +f=f(:); +v=v(:); + +n_f=length(f); +n_v=length(v); + +uncomp=cell(n_f,order); +derivs=cell(n_f,order); +% differentiate rows of f separately w.r.t to relevant variables ONLY +relevant_v=logical(jacobian(f(:),v)~=0); +for frow=1:n_f +% disp(['Differentiating row no. ' num2str(frow) ' of ' fname ' ...']) + [derivs(frow,:),uncomp(frow,:)]=compderivs_u(f(frow),v(relevant_v(frow,:)),order); +end + +% transform uncompression matrices into indices, and create totalloc. +% totalloc(frow,k) stores the total number of nonzero unique k-order derivatives of f(frow). +index=[]; +totalloc=zeros(n_f,order); +for k=1:order + for frow=1:n_f + [index.loc{frow,k},index.nnz{frow,k}]=find(uncomp{frow,k}); + totalloc(frow,k)=length(index.loc{frow,k}); + if isempty(index.loc{frow,k}) + index.loc{frow,k}=0; + end + end +end + +% create matlab functions to calculate the derivatives +for k=1:order + fun_name=[fname '_d_c' num2str(k)]; + fid = fopen([fun_name '.m'], 'w'); + fprintf(fid,'%s\n', ['function derivs=' fun_name '(vars,params,index)']); + fprintf(fid,'%s\n', 'n_s=size(vars,1);'); + for i=1:length(v) + fprintf(fid,'%s\n', [char(v(i)) '=vars(:,' num2str(i) ');']); + end + for i=1:length(symparams) + fprintf(fid,'%s\n', [char(symparams(i)) '=params(:,' num2str(i) ');']); + end + fprintf(fid,'%s\n', ['full_rows=zeros(' num2str(sum(totalloc(:,k))) ',1);']); + fprintf(fid,'%s\n', ['full_cols=zeros(' num2str(sum(totalloc(:,k))) ',1);']); + fprintf(fid,'%s\n', ['full_vals=zeros(n_s,' num2str(sum(totalloc(:,k))) ');']); + fprintf(fid,'%s\n', ['svec=1:n_s;']); + for frow=1:n_f + if totalloc(frow,k)>0 + tempderiv=derivs{frow,k}; + fprintf(fid,'%s\n', ['compressed_deriv=zeros(n_s,' num2str(length(tempderiv)) ');']); + for i=1:length(tempderiv) + disp_fun_row('compressed_deriv',tempderiv(i),i,fid); + end + fprintf(fid,'%s\n', ['uncompressed_deriv=compressed_deriv(:,index.nnz{' num2str(frow) ',' num2str(k) '});']); + tempstart=sum(totalloc(1:frow-1,k)); + tempend=sum(totalloc(1:frow,k)); + fprintf(fid,'%s\n', ['full_vals(:,' num2str(tempstart+1) ':' num2str(tempend) ')=uncompressed_deriv;']); + + % transform columns to n-dimensions + tempcols='tempcol1'; + n_relevant_v=sum(relevant_v(frow,:)); + tempdim=num2str(n_relevant_v); + for tempk=2:k + tempcols=[tempcols ',tempcol' num2str(tempk)]; + tempdim=[tempdim ',' num2str(n_relevant_v)]; + end + eval(['[' tempcols ']=ind2sub([' tempdim '],index.loc{' num2str(frow) ',' num2str(k) '});']); + tempcols=eval(['[' tempcols ']']); + % each row of f was differentiated w.r.t relevant variables. + % now, translate dimensions to the full vector of variables. + tempv=1:n_v; + takev=tempv(relevant_v(frow,:)); + + tempcols=takev(tempcols); + if k==1 + tempcols=tempcols(:); + end + + % find location in compressed matrix + uniqueind=uniquecols2ind(tempcols,n_v); + % return to index + index.loc{frow,k}=uniqueind; + fprintf(fid,'%s\n', ['full_cols(' num2str(tempstart+1) ':' num2str(tempend) ',:)=index.loc{' num2str(frow) ',' num2str(k) '};']); + fprintf(fid,'%s\n', ['full_rows(' num2str(tempstart+1) ':' num2str(tempend) ')=' num2str(frow) ';']); + end + end + fprintf(fid,'%s\n', ['derivs=sptensor(full_rows,full_cols,full_vals,' num2str(n_f) ',' num2str(nchoosek(n_v+k-1,k)) ');']); + fclose(fid); +end + + diff --git a/105/replication_package/solution_methods/taylor_projection/getderivs_tensor.m b/105/replication_package/solution_methods/taylor_projection/getderivs_tensor.m new file mode 100644 index 0000000000000000000000000000000000000000..f07c64686021501c4a218c57483a70aa7f9d2996 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/getderivs_tensor.m @@ -0,0 +1,97 @@ +function [index]=getderivs_tensor(f,v,order,symparams,fname) +%This function differentiates f w.r.t v up to order, and generates +%vectorized functions that calculate these derivatives. The derivatives are +%stored in a sparse tensor of dimensions n_f,n_v,..,n_v, where n_f +%is the size of f and n_v is the size of v. +% +% � Copyright, Oren Levintal, June 13, 2016. + + +if order<1 + error('order must be at least 1') +end + +f=f(:); +v=v(:); + +n_f=length(f); +n_v=length(v); + +uncomp=cell(n_f,order); +derivs=cell(n_f,order); + +% differentiate rows of f separately w.r.t to relevant variables ONLY +relevant_v=logical(jacobian(f(:),v)~=0); +for frow=1:n_f + [derivs(frow,:),uncomp(frow,:)]=compderivs(f(frow),v(relevant_v(frow,:)),order); +end + +% transform uncompression matrices into indices, and create totalloc. +% totalloc(frow,k) stores the total number of nonzero k-order derivatives of f(frow), including all (nonzero) mixed derivatives. +index=[]; +totalloc=zeros(n_f,order); +for k=1:order + for frow=1:n_f + [index.loc{frow,k},index.nnz{frow,k}]=find(uncomp{frow,k}); + totalloc(frow,k)=length(index.loc{frow,k}); + if isempty(index.loc{frow,k}) + index.loc{frow,k}=0; + end + end +end + +% create matlab functions to calculate the derivatives +for k=1:order + fun_name=[fname '_d' num2str(k)]; + fid = fopen([fun_name '.m'], 'w'); + fprintf(fid,'%s\n', ['function derivs=' fun_name '(vars,params,index)']); + fprintf(fid,'%s\n', 'n_s=size(vars,1);'); + for i=1:length(v) + fprintf(fid,'%s\n', [char(v(i)) '=vars(:,' num2str(i) ');']); + end + for i=1:length(symparams) + fprintf(fid,'%s\n', [char(symparams(i)) '=params(:,' num2str(i) ');']); + end + fprintf(fid,'%s\n', ['full_rows=zeros(' num2str(sum(totalloc(:,k))) ',1);']); + fprintf(fid,'%s\n', ['full_cols=zeros(' num2str(sum(totalloc(:,k))) ',' num2str(k) ');']); + fprintf(fid,'%s\n', ['full_vals=zeros(n_s,' num2str(sum(totalloc(:,k))) ');']); + + for frow=1:n_f + if totalloc(frow,k)>0 + tempderiv=derivs{frow,k}; + fprintf(fid,'%s\n', ['compressed_deriv=zeros(n_s,' num2str(length(tempderiv)) ');']); + for i=1:length(tempderiv) + disp_fun_row('compressed_deriv',tempderiv(i),i,fid); + end + fprintf(fid,'%s\n', ['uncompressed_deriv=compressed_deriv(:,index.nnz{' num2str(frow) ',' num2str(k) '});']); + tempstart=sum(totalloc(1:frow-1,k)); + tempend=sum(totalloc(1:frow,k)); + fprintf(fid,'%s\n', ['full_vals(:,' num2str(tempstart+1) ':' num2str(tempend) ')=uncompressed_deriv;']); + + % transform columns to n-dimensions + tempcols='tempcol1'; + n_relevant_v=sum(relevant_v(frow,:)); + tempdim=num2str(n_relevant_v); + for tempk=2:k + tempcols=[tempcols ',tempcol' num2str(tempk)]; + tempdim=[tempdim ',' num2str(n_relevant_v)]; + end + eval(['[' tempcols ']=ind2sub([' tempdim '],index.loc{' num2str(frow) ',' num2str(k) '});']); + tempcols=eval(['[' tempcols ']']); + % each row of f was differentiated w.r.t relevant variables. + % now, translate dimensions to the full vector of variables. + tempv=1:n_v; + takev=tempv(relevant_v(frow,:)); + tempcols=takev(tempcols); + % return to index + index.loc{frow,k}=tempcols; + fprintf(fid,'%s\n', ['full_cols(' num2str(tempstart+1) ':' num2str(tempend) ',:)=index.loc{' num2str(frow) ',' num2str(k) '};']); + + fprintf(fid,'%s\n', ['full_rows(' num2str(tempstart+1) ':' num2str(tempend) ')=' num2str(frow) ';']); + end + end + fprintf(fid,'%s\n', ['derivs=sptensor(full_rows,full_cols,full_vals,' num2str(n_f) ',repmat(' num2str(n_v) ',1,' num2str(k) '));']); + fclose(fid); +end + + diff --git a/105/replication_package/solution_methods/taylor_projection/make_residual.m b/105/replication_package/solution_methods/taylor_projection/make_residual.m new file mode 100644 index 0000000000000000000000000000000000000000..26830f78dfe9e35960346efc0aae75a9e38a039f --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/make_residual.m @@ -0,0 +1,370 @@ +function make_residual(f,Phi,yp,y,xp,x,symparams,eta,order,varargin) +% The function creates a Matlab file that computes the residual function. + +if nargin==9 + ufun=[]; + u=[]; + type='normal'; + logicalparams=[]; + logicalvars=[]; +elseif nargin==12 + ufun=varargin{1}; + u=varargin{2}; + uu0=varargin{3}; + type='normal'; + logicalparams=[]; + logicalvars=[]; +elseif nargin==13 + ufun=varargin{1}; + u=varargin{2}; + uu0=varargin{3}; + type=varargin{4}; + logicalparams=[]; + logicalvars=[]; +elseif nargin==14 + ufun=varargin{1}; + u=varargin{2}; + uu0=varargin{3}; + type='normal'; + logicalparams=varargin{4}; + logicalvars=varargin{5}; +elseif nargin==15 + ufun=varargin{1}; + u=varargin{2}; + uu0=varargin{3}; + type=varargin{4}; + logicalparams=varargin{5}; + logicalvars=varargin{6}; +else + error('wrong number of input arguments') +end + +% search for reserved names + +allnames=[yp(:);y(:);xp(:);x(:);symparams(:);u(:)]; +reserved_names={'coeffs','x','params','c0','nodes','weights','n_y','n_x1',... + 'n_f','X','n_b','endogenous_vars','y','expected_endogenous_states',... + 'expected_exogenous_states','h_fun','eta_matrix','Resid','i','xp','Xp','yp','f'}; + +reserved=''; + + +for i=1:length(reserved_names) + if nnz(logical(allnames==sym(reserved_names{i})))~=0 + reserved=[reserved, ' \n ', reserved_names{i}]; + end +end + +if ~isempty(reserved) + error_message=['The following names are reserved and should be changed:', reserved]; + error('ErrorTests:convertTest',error_message) +end + +% Lenght of vectors +n_f=length(f); n_x=length(x); n_y=length(y); n_x2=size(Phi,1); n_x1=n_x-n_x2; +n_e=size(eta,2); n_u=length(u); +% n_subs=find_n_new(ufun,u); + +n_subs=1; +if ~isempty(u) + uu=sparse(uu0); + while nnz(uu)>0 + n_subs=n_subs+1; + uu=uu*uu0; + end +end +order=order(1); +n_b=nchoosek(n_x+order,order); + +% make a basis function + +A=cell(1000+n_b+n_x,1); +l=1; + +A{l}='function X=make_basis(x,c0)'; l=l+1; + +A{l}='% The function computes the basis function at x'; l=l+1; + +A{l}=''; l=l+1; +A{l}='% compute x-c0'; l=l+1; + +x_c=sym(zeros(n_x,1)); +for i=1:n_x + A{l}=['x' num2str(i) '=x(' num2str(i) ')-c0(' num2str(i) ');']; l=l+1; + x_c(i)=sym(['x' num2str(i)]); +end + +A{l}=''; l=l+1; +A{l}='% create the basis function X'; l=l+1; + + +kronx=x_c; +symX=sym(1); +if order>=1 + symX=[sym(1);kronx]; +end +for i=2:order + kronx=kron(x_c,kronx); + [~,W]=create_UW(n_x,i); + symX=[symX;W*kronx]; +end + +A{l}=['X=zeros(' num2str(length(symX)) ',1);']; l=l+1; + +for i=1:length(symX) + A{l}=['X(' num2str(i) ')=' char(symX(i)) ';']; + l=l+1; +end + +% Write cell A into txt + +fid = fopen(['make_basis.m'], 'w'); +for i = 1:l-1 + fprintf(fid,'%s\n', A{i}); +end + +fclose(fid); + +%%%%%%%%%%%%%%%%%%%% + +if strcmp(type,'normal') + A=cell(1000+length(symparams)+2*n_x+2*n_y+n_subs*n_u+n_f,1); + l=1; + A{l}='function Resid=residual(coeffs,x,params,c0,nodes,weights)'; l=l+1; +elseif strcmp(type,'MS') + A=cell(1100+length(symparams)+2*n_x+2*n_y+n_subs*n_u+n_f,1); + l=1; + A{l}='function RMS=residual(coeffs,x,params,msparams,transition,c0,nodes,weights)'; l=l+1; + + A{l}='% The function computes the residual function of a model with Markov-switching parameters'; l=l+1; + + A{l}=''; l=l+1; + A{l}='n_regimes=size(transition,1);'; l=l+1; + A{l}=['n_f=' num2str(length(f)) ';']; l=l+1; + + A{l}=''; l=l+1; + A{l}='% compute residual function for all current regimes'; l=l+1; + A{l}='RMS=zeros(n_f,n_regimes);'; l=l+1; + + A{l}=''; l=l+1; + A{l}='for i=1:n_regimes'; l=l+1; + A{l}=' for j=1:n_regimes'; l=l+1; + A{l}=''; l=l+1; + A{l}=' % all model parameters given current regime i and future regime j'; l=l+1; + A{l}=' all_params=[params(:);msparams(:,i);msparams(:,j)];'; l=l+1; + + A{l}=''; l=l+1; + A{l}=' % model conditions given current regime i and future regime j'; l=l+1; + A{l}=' R=residual_sub(coeffs(:,i),coeffs(:,j),x,all_params,c0,nodes,weights);'; l=l+1; + A{l}=''; l=l+1; + A{l}=' % weight by transition probabilities'; l=l+1; + A{l}=' RMS(:,i)=RMS(:,i)+R*transition(i,j);'; l=l+1; + A{l}=' end'; l=l+1; + A{l}='end'; l=l+1; + A{l}=''; l=l+1; + A{l}='end'; l=l+1; + A{l}=''; l=l+1; + A{l}=''; l=l+1; + A{l}='function Resid=residual_sub(coeffs,coeffsp,x,params,c0,nodes,weights)'; l=l+1; +end + +A{l}=''; l=l+1; +A{l}='% parameters'; l=l+1; + +for i=1:length(symparams) + A{l}=[char(symparams(i)) '=params(' num2str(i) ');']; l=l+1; +end + +A{l}=''; l=l+1; +A{l}='% number of control variables'; l=l+1; +A{l}=['n_y=' num2str(n_y) ';']; l=l+1; + +A{l}=''; l=l+1; +A{l}='% number of endogenous state variables'; l=l+1; +A{l}=['n_x1=' num2str(n_x1) ';']; l=l+1; + +A{l}=''; l=l+1; +A{l}='% number of all endogenous variables (controls and states)'; l=l+1; +A{l}=['n_f=n_y+n_x1;']; l=l+1; + +A{l}=''; l=l+1; +A{l}='% state variables'; l=l+1; + +for i=1:n_x + A{l}=[char(x(i)) '=x(' num2str(i) ');'];l=l+1; +end + +A{l}=''; l=l+1; +A{l}='% basis function at the current state x'; l=l+1; + +A{l}='X=make_basis(x,c0);'; l=l+1; + +A{l}=''; l=l+1; +A{l}='% size of basis function'; l=l+1; + +A{l}='n_b=size(X,1);'; l=l+1; + + + +A{l}='coeffs=reshape(coeffs,n_f,n_b);'; l=l+1; + + +A{l}='endogenous_vars=coeffs*X;'; l=l+1; + +A{l}=''; l=l+1; +A{l}='% control variables y'; l=l+1; + +A{l}=['y=endogenous_vars(1:n_y);']; l=l+1; + +for i=1:n_y + A{l}=[char(y(i)) '=y(' num2str(i) ');'];l=l+1; +end + +A{l}=''; l=l+1; +A{l}='% expected value of future state variables'; l=l+1; + +A{l}=['expected_endogenous_states=endogenous_vars(n_y+1:end);']; l=l+1; + +A{l}=['expected_exogenous_states=zeros(' num2str(n_x2) ',1);']; l=l+1; + +for i=1:n_x2 + A{l}=['expected_exogenous_states(' num2str(i) ')=' char(Phi(i)) ';'];l=l+1; +end + +A{l}=['h_fun=[expected_endogenous_states;expected_exogenous_states];']; l=l+1; + +A{l}=''; l=l+1; +A{l}='% eta matrix'; l=l+1; + +A{l}=['eta_matrix=zeros(' num2str(n_x) ',' num2str(n_e) ');']; l=l+1; + +for i=1:n_x + for j=1:n_e + if eta(i,j)~=0 + A{l}=['eta_matrix(' num2str(i) ',' num2str(j) ')=' char(eta(i,j)) ';'];l=l+1; + end + end +end + + + +A{l}=''; l=l+1; +A{l}='% compute the residual function'; l=l+1; + +A{l}='Resid=zeros(n_f,1);'; l=l+1; + +A{l}=''; l=l+1; +A{l}='% use quadrature nodes and weights to approximate expectations'; l=l+1; + +A{l}='for i=1:length(weights)'; l=l+1; + +A{l}=''; l=l+1; +A{l}=' % future state variables for node i'; l=l+1; + +A{l}=' xp=h_fun+eta_matrix*nodes(:,i);'; l=l+1; + +for i=1:n_x + A{l}=[' ' char(xp(i)) '=xp(' num2str(i) ');'];l=l+1; +end + +A{l}=''; l=l+1; +A{l}=' % basis function at the future state xp'; l=l+1; + +A{l}=' Xp=make_basis(xp,c0);'; l=l+1; + +if strcmp(type,'normal') + A{l}=' yp=coeffs(1:n_y,:)*Xp;'; l=l+1; +elseif strcmp(type,'MS') + A{l}=' coeffsp=reshape(coeffsp,n_f,n_b);'; l=l+1; + A{l}=' yp=coeffsp(1:n_y,:)*Xp;'; l=l+1; +end + +for i=1:n_y + A{l}=[' ' char(yp(i)) '=yp(' num2str(i) ');'];l=l+1; +end + +if ~isempty(u) + A{l}=''; l=l+1; + A{l}=' % auxiliary variables'; l=l+1; + + % v=[yp(:);y(:);xp(:);x(:)]; + + + % subsu=ufun; + % newsubsu=subs(subsu,u,ufun); + % + % uind=1:n_u; + % while ~isequal(subsu,newsubsu) + % for i=uind(logical(newsubsu==subsu)) + % A{l}=[' ' char(u(i)) '=' char(ufun(i)) ';'];l=l+1; + % end + % uind=uind(logical(newsubsu~=subsu)); + % subsu=newsubsu(logical(newsubsu~=subsu)); + % newsubsu=subs(subsu,u,ufun); + % end + % for i=uind + % A{l}=[' ' char(u(i)) '=' char(ufun(i)) ';'];l=l+1; + % end + + % version 2 + + % if nargin~=8 +% uu0=double(logical(jacobian(ufun(:),u)~=0)); + % end + + + uu=uu0; + + n_u=length(u); + uind=1:n_u; + while nnz(uu)~=0 + for i=uind(logical(sum(uu,2)==0)) + A{l}=[' ' char(u(i)) '=' char(ufun(i)) ';'];l=l+1; + end + uind=uind(logical(sum(uu,2)~=0)); + uu=uu(logical(sum(uu,2)~=0),:); + uu=uu*uu0; + end + for i=uind + A{l}=[' ' char(u(i)) '=' char(ufun(i)) ';'];l=l+1; + end +end + +%%%%%%%%%% + +if ~isempty(logicalparams) + A{l}=''; l=l+1; + for i=1:length(logicalparams) + A{l}=[' ' char(logicalparams(i)) '=double(logical(' char(logicalvars(i)) '>=0));'];l=l+1; + end +end + +A{l}=''; l=l+1; +A{l}=[' % compute function f'];l=l+1; + +A{l}=[' f=zeros(n_f,1);'];l=l+1; +for i=1:n_f + A{l}=[' f(' num2str(i) ')=' char(f(i)) ';'];l=l+1; +end + +A{l}=''; l=l+1; +A{l}=[' % multiply by weight i and add to Resid'];l=l+1; + +A{l}=[' Resid=Resid+f*weights(i);'];l=l+1; + +A{l}='end'; l=l+1; +A{l}=''; l=l+1; +A{l}='end'; l=l+1; + + +% Write cell A into txt + +fid = fopen(['residual.m'], 'w'); +for i = 1:l-1 + fprintf(fid,'%s\n', A{i}); +end + +fclose(fid); + +rehash; + diff --git a/105/replication_package/solution_methods/taylor_projection/make_residual2.m b/105/replication_package/solution_methods/taylor_projection/make_residual2.m new file mode 100644 index 0000000000000000000000000000000000000000..2b6882836c854ef2c87bd7d28746fea6bfdeb730 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/make_residual2.m @@ -0,0 +1,377 @@ +function make_residual2(f,Phi,yp,y,xp,x,shocks,symparams,eta,order,varargin) +% The function creates a Matlab file that computes the residual function. + +nargs=1; + +if nargin==nargs+9 + ufun=[]; + u=[]; + type='normal'; + logicalparams=[]; + logicalvars=[]; +elseif nargin==nargs+12 + ufun=varargin{1}; + u=varargin{2}; + uu0=varargin{3}; + type='normal'; + logicalparams=[]; + logicalvars=[]; +elseif nargin==nargs+13 + ufun=varargin{1}; + u=varargin{2}; + uu0=varargin{3}; + type=varargin{4}; + logicalparams=[]; + logicalvars=[]; +elseif nargin==nargs+14 + ufun=varargin{1}; + u=varargin{2}; + uu0=varargin{3}; + type='normal'; + logicalparams=varargin{4}; + logicalvars=varargin{5}; +elseif nargin==nargs+15 + ufun=varargin{1}; + u=varargin{2}; + uu0=varargin{3}; + type=varargin{4}; + logicalparams=varargin{5}; + logicalvars=varargin{6}; +else + error('wrong number of input arguments') +end + +% search for reserved names + +allnames=[yp(:);y(:);xp(:);x(:);symparams(:);u(:);shocks(:)]; +reserved_names={'coeffs','x','params','c0','nodes','weights','n_y','n_x1',... + 'n_f','X','n_b','n_nodes','endogenous_vars','y','expected_endogenous_states',... + 'expected_exogenous_states','h_fun','eta_matrix','Resid','i','xp','Xp','yp','f'}; + +reserved=''; + + +for i=1:length(reserved_names) + if nnz(logical(allnames==sym(reserved_names{i})))~=0 + reserved=[reserved, ' \n ', reserved_names{i}]; + end +end + +if ~isempty(reserved) + error_message=['The following names are reserved and should be changed:', reserved]; + error('ErrorTests:convertTest',error_message) +end + +% Lenght of vectors +n_f=length(f); n_x=length(x); n_y=length(y); n_x2=size(Phi,1); n_x1=n_x-n_x2; +n_e=size(eta,2); n_u=length(u); +% n_subs=find_n_new(ufun,u); + +n_subs=1; +if ~isempty(u) + uu=sparse(uu0); + while nnz(uu)>0 + n_subs=n_subs+1; + uu=uu*uu0; + end +end +order=order(1); +n_b=nchoosek(n_x+order,order); + +% make a basis function + +A=cell(1000+n_b+n_x,1); +l=1; + +A{l}='function X=make_basis(x,c0)'; l=l+1; + +A{l}='% The function computes the basis function at x'; l=l+1; + +A{l}=''; l=l+1; +A{l}='% compute x-c0'; l=l+1; + +x_c=sym(zeros(n_x,1)); +for i=1:n_x + A{l}=['x' num2str(i) '=x(' num2str(i) ')-c0(' num2str(i) ');']; l=l+1; + x_c(i)=sym(['x' num2str(i)]); +end + +A{l}=''; l=l+1; +A{l}='% create the basis function X'; l=l+1; + + +kronx=x_c; +symX=sym(1); +if order>=1 + symX=[sym(1);kronx]; +end +for i=2:order + kronx=kron(x_c,kronx); + [~,W]=create_UW(n_x,i); + symX=[symX;W*kronx]; +end + +A{l}=['X=zeros(' num2str(length(symX)) ',1);']; l=l+1; + +for i=1:length(symX) + A{l}=['X(' num2str(i) ')=' char(symX(i)) ';']; + l=l+1; +end + +% Write cell A into txt + +fid = fopen(['make_basis.m'], 'w'); +for i = 1:l-1 + fprintf(fid,'%s\n', A{i}); +end + +fclose(fid); + +%%%%%%%%%%%%%%%%%%%% + +if strcmp(type,'normal') + A=cell(1000+length(symparams)+2*n_x+2*n_y+n_subs*n_u+n_f,1); + l=1; + A{l}='function [Resid,y,tilh_fun,Phi_fun]=residual(coeffs,x,params,c0,nodes,weights)'; l=l+1; +elseif strcmp(type,'MS') + A=cell(1100+length(symparams)+2*n_x+2*n_y+n_subs*n_u+n_f,1); + l=1; + A{l}='function [RMS,yMS,tilh_funMS,Phi_funMS]=residual(coeffs,x,params,msparams,transition,c0,nodes,weights)'; l=l+1; + + A{l}='% The function computes the residual function of a model with Markov-switching parameters'; l=l+1; + + A{l}=''; l=l+1; + A{l}='n_regimes=size(transition,1);'; l=l+1; + A{l}=['n_f=' num2str(length(f)) ';']; l=l+1; + A{l}=['n_y=' num2str(length(y)) ';']; l=l+1; + A{l}=['n_x1=' num2str(n_x1) ';']; l=l+1; + A{l}=['n_x2=' num2str(n_x2) ';']; l=l+1; + A{l}=['n_nodes=length(weights);']; l=l+1; + + A{l}=''; l=l+1; + A{l}='% compute residual function for all current regimes'; l=l+1; + A{l}='RMS=zeros(n_f,n_regimes);'; l=l+1; + A{l}='yMS=zeros(n_y,n_regimes);'; l=l+1; + A{l}='tilh_funMS=zeros(n_x1,n_regimes);'; l=l+1; + A{l}='Phi_funMS=zeros(n_x2,n_nodes,n_regimes,n_regimes);'; l=l+1; + + A{l}=''; l=l+1; + A{l}='for i=1:n_regimes'; l=l+1; + A{l}=' for j=1:n_regimes'; l=l+1; + A{l}=''; l=l+1; + A{l}=' % all model parameters given current regime i and future regime j'; l=l+1; + A{l}=' all_params=[params(:);msparams(:,i);msparams(:,j)];'; l=l+1; + + A{l}=''; l=l+1; + A{l}=' % model conditions given current regime i and future regime j'; l=l+1; + A{l}=' [R,y,tilh_fun,Phi_fun]=residual_sub(coeffs(:,i),coeffs(:,j),x,all_params,c0,nodes,weights);'; l=l+1; + A{l}=''; l=l+1; + A{l}=' % weight by transition probabilities'; l=l+1; + A{l}=' RMS(:,i)=RMS(:,i)+R*transition(i,j);'; l=l+1; + A{l}=' Phi_funMS(:,:,i,j)=Phi_fun;'; l=l+1; + A{l}=' end'; l=l+1; + A{l}=' yMS(:,i)=y;'; l=l+1; + A{l}=' tilh_funMS(:,i)=reshape(tilh_fun,n_x1,1);'; l=l+1; + + A{l}='end'; l=l+1; + A{l}=''; l=l+1; + A{l}='end'; l=l+1; + A{l}=''; l=l+1; + A{l}=''; l=l+1; + A{l}='function [Resid,y,tilh_fun,Phi_fun]=residual_sub(coeffs,coeffsp,x,params,c0,nodes,weights)'; l=l+1; +end + +A{l}=''; l=l+1; +A{l}='% parameters'; l=l+1; + +for i=1:length(symparams) + A{l}=[char(symparams(i)) '=params(' num2str(i) ');']; l=l+1; +end + +A{l}=''; l=l+1; +A{l}='% number of control variables'; l=l+1; +A{l}=['n_y=' num2str(n_y) ';']; l=l+1; + +A{l}=''; l=l+1; +A{l}='% number of endogenous state variables'; l=l+1; +A{l}=['n_x1=' num2str(n_x1) ';']; l=l+1; + +A{l}=''; l=l+1; +A{l}='% number of all endogenous variables (controls and states)'; l=l+1; +A{l}=['n_f=n_y+n_x1;']; l=l+1; + +A{l}=''; l=l+1; +A{l}='% state variables'; l=l+1; + +for i=1:n_x + A{l}=[char(x(i)) '=x(' num2str(i) ');'];l=l+1; +end + +A{l}=''; l=l+1; +A{l}='% basis function at the current state x'; l=l+1; + +A{l}='X=make_basis(x,c0);'; l=l+1; + +A{l}=''; l=l+1; +A{l}='% size of basis function'; l=l+1; + +A{l}='n_b=size(X,1);'; l=l+1; + + + +A{l}='coeffs=reshape(coeffs,n_f,n_b);'; l=l+1; + + +A{l}='endogenous_vars=coeffs*X;'; l=l+1; + +A{l}=''; l=l+1; +A{l}='% control variables y'; l=l+1; + +A{l}=['y=endogenous_vars(1:n_y);']; l=l+1; + +for i=1:n_y + A{l}=[char(y(i)) '=y(' num2str(i) ');'];l=l+1; +end + +A{l}=''; l=l+1; +A{l}='% future state variables'; l=l+1; + +if n_x1>0 + A{l}=['tilh_fun=endogenous_vars(n_y+1:end);']; l=l+1; +else + A{l}=['tilh_fun=zeros(0,1);']; l=l+1; +end + +A{l}=''; l=l+1; +A{l}=['n_nodes=length(weights);']; l=l+1; + +A{l}=''; l=l+1; +A{l}=['Phi_fun=zeros(' num2str(n_x2) ',n_nodes);']; l=l+1; + + + +% A{l}=['h_fun=[expected_endogenous_states;expected_exogenous_states];']; l=l+1; +% A{l}=['tilh_fun=future_endogenous_states;']; l=l+1; + +A{l}=''; l=l+1; +A{l}='% eta matrix'; l=l+1; + +A{l}=['eta_matrix=zeros(' num2str(n_x) ',' num2str(n_e) ');']; l=l+1; + +for i=1:n_x + for j=1:n_e + if eta(i,j)~=0 + A{l}=['eta_matrix(' num2str(i) ',' num2str(j) ')=' char(eta(i,j)) ';'];l=l+1; + end + end +end + + + +A{l}=''; l=l+1; +A{l}='% compute the residual function'; l=l+1; + +A{l}='Resid=zeros(n_f,1);'; l=l+1; + +A{l}=''; l=l+1; +A{l}='% use quadrature nodes and weights to approximate expectations'; l=l+1; + +A{l}='for i=1:length(weights)'; l=l+1; + +A{l}=''; l=l+1; +A{l}=' % future state variables for node i'; l=l+1; + +for j=1:length(shocks) + A{l}=[' ' char(shocks(j)) '=nodes(' num2str(j) ',i);'];l=l+1; +end + +A{l}=''; l=l+1; + +subsPhi=subsf(Phi,u,ufun); +for i=1:n_x2 + A{l}=[' Phi_fun(' num2str(i) ',i)=' char(subsPhi(i)) ';'];l=l+1; +end + +A{l}=' xp=[tilh_fun;Phi_fun(:,i)]+eta_matrix*nodes(:,i);'; l=l+1; + +for i=1:n_x + A{l}=[' ' char(xp(i)) '=xp(' num2str(i) ');'];l=l+1; +end + +A{l}=''; l=l+1; + +A{l}=''; l=l+1; +A{l}=' % basis function at the future state xp'; l=l+1; + +A{l}=' Xp=make_basis(xp,c0);'; l=l+1; + +if strcmp(type,'normal') + A{l}=' yp=coeffs(1:n_y,:)*Xp;'; l=l+1; +elseif strcmp(type,'MS') + A{l}=' coeffsp=reshape(coeffsp,n_f,n_b);'; l=l+1; + A{l}=' yp=coeffsp(1:n_y,:)*Xp;'; l=l+1; +end + +for i=1:n_y + A{l}=[' ' char(yp(i)) '=yp(' num2str(i) ');'];l=l+1; +end + +if ~isempty(u) + A{l}=''; l=l+1; + A{l}=' % auxiliary variables'; l=l+1; + + uu=uu0; + + n_u=length(u); + uind=1:n_u; + while nnz(uu)~=0 + for i=uind(logical(sum(uu,2)==0)) + A{l}=[' ' char(u(i)) '=' char(ufun(i)) ';'];l=l+1; + end + uind=uind(logical(sum(uu,2)~=0)); + uu=uu(logical(sum(uu,2)~=0),:); + uu=uu*uu0; + end + for i=uind + A{l}=[' ' char(u(i)) '=' char(ufun(i)) ';'];l=l+1; + end +end + +%%%%%%%%%% + +if ~isempty(logicalparams) + A{l}=''; l=l+1; + for i=1:length(logicalparams) + A{l}=[' ' char(logicalparams(i)) '=double(logical(' char(logicalvars(i)) '>=0));'];l=l+1; + end +end + +A{l}=''; l=l+1; +A{l}=[' % compute function f'];l=l+1; + +A{l}=[' f=zeros(n_f,1);'];l=l+1; +for i=1:n_f + A{l}=[' f(' num2str(i) ')=' char(f(i)) ';'];l=l+1; +end + +A{l}=''; l=l+1; +A{l}=[' % multiply by weight i and add to Resid'];l=l+1; + +A{l}=[' Resid=Resid+f*weights(i);'];l=l+1; + +A{l}='end'; l=l+1; +A{l}=''; l=l+1; +A{l}='end'; l=l+1; + + +% Write cell A into txt + +fid = fopen(['residual.m'], 'w'); +for i = 1:l-1 + fprintf(fid,'%s\n', A{i}); +end + +fclose(fid); + +rehash; + diff --git a/105/replication_package/solution_methods/taylor_projection/make_residual3.m b/105/replication_package/solution_methods/taylor_projection/make_residual3.m new file mode 100644 index 0000000000000000000000000000000000000000..0a3861de417406ed7a278c38ef46732cd8942d6a --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/make_residual3.m @@ -0,0 +1,565 @@ +function make_residual3(f,Phi,yp,y,xp,x,shocks,symparams,order,varargin) +% The function creates a Matlab file that computes the residual function. + +nargs=0; + +if nargin==nargs+9 + ufun=[]; + u=[]; + type='normal'; + logicalparams=[]; + logicalvars=[]; +elseif nargin==nargs+12 + ufun=varargin{1}; + u=varargin{2}; + model=varargin{3}; + type='normal'; + logicalparams=[]; + logicalvars=[]; +elseif nargin==nargs+13 + ufun=varargin{1}; + u=varargin{2}; + model=varargin{3}; + type=varargin{4}; + logicalparams=[]; + logicalvars=[]; +elseif nargin==nargs+14 + ufun=varargin{1}; + u=varargin{2}; + model=varargin{3}; + type='normal'; + logicalparams=varargin{4}; + logicalvars=varargin{5}; +elseif nargin==nargs+15 + ufun=varargin{1}; + u=varargin{2}; + model=varargin{3}; + type=varargin{4}; + logicalparams=varargin{5}; + logicalvars=varargin{6}; +else + error('wrong number of input arguments') +end + +uu0=model.piu0; +tilPhiu=model.tilPhiu*model.uu; % this is a matrix for all auxiliary variables that affect Phi (through all substitutions) + + + +% search for reserved names + +allnames=[yp(:);y(:);xp(:);x(:);symparams(:);u(:);shocks(:)]; +reserved_names={'coeffs','coeffsp','state','future_state','control','future_control','regime','future_regime','params','msparams','regimes','n_regimes',... + 'shock','center','nodes','n_nodes','weights','Basis','n_nodes','endogenous_vars','transition',... + 'R_fun','g_fun','Phi_fun','aux_fun','i','j','f_fun',... + 'R_funMS','g_funMS','Phi_funMS','aux_funMS'}; + +reserved=''; + + +for i=1:length(reserved_names) + if nnz(logical(allnames==sym(reserved_names{i})))~=0 + reserved=[reserved, ' \n ', reserved_names{i}]; + end +end + +if ~isempty(reserved) + error_message=['The following names are reserved and should be changed:', reserved]; + error('ErrorTests:convertTest',error_message) +end + +% Length of vectors +n_f=length(f); n_x=length(x); n_y=length(y); n_x2=size(Phi,1); n_x1=n_x-n_x2; +n_e=length(shocks); n_u=length(u); +% n_subs=find_n_new(ufun,u); + +n_subs=1; +if ~isempty(u) + uu=sparse(uu0); + while nnz(uu)>0 + n_subs=n_subs+1; + uu=uu*uu0; + end +end +order=order(1); +n_b=nchoosek(n_x+order,order); + +% make a basis function + +A=cell(1000+n_b+n_x,1); +l=1; + +A{l}='function X=make_basis(x,c0)'; l=l+1; + +A{l}='% The function computes the basis function at x'; l=l+1; + +A{l}=''; l=l+1; +A{l}='% compute x-c0'; l=l+1; + +x_c=sym(zeros(n_x,1)); +for i=1:n_x + A{l}=['x' num2str(i) '=x(' num2str(i) ')-c0(' num2str(i) ');']; l=l+1; + x_c(i)=sym(['x' num2str(i)]); +end + +A{l}=''; l=l+1; +A{l}='% create the basis function X'; l=l+1; + + +kronx=x_c; +symX=sym(1); +if order>=1 + symX=[sym(1);kronx]; +end +for i=2:order + kronx=kron(x_c,kronx); + [~,W]=create_UW(n_x,i); + symX=[symX;W*kronx]; +end + +A{l}=['X=zeros(' num2str(length(symX)) ',1);']; l=l+1; + +for i=1:length(symX) + A{l}=['X(' num2str(i) ')=' char(symX(i)) ';']; + l=l+1; +end + +% Write cell A into txt + +fid = fopen(['make_basis.m'], 'w'); +for i = 1:l-1 + fprintf(fid,'%s\n', A{i}); +end + +fclose(fid); + +%%%%%%%%%%%%%%%%%%%% + +if strcmp(type,'normal') + A=cell(1000+length(symparams)+2*n_x+2*n_y+n_subs*n_u+n_f,1); + l=1; + A{l}='function [R_fun,g_fun,Phi_fun,aux_fun]=residual(coeffs,state,params,center,nodes,weights)'; l=l+1; + A{l}='% The function computes the residual function for a model with iid shocks'; l=l+1; +elseif strcmp(type,'MS') + A=cell(1100+length(symparams)+2*n_x+2*n_y+n_subs*n_u+n_f,1); + l=1; + A{l}='function [R_funMS,g_funMS,Phi_funMS,aux_funMS]=residual(coeffs,state,params,msparams,transition,center,nodes,weights,varargin)'; l=l+1; + + A{l}='% The function computes the residual function for a model with iid shocks and Markov shocks'; l=l+1; + + A{l}=''; l=l+1; + + A{l}='if nargin==8'; l=l+1; + A{l}=[' regimes=1:' num2str(model.n_regimes) ';']; l=l+1; + A{l}='else'; l=l+1; + A{l}=[' regimes=varargin{1};']; l=l+1; + A{l}='end'; l=l+1; + A{l}='n_regimes=length(regimes);'; l=l+1; + A{l}=''; l=l+1; +% A{l}=['n_f=' num2str(length(f)) ';']; l=l+1; +% A{l}=['n_y=' num2str(length(y)) ';']; l=l+1; +% % A{l}=['n_x1=' num2str(n_x1) ';']; l=l+1; +% A{l}=['n_x=' num2str(n_x2) ';']; l=l+1; + A{l}=['n_nodes=length(weights);']; l=l+1; +% A{l}='n_regimes=size(transition,1);'; l=l+1; + + A{l}=''; l=l+1; + A{l}=['coeffs=reshape(coeffs,' num2str(model.n_y*model.n_b) ',' num2str(model.n_regimes) ');']; l=l+1; + A{l}=['msparams=reshape(msparams,' num2str(model.n_msparams) ',' num2str(model.n_regimes) ');']; l=l+1; + + A{l}=''; l=l+1; + A{l}='% preallocate variables'; l=l+1; + A{l}=['R_funMS=zeros(' num2str(model.n_f) ',n_regimes);']; l=l+1; + A{l}=['g_funMS=zeros(' num2str(model.n_y) ',n_regimes);']; l=l+1; +% A{l}='h_funMS=zeros(n_x1,n_regimes);'; l=l+1; + A{l}=['Phi_funMS=zeros(' num2str(model.n_x) ',n_nodes,n_regimes,' num2str(model.n_regimes) ');']; l=l+1; + A{l}=['aux_funMS=zeros(' num2str(n_u) ',n_nodes,n_regimes,' num2str(model.n_regimes) ');']; l=l+1; + + A{l}=''; l=l+1; + A{l}='loc=0;'; l=l+1; + A{l}=['for i=regimes']; l=l+1; + A{l}=[' loc=loc+1;']; l=l+1; + A{l}=[' for j=1:' num2str(model.n_regimes)]; l=l+1; + A{l}=''; l=l+1; + A{l}=' % all model parameters given current regime i and future regime j'; l=l+1; + A{l}=' all_params=[params(:);msparams(:,i);msparams(:,j)];'; l=l+1; + + A{l}=''; l=l+1; + A{l}=' % model conditions given current regime i and future regime j'; l=l+1; + A{l}=' [R_fun,g_fun,Phi_fun,aux_fun]=residual_sub(coeffs,state,i,j,all_params,center,nodes,weights);'; l=l+1; + A{l}=''; l=l+1; + A{l}=' % weight by transition probabilities'; l=l+1; + A{l}=' R_funMS(:,loc)=R_funMS(:,loc)+R_fun*transition(i,j);'; l=l+1; + A{l}=' Phi_funMS(:,:,loc,j)=Phi_fun;'; l=l+1; + A{l}=' aux_funMS(:,:,loc,j)=aux_fun;'; l=l+1; + A{l}=' end'; l=l+1; + A{l}=' g_funMS(:,loc)=g_fun;'; l=l+1; +% A{l}=' h_funMS(:,i)=reshape(h_fun,n_x1,1);'; l=l+1; + + A{l}='end'; l=l+1; + A{l}=''; l=l+1; + A{l}='end'; l=l+1; + A{l}=''; l=l+1; + A{l}=''; l=l+1; + A{l}='function [R_fun,g_fun,Phi_fun,aux_fun]=residual_sub(coeffs,state,regime,future_regime,params,center,nodes,weights)'; l=l+1; +end + +l1=l; +A{l}=''; l=l+1; +A{l}='% parameters'; l=l+1; + +for i=1:length(symparams) + A{l}=[char(symparams(i)) '=params(' num2str(i) ');']; l=l+1; +end +l2=l; + +% A{l}=''; l=l+1; +% A{l}='% number of control variables'; l=l+1; +% A{l}=['n_y=' num2str(n_y) ';']; l=l+1; + +% A{l}=''; l=l+1; +% A{l}='% number of predetermined state variables'; l=l+1; +% A{l}=['n_x1=' num2str(n_x1) ';']; l=l+1; +% +% A{l}=''; l=l+1; +% A{l}='% number of endogenous variables'; l=l+1; +% A{l}=['n_endog=n_y+n_x1;']; l=l+1; + +A{l}=''; l=l+1; +l3=l; + +A{l}='% state variables'; l=l+1; + +for i=1:n_x + A{l}=[char(x(i)) '=state(' num2str(i) ');'];l=l+1; +end +l4=l; + +% A{l}='% basis function at the current state'; l=l+1; +% +% A{l}='Basis=make_basis(state,c0);'; l=l+1; +% +% A{l}=''; l=l+1; +% A{l}='% size of basis function'; l=l+1; +% +% A{l}='n_b=size(Basis,1);'; l=l+1; + + +% A{l}=''; l=l+1; + +% A{l}=['coeffs=reshape(coeffs,' num2str(model.n_y) ',' num2str(model.n_b) ');']; l=l+1; +% if strcmp(type,'MS') +% A{l}='coeffsp=reshape(coeffsp,n_y,n_b);'; l=l+1; +% end + +% A{l}='endogenous_vars=coeffs*X;'; l=l+1; + +A{l}=''; l=l+1; +A{l}='% the function g(x)'; l=l+1; +if strcmp(type,'normal') + A{l}=['g_fun=evalg(state,coeffs,center);']; l=l+1; +else + A{l}=['g_fun=evalg(state,regime,coeffs,center);']; l=l+1; +end + +l5=l; +A{l}=''; l=l+1; +A{l}='% control variables'; l=l+1; + + +for i=1:n_y + A{l}=[char(y(i)) '=g_fun(' num2str(i) ');'];l=l+1; +end +l6=l; +%%%%% + + + +%%%%% + +A{l}=''; l=l+1; +A{l}=['if isempty(weights) || isempty(nodes)']; l=l+1; +A{l}=[' weights=1;']; l=l+1; +A{l}=[' nodes=0;']; l=l+1; +A{l}=['end']; l=l+1; + +A{l}=''; l=l+1; +A{l}=['n_nodes=length(weights);']; l=l+1; +% A{l}=['n_f=' num2str(length(f)) ';']; l=l+1; + + + +% A{l}=['h_fun=[expected_endogenous_states;expected_exogenous_states];']; l=l+1; +% A{l}=['h_fun=future_endogenous_states;']; l=l+1; + +A{l}=''; l=l+1; +A{l}='% preallocate variables'; l=l+1; +A{l}=['f_fun=zeros(' num2str(model.n_f) ',1);'];l=l+1; +A{l}=['R_fun=zeros(' num2str(model.n_f) ',1);']; l=l+1; +A{l}=['Phi_fun=zeros(' num2str(n_x2) ',n_nodes);']; l=l+1; +A{l}=['aux_fun=zeros(' num2str(n_u) ',n_nodes);']; l=l+1; + + +A{l}=''; l=l+1; +A{l}='% approximate expectations by quadrature nodes and weights'; l=l+1; + +A{l}='for i=1:n_nodes'; l=l+1; + +A{l}=''; l=l+1; +A{l}=' % realization of shocks at node i'; l=l+1; + +for j=1:length(shocks) + A{l}=[' ' char(shocks(j)) '=nodes(' num2str(j) ',i);'];l=l+1; +end + +if isempty(u) + A{l}=''; l=l+1; + for i=1:n_x2 + A{l}=[' Phi_fun(' num2str(i) ',i)=' char(Phi(i)) ';'];l=l+1; + end +else + l7=l; + A{l}=''; l=l+1; + + + n_u=length(u); + uind=1:n_u; + + uu=uu0; + newuind=uind; + Phiuind=find(logical(sum(tilPhiu,1)~=0)); + while nnz(uu(Phiuind,:))~=0 + + for i=Phiuind(logical(sum(uu(Phiuind,:),2)==0)) + if l==l7+1 + A{l}=' % auxiliary variables'; l=l+1; + end + A{l}=[' ' char(u(i)) '=' char(ufun(i)) ';'];l=l+1; + newuind(i)=0; + end + Phiuind=Phiuind(logical(sum(uu(Phiuind,:),2)~=0)); + uu=uu*uu0; + end + for i=Phiuind + A{l}=[' ' char(u(i)) '=' char(ufun(i)) ';'];l=l+1; + newuind(i)=0; + end + l8=l; + A{l}=''; l=l+1; + A{l}=' % function Phi'; l=l+1; + + for i=1:n_x2 + A{l}=[' Phi_fun(' num2str(i) ',i)=' char(Phi(i)) ';'];l=l+1; + end + +% A{l}=''; l=l+1; +% A{l}=' % store auxiliary variables'; l=l+1; +% for i=1:length(u) +% A{l}=[' auxvars(' num2str(i) ',i)=' char(u(i)) ';'];l=l+1; +% end +end + +A{l}=''; l=l+1; +A{l}=' % future state variables'; l=l+1; + +A{l}=' future_state=Phi_fun(:,i);'; l=l+1; + +% A{l}=''; l=l+1; +for i=1:n_x + A{l}=[' ' char(xp(i)) '=future_state(' num2str(i) ');'];l=l+1; +end + +% A{l}=''; l=l+1; +% A{l}=' % basis function at the future state xp'; l=l+1; +% +% A{l}=' Xp=make_basis(xp,c0);'; l=l+1; + +A{l}=''; l=l+1; +A{l}=' % control variables at the future state'; l=l+1; + +if strcmp(type,'normal') + A{l}=' future_control=evalg(future_state,coeffs,center);'; l=l+1; +elseif strcmp(type,'MS') + A{l}=' future_control=evalg(future_state,future_regime,coeffs,center);'; l=l+1; +end + +for i=1:n_y + A{l}=[' ' char(yp(i)) '=future_control(' num2str(i) ');'];l=l+1; +end + +if ~isempty(u) && nnz(newuind)>0 + A{l}=''; l=l+1; + A{l}=' % auxiliary variables'; l=l+1; + + + uu=uu0; + + uind=nonzeros(newuind); + uind=uind(:)'; + uu=uu(uind,:); + while nnz(uu)~=0 + for i=uind(logical(sum(uu,2)==0)) + A{l}=[' ' char(u(i)) '=' char(ufun(i)) ';'];l=l+1; + end + uind=uind(logical(sum(uu,2)~=0)); + uu=uu(logical(sum(uu,2)~=0),:); + uu=uu*uu0; + end + for i=uind + A{l}=[' ' char(u(i)) '=' char(ufun(i)) ';'];l=l+1; + end + + A{l}=''; l=l+1; + A{l}=' % store auxiliary variables'; l=l+1; + for i=1:n_u + A{l}=[' aux_fun(' num2str(i) ',i)=' char(u(i)) ';'];l=l+1; + end + +end + +%%%%%%%%%% + +if ~isempty(logicalparams) + A{l}=''; l=l+1; + A{l}=[' % logical parameters'];l=l+1; + for i=1:length(logicalparams) + A{l}=[' ' char(logicalparams(i)) '=double(logical(' char(logicalvars(i)) '>0));'];l=l+1; + end +end + +A{l}=''; l=l+1; +A{l}=[' % compute function f'];l=l+1; + +for i=1:n_f + A{l}=[' f_fun(' num2str(i) ')=' char(f(i)) ';'];l=l+1; +end + +A{l}=''; l=l+1; +A{l}=[' % multiply by weight i and add to R_fun'];l=l+1; + +A{l}=[' R_fun=R_fun+f_fun*weights(i);'];l=l+1; + +A{l}='end'; l=l+1; +A{l}=''; l=l+1; +A{l}='end'; l=l+1; + + +% Write cell A into txt + +fid = fopen(['residual.m'], 'w'); +for i = 1:l-1 + fprintf(fid,'%s\n', A{i}); +end + +fclose(fid); + + +% Write evalg + +fid = fopen(['evalg.m'], 'w'); + +if strcmp(type,'normal') + fprintf(fid,'%s\n', 'function g_fun=evalg(x,coeffs,c0)'); + fprintf(fid,'%s\n', '% The function computes the function g(x), where x is the state vector'); +else + fprintf(fid,'%s\n', 'function g_fun=evalg(x,s,coeffs,c0)'); + fprintf(fid,'%s\n', '% The function computes the function g(x,s), where x is the state vector and s is the regime'); +end + +fprintf(fid,'%s\n', ''); + +fprintf(fid,'%s\n', ['Basis=make_basis(x,c0);']); +fprintf(fid,'%s\n', ''); +if strcmp(type,'MS') + fprintf(fid,'%s\n', ['coeffs=reshape(coeffs,' num2str(model.n_y*model.n_b) ',' num2str(model.n_regimes) ');']); + fprintf(fid,'%s\n', ['coeffs=coeffs(:,s);']); +end +fprintf(fid,'%s\n', ['coeffs=reshape(coeffs,' num2str(model.n_y) ',' num2str(model.n_b) ');']); +fprintf(fid,'%s\n', ''); +fprintf(fid,'%s\n', ['g_fun=coeffs*Basis;']); +fprintf(fid,'%s\n', ''); + +fprintf(fid,'%s\n', ['end']); + + +fclose(fid); + + +% Write evalPhi + +fid = fopen(['evalPhi.m'], 'w'); + +if strcmp(type,'normal') + fprintf(fid,'%s\n', 'function Phi_fun=evalPhi(state,control,shock,params)'); + fprintf(fid,'%s\n', '% The function computes the function Phi(x,y,epsp), where x is the state vector,'); + fprintf(fid,'%s\n', '% y is the control vector given by y=g(x), and epsp is the realization of the shocks next period.'); +else + fprintf(fid,'%s\n', 'function Phi_fun=evalPhi(state,control,shock,future_regime,regime,params,msparams)'); + fprintf(fid,'%s\n', '% The function computes the function Phi(x,y,epsp,chi(sp),chi(s)), where x is the state vector,'); + fprintf(fid,'%s\n', '% y is the control vector given by y=g(x,s), chi(s) is the value of the Markov shocks at the current regime s,'); + fprintf(fid,'%s\n', '% chi(sp) is the value of the Markov shocks at the future regime sp, and epsp is the realization of the shocks next period.'); +end + +% parameters +if strcmp(type,'MS') + fprintf(fid,'%s\n', ''); + temp='params=[params(:);msparams(:,regime);msparams(:,future_regime)];'; + fprintf(fid,'%s\n', temp); +end + +for i = l1:l2 + fprintf(fid,'%s\n', A{i}); +end + + +% state variables +for i = l3:l4 + fprintf(fid,'%s\n', A{i}); +end + +% control variables +temp=['% control variables']; +fprintf(fid,'%s\n', temp); + +for j=1:model.n_y + temp=[char(y(j)) '=control(' num2str(j) ');']; + fprintf(fid,'%s\n', temp); +end +fprintf(fid,'%s\n', ''); + +temp=['% shocks']; +fprintf(fid,'%s\n', temp); + +% shocks +for j=1:length(shocks) + temp=[char(shocks(j)) '=shock(' num2str(j) ');']; + fprintf(fid,'%s\n', temp); +end +fprintf(fid,'%s\n', ''); + +temp=['% function Phi']; +fprintf(fid,'%s\n', temp); + +if ~isempty(u) + for i = l7:l8 + fprintf(fid,'%s\n', A{i}(4:end)); + end +end + +temp=['Phi_fun=zeros(' num2str(model.n_x2) ',1);']; +fprintf(fid,'%s\n', temp); + +for i=1:n_x2 + temp=['Phi_fun(' num2str(i) ')=' char(Phi(i)) ';']; + fprintf(fid,'%s\n', temp); +end + +fprintf(fid,'%s\n', ''); + +fprintf(fid,'%s\n', ['end']); + + +fclose(fid); + +rehash; + diff --git a/105/replication_package/solution_methods/taylor_projection/make_residualMS.m b/105/replication_package/solution_methods/taylor_projection/make_residualMS.m new file mode 100644 index 0000000000000000000000000000000000000000..4deb8a0f3ea3ec8f8170434a9d4714602fb8d5a4 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/make_residualMS.m @@ -0,0 +1,12 @@ +function make_residualMS(f,Phi,yp,y,xp,x,chip,chi,symparams,eta,order,ufun,u,uu0,logicalparams,logicalvars) +% make_residualMS(f,Phi,yp,y,xp,x,symparams_msp,symparams_ms,symparams,eta,order,auxfuns,auxvars,model.uu0,logicalparams,logicalvars); +% The function creates a Matlab file that computes the residual function for +% a model with Markov-switching parameters. + +all_symparams=[symparams(:);chi(:);chip(:)]; + +make_residual(f,Phi,yp,y,xp,x,all_symparams,eta,order,ufun,u,uu0,'MS',logicalparams,logicalvars); + + + + diff --git a/105/replication_package/solution_methods/taylor_projection/make_residualMS2.m b/105/replication_package/solution_methods/taylor_projection/make_residualMS2.m new file mode 100644 index 0000000000000000000000000000000000000000..1b69d10a32109800d34dae349f7c3254a91f9ee0 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/make_residualMS2.m @@ -0,0 +1,12 @@ +function make_residualMS2(f,Phi,yp,y,xp,x,shocks,chip,chi,symparams,eta,order,ufun,u,uu0,logicalparams,logicalvars) +% make_residualMS(f,Phi,yp,y,xp,x,symparams_msp,symparams_ms,symparams,eta,order,auxfuns,auxvars,model.uu0,logicalparams,logicalvars); +% The function creates a Matlab file that computes the residual function for +% a model with Markov-switching parameters. + +all_symparams=[symparams(:);chi(:);chip(:)]; + +make_residual2(f,Phi,yp,y,xp,x,shocks,all_symparams,eta,order,ufun,u,uu0,'MS',logicalparams,logicalvars); + + + + diff --git a/105/replication_package/solution_methods/taylor_projection/make_residualMS3.m b/105/replication_package/solution_methods/taylor_projection/make_residualMS3.m new file mode 100644 index 0000000000000000000000000000000000000000..ca13884e6c3a2e9779cddc919c0e82e10aff52e1 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/make_residualMS3.m @@ -0,0 +1,12 @@ +function make_residualMS3(f,Phi,yp,y,xp,x,shocks,chip,chi,symparams,order,ufun,u,uu0,logicalparams,logicalvars) +% make_residualMS(f,Phi,yp,y,xp,x,symparams_msp,symparams_ms,symparams,eta,order,auxfuns,auxvars,model.uu0,logicalparams,logicalvars); +% The function creates a Matlab file that computes the residual function for +% a model with Markov-switching parameters. + +all_symparams=[symparams(:);chi(:);chip(:)]; + +make_residual3(f,Phi,yp,y,xp,x,shocks,all_symparams,order,ufun,u,uu0,'MS',logicalparams,logicalvars); + + + + diff --git a/105/replication_package/solution_methods/taylor_projection/model.mat b/105/replication_package/solution_methods/taylor_projection/model.mat new file mode 100644 index 0000000000000000000000000000000000000000..75f32963ea598a163421ccc81cadd9b8ad20f8bb Binary files /dev/null and b/105/replication_package/solution_methods/taylor_projection/model.mat differ diff --git a/105/replication_package/solution_methods/taylor_projection/nnz_UW.m b/105/replication_package/solution_methods/taylor_projection/nnz_UW.m new file mode 100644 index 0000000000000000000000000000000000000000..0139484e32efcac9fe45f52bdae979361312bb7d --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/nnz_UW.m @@ -0,0 +1,98 @@ +function [varout1,varout2]=nnz_UW(n,k,nonzero,varargin) +% [U,W]=nnz_UW(n,k,nonzero) creates compression matrices that compress a +% symmetric row vector A, where A(i)~=0 iff nonzero(i)~=0. +% [loc,ind]=nnz_UW(n,k,nonzero,'ind') returns two indices. loc(i) is the +% location in the compressed matrix of elemnt ind(i) in the uncompressed +% matrix. +% +% � Copyright, Oren Levintal, June 13, 2016. +% bug fixed on Sep 9, 2017 (the case nonzero==0 was not addressed properly) + +if ~isempty(varargin) + if strcmp(varargin{1},'sparse') + dosparse=1; + elseif strcmp(varargin{1},'ind') + dosparse=0; + else + error('allowed options are sparse or ind') + end +else + dosparse=1; +end + +I=find(nonzero); + +if isempty(I) + if dosparse==1 + U=sparse(n^k,nchoosek(n+k-1,k)); + W=sparse(nchoosek(n+k-1,k),n^k); + varout1=U; + varout2=W; + else + varout1=[]; + varout2=[]; + end +else + I=I(:); + origI=I; + sizeM='n'; + subind='I1'; + for i=2:k + sizeM=[sizeM ' n']; + subind=[subind ',I' num2str(i) ]; + end + + eval(['[' subind ']=ind2sub([' sizeM '],I);']); % I is a linear index of all nonzero elements. + eval(['M=[' subind '];']); + + sortM=sort(M,2); % sort columns + [M,I]=sortrows(sortM); % sort rows + if size(M,1)==1 + DM=1; + else + DM=[1;(sum(abs(diff(M)),2)~=0)]; + end + group=cumsum(DM); + minI=accumarray(group,I,[],@min); + newi=minI(group); + + unique=newi(DM>0); % index of unique nonzero elements + + n_unique=length(unique); + + if k>1 + sortM=sortM(unique,:); + tempmat=repmat(n+k:-1:n+1,n_unique,1); + loc=(repmat(prod(n+k-1:-1:n),n_unique,1)-prod(tempmat-repmat(sortM(:,1),1,k),2))/factorial(k)+1; + + for j=2:k-1 + tempmat=repmat(n+k-j+1:-1:n+1,n_unique,1); + loc=loc+(prod(tempmat-repmat(sortM(:,j-1),1,k-j+1),2)-prod(tempmat-repmat(sortM(:,j),1,k-j+1),2))/factorial(k-j+1); + end + loc=loc+sortM(:,k)-sortM(:,k-1); + if dosparse==1 + U= sparse(origI(unique),loc,ones(n_unique,1),n^k,nchoosek(n+k-1,k)); + origI=origI(I); % sort the original index + W= sparse(loc(group),origI,ones(length(origI),1),nchoosek(n+k-1,k),n^k); + varout1=U; + varout2=W; + else + varout1=loc; + varout2=origI(unique); + end + elseif k==1 + if dosparse==1 + U=sparse(origI,origI,ones(length(origI),1),n,n); + W=U; + varout1=U; + varout2=W; + else + varout1=origI; + varout2=origI; + end + end +end + +end + + diff --git a/105/replication_package/solution_methods/taylor_projection/precompute.m b/105/replication_package/solution_methods/taylor_projection/precompute.m new file mode 100644 index 0000000000000000000000000000000000000000..fcc47ef5fd3bfa466b05c87a363d22d4473f1994 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/precompute.m @@ -0,0 +1,106 @@ +function [ g_theta,h_theta,gx_theta,hx_theta,gxxc_theta,hxxc_theta,gxxxc_theta,hxxxc_theta,gxxxxc_theta,hxxxxc_theta,model ] = precompute(x0,c0,model,order ) +%This function precomputese expressions that are independent of coeffs. +% +% � Copyright, Oren Levintal, June 13, 2016. + +x0=full(x0); +c0=full(c0); + +if ~isequal(x0,c0) + error('x0 is not equal to c0') +end + +n_x=model.n_x; +n_x2=model.n_x2; +n_y=model.n_y; +n_f=model.n_x1+model.n_y; % n_f here is the number of endogenous variables, which might be different than the number of equations in HA models +n_theta=model.n_theta; +U=model.U; +W=model.W; + +if ~isfield(model,'unique2') + model.unique2=[]; +end +if ~isfield(model,'unique3') + model.unique3=[]; +end +if ~isfield(model,'unique4') + model.unique4=[]; +end + +[X,Xx,Xxx,Xxxx,Xxxxx]=create_X(order,n_x,x0,c0,W{2},model.unique2,W{3},model.unique3,W{4},model.unique4); +X=spmat2sptensor(X); Xxxc=[];Xxxxc=[]; Xxxxxc=[]; + +if order>=1 + Xx=spmat2sptensor(Xx); +end +if order>=2 + Xxxc=Xxx*U{2}; + Xxxc=spmat2sptensor(Xxxc); +end +if order>=3 + Xxxxc=Xxxx*U{3}; + Xxxxc=spmat2sptensor(Xxxxc); +end +if order>=4 + Xxxxxc=Xxxxx*U{4}; + Xxxxxc=spmat2sptensor(Xxxxxc); +end + +if ~isfield(model,'ind') + model.ind=cell(model.totindi,1); +end +indi=1; + +if ~isfield(model,'n_ind') + n_ind=1; +else + n_ind=model.n_ind; +end + +hx_theta=[]; hxxc_theta=[]; hxxxc_theta=[]; hxxxxc_theta=[]; +gx_theta=[]; gxxc_theta=[]; gxxxc_theta=[]; gxxxxc_theta=[]; + +IfT=spteye(n_f); % this is the identity matrix + +[gh_theta,model.ind{indi}]=tkron(ttranspose(X),IfT,model.ind{indi},n_ind); +indi=indi+1; +gh_theta=unfold(gh_theta); +g_theta=takerows(gh_theta,1:n_y); +h_theta=vconcat(takerows(gh_theta,n_y+1:n_f),sptensor(n_x2,n_theta)); + +if order>=1 + [ghx_theta,model.ind{indi}]=tkron(ttranspose(Xx),IfT,model.ind{indi},n_ind); + indi=indi+1; + ghx_theta=ptr2col(ptr2d(unfold(ghx_theta),n_f,n_x),1); %n_y,n_x,n_theta + gx_theta=takerows(ghx_theta,1:n_y); + hx_theta=vconcat(takerows(ghx_theta,n_y+1:n_f),sptensor(n_x2,[n_x,n_theta])); +end + +if order>=2 + [ghxxc_theta,model.ind{indi}]=tkron(ttranspose(Xxxc),IfT,model.ind{indi},n_ind); + indi=indi+1; + ghxxc_theta=ptr2col(ptr2d(unfold(ghxxc_theta),n_f,model.unique2),1); %n_y,unique2,n_theta + gxxc_theta=takerows(ghxxc_theta,1:n_y); + hxxc_theta=vconcat(takerows(ghxxc_theta,n_y+1:n_f),sptensor(n_x2,[model.unique2,n_theta])); +end + +if order>=3 + [ghxxxc_theta,model.ind{indi}]=tkron(ttranspose(Xxxxc),IfT,model.ind{indi},n_ind); + indi=indi+1; + ghxxxc_theta=ptr2col(ptr2d(unfold(ghxxxc_theta),n_f,model.unique3),1); %n_y,unique3,n_theta + gxxxc_theta=takerows(ghxxxc_theta,1:n_y); + hxxxc_theta=vconcat(takerows(ghxxxc_theta,n_y+1:n_f),sptensor(n_x2,[model.unique3,n_theta])); +end + +if order>=4 +% [ghxxxxc_theta,model.ind{indi}]=tkron(ttranspose(Xxxxxc),IfT,model.ind{indi},n_ind); + [ghxxxxc_theta]=tkron(ttranspose(Xxxxxc),IfT); +% indi=indi+1; + ghxxxxc_theta=ptr2col(ptr2d(unfold(ghxxxxc_theta),n_f,model.unique4),1); %n_y,unique4,n_theta + gxxxxc_theta=takerows(ghxxxxc_theta,1:n_y); + hxxxxc_theta=vconcat(takerows(ghxxxxc_theta,n_y+1:n_f),sptensor(n_x2,[model.unique4,n_theta])); +end + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/precompute_no_shift.m b/105/replication_package/solution_methods/taylor_projection/precompute_no_shift.m new file mode 100644 index 0000000000000000000000000000000000000000..0a4134a0a212133965b8979c5cf9d45e6346bc9c --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/precompute_no_shift.m @@ -0,0 +1,89 @@ +function [ g_theta,h_theta,gx_theta,hx_theta,gxxc_theta,hxxc_theta,gxxxc_theta,hxxxc_theta,model ] = precompute_no_shift(x0,c0,model,order ) +%This function precomputese expressions that are independent of coeffs. +% +% � Copyright, Oren Levintal, June 13, 2016. + +x0=full(x0); +c0=full(c0); + +% if ~isequal(x0,c0) +% error('x0 is not equal to c0') +% end + +n_x=model.n_x; +n_x2=model.n_x2; +n_y=model.n_y; +n_f=model.n_f; +n_theta=model.n_theta; +U=model.U; +W=model.W; + +if ~isfield(model,'unique2') + model.unique2=[]; +end +if ~isfield(model,'unique3') + model.unique3=[]; +end + +[X,Xx,Xxx,Xxxx]=create_X(order,n_x,x0,c0,W{2},model.unique2,W{3},model.unique3); +X=spmat2sptensor(X); Xxxc=[];Xxxxc=[]; + +if order>=1 + Xx=spmat2sptensor(Xx); +end +if order>=2 + Xxxc=Xxx*U{2}; + Xxxc=spmat2sptensor(Xxxc); +end +if order>=3 + Xxxxc=Xxxx*U{3}; + Xxxxc=spmat2sptensor(Xxxxc); +end + +if ~isfield(model,'ind') + model.ind=cell(model.totindi,1); +end +indi=1; + +if ~isfield(model,'n_ind') + n_ind=1; +else + n_ind=model.n_ind; +end + +hx_theta=[]; hxxc_theta=[]; hxxxc_theta=[]; +gx_theta=[]; gxxc_theta=[]; gxxxc_theta=[]; + +IfT=spteye(n_f); +[gh_theta,model.ind{indi}]=tkron(ttranspose(X),IfT,model.ind{indi},n_ind); +indi=indi+1; +gh_theta=unfold(gh_theta); +g_theta=takerows(gh_theta,1:n_y); +h_theta=vconcat(takerows(gh_theta,n_y+1:n_f),sptensor(n_x2,n_theta)); + +if order>=1 + [ghx_theta,model.ind{indi}]=tkron(ttranspose(Xx),IfT,model.ind{indi},n_ind); + indi=indi+1; + ghx_theta=ptr2col(ptr2d(unfold(ghx_theta),n_f,n_x),1); %n_y,n_x,n_theta + gx_theta=takerows(ghx_theta,1:n_y); + hx_theta=vconcat(takerows(ghx_theta,n_y+1:n_f),sptensor(n_x2,[n_x,n_theta])); +end + +if order>=2 + [ghxxc_theta,model.ind{indi}]=tkron(ttranspose(Xxxc),IfT,model.ind{indi},n_ind); + indi=indi+1; + ghxxc_theta=ptr2col(ptr2d(unfold(ghxxc_theta),n_f,model.unique2),1); %n_y,unique2,n_theta + gxxc_theta=takerows(ghxxc_theta,1:n_y); + hxxc_theta=vconcat(takerows(ghxxc_theta,n_y+1:n_f),sptensor(n_x2,[model.unique2,n_theta])); +end + +if order>=3 + [ghxxxc_theta,model.ind{indi}]=tkron(ttranspose(Xxxxc),IfT,model.ind{indi},n_ind); + indi=indi+1; + ghxxxc_theta=ptr2col(ptr2d(unfold(ghxxxc_theta),n_f,model.unique3),1); %n_y,unique3,n_theta + gxxxc_theta=takerows(ghxxxc_theta,1:n_y); + hxxxc_theta=vconcat(takerows(ghxxxc_theta,n_y+1:n_f),sptensor(n_x2,[model.unique3,n_theta])); +end + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/precomputevec.m b/105/replication_package/solution_methods/taylor_projection/precomputevec.m new file mode 100644 index 0000000000000000000000000000000000000000..d16d89e137623e410cf6311aa7d45e3c699f01d2 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/precomputevec.m @@ -0,0 +1,116 @@ +function [ g_theta,h_theta,gx_theta,hx_theta,gxxc_theta,hxxc_theta,gxxxc_theta,hxxxc_theta,model ] = precomputevec(x0vec,c0vec,model,order ) +%This function precomputese expressions that are independent of coeffs. +% +% � Copyright, Oren Levintal, June 13, 2016. + +x0vec=full(x0vec); +c0vec=full(c0vec); + +if ~isequal(x0vec,c0vec) + error('x0 is not equal to c0') +end + +n_x=model.n_x; +n_x2=model.n_x2; +n_y=model.n_y; +n_f=model.n_x1+model.n_y; % n_f here is the number of endogenous varaibles, which might be different than the number of equations in HA models +n_theta=model.n_theta; +U=model.U; +W=model.W; + +if ~isfield(model,'unique2') + model.unique2=[]; +end +if ~isfield(model,'unique3') + model.unique3=[]; +end + +if ~isfield(model,'n_ind') + n_ind=1; +else + n_ind=model.n_ind; +end + +indi=1; + +if ~isfield(model,'M2') + model.M2=[]; + model.M3=[]; + model.M3x=[]; + model.TW2=[]; + model.TW3=[]; + if order>=2 + model.M2=fold(spmat2sptensor(model.W{2}*model.W{2}'*model.U{2}'),n_x,n_x); + model.TW2=fold(spmat2sptensor(model.W{2}),n_x,n_x); + model.TW2U2=spmat2sptensor(model.W{2}*model.U{2}); + end + if order>=3 + model.M3=fold(spmat2sptensor(model.W{3}*model.W{3}'*model.U{3}'),n_x,n_x,n_x); + model.M3x=fold(spmat2sptensor(3*model.W{3}*kron(model.W{2}'*model.U{2}',speye(n_x))),n_x,n_x,n_x); + model.TW3=fold(spmat2sptensor(model.W{3}),n_x,n_x,n_x); + model.TW3U3=spmat2sptensor(model.W{3}*model.U{3}); + end +end + +[X,Xx,Xxx,Xxxx,model.ind{indi}]=create_X_tensor(order,nxp_c0,... + model.M2,model.M3,model.M3x,model.TW2,model.TW3,unique2,unique3,model.ind{indi},n_ind,maxload,'vec'); +indi=indi+1; + +[X,Xx,Xxx,Xxxx]=create_X(order,n_x,x0,c0,W{2},model.unique2,W{3},model.unique3); +X=spmat2sptensor(X); Xxxc=[];Xxxxc=[]; + +if order>=1 + Xx=spmat2sptensor(Xx); +end +if order>=2 + Xxxc=Xxx*U{2}; + Xxxc=spmat2sptensor(Xxxc); +end +if order>=3 + Xxxxc=Xxxx*U{3}; + Xxxxc=spmat2sptensor(Xxxxc); +end + +if ~isfield(model,'ind') + model.ind=cell(model.totindi,1); +end +indi=1; + + + +hx_theta=[]; hxxc_theta=[]; hxxxc_theta=[]; +gx_theta=[]; gxxc_theta=[]; gxxxc_theta=[]; + +IfT=spteye(n_f); +[gh_theta,model.ind{indi}]=tkron(ttranspose(X),IfT,model.ind{indi},n_ind); +indi=indi+1; +gh_theta=unfold(gh_theta); +g_theta=takerows(gh_theta,1:n_y); +h_theta=vconcat(takerows(gh_theta,n_y+1:n_f),sptensor(n_x2,n_theta)); + +if order>=1 + [ghx_theta,model.ind{indi}]=tkron(ttranspose(Xx),IfT,model.ind{indi},n_ind); + indi=indi+1; + ghx_theta=ptr2col(ptr2d(unfold(ghx_theta),n_f,n_x),1); %n_y,n_x,n_theta + gx_theta=takerows(ghx_theta,1:n_y); + hx_theta=vconcat(takerows(ghx_theta,n_y+1:n_f),sptensor(n_x2,[n_x,n_theta])); +end + +if order>=2 + [ghxxc_theta,model.ind{indi}]=tkron(ttranspose(Xxxc),IfT,model.ind{indi},n_ind); + indi=indi+1; + ghxxc_theta=ptr2col(ptr2d(unfold(ghxxc_theta),n_f,model.unique2),1); %n_y,unique2,n_theta + gxxc_theta=takerows(ghxxc_theta,1:n_y); + hxxc_theta=vconcat(takerows(ghxxc_theta,n_y+1:n_f),sptensor(n_x2,[model.unique2,n_theta])); +end + +if order>=3 + [ghxxxc_theta,model.ind{indi}]=tkron(ttranspose(Xxxxc),IfT,model.ind{indi},n_ind); + indi=indi+1; + ghxxxc_theta=ptr2col(ptr2d(unfold(ghxxxc_theta),n_f,model.unique3),1); %n_y,unique3,n_theta + gxxxc_theta=takerows(ghxxxc_theta,1:n_y); + hxxxc_theta=vconcat(takerows(ghxxxc_theta,n_y+1:n_f),sptensor(n_x2,[model.unique3,n_theta])); +end + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/prepare_tp.m b/105/replication_package/solution_methods/taylor_projection/prepare_tp.m new file mode 100644 index 0000000000000000000000000000000000000000..e508a89dc36a851f662ef7fb5ee588c9319b6f45 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/prepare_tp.m @@ -0,0 +1,150 @@ +function model=prepare_tp(f,Phi,yp,y,xp,x,shocks,varargin) +% function model=prepare_tp(f,Phi,yp,y,xp,x,shocks,symparams,order) + +% This file prepares codes and data that are used later to compute the +% nonlinear system of Taylor projection and the Jacobian. +% Input args: +% f = symbolic vector of the model conditions (Ef=0) +% Phi = symbolic vector of the law of motion of state varialbes. +% yp,y,xp,x = symbolic vectors of the control and state varaibles for +% current (y,x) and future (yp,xp) periods. +% shocks = symbolic shocks. +% symparams = symbolic vector of the model parameters. +% order = order of the approximiating Polynomials. Can be 1, 2, 3 or 4. +% Optional arguments: +% subsfuns,subsvars = subsvars (the second optional argument) is a symbolic +% vector of auxiliary variables that are eventually substituted out. +% subsfuns (the first optional argument) is a symbolic vector of the +% expressions of subsvars (see example in the documentation). Use +% subsfuns and subsvars to speed up differentiation. +% Output arg: +% model = a structure variable with data, that is used to compute the +% system. +% +% � Copyright, Oren Levintal, March 19, 2017. +% changed on April 19, 2018 + +disp('Taylor Projection:') + +n_regimes=1; +chi=[]; +chip=[]; +auxfuns=[]; +auxvars=[]; +logicalparams=[]; +logicalvars=[]; + +nargs=9; + +if nargin==nargs + symparams=varargin{1}; + order=varargin{2}; +elseif nargin==nargs+2 + symparams=varargin{1}; + order=varargin{2}; + auxfuns=varargin{3}; + auxvars=varargin{4}; +elseif nargin==nargs+4 + symparams=varargin{1}; + order=varargin{2}; + auxfuns=varargin{3}; + auxvars=varargin{4}; + logicalparams=varargin{5}; + logicalvars=varargin{6}; +elseif nargin==nargs+3 + chip=varargin{1}; + chi=varargin{2}; + symparams=varargin{3}; + order=varargin{4}; + n_regimes=varargin{5}; +elseif nargin==nargs+5 + chip=varargin{1}; + chi=varargin{2}; + symparams=varargin{3}; + order=varargin{4}; + n_regimes=varargin{5}; + auxfuns=varargin{6}; + auxvars=varargin{7}; +elseif nargin==nargs+7 + chip=varargin{1}; + chi=varargin{2}; + symparams=varargin{3}; + order=varargin{4}; + n_regimes=varargin{5}; + auxfuns=varargin{6}; + auxvars=varargin{7}; + logicalparams=varargin{8}; + logicalvars=varargin{9}; +else + error('wrong number of input arguments') +end + +f=f(:); +Phi=Phi(:); +yp=yp(:); +y=y(:); +xp=xp(:); +x=x(:); +shocks=shocks(:); +chip=chip(:); +chi=chi(:); +symparams=symparams(:); +auxfuns=auxfuns(:); +auxvars=auxvars(:); +logicalparams=logicalparams(:); +logicalvars=logicalvars(:); + +if length(yp)~=length(y) + error('current and future control variables must have the same number of elements') +end +if length(xp)~=length(x) + error('current and future state variables must have the same number of elements') +end +if length(chip)~=length(chi) + error('current and future Markov-switching parameters must have the same number of elements') +end +if length(auxvars)~=length(auxfuns) + error('auxiliary functions and variables must have the same number of elements') +end +if length(logicalparams)~=length(logicalvars) + error('logical parameters and their arguments must have the same number of elements') +end + + + +symparams_ms=chi; +symparams_msp=chip; + +fname='ms'; +nocheck=0; +uname=''; + +Phi=sym(Phi); +if isempty(shocks) + shocks=sym('unused_shock__'); + eta=sym(zeros(length(x),1)); +else + eta=sym(zeros(length(x),length(shocks))); +end + +model=prepare_tpMS3(f,Phi,yp,y,xp,x,shocks,symparams_msp,symparams_ms,symparams,eta,... + n_regimes,order,auxfuns,auxvars,fname,nocheck,uname,logicalparams,logicalvars); +model.pde=0; + +fprintf('writing residual function to file...') +home_folder=pwd; +if ~exist([pwd '\files'], 'dir') + mkdir('files'); +end +cd('files') +if isempty(chi) + make_residual3(f,Phi,yp,y,xp,x,shocks,symparams,order,auxfuns,auxvars,model,logicalparams,logicalvars); +else + make_residualMS3(f,Phi,yp,y,xp,x,shocks,symparams_msp,symparams_ms,symparams,order,auxfuns,auxvars,model,logicalparams,logicalvars); +end +cd(home_folder); +fprintf('done\n') + +model.hybrid=3; + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/prepare_tp3.m b/105/replication_package/solution_methods/taylor_projection/prepare_tp3.m new file mode 100644 index 0000000000000000000000000000000000000000..ca0b09e9f736f49f92654049e31c403c1f2ffc3b --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/prepare_tp3.m @@ -0,0 +1,122 @@ +function model=prepare_tp3(f,Phi,yp,y,xp,x,shocks,varargin) +% function model=prepare_tp(f,Phi,yp,y,xp,x,symparams,eta,order,varargin) + +% This file prepares codes and data that are used later to compute the +% nonlinear system of Taylor projection and the Jacobian. +% Input args: +% f = symbolic vector of the model conditions (Ef=0) +% Phi = symbolic vector of the lower block of h(x). This is the evolution law +% of the exogenoust state variables, or any other state variables with a +% known policy function. +% yp,y,xp,x = symbolic vectors of the control and state varaibles for +% current (y,x) and future (yp,xp) periods. +% symparams = symbolic vector of the model parameters. +% eta = the matrix eta as in Schmitt-Grohe and Uribe (2004). +% order = order of the approximiating Polynomials. Can be 1, 2 or 3. +% Optional arguments: +% subsfuns,subsvars = subsvars (the second optional argument) is a symbolic +% vector of auxiliary variables that are eventually substituted out. +% subsfuns (the first optional argument) is a symbolic vector of the +% expressions of subsvars (see example in the documentation). Use +% subsfuns and subsvars to speed up differentiation. +% Output arg: +% model = a structure variable with data, that is used to compute the +% system. +% +% � Copyright, Oren Levintal, March 19, 2017. + +disp('Taylor Projection:') + +n_regimes=1; +chi=[]; +chip=[]; +auxfuns=[]; +auxvars=[]; +logicalparams=[]; +logicalvars=[]; + +% if isempty(shocks) +% error('shocks are empty') +% end +nargs=9; + +if nargin==nargs + symparams=varargin{1}; + order=varargin{2}; +elseif nargin==nargs+2 + symparams=varargin{1}; + order=varargin{2}; + auxfuns=varargin{3}; + auxvars=varargin{4}; +elseif nargin==nargs+4 + symparams=varargin{1}; + order=varargin{2}; + auxfuns=varargin{3}; + auxvars=varargin{4}; + logicalparams=varargin{5}; + logicalvars=varargin{6}; +elseif nargin==nargs+3 + chip=varargin{1}; + chi=varargin{2}; + symparams=varargin{3}; + order=varargin{4}; + n_regimes=varargin{5}; +elseif nargin==nargs+5 + chip=varargin{1}; + chi=varargin{2}; + symparams=varargin{3}; + order=varargin{4}; + n_regimes=varargin{5}; + auxfuns=varargin{6}; + auxvars=varargin{7}; +elseif nargin==nargs+7 + chip=varargin{1}; + chi=varargin{2}; + symparams=varargin{3}; + order=varargin{4}; + n_regimes=varargin{5}; + auxfuns=varargin{6}; + auxvars=varargin{7}; + logicalparams=varargin{8}; + logicalvars=varargin{9}; +else + error('wrong number of input arguments') +end + +symparams_ms=chi; +symparams_msp=chip; + +fname='ms'; +nocheck=0; +uname=''; + +Phi=sym(Phi); +if isempty(shocks) + shocks=sym('unused_shock'); + eta=sym(zeros(length(x),1)); +else + eta=sym(zeros(length(x),length(shocks))); +end + + + +model=prepare_tpMS3(f,Phi,yp,y,xp,x,shocks,symparams_msp,symparams_ms,symparams,eta,... + n_regimes,order,auxfuns,auxvars,fname,nocheck,uname,logicalparams,logicalvars); + +fprintf('writing residual function to file...') +home_folder=pwd; +if ~exist([pwd '\files'], 'dir') + mkdir('files'); +end +cd('files') +if isempty(chi) + make_residual3(f,Phi,yp,y,xp,x,shocks,symparams,order,auxfuns,auxvars,model.uu0,logicalparams,logicalvars); +else + make_residualMS3(f,Phi,yp,y,xp,x,shocks,symparams_msp,symparams_ms,symparams,order,auxfuns,auxvars,model.uu0,logicalparams,logicalvars); +end +cd(home_folder); +fprintf('done\n') + +model.hybrid=3; + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/prepare_tp3i.m b/105/replication_package/solution_methods/taylor_projection/prepare_tp3i.m new file mode 100644 index 0000000000000000000000000000000000000000..fb2a1d4dd34087448034fd19fec794a551dca498 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/prepare_tp3i.m @@ -0,0 +1,135 @@ +function model=prepare_tp3i(f,Phi,yp,y,xp,x,shocks,varargin) +% function model=prepare_tp(f,Phi,yp,y,xp,x,symparams,eta,order,varargin) + +% This file prepares codes and data that are used later to compute the +% nonlinear system of Taylor projection and the Jacobian. +% Input args: +% f = symbolic vector of the model conditions (Ef=0) +% Phi = symbolic vector of the lower block of h(x). This is the evolution law +% of the exogenoust state variables, or any other state variables with a +% known policy function. +% yp,y,xp,x = symbolic vectors of the control and state varaibles for +% current (y,x) and future (yp,xp) periods. +% symparams = symbolic vector of the model parameters. +% eta = the matrix eta as in Schmitt-Grohe and Uribe (2004). +% order = order of the approximiating Polynomials. Can be 1, 2 or 3. +% Optional arguments: +% subsfuns,subsvars = subsvars (the second optional argument) is a symbolic +% vector of auxiliary variables that are eventually substituted out. +% subsfuns (the first optional argument) is a symbolic vector of the +% expressions of subsvars (see example in the documentation). Use +% subsfuns and subsvars to speed up differentiation. +% Output arg: +% model = a structure variable with data, that is used to compute the +% system. +% +% � Copyright, Oren Levintal, March 19, 2017. + +disp('Taylor Projection:') + +n_regimes=1; +chi=[]; +chip=[]; +auxfuns=[]; +auxvars=[]; +logicalparams=[]; +logicalvars=[]; + +% if isempty(shocks) +% error('shocks are empty') +% end +nargs=10; + +if nargin==nargs + symparams=varargin{1}; + symparamsi=varargin{2}; + order=varargin{3}; +elseif nargin==nargs+2 + symparams=varargin{1}; + symparamsi=varargin{2}; + order=varargin{3}; + auxfuns=varargin{4}; + auxvars=varargin{5}; +elseif nargin==nargs+4 + symparams=varargin{1}; + symparamsi=varargin{2}; + order=varargin{3}; + auxfuns=varargin{4}; + auxvars=varargin{5}; + logicalparams=varargin{6}; + logicalvars=varargin{7}; +elseif nargin==nargs+3 + chip=varargin{1}; + chi=varargin{2}; + symparams=varargin{3}; + symparamsi=varargin{4}; + order=varargin{5}; + n_regimes=varargin{6}; +elseif nargin==nargs+5 + chip=varargin{1}; + chi=varargin{2}; + symparams=varargin{3}; + symparamsi=varargin{4}; + order=varargin{5}; + n_regimes=varargin{6}; + auxfuns=varargin{7}; + auxvars=varargin{8}; +elseif nargin==nargs+7 + chip=varargin{1}; + chi=varargin{2}; + symparams=varargin{3}; + symparamsi=varargin{4}; + order=varargin{5}; + n_regimes=varargin{6}; + auxfuns=varargin{7}; + auxvars=varargin{8}; + logicalparams=varargin{9}; + logicalvars=varargin{10}; +else + error('wrong number of input arguments') +end + +n_paramsi=numel(symparamsi); +symparams=[symparams(:);symparamsi(:)]; + +symparams_ms=chi; +symparams_msp=chip; + +fname='ms'; +nocheck=1; +uname=''; + +Phi=sym(Phi); +if isempty(shocks) + shocks=sym('unused_shock'); + eta=sym(zeros(length(x),1)); +else + eta=sym(zeros(length(x),length(shocks))); +end + + + +model=prepare_tpMS3(f,Phi,yp,y,xp,x,shocks,symparams_msp,symparams_ms,symparams,eta,... + n_regimes,order,auxfuns,auxvars,fname,nocheck,uname,logicalparams,logicalvars); + +fprintf('writing residual function to file...') +home_folder=pwd; +if ~exist([pwd '\files'], 'dir') + mkdir('files'); +end +cd('files') +if isempty(chi) + make_residual3(f,Phi,yp,y,xp,x,shocks,symparams,order,auxfuns,auxvars,model,logicalparams,logicalvars); +else + make_residualMS3(f,Phi,yp,y,xp,x,shocks,symparams_msp,symparams_ms,symparams,order,auxfuns,auxvars,model,logicalparams,logicalvars); +end +cd(home_folder); +fprintf('done\n') + +model.hybrid=3; + +model.n_paramsi=n_paramsi; + +model.pde=0; + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/prepare_tpMS.m b/105/replication_package/solution_methods/taylor_projection/prepare_tpMS.m new file mode 100644 index 0000000000000000000000000000000000000000..7792398d4beb4d578c4e5186738b91b99984cb56 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/prepare_tpMS.m @@ -0,0 +1,56 @@ +function [ model ] = prepare_tpMS( f,Phi,yp,y,xp,x,symparams_msp,symparams_ms,symparams,eta,n_regimes,order,auxfuns,auxvars,varargin ) + + +n_f=length(f); n_x=length(x); n_y=length(y); n_x2=length(Phi); n_x1=n_x-n_x2; + +fname='ms'; +nocheck=0; +uname=''; +logicalparams=[]; +logicalvars=[]; + +if ~isempty(varargin) + fname=varargin{1}; + if ~ischar(fname) + error('function name must be a string') + end + if length(varargin)>1 + nocheck=varargin{2}; + end + if length(varargin)>2 + uname=varargin{3}; + end + if length(varargin)>3 + logicalparams=varargin{4}; + logicalvars=varargin{5}; + end +end + +if nocheck==0 + fprintf('preprocessing (this may take a while)...') +end + +if n_f~=n_y+n_x1 && nocheck==0 + error('number of model conditions should be equal to the number of endogenous variables') +end + +if numel(symparams_msp)~=numel(symparams_ms) + error('wrong size of future and current Markov switching parameters') +end + +new_symparams=[symparams(:);symparams_ms(:);symparams_msp(:)]; + +model=prepare_tpvec(f,Phi,yp,y,xp,x,new_symparams,eta,order,auxfuns,auxvars,fname,uname,logicalparams,logicalvars); +model.n_regimes=n_regimes; + +model.n_msparams=numel(symparams_ms); +model.n_params_no_ms=numel(symparams)+length(logicalparams); + +model.steady_state=0; + +if nocheck==0 + fprintf('done\n') +end + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/prepare_tpMS2.m b/105/replication_package/solution_methods/taylor_projection/prepare_tpMS2.m new file mode 100644 index 0000000000000000000000000000000000000000..dede6595d389f394ef654c82110820dc39b14886 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/prepare_tpMS2.m @@ -0,0 +1,57 @@ +function [ model ] = prepare_tpMS2( f,Phi,yp,y,xp,x,shocks,symparams_msp,symparams_ms,symparams,... + eta,n_regimes,order,auxfuns,auxvars,varargin ) + + +n_f=length(f); n_x=length(x); n_y=length(y); n_x2=length(Phi); n_x1=n_x-n_x2; + +fname='ms'; +nocheck=0; +uname=''; +logicalparams=[]; +logicalvars=[]; + +if ~isempty(varargin) + fname=varargin{1}; + if ~ischar(fname) + error('function name must be a string') + end + if length(varargin)>1 + nocheck=varargin{2}; + end + if length(varargin)>2 + uname=varargin{3}; + end + if length(varargin)>3 + logicalparams=varargin{4}; + logicalvars=varargin{5}; + end +end + +if nocheck==0 + fprintf('preprocessing (this may take a while)...') +end + +if n_f~=n_y+n_x1 && nocheck==0 + error('number of model conditions should be equal to the number of endogenous variables') +end + +if numel(symparams_msp)~=numel(symparams_ms) + error('wrong size of future and current Markov switching parameters') +end + +new_symparams=[symparams(:);symparams_ms(:);symparams_msp(:)]; + +model=prepare_tpvec2(f,Phi,yp,y,xp,x,shocks,new_symparams,eta,order,auxfuns,auxvars,fname,uname,logicalparams,logicalvars); +model.n_regimes=n_regimes; + +model.n_msparams=numel(symparams_ms); +model.n_params_no_ms=numel(symparams)+length(logicalparams); + +model.steady_state=0; + +if nocheck==0 + fprintf('done\n') +end + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/prepare_tpMS3.m b/105/replication_package/solution_methods/taylor_projection/prepare_tpMS3.m new file mode 100644 index 0000000000000000000000000000000000000000..1b26a2c59d68c39c95f82b57e1073c7023d35407 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/prepare_tpMS3.m @@ -0,0 +1,54 @@ +function [ model ] = prepare_tpMS3( f,Phi,yp,y,xp,x,shocks,symparams_msp,symparams_ms,symparams,... + eta,n_regimes,order,auxfuns,auxvars,varargin ) + + +n_f=length(f); n_x=length(x); n_y=length(y); n_x2=length(Phi); n_x1=n_x-n_x2; + +fname='ms'; +nocheck=0; +uname=''; +logicalparams=[]; +logicalvars=[]; + +if ~isempty(varargin) + fname=varargin{1}; + if ~ischar(fname) + error('function name must be a string') + end + if length(varargin)>1 + nocheck=varargin{2}; + end + if length(varargin)>2 + uname=varargin{3}; + end + if length(varargin)>3 + logicalparams=varargin{4}; + logicalvars=varargin{5}; + end +end + +fprintf('preprocessing (this may take a while)...') + +if n_f~=n_y && nocheck==0 + error('number of model conditions should be equal to the number of endogenous variables') +end + +if numel(symparams_msp)~=numel(symparams_ms) + error('wrong size of future and current Markov switching parameters') +end + +new_symparams=[symparams(:);symparams_ms(:);symparams_msp(:)]; + +model=prepare_tpvec3(f,Phi,yp,y,xp,x,shocks,new_symparams,eta,order,auxfuns,auxvars,fname,uname,logicalparams,logicalvars); + +model.n_regimes=n_regimes; + +model.n_msparams=numel(symparams_ms); +model.n_params_no_ms=numel(symparams)+length(logicalparams); + +model.steady_state=0; + +fprintf('done\n') + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/prepare_tpvec.m b/105/replication_package/solution_methods/taylor_projection/prepare_tpvec.m new file mode 100644 index 0000000000000000000000000000000000000000..ba9f5ea76e7e4d0efa195d177028e6f6e64135e9 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/prepare_tpvec.m @@ -0,0 +1,533 @@ +function model=prepare_tpvec(f,Phi,yp,y,xp,x,symparams,eta,order,varargin) + +% This file prepares codes and data that are used later to compute the +% nonlinear system of Taylor projection and the Jacobian. +% Input args: +% f = symbolic vector of the model conditions (Ef=0) +% Phi = symbolic vector of the lower block of h(x). This is the evolution law +% of the exogenoust state variables, or any other state variables with a +% known policy function. +% yp,y,xp,x = symbolic vectors of the control and state varaibles for +% current (y,x) and future (yp,xp) periods. +% symparams = symbolic vector of the model parameters. +% eta = the matrix eta as in Schmitt-Grohe and Uribe (2004). +% order = order of the approximiating Polynomials. Can be 1, 2 or 3. +% Optional arguments: +% subsfuns,subsvars = subsvars (the second optional argument) is a symbolic +% vector of auxiliary variables that are eventually substituted out. +% subsfuns (the first optional argument) is a symbolic vector of the +% expressions of subsvars (see example in the documentation). Use +% subsfuns and subsvars to speed up differentiation. +% Output arg: +% model = a structure variable with data, that is used to compute the +% system. +% +% � Copyright, Oren Levintal, June 13, 2016. +% changed on March 19, 2017 - the function is vectorized and extended to +% fourth order. + + + +model.n_e=size(eta,2); + +f=sym(f(:)); +Phi=sym(Phi(:)); +eta=sym(eta); + +x=sym(x(:)); +xp=sym(xp(:)); +y=sym(y(:)); +yp=sym(yp(:)); + +if length(x)~=length(xp) + error('wrong size of current or future state variables') +end +if length(y)~=length(yp) + error('wrong size of current or future control variables') +end + + +% SIZE VARIABLES +n_f=length(f); n_x=length(x); n_y=length(y); n_x2=length(Phi); n_x1=n_x-n_x2; +v=[yp(:); y(:); xp(:); x(:)]; +n_v=length(v); + +if size(eta,1)~=n_x + error('wrong number of rows for matrix eta') +end +if nnz(eta(1:n_x1,:))~=0 + error('the first n_x1 rows of eta should be zero') +end + +% if n_f>n_y+n_x1 +% error('number of model conditions exceeds the number of endogenous variables'); +% elseif n_f4 + error('perturbation order cannot exceed 4'); + end + order=order(1); +else + pert_order=order; +end +model.order=[order,pert_order]; + +n_b=1; +for k=1:order + n_b=n_b+nchoosek(n_x+k-1,k); % number of parameters in the basis function +end + +n_theta=n_b*(n_y+n_x1); % total number of parameters to be solved + +% if order>=2 + model.unique2=nchoosek(n_x+1,2); +% end +% if order>=3 + model.unique3=nchoosek(n_x+2,3); +% end +% if order>=4 + model.unique4=nchoosek(n_x+3,4); +% end + +% fname + +if nargin>11 + fname=varargin{3}; + if ~ischar(fname) + error('function name must be a string') + end +else + fname=''; +end +if nargin>12 + uname=varargin{4}; + if ~ischar(fname) + error('function name must be a string') + end +else + uname=''; +end +model.fname=fname; +model.uname=uname; + +if nargin>13 + logicalparams=varargin{5}; + logicalvars=varargin{6}; + if length(logicalparams)~=length(logicalvars) + error('wrong size of logical parameters or variables') + end +else + logicalparams=sym([]); + logicalvars=sym([]); +end + +% DEFINE pi_ and u +if isempty(varargin) + pi_=sym([]); + u=sym([]); +elseif isempty(varargin{1}) + warning('no substitutions assumed') + pi_=sym([]); + u=sym([]); +else + pi_=varargin{1}; % pi_ is the function pi(v,u) + pi_=pi_(:); + u=varargin{2}; % auxiliary variables that are eventually substituted out + u=u(:); + if length(pi_)~=length(u) + error('wrong size of substituted variables or functions') + end + if ~isequal(sort(u),sort(unique(u))) + error('substituted variables are not uniquely determined') + end +end + +% check that auxiliary functions do not depend on logical parameters +if ~isempty(logicalparams) && ~isempty(pi_) + if ~isequal(pi_,subs(pi_,logicalparams,sym(zeros(size(logicalparams))))) + error('auxiliary variables must not depend on logical parameters') + end +end + +% check that Phi function does not depend on logical parameters +if ~isempty(logicalparams) && ~isempty(Phi) + if ~isequal(Phi,subs(Phi,logicalparams,sym(zeros(size(logicalparams))))) + error('function Phi must not depend on logical parameters') + end +end + +% check that all symbolic variables/parameters are defined + +actualsymvars=symvar([f;pi_;eta(:);Phi(:)]); +definedvars=[v(:);u(:);symparams(:);logicalparams(:)]; +actualsymvars=sort(actualsymvars(:)); +definedvars=sort(definedvars); + +n_definedvars=length(definedvars); +j=0; +for i=1:length(actualsymvars) + j=j+1; + if j>n_definedvars + error([char(actualsymvars(i)) ' is not defined']) + end + while ~isequal(actualsymvars(i),definedvars(j)) + j=j+1; + if j>n_definedvars + error([char(actualsymvars(i)) ' is not defined']) + end + end +end + +% check that logical variables are defined +actualsymvars=unique(logicalvars); +definedvars=[v(:);u(:)]; +actualsymvars=sort(actualsymvars(:)); +definedvars=sort(definedvars); +n_definedvars=length(definedvars); + +j=0; +for i=1:length(actualsymvars) + j=j+1; + if j>n_definedvars + error([char(actualsymvars(i)) ' is not defined']) + end + while ~isequal(actualsymvars(i),definedvars(j)) + j=j+1; + if j>n_definedvars + error([char(actualsymvars(i)) ' is not defined']) + end + end +end + + +% for i=1:length(logicalvars) +% if isempty(v(v==logicalvars(i))) && isempty(u(u==logicalvars(i))) +% error([char(logicalvars(i)) ' is not defined']) +% end +% end + +symparams=[symparams(:);logicalparams(:)]; +model.n_params=numel(symparams); +model.logical_params_loc=model.n_params-length(logicalparams)+1:model.n_params; +model.n_logicalparams=length(logicalparams); + +n_u=length(u); +model.n_u=n_u; +tilf=f; % tilf(v,u) is a function of v and u +% n=find_n(pi_,u); % number of substitutions needed to eliminate u +[n,piu0]=find_n_new(pi_,u); +model.uu0=piu0; + +% Identify variables that affect u +u_v=u; %u_v which is u as a function of v only u(v) +uu=eye(n_u); % matrix to store which of u affect u +uv=zeros(n_u,n_v); + +% piu0=double(logical(jacobian(pi_,u)~=0)); +piv0=double(logical(jacobian(pi_,v)~=0)); +piu=piu0; +piv=piv0; + +for k=1:n + uu=uu+piu; + uv=uv+piv; + piv=piu*piv0; + piu=piu*piu0; + u_v=subs(u_v,u,pi_); % substitute pi_ into itself n times +end + +% for k=1:n +% u_v=subs(u_v,u,pi_); % substitute pi_ into itself n times +% uu=uu+logical(jacobian(u_v,u)~=0); % uu is a n_u-by-n_u matrix. the ij element is zero only if ui is independent of uj through all substitutions +% uv=uv+logical(jacobian(u_v,v)~=0); % uv is a n_u-by-n_v matrix. the ij element is zero only if ui is independent of vj through all substitutions +% end + +% Identify stochasic and predetermined functions and variables +if n_x2>0 + stochexog=find(sum(1-logical(eta(n_x1+1:end,:)==0),2)); % stochastic exogenous variables +else + stochexog=[]; +end +preexog=1:n_x2; +preexog(stochexog)=[]; % predetermined exogenous variables + +stochvars=[1:n_y,2*n_y+n_x1+stochexog']; % all stochastic variables + +tilfv=double(logical(jacobian(tilf,v)~=0)); +tilfu=double(logical(jacobian(tilf,u)~=0)); +fv=double(logical(tilfv+tilfu*uv~=0)); % logical Jacobian of f w.r.t v + +stochfrows=find(sum( 1-logical(fv(:,stochvars)==0),2)); % stochastic rows of f +prefrows=1:n_f; +prefrows(stochfrows)=[]; % predetermined rows of f + +% variables that affect the predetermined and stochastic rows of f + +prefvars=find(sum(1-logical(fv(prefrows,:)==0),1)); +stochfvars=find(sum(1-logical(fv(stochfrows,:)==0),1)); + + +currentFolder=pwd; +if ~exist([pwd '\files'], 'dir') + mkdir('files'); +end + +cd 'files' + +% generate a function that computes eta +gen_fun_vec(eta(:),[],symparams,['eta' uname],'row'); + + +% Create an m file for Phi and its derivatives w.r.t x +gen_fun_vec(Phi,symparams,x,['Phi' uname],'row'); +if order>=1 + model.Phi_indc=getderivs_c(Phi,x,max(order,pert_order),symparams,'Phi'); +end + +% Create an m file for u +% newuv=jacobian(u_v,v); % calculate uv again +newuv=uv; +stochurows=find(sum( 1-logical(newuv(:,stochvars)==0),2)); % stochastic rows of u +model.stochurows=stochurows; +preurows=1:n_u; +preurows(stochurows)=[]; % predetermined rows of u +model.preurows=preurows; +preuvars=find(sum( logical(newuv(preurows,:)~=0),1)); % variables of predetermined rows of u +stochuvars=find(sum( logical(newuv(stochurows,:)~=0),1)); % variables of stochastic rows of u + +% gen_fun_vec(u_v(preurows),symparams,v(preuvars),['preu' uname],'row'); +% gen_fun_vec(u_v(stochurows),symparams,v(stochuvars),['stochu' uname],'row'); +preurows_allsubs=logical(sum(uu(preurows,:),1)); +gen_fun_vec_subs(u(preurows),symparams,v(preuvars),pi_(preurows_allsubs),u(preurows_allsubs),['preu' uname],'row',piu0(preurows_allsubs,preurows_allsubs)); + +stochurows_allsubs=logical(sum(uu(stochurows,:),1)); +gen_fun_vec_subs(u(stochurows),symparams,v(stochuvars),pi_(stochurows_allsubs),u(stochurows_allsubs),['stochu' uname],'row',piu0(stochurows_allsubs,stochurows_allsubs)); + +model.preuvars=preuvars; +model.stochuvars=stochuvars; + +% build z and find the Jacobian of z +z=[v;u]; + +% locate the logical variables in z + +logical_zvars=zeros(length(logicalvars),1); +for i=1:length(logical_zvars) + logical_zvars(i)=find(logical(z==logicalvars(i))); +end +model.logical_zvars=logical_zvars; + +n_z=n_v+n_u; +zz=[eye(n_v),zeros(n_v,n_u);uv,uu]; +for i=1:n_z + temp=zz(i,:); + temp(temp~=0)=1:nnz(temp); + zz(i,:)=temp; +end +zz=intarray(zz); +model.maxzz=intarray(max(zz(:))); + +% build fv similar to zz +fv=double(fv); +for i=1:n_f + temp=fv(i,:); + temp(temp~=0)=1:nnz(temp); + fv(i,:)=temp; +end +model.fv=fv; + +% tilfz=jacobian(tilf,z); +tilfz=[tilfv,tilfu]; + +% build tilfz +% tilfz=double(logical(tilfz~=0)); % only direct effects +for i=1:n_f + temp=tilfz(i,:); + temp(temp~=0)=1:nnz(temp); + tilfz(i,:)=temp; +end +model.tilfz=tilfz; +model.maxtilfz=intarray(max(tilfz(:))); + +% Create an m file for tilf +pretilfzvars=find(sum(1-logical(tilfz(prefrows,:)==0),1)); +model.pretilfzvars=pretilfzvars; % variables in z that affect pretilf +gen_fun_vec(tilf(prefrows),symparams,z(pretilfzvars),['pretilf' fname],'row'); + +stochtilfzvars=find(sum(1-logical(tilfz(stochfrows,:)==0),1)); +model.stochtilfzvars=stochtilfzvars; % variables in z that affect stochtilf +gen_fun_vec(tilf(stochfrows),symparams,z(stochtilfzvars),['stochtilf' fname],'row'); + +% Differentiate PI and create m files + +PI=[v;pi_]; +prePI=PI; +prePI(n_v+stochurows)=0; % stochastic rows of PI are set to zero. Note: the first n_v rows include stochastic variables but their derivatives w.r.t are ones or zeros. +stochPI=PI; +stochPI([1:n_v,n_v+preurows])=0; % nonstochastic rows are set to zero. See the note above. + +[model.prePI_ind_u]=getderivs_tensor(prePI,z,max(order+1,pert_order),symparams,['prePI' uname]); +[model.stochPI_ind_u]=getderivs_tensor(stochPI,z,max(order+1,pert_order),symparams,['stochPI' uname]); + +prefuvars=find(sum(uu(logical(sum(logical(tilfu(prefrows,:)~=0),1)~=0),:),1)); +stochfuvars=find(sum(uu(logical(sum(logical(tilfu(stochfrows,:)~=0),1)~=0),:),1)); +model.prefuvars=prefuvars; +model.stochfuvars=stochfuvars; + +prefzvars=[prefvars,n_v+prefuvars]; +stochfzvars=[stochfvars,n_v+stochfuvars]; +model.n_prefzvars=length(prefzvars); +model.n_stochfzvars=length(stochfzvars); + +[model.stochtilf_ind_u,model.stoch_n]=gen_chainderivs_tensor(tilf(stochfrows),v(stochfvars),u(stochfuvars),pi_(stochfuvars),max(order+1,pert_order),symparams,['stochtilf' fname]); +[model.pretilf_ind_u,model.pre_n]=gen_chainderivs_tensor(tilf(prefrows),v(prefvars),u(prefuvars),pi_(prefuvars),max(order+1,pert_order),symparams,['pretilf' fname]); + + +% Store variables in struct model +model.prefrows=prefrows; +model.stochfrows=stochfrows; +model.prefvars=prefvars; +model.stochfvars=stochfvars; +model.stochexog=stochexog; +model.preexog=preexog; +model.n_stochexog=length(stochexog); +model.n_preexog=length(preexog); +model.stochfzvars=stochfzvars; +model.prefzvars=prefzvars; + +model.n_theta=n_theta; +model.n_b=n_b; + +model.n_f=n_f; +model.n_x=n_x; +model.n_y=n_y; +model.n_x1=n_x1; +model.n_x2=n_x2; + +model.n_v=n_v; +model.n_z=n_z; +model.n_u=n_u; + +model.n_ind=1; + +model.U=cell(4,1); +model.W=cell(4,1); +for i=2:order+1 + [model.U{i},model.W{i}]=create_UW(n_x,i); +end + +model.stochzz=zz(model.stochfzvars,model.stochfzvars); +model.prezz=zz(model.prefzvars,model.prefzvars); + +model.stochtilfz=tilfz(model.stochfrows,model.stochfzvars); +model.pretilfz=tilfz(model.prefrows,model.prefzvars); + +% calculate some big matrices now + +if order>=3 + save('tempfile') + n_prefvars=length(prefvars); + clearvars -except n_prefvars + + if n_prefvars>0 + [ tempM ] = chainsM( n_prefvars,4 ); + else + tempM=cell(4,1); + end + load('tempfile') + model.prefvars_chain4c_M2=tempM{2}; + model.prefvars_chain4c_M3=tempM{3}; + model.prefvars_chain4c_M4=tempM{4}; + clear tempM + save('tempfile') + + + + n_stochfvars=length(stochfvars); + clearvars -except n_stochfvars + + if n_stochfvars>0 + [ tempM ] = chainsM( n_stochfvars,4 ); + else + tempM=cell(4,1); + end + load('tempfile') + model.stochfvars_chain4c_M2=tempM{2}; + model.stochfvars_chain4c_M3=tempM{3}; + model.stochfvars_chain4c_M4=tempM{4}; + clear tempM + delete('tempfile.mat') +end + +if order>=4 + save('tempfile') + n_prefvars=length(prefvars); + clearvars -except n_prefvars + + if n_prefvars>0 + [ tempM ] = chainsM( n_prefvars,5 ); + else + tempM=cell(6,1); + end + load('tempfile') + model.prefvars_chain5c_M1=tempM{1}; + model.prefvars_chain5c_M2=tempM{2}; + model.prefvars_chain5c_M3=tempM{3}; + model.prefvars_chain5c_M4=tempM{4}; + model.prefvars_chain5c_M5=tempM{5}; + model.prefvars_chain5c_M6=tempM{6}; + + clear tempM + save('tempfile') + + + + n_stochfvars=length(stochfvars); + clearvars -except n_stochfvars + + if n_stochfvars>0 + [ tempM ] = chainsM( n_stochfvars,5 ); + else + tempM=cell(6,1); + end + load('tempfile') + model.stochfvars_chain5c_M1=tempM{1}; + model.stochfvars_chain5c_M2=tempM{2}; + model.stochfvars_chain5c_M3=tempM{3}; + model.stochfvars_chain5c_M4=tempM{4}; + model.stochfvars_chain5c_M5=tempM{5}; + model.stochfvars_chain5c_M6=tempM{6}; + + clear tempM + delete('tempfile.mat') +end + +totindi=5+8; +totindi=totindi+(model.pre_n-1)*(1+3+4+6)+1+4+6+9; +totindi=totindi+3; +totindi=totindi+4; +totindi=totindi+2; +totindi=totindi+2; +totindi=totindi+1; +totindi=totindi+9; +totindi=totindi+8; +totindi=totindi+8+(model.stoch_n-1)*(1+3+4+6)+1+4+6+9; +totindi=totindi+2; +totindi=totindi+9; +totindi=totindi+7; + +model.totindi=totindi; + +model.count_pre_n=0; +model.count_stoch_n=0; + +rehash; + + +cd(currentFolder) \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/prepare_tpvec2.m b/105/replication_package/solution_methods/taylor_projection/prepare_tpvec2.m new file mode 100644 index 0000000000000000000000000000000000000000..7f3afd4e2779ee536f69ecb5196b19da407f7c9a --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/prepare_tpvec2.m @@ -0,0 +1,661 @@ +function model=prepare_tpvec2(f,Phi,yp,y,xp,x,shocks,symparams,eta,order,varargin) + +% This file prepares codes and data that are used later to compute the +% nonlinear system of Taylor projection and the Jacobian. +% Input args: +% f = symbolic vector of the model conditions (Ef=0) +% Phi = symbolic vector of the lower block of h(x). This is the evolution law +% of the exogenoust state variables, or any other state variables with a +% known policy function. +% yp,y,xp,x = symbolic vectors of the control and state varaibles for +% current (y,x) and future (yp,xp) periods. +% symparams = symbolic vector of the model parameters. +% eta = the matrix eta as in Schmitt-Grohe and Uribe (2004). +% order = order of the approximiating Polynomials. Can be 1, 2 or 3. +% Optional arguments: +% subsfuns,subsvars = subsvars (the second optional argument) is a symbolic +% vector of auxiliary variables that are eventually substituted out. +% subsfuns (the first optional argument) is a symbolic vector of the +% expressions of subsvars (see example in the documentation). Use +% subsfuns and subsvars to speed up differentiation. +% Output arg: +% model = a structure variable with data, that is used to compute the +% system. +% +% � Copyright, Oren Levintal, June 13, 2016. +% changed on March 19, 2017 - the function is vectorized and extended to +% fourth order. + + + +model.n_e=size(eta,2); + +f=sym(f(:)); +Phi=sym(Phi(:)); +eta=sym(eta); + +x=sym(x(:)); +xp=sym(xp(:)); +y=sym(y(:)); +yp=sym(yp(:)); +shocks=sym(shocks(:)); + +if length(x)~=length(xp) + error('wrong size of current or future state variables') +end +if length(y)~=length(yp) + error('wrong size of current or future control variables') +end + + +% SIZE VARIABLES +n_f=length(f); n_x=length(x); n_y=length(y); n_x2=length(Phi); n_x1=n_x-n_x2; +v=[yp(:); y(:); xp(:); x(:)]; +n_v=length(v); + +if size(eta,1)~=n_x + error('wrong number of rows for matrix eta') +elseif size(eta,2)~=numel(shocks) + error('wrong number of columns for matrix eta') +end +if nnz(eta(1:n_x1,:))~=0 + error('the first n_x1 rows of eta should be zero') +end + +% if n_f>n_y+n_x1 +% error('number of model conditions exceeds the number of endogenous variables'); +% elseif n_f4 + error('perturbation order cannot exceed 4'); + end + order=order(1); +else + pert_order=order; +end +model.order=[order,pert_order]; + +n_b=0; +for k=0:order + n_b=n_b+nchoosek(n_x+k-1,k); % number of parameters in the basis function +end + +n_theta=n_b*(n_y+n_x1); % total number of parameters to be solved + +if order>=2 + model.unique2=nchoosek(n_x+1,2); +end +if order>=3 + model.unique3=nchoosek(n_x+2,3); +end +if order>=4 + model.unique4=nchoosek(n_x+3,4); +end + +% fname +nargs=11; + +if nargin>nargs + fname=varargin{3}; + if ~ischar(fname) + error('function name must be a string') + end +else + fname=''; +end +if nargin>nargs+1 + uname=varargin{4}; + if ~ischar(fname) + error('function name must be a string') + end +else + uname=''; +end +model.fname=fname; +model.uname=uname; + +if nargin>nargs+2 + logicalparams=varargin{5}; + logicalvars=varargin{6}; + if length(logicalparams)~=length(logicalvars) + error('wrong size of logical parameters or variables') + end +else + logicalparams=sym([]); + logicalvars=sym([]); +end + + +% DEFINE pi_ and u +if isempty(varargin) + pi_=sym([]); + u=sym([]); +elseif isempty(varargin{1}) + warning('no substitutions assumed') + pi_=sym([]); + u=sym([]); +else + pi_=varargin{1}; % pi_ is the function pi(v,u) + pi_=pi_(:); + u=varargin{2}; % auxiliary variables that are eventually substituted out + u=u(:); + if length(pi_)~=length(u) + error('wrong size of substituted variables or functions') + end + if ~isequal(sort(u),sort(unique(u))) + error('substituted variables are not uniquely determined') + end +end + +% check that auxiliary functions do not depend on logical parameters +if ~isempty(logicalparams) && ~isempty(pi_) + if ~isequal(pi_,subs(pi_,logicalparams,sym(zeros(size(logicalparams))))) + error('auxiliary variables must not depend on logical parameters') + end +end + +% check that Phi function does not depend on logical parameters +if ~isempty(logicalparams) && ~isempty(Phi) + if ~isequal(Phi,subs(Phi,logicalparams,sym(zeros(size(logicalparams))))) + error('function Phi must not depend on logical parameters') + end +end + +%%%% NEED TO ADD MORE CHECKS ON PHI - must be independent of yp and xp +%%%% directly and through all substitutions and must be independent of +%%%% stochastic auxiliary vars. + +% check that all symbolic variables/parameters are defined + +actualsymvars=symvar([f;pi_;eta(:);Phi(:)]); +definedvars=[v(:);u(:);symparams(:);logicalparams(:);shocks(:)]; +actualsymvars=sort(actualsymvars(:)); +definedvars=sort(definedvars); + +n_definedvars=length(definedvars); +j=0; +for i=1:length(actualsymvars) + j=j+1; + if j>n_definedvars + error([char(actualsymvars(i)) ' is not defined']) + end + while ~isequal(actualsymvars(i),definedvars(j)) + j=j+1; + if j>n_definedvars + error([char(actualsymvars(i)) ' is not defined']) + end + end +end + +% check that logical variables are defined +actualsymvars=unique(logicalvars); +definedvars=[v(:);u(:)]; +actualsymvars=sort(actualsymvars(:)); +definedvars=sort(definedvars); +n_definedvars=length(definedvars); + +j=0; +for i=1:length(actualsymvars) + j=j+1; + if j>n_definedvars + error([char(actualsymvars(i)) ' is not defined']) + end + while ~isequal(actualsymvars(i),definedvars(j)) + j=j+1; + if j>n_definedvars + error([char(actualsymvars(i)) ' is not defined']) + end + end +end + +% substitute x2p in f and create an auxiliary variable + +x2p=Phi+eta(n_x1+1:end,:)*shocks; +n_u=length(u); +u=[u(:);sym(zeros(n_x2,1))]; + +for i=1:n_x2 + u(n_u+i)=sym([char(xp(n_x1+i)),'_aux']); +end + +f=subs(f,xp(n_x1+1:end),u(n_u+1:end)); +warning('i am substituting x2p into auxiliary functions - need to check that it is correct') +pi_=subs(pi_,xp(n_x1+1:end),u(n_u+1:end)); + + +pi_=[pi_(:);x2p(:)]; + +model.f=f; +model.auxvars=u; +model.auxfuns=pi_; + +new_eta=eta; +new_eta(n_x1+1:end,:)=jacobian(x2p,shocks); + +%%%%%%%%%%%%%% +symparams=[symparams(:);logicalparams(:)]; +model.n_params=numel(symparams); +model.logical_params_loc=model.n_params+model.n_e-length(logicalparams)+(1:length(logicalparams)); +model.n_logicalparams=length(logicalparams); + +% add shocks to symparams +symparams=[shocks(:);symparams(:)]; + +n_u=length(u); +model.n_u=n_u; +tilf=f; % tilf(v,u) is a function of v and u +% n=find_n(pi_,u); % number of substitutions needed to eliminate u +[n,piu0]=find_n_new(pi_,u); +model.uu0=piu0(1:end-n_x2,1:end-n_x2); + +% Identify variables that affect u +% u_v=u; %u_v which is u as a function of v only u(v) +uu=eye(n_u); % matrix to store which of u affect u +uv=zeros(n_u,n_v); + +% piu0=double(logical(jacobian(pi_,u)~=0)); +piv0=double(logical(jacobian(pi_,v)~=0)); +piu=piu0; +piv=piv0; + + +for k=1:n + uu=uu+piu; + uv=uv+piv; + piv=piu*piv0; + piu=piu*piu0; +% u_v=subs(u_v,u,pi_); % substitute pi_ into itself n times +end + +pishocks0=double(sum(logical(jacobian(pi_,shocks)~=0),2)); +ushocks=uu*pishocks0; +% for k=1:n +% u_v=subs(u_v,u,pi_); % substitute pi_ into itself n times +% uu=uu+logical(jacobian(u_v,u)~=0); % uu is a n_u-by-n_u matrix. the ij element is zero only if ui is independent of uj through all substitutions +% uv=uv+logical(jacobian(u_v,v)~=0); % uv is a n_u-by-n_v matrix. the ij element is zero only if ui is independent of vj through all substitutions +% end + +% Identify stochasic and predetermined functions and variables +warning('need to define all exog vars as stochastic') +if n_x2>0 + stochexog=find(sum(1-logical(new_eta(n_x1+1:end,:)==0),2)); % stochastic exogenous variables +else + stochexog=[]; +end +preexog=1:n_x2; +preexog(stochexog)=[]; % predetermined exogenous variables + +stochvars=[1:n_y,2*n_y+n_x1+stochexog']; % all stochastic variables + +tilfv=double(logical(jacobian(tilf,v)~=0)); +tilfu=double(logical(jacobian(tilf,u)~=0)); +tilfshocks=sum(double(logical(jacobian(tilf,shocks)~=0)),2); + +fv=double(logical(tilfv+tilfu*uv~=0)); % logical Jacobian of f w.r.t v +fshocks=double(logical(tilfshocks+tilfu*ushocks~=0)); % logical Jacobian of f w.r.t shocks + +tilPhiv=double(logical(jacobian(Phi,v)~=0)); +tilPhiu=double(logical(jacobian(Phi,u)~=0)); +Phiv=double(logical(tilPhiv+tilPhiu*uv~=0)); % logical Jacobian of Phi w.r.t v + + +tempind=sum( 1-logical(fv(:,stochvars)==0),2)+fshocks; + + +stochfrows=find(tempind); % stochastic rows of f +prefrows=1:n_f; + + +prefrows(stochfrows)=[]; % predetermined rows of f + +% variables that affect the predetermined and stochastic rows of f + +prefvars=find(sum(1-logical(fv(prefrows,:)==0),1)); +stochfvars=find(sum(1-logical(fv(stochfrows,:)==0),1)); + +Phivars=find(sum(1-logical(Phiv==0),1)); + +currentFolder=pwd; +if ~exist([pwd '\files'], 'dir') + mkdir('files'); +end + +cd 'files' + +% generate a function that computes eta +gen_fun_vec(eta(:),[],symparams,['eta' uname],'row'); + + +% if order>=1 +% model.Phi_indc=getderivs_c(Phi,x,max(order,pert_order),symparams,'Phi'); +% end + +% Create an m file for u +% newuv=jacobian(u_v,v); % calculate uv again +newuv=uv; +tempind=sum( 1-logical(newuv(:,stochvars)==0),2)+ushocks; % logical index of stochastic auxiliary variables +% tempind(end-n_x2+1:end)=stochexog; % add the stochastic exogenous variables to the stochastic auxiliary variables +stochurows=find(tempind); % stochastic rows of u +model.stochurows=stochurows; +preurows=1:n_u; +preurows(stochurows)=[]; % predetermined rows of u +model.preurows=preurows; +preuvars=find(sum( logical(newuv(preurows,:)~=0),1)); % variables of predetermined rows of u +stochuvars=find(sum( logical(newuv(stochurows,:)~=0),1)); % variables of stochastic rows of u + +% gen_fun_vec(u_v(preurows),symparams,v(preuvars),['preu' uname],'row'); +% gen_fun_vec(u_v(stochurows),symparams,v(stochuvars),['stochu' uname],'row'); +preurows_allsubs=logical(sum(uu(preurows,:),1)); +gen_fun_vec_subs(u(preurows),symparams,v(preuvars),pi_(preurows_allsubs),u(preurows_allsubs),['preu' uname],'row',piu0(preurows_allsubs,preurows_allsubs)); + +stochurows_allsubs=logical(sum(uu(stochurows,:),1)); +gen_fun_vec_subs(u(stochurows),symparams,v(stochuvars),pi_(stochurows_allsubs),u(stochurows_allsubs),['stochu' uname],'row',piu0(stochurows_allsubs,stochurows_allsubs)); + +model.preuvars=preuvars; +model.stochuvars=stochuvars; + +% Create an m file for Phi and its derivatives w.r.t x +gen_fun_vec(Phi,symparams,[x(:);y(:);u(preurows)],['Phi' uname],'row'); + +gen_fun_vec(new_eta,symparams,[x(:);y(:);u(preurows)],['new_eta' uname],'row'); + +% build z and find the Jacobian of z +z=[v;u]; + +% locate the logical variables in z + +logical_zvars=zeros(length(logicalvars),1); +for i=1:length(logical_zvars) + logical_zvars(i)=find(logical(z==logicalvars(i))); +end +model.logical_zvars=logical_zvars; + +n_z=n_v+n_u; +zz=[eye(n_v),zeros(n_v,n_u);uv,uu]; +for i=1:n_z + temp=zz(i,:); + temp(temp~=0)=1:nnz(temp); + zz(i,:)=temp; +end +zz=intarray(zz); +model.maxzz=intarray(max(zz(:))); + +% build fv similar to zz +fv=double(fv); +for i=1:n_f + temp=fv(i,:); + temp(temp~=0)=1:nnz(temp); + fv(i,:)=temp; +end +model.fv=fv; + +% build Phiv similar to zz +Phiv=double(Phiv); +for i=1:n_x2 + temp=Phiv(i,:); + temp(temp~=0)=1:nnz(temp); + Phiv(i,:)=temp; +end +model.Phiv=Phiv; + +% tilfz=jacobian(tilf,z); +tilfz=[tilfv,tilfu]; + +% build tilfz +% tilfz=double(logical(tilfz~=0)); % only direct effects +for i=1:n_f + temp=tilfz(i,:); + temp(temp~=0)=1:nnz(temp); + tilfz(i,:)=temp; +end +model.tilfz=tilfz; +model.maxtilfz=intarray(max(tilfz(:))); + +% build tilPhiz +tilPhiz=[tilPhiv,tilPhiu]; +for i=1:n_x2 + temp=tilPhiz(i,:); + temp(temp~=0)=1:nnz(temp); + tilPhiz(i,:)=temp; +end +% model.stochtilfz=tilfz(model.stochfrows,model.stochfzvars); + +% Create an m file for tilf +pretilfzvars=find(sum(1-logical(tilfz(prefrows,:)==0),1)); +model.pretilfzvars=pretilfzvars; % variables in z that affect pretilf +gen_fun_vec(tilf(prefrows),symparams,z(pretilfzvars),['pretilf' fname],'row'); + +stochtilfzvars=find(sum(1-logical(tilfz(stochfrows,:)==0),1)); +model.stochtilfzvars=stochtilfzvars; % variables in z that affect stochtilf +gen_fun_vec(tilf(stochfrows),symparams,z(stochtilfzvars),['stochtilf' fname],'row'); + +% Differentiate PI and create m files + +PI=[v;pi_]; +prePI=PI; +prePI(n_v+stochurows)=0; % stochastic rows of PI are set to zero. Note: the first n_v rows include stochastic variables but their derivatives w.r.t are ones or zeros. +stochPI=PI; +stochPI([1:n_v,n_v+preurows])=0; % nonstochastic rows are set to zero. See the note above. + +[model.prePI_ind_u]=getderivs_tensor(prePI,z,max(order+1,pert_order),symparams,['prePI' uname]); +[model.stochPI_ind_u]=getderivs_tensor(stochPI,z,max(order+1,pert_order),symparams,['stochPI' uname]); + +prefuvars=find(sum(uu(logical(sum(logical(tilfu(prefrows,:)~=0),1)~=0),:),1)); +stochfuvars=find(sum(uu(logical(sum(logical(tilfu(stochfrows,:)~=0),1)~=0),:),1)); + +Phiuvars=find(sum(uu(logical(sum(logical(tilPhiu~=0),1)~=0),:),1)); + +model.prefuvars=prefuvars; +model.stochfuvars=stochfuvars; +model.Phiuvars=Phiuvars; + +prefzvars=[prefvars,n_v+prefuvars]; +stochfzvars=[stochfvars,n_v+stochfuvars]; + +Phizvars=[Phivars,n_v+Phiuvars]; + +model.n_prefzvars=length(prefzvars); +model.n_stochfzvars=length(stochfzvars); +model.n_Phizvars=length(Phizvars); + +[model.stochtilf_ind_u,model.stoch_n]=gen_chainderivs_tensor(tilf(stochfrows),v(stochfvars),u(stochfuvars),pi_(stochfuvars),max(order+1,pert_order),symparams,['stochtilf' fname]); +[model.pretilf_ind_u,model.pre_n]=gen_chainderivs_tensor(tilf(prefrows),v(prefvars),u(prefuvars),pi_(prefuvars),max(order+1,pert_order),symparams,['pretilf' fname]); + +[model.Phi_ind_u,model.Phi_n]=gen_chainderivs_tensor(Phi,v(Phivars),u(Phiuvars),pi_(Phiuvars),max(order+1,pert_order),symparams,['Phi' fname]); + +% Store variables in struct model +model.prefrows=prefrows; +model.stochfrows=stochfrows; +model.prefvars=prefvars; +model.stochfvars=stochfvars; +model.stochexog=stochexog; +model.preexog=preexog; +model.n_stochexog=length(stochexog); +model.n_preexog=length(preexog); +model.stochfzvars=stochfzvars; +model.prefzvars=prefzvars; +model.Phizvars=Phizvars; +model.Phivars=Phivars; + +model.n_theta=n_theta; +model.n_b=n_b; + +model.n_f=n_f; +model.n_x=n_x; +model.n_y=n_y; +model.n_x1=n_x1; +model.n_x2=n_x2; + +model.n_v=n_v; +model.n_z=n_z; +model.n_u=n_u; + +model.n_ind=1; + +model.U=cell(4,1); +model.W=cell(4,1); +for i=2:order+1 + [model.U{i},model.W{i}]=create_UW(n_x,i); +end + +model.stochzz=zz(model.stochfzvars,model.stochfzvars); +model.prezz=zz(model.prefzvars,model.prefzvars); + +model.Phizz=zz(model.Phizvars,model.Phizvars); + +model.stochtilfz=tilfz(model.stochfrows,model.stochfzvars); +model.pretilfz=tilfz(model.prefrows,model.prefzvars); + +model.tilPhiz=tilPhiz(:,Phizvars); +model.maxtilPhiz=intarray(max(tilPhiz(:))); + +% calculate some big matrices now + +if order>=3 + save('tempfile') + n_prefvars=length(prefvars); + clearvars -except n_prefvars + + if n_prefvars>0 + [ tempM ] = chainsM( n_prefvars,4 ); + else + tempM=cell(4,1); + end + load('tempfile') + model.prefvars_chain4c_M2=tempM{2}; + model.prefvars_chain4c_M3=tempM{3}; + model.prefvars_chain4c_M4=tempM{4}; + clear tempM + + save('tempfile') + n_stochfvars=length(stochfvars); + clearvars -except n_stochfvars + + if n_stochfvars>0 + [ tempM ] = chainsM( n_stochfvars,4 ); + else + tempM=cell(4,1); + end + load('tempfile') + model.stochfvars_chain4c_M2=tempM{2}; + model.stochfvars_chain4c_M3=tempM{3}; + model.stochfvars_chain4c_M4=tempM{4}; + clear tempM + + save('tempfile') + n_Phivars=length(Phivars); + clearvars -except n_Phivars + + if n_Phivars>0 + [ tempM ] = chainsM( n_Phivars,4 ); + else + tempM=cell(4,1); + end + load('tempfile') + model.Phivars_chain4c_M2=tempM{2}; + model.Phivars_chain4c_M3=tempM{3}; + model.Phivars_chain4c_M4=tempM{4}; + clear tempM + + + delete('tempfile.mat') +end + +if order>=4 + save('tempfile') + n_prefvars=length(prefvars); + clearvars -except n_prefvars + + if n_prefvars>0 + [ tempM ] = chainsM( n_prefvars,5 ); + else + tempM=cell(6,1); + end + load('tempfile') + model.prefvars_chain5c_M1=tempM{1}; + model.prefvars_chain5c_M2=tempM{2}; + model.prefvars_chain5c_M3=tempM{3}; + model.prefvars_chain5c_M4=tempM{4}; + model.prefvars_chain5c_M5=tempM{5}; + model.prefvars_chain5c_M6=tempM{6}; + + clear tempM + + save('tempfile') + n_stochfvars=length(stochfvars); + clearvars -except n_stochfvars + + if n_stochfvars>0 + [ tempM ] = chainsM( n_stochfvars,5 ); + else + tempM=cell(6,1); + end + load('tempfile') + model.stochfvars_chain5c_M1=tempM{1}; + model.stochfvars_chain5c_M2=tempM{2}; + model.stochfvars_chain5c_M3=tempM{3}; + model.stochfvars_chain5c_M4=tempM{4}; + model.stochfvars_chain5c_M5=tempM{5}; + model.stochfvars_chain5c_M6=tempM{6}; + + clear tempM + + save('tempfile') + n_Phivars=length(Phivars); + clearvars -except n_Phivars + + if n_Phivars>0 + [ tempM ] = chainsM( n_Phivars,5 ); + else + tempM=cell(6,1); + end + load('tempfile') + model.Phivars_chain5c_M1=tempM{1}; + model.Phivars_chain5c_M2=tempM{2}; + model.Phivars_chain5c_M3=tempM{3}; + model.Phivars_chain5c_M4=tempM{4}; + model.Phivars_chain5c_M5=tempM{5}; + model.Phivars_chain5c_M6=tempM{6}; + + clear tempM + + + delete('tempfile.mat') +end + +model.count_pre_n=model.pre_n-1; +if model.count_pre_n<0 + model.count_pre_n=0; +end + +model.count_stoch_n=model.stoch_n-1; +if model.count_stoch_n<0 + model.count_stoch_n=0; +end + +totindi=5+8; +totindi=totindi+model.count_pre_n*(1+3+4+6)+1+4+6+9; +totindi=totindi+3; +totindi=totindi+4; +totindi=totindi+2; +totindi=totindi+2; +totindi=totindi+1; +totindi=totindi+9; +totindi=totindi+8; +totindi=totindi+8+model.count_stoch_n*(1+3+4+6)+1+4+6+9; +totindi=totindi+2; +totindi=totindi+9; +totindi=totindi+7; + +model.totindi=totindi; + +rehash; + + +cd(currentFolder) \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/prepare_tpvec3.m b/105/replication_package/solution_methods/taylor_projection/prepare_tpvec3.m new file mode 100644 index 0000000000000000000000000000000000000000..05dd84e88797ecca16b11c910a7e4c8fe69f7cc5 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/prepare_tpvec3.m @@ -0,0 +1,702 @@ +function model=prepare_tpvec3(f,Phi,yp,y,xp,x,shocks,symparams,eta,order,varargin) + +% This file prepares codes and data that are used later to compute the +% nonlinear system of Taylor projection and the Jacobian. +% Input args: +% f = symbolic vector of the model conditions (Ef=0) +% Phi = symbolic vector of the lower block of h(x). This is the evolution law +% of the exogenoust state variables, or any other state variables with a +% known policy function. +% yp,y,xp,x = symbolic vectors of the control and state varaibles for +% current (y,x) and future (yp,xp) periods. +% symparams = symbolic vector of the model parameters. +% eta = the matrix eta as in Schmitt-Grohe and Uribe (2004). +% order = order of the approximiating Polynomials. Can be 1, 2 or 3. +% Optional arguments: +% subsfuns,subsvars = subsvars (the second optional argument) is a symbolic +% vector of auxiliary variables that are eventually substituted out. +% subsfuns (the first optional argument) is a symbolic vector of the +% expressions of subsvars (see example in the documentation). Use +% subsfuns and subsvars to speed up differentiation. +% Output arg: +% model = a structure variable with data, that is used to compute the +% system. +% +% � Copyright, Oren Levintal, June 13, 2016. +% changed on March 19, 2017 - the function is vectorized and extended to +% fourth order. + + + +model.n_e=size(eta,2); + +f=sym(f(:)); +Phi=sym(Phi(:)); +eta=sym(eta); + +x=sym(x(:)); +xp=sym(xp(:)); +y=sym(y(:)); +yp=sym(yp(:)); +shocks=sym(shocks(:)); + + + +if length(x)~=length(xp) + error('wrong size of current or future state variables') +end +if length(x)~=length(Phi) + error('wrong size of law of motion of state variables') +end +if length(y)~=length(yp) + error('wrong size of current or future control variables') +end + +% SIZE VARIABLES +n_f=length(f); n_x=length(x); n_y=length(y); n_x2=length(Phi); n_x1=n_x-n_x2; +v=[yp(:); y(:); xp(:); x(:)]; +n_v=length(v); + +if size(eta,1)~=n_x + error('wrong number of rows for matrix eta') +end +if nnz(eta(1:n_x1,:))~=0 + error('the first n_x1 rows of eta should be zero') +end + +% if order is a vector of length 2, the first element is the order of +% Taylor projection and the second is the order of perturbation. +if length(order)==2 + pert_order=order(2); + if pert_order>4 + error('perturbation order cannot exceed 4'); + end + order=order(1); +else + pert_order=order; +end +model.order=[order,pert_order]; + +n_b=1; +for k=1:order + n_b=n_b+nchoosek(n_x+k-1,k); % number of parameters in the basis function +end + +n_theta=n_b*(n_y+n_x1); % total number of parameters to be solved + +% if order>=2 + model.unique2=nchoosek(n_x+1,2); +% end +% if order>=3 + model.unique3=nchoosek(n_x+2,3); +% end +% if order>=4 + model.unique4=nchoosek(n_x+3,4); +% end + +% fname +nargs=11; + +if nargin>nargs + fname=varargin{3}; + if ~ischar(fname) + error('function name must be a string') + end +else + fname=''; +end +if nargin>nargs+1 + uname=varargin{4}; + if ~ischar(fname) + error('function name must be a string') + end +else + uname=''; +end +model.fname=fname; +model.uname=uname; + +if nargin>nargs+2 + logicalparams=varargin{5}; + logicalvars=varargin{6}; + if length(logicalparams)~=length(logicalvars) + error('wrong size of logical parameters or variables') + end +else + logicalparams=sym([]); + logicalvars=sym([]); +end + + +% DEFINE pi_ and u +if isempty(varargin) + pi_=sym([]); + u=sym([]); +elseif isempty(varargin{1}) +% warning('no substitutions assumed') + pi_=sym([]); + u=sym([]); +else + pi_=varargin{1}; % pi_ is the function pi(v,u) + pi_=pi_(:); + u=varargin{2}; % auxiliary variables that are eventually substituted out + u=u(:); + if length(pi_)~=length(u) + error('wrong size of substituted variables or functions') + end + if ~isequal(sort(u),sort(unique(u))) + error('substituted variables are not uniquely determined') + end +end + +% check that auxiliary functions do not depend on logical parameters +if ~isempty(logicalparams) && ~isempty(pi_) + if ~isequal(pi_,subs(pi_,logicalparams,sym(zeros(size(logicalparams))))) + error('auxiliary variables must not depend on logical parameters') + end +end + +% check that Phi function does not depend on logical parameters +if ~isempty(logicalparams) && ~isempty(Phi) + if ~isequal(Phi,subs(Phi,logicalparams,sym(zeros(size(logicalparams))))) + error('function Phi must not depend on logical parameters') + end +end + +%%%% NEED TO ADD MORE CHECKS ON PHI - must be independent of yp and xp +%%%% directly and through all substitutions - done below +% and must be independent of +%%%% stochastic auxiliary vars - i removed this restriction - to evaluate +%%%% the function i substitute auxvars out, and to compute derivatives i do +%%%% it after i have all stochastic auxiliary variables. +subsPhi=subsf(Phi,u,pi_); +% subsPhi=Phi; + +%%%%%%%%%% search for reserved names + +allnames=[v(:);u(:);symparams(:);logicalparams(:);shocks(:)]; +reserved_names={'coeffs','coeffsp','state','future_state','control','future_control','regime','future_regime','params','msparams','regimes','n_regimes',... + 'shock','center','nodes','n_nodes','weights','Basis','n_nodes','endogenous_vars','transition',... + 'R_fun','g_fun','Phi_fun','aux_fun','i','j','f_fun',... + 'R_funMS','g_funMS','Phi_funMS','aux_funMS','Amat'}; + +reserved=''; + +for i=1:length(reserved_names) + if nnz(logical(allnames==sym(reserved_names{i})))~=0 + reserved=[reserved, ' \n ', reserved_names{i}]; + end +end + +if ~isempty(reserved) + error_message=['The following names are reserved and should be changed:', reserved]; + error('ErrorTests:convertTest',error_message) +end + +%%%%%%%%%%% + +% check that all symbolic variables/parameters are defined + +actualsymvars=symvar([f;pi_;eta(:);Phi(:)]); +definedvars=[v(:);u(:);symparams(:);logicalparams(:);shocks(:)]; +actualsymvars=sort(actualsymvars(:)); +definedvars=sort(definedvars); + +n_definedvars=length(definedvars); +j=0; +for i=1:length(actualsymvars) + j=j+1; + if j>n_definedvars + error([char(actualsymvars(i)) ' is not defined']) + end + while ~isequal(actualsymvars(i),definedvars(j)) + j=j+1; + if j>n_definedvars + error([char(actualsymvars(i)) ' is not defined']) + end + end +end + +% check that logical variables are defined +actualsymvars=unique(logicalvars); +definedvars=[v(:);u(:)]; +actualsymvars=sort(actualsymvars(:)); +definedvars=sort(definedvars); +n_definedvars=length(definedvars); + +j=0; +for i=1:length(actualsymvars) + j=j+1; + if j>n_definedvars + error([char(actualsymvars(i)) ' is not defined']) + end + while ~isequal(actualsymvars(i),definedvars(j)) + j=j+1; + if j>n_definedvars + error([char(actualsymvars(i)) ' is not defined']) + end + end +end + +% substitute x2p in f and create an auxiliary variable + +% x2p=Phi+eta(n_x1+1:end,:)*shocks; +% n_u=length(u); +% u=[u(:);sym(zeros(n_x2,1))]; +% +% for i=1:n_x2 +% u(n_u+i)=sym([char(xp(n_x1+i)),'_aux']); +% end +% +% f=subs(f,xp(n_x1+1:end),u(n_u+1:end)); +% warning('i am substituting x2p into auxiliary functions - need to check that it is correct') +% pi_=subs(pi_,xp(n_x1+1:end),u(n_u+1:end)); +% +% +% pi_=[pi_(:);x2p(:)]; + +% model.f=f; +% model.auxvars=u; +% model.auxfuns=pi_; + +new_eta=eta; +new_eta(n_x1+1:end,:)=jacobian(subsPhi,shocks); + +%%%%%%%%%%%%%% +symparams=[symparams(:);logicalparams(:)]; +model.n_params=numel(symparams); +model.logical_params_loc=model.n_params+model.n_e-length(logicalparams)+(1:length(logicalparams)); +model.n_logicalparams=length(logicalparams); + +% add shocks to symparams +symparams=[shocks(:);symparams(:)]; + +n_u=length(u); +model.n_u=n_u; +tilf=f; % tilf(v,u) is a function of v and u +% n=find_n(pi_,u); % number of substitutions needed to eliminate u +[n,piu0]=find_n_new(pi_,u); +model.piu0=piu0; + +% Identify variables that affect u +% u_v=u; %u_v which is u as a function of v only u(v) +uu=eye(n_u); % matrix to store which of u affect u +uv=zeros(n_u,n_v); + +% piu0=double(logical(jacobian(pi_,u)~=0)); +piv0=double(logical(jacobian(pi_,v)~=0)); +piu=piu0; +piv=piv0; + + +for k=1:n + uu=uu+piu; + uv=uv+piv; + piv=piu*piv0; + piu=piu*piu0; +% u_v=subs(u_v,u,pi_); % substitute pi_ into itself n times +end +model.uu=uu; + +pishocks0=double(sum(logical(jacobian(pi_,shocks)~=0),2)); +ushocks=uu*pishocks0; +% for k=1:n +% u_v=subs(u_v,u,pi_); % substitute pi_ into itself n times +% uu=uu+logical(jacobian(u_v,u)~=0); % uu is a n_u-by-n_u matrix. the ij element is zero only if ui is independent of uj through all substitutions +% uv=uv+logical(jacobian(u_v,v)~=0); % uv is a n_u-by-n_v matrix. the ij element is zero only if ui is independent of vj through all substitutions +% end + +% Identify stochasic and predetermined functions and variables +% warning('need to define all exog vars as stochastic') +% if n_x2>0 +% stochexog=find(sum(1-logical(new_eta(n_x1+1:end,:)==0),2)); % stochastic exogenous variables +% else +% stochexog=[]; +% end +% preexog=1:n_x2; +% preexog(stochexog)=[]; % predetermined exogenous variables + +preexog=[]; +stochexog=reshape((1:n_x2),n_x2,1); % all exogenous vars are assumed stochastic. + +stochvars=[1:n_y,2*n_y+n_x1+stochexog']; % all stochastic variables + +tilfv=double(logical(jacobian(tilf,v)~=0)); +tilfu=double(logical(jacobian(tilf,u)~=0)); +tilfshocks=sum(double(logical(jacobian(tilf,shocks)~=0)),2); + +fv=double(logical(tilfv+tilfu*uv~=0)); % logical Jacobian of f w.r.t v +fshocks=double(logical(tilfshocks+tilfu*ushocks~=0)); % logical Jacobian of f w.r.t shocks + +tilPhiv=double(logical(jacobian(Phi,v)~=0)); +tilPhiu=double(logical(jacobian(Phi,u)~=0)); +model.tilPhiu=tilPhiu; +Phiv=double(logical(tilPhiv+tilPhiu*uv~=0)); % logical Jacobian of Phi w.r.t v + +if nnz(Phiv(:,1:n_y))>0 + error('Function Phi cannot depend on future control variables') +end + +if nnz(Phiv(:,2*n_y+n_x1+(1:n_x2)))>0 + error('Function Phi cannot depend on future state variables') +end + + +tempind=sum( 1-logical(fv(:,stochvars)==0),2)+fshocks; + + +stochfrows=find(tempind); % stochastic rows of f +prefrows=1:n_f; + + +prefrows(stochfrows)=[]; % predetermined rows of f + +% variables that affect the predetermined and stochastic rows of f + +prefvars=find(sum(1-logical(fv(prefrows,:)==0),1)); +stochfvars=find(sum(1-logical(fv(stochfrows,:)==0),1)); + +Phivars=find(sum(1-logical(Phiv==0),1)); + +currentFolder=pwd; +if ~exist([pwd '\files'], 'dir') + mkdir('files'); +end + +cd 'files' + +% generate a function that computes eta +gen_fun_vec(eta(:),[],symparams,['eta' uname],'row'); + + +% if order>=1 +% model.Phi_indc=getderivs_c(Phi,x,max(order,pert_order),symparams,'Phi'); +% end + +% Create an m file for u +% newuv=jacobian(u_v,v); % calculate uv again +newuv=uv; +tempind=sum( 1-logical(newuv(:,stochvars)==0),2)+ushocks; % logical index of stochastic auxiliary variables +% tempind(end-n_x2+1:end)=stochexog; % add the stochastic exogenous variables to the stochastic auxiliary variables +stochurows=find(tempind); % stochastic rows of u +model.stochurows=stochurows; +preurows=1:n_u; +preurows(stochurows)=[]; % predetermined rows of u +model.preurows=preurows; +preuvars=find(sum( logical(newuv(preurows,:)~=0),1)); % variables of predetermined rows of u +stochuvars=find(sum( logical(newuv(stochurows,:)~=0),1)); % variables of stochastic rows of u + +% gen_fun_vec(u_v(preurows),symparams,v(preuvars),['preu' uname],'row'); +% gen_fun_vec(u_v(stochurows),symparams,v(stochuvars),['stochu' uname],'row'); +preurows_allsubs=logical(sum(uu(preurows,:),1)); +gen_fun_vec_subs(u(preurows),symparams,v(preuvars),pi_(preurows_allsubs),u(preurows_allsubs),['preu' uname],'row',piu0(preurows_allsubs,preurows_allsubs)); + +stochurows_allsubs=logical(sum(uu(stochurows,:),1)); +gen_fun_vec_subs(u(stochurows),symparams,v(stochuvars),pi_(stochurows_allsubs),u(stochurows_allsubs),['stochu' uname],'row',piu0(stochurows_allsubs,stochurows_allsubs)); + +model.preuvars=preuvars; +model.stochuvars=stochuvars; + + +% build z and find the Jacobian of z +z=[v;u]; + +% locate the logical variables in z + +logical_zvars=zeros(length(logicalvars),1); +for i=1:length(logical_zvars) + logical_zvars(i)=find(logical(z==logicalvars(i))); +end +model.logical_zvars=logical_zvars; + +n_z=n_v+n_u; +zz=[eye(n_v),zeros(n_v,n_u);uv,uu]; +for i=1:n_z + temp=zz(i,:); + temp(temp~=0)=1:nnz(temp); + zz(i,:)=temp; +end +zz=intarray(zz); +model.maxzz=intarray(max(zz(:))); + +% build fv similar to zz +fv=double(fv); +for i=1:n_f + temp=fv(i,:); + temp(temp~=0)=1:nnz(temp); + fv(i,:)=temp; +end +model.fv=fv; + +% build Phiv similar to zz +Phiv=double(Phiv); +for i=1:n_x2 + temp=Phiv(i,:); + temp(temp~=0)=1:nnz(temp); + Phiv(i,:)=temp; +end +model.Phiv=Phiv; + +% tilfz=jacobian(tilf,z); +tilfz=[tilfv,tilfu]; + +% build tilfz +% tilfz=double(logical(tilfz~=0)); % only direct effects +for i=1:n_f + temp=tilfz(i,:); + temp(temp~=0)=1:nnz(temp); + tilfz(i,:)=temp; +end +model.tilfz=tilfz; +model.maxtilfz=intarray(max(tilfz(:))); + +% build tilPhiz +tilPhiz=[tilPhiv,tilPhiu]; +for i=1:n_x2 + temp=tilPhiz(i,:); + temp(temp~=0)=1:nnz(temp); + tilPhiz(i,:)=temp; +end +% model.stochtilfz=tilfz(model.stochfrows,model.stochfzvars); + +% Create an m file for tilf +pretilfzvars=find(sum(1-logical(tilfz(prefrows,:)==0),1)); +model.pretilfzvars=pretilfzvars; % variables in z that affect pretilf +gen_fun_vec(tilf(prefrows),symparams,z(pretilfzvars),['pretilf' fname],'row'); + +stochtilfzvars=find(sum(1-logical(tilfz(stochfrows,:)==0),1)); +model.stochtilfzvars=stochtilfzvars; % variables in z that affect stochtilf +gen_fun_vec(tilf(stochfrows),symparams,z(stochtilfzvars),['stochtilf' fname],'row'); + +% Differentiate PI and create m files + +PI=[v;pi_]; +prePI=PI; +prePI(n_v+stochurows)=0; % stochastic rows of PI are set to zero. Note: the first n_v rows include stochastic variables but their derivatives w.r.t are ones or zeros. +stochPI=PI; +stochPI([1:n_v,n_v+preurows])=0; % nonstochastic rows are set to zero. See the note above. + +[model.prePI_ind_u]=getderivs_tensor(prePI,z,max(order+1,pert_order),symparams,['prePI' uname]); +[model.stochPI_ind_u]=getderivs_tensor(stochPI,z,max(order+1,pert_order),symparams,['stochPI' uname]); + +prefuvars=find(sum(uu(logical(sum(logical(tilfu(prefrows,:)~=0),1)~=0),:),1)); +stochfuvars=find(sum(uu(logical(sum(logical(tilfu(stochfrows,:)~=0),1)~=0),:),1)); + +Phiuvars=find(sum(uu(logical(sum(logical(tilPhiu~=0),1)~=0),:),1)); + +model.prefuvars=prefuvars; +model.stochfuvars=stochfuvars; +model.Phiuvars=Phiuvars; + +prefzvars=[prefvars,n_v+prefuvars]; +stochfzvars=[stochfvars,n_v+stochfuvars]; + +Phizvars=[Phivars,n_v+Phiuvars]; + +model.n_prefzvars=length(prefzvars); +model.n_stochfzvars=length(stochfzvars); +model.n_Phizvars=length(Phizvars); + +[model.stochtilf_ind_u,model.stoch_n]=gen_chainderivs_tensor(tilf(stochfrows),v(stochfvars),u(stochfuvars),pi_(stochfuvars),max(order+1,pert_order),symparams,['stochtilf' fname]); +[model.pretilf_ind_u,model.pre_n]=gen_chainderivs_tensor(tilf(prefrows),v(prefvars),u(prefuvars),pi_(prefuvars),max(order+1,pert_order),symparams,['pretilf' fname]); + +[model.Phi_ind_u,model.Phi_n]=gen_chainderivs_tensor(Phi,v(Phivars),u(Phiuvars),pi_(Phiuvars),max(order+1,pert_order),symparams,['Phi' fname]); + +% Create an m file for Phi and its derivatives w.r.t x +gen_fun_vec(subsPhi,symparams,z(Phizvars),['Phi' uname],'row'); + +gen_fun_vec(new_eta,symparams,z(Phizvars),['new_eta' uname],'row'); + + +% Store variables in struct model +model.prefrows=prefrows; +model.stochfrows=stochfrows; +model.prefvars=prefvars; +model.stochfvars=stochfvars; +model.stochexog=stochexog; +model.preexog=preexog; +model.n_stochexog=length(stochexog); +model.n_preexog=length(preexog); +model.stochfzvars=stochfzvars; +model.prefzvars=prefzvars; +model.Phizvars=Phizvars; +model.Phivars=Phivars; + +model.n_theta=n_theta; +model.n_b=n_b; + +model.n_f=n_f; +model.n_x=n_x; +model.n_y=n_y; +model.n_x1=n_x1; +model.n_x2=n_x2; + +model.n_v=n_v; +model.n_z=n_z; +model.n_u=n_u; + +model.n_ind=1; + +model.U=cell(4,1); +model.W=cell(4,1); +maxorder=4; +for i=2:maxorder+1 + [model.U{i},model.W{i}]=create_UW(n_x,i); +end + +model.stochzz=zz(model.stochfzvars,model.stochfzvars); +model.prezz=zz(model.prefzvars,model.prefzvars); + +model.Phizz=zz(model.Phizvars,model.Phizvars); + +model.stochtilfz=tilfz(model.stochfrows,model.stochfzvars); +model.pretilfz=tilfz(model.prefrows,model.prefzvars); + +model.tilPhiz=tilPhiz(:,Phizvars); +model.maxtilPhiz=intarray(max(tilPhiz(:))); + +% calculate some big matrices now + +if order>=3 + save('tempfile') + n_prefvars=length(prefvars); + clearvars -except n_prefvars + + if n_prefvars>0 + [ tempM ] = chainsM( n_prefvars,4 ); + else + tempM=cell(4,1); + end + load('tempfile') + model.prefvars_chain4c_M2=tempM{2}; + model.prefvars_chain4c_M3=tempM{3}; + model.prefvars_chain4c_M4=tempM{4}; + clear tempM + + save('tempfile') + n_stochfvars=length(stochfvars); + clearvars -except n_stochfvars + + if n_stochfvars>0 + [ tempM ] = chainsM( n_stochfvars,4 ); + else + tempM=cell(4,1); + end + load('tempfile') + model.stochfvars_chain4c_M2=tempM{2}; + model.stochfvars_chain4c_M3=tempM{3}; + model.stochfvars_chain4c_M4=tempM{4}; + clear tempM + + save('tempfile') + n_Phivars=length(Phivars); + clearvars -except n_Phivars + + if n_Phivars>0 + [ tempM ] = chainsM( n_Phivars,4 ); + else + tempM=cell(4,1); + end + load('tempfile') + model.Phivars_chain4c_M2=tempM{2}; + model.Phivars_chain4c_M3=tempM{3}; + model.Phivars_chain4c_M4=tempM{4}; + clear tempM + + + delete('tempfile.mat') +end + +if order>=4 + save('tempfile') + n_prefvars=length(prefvars); + clearvars -except n_prefvars + + if n_prefvars>0 + [ tempM ] = chainsM( n_prefvars,5 ); + else + tempM=cell(6,1); + end + load('tempfile') + model.prefvars_chain5c_M1=tempM{1}; + model.prefvars_chain5c_M2=tempM{2}; + model.prefvars_chain5c_M3=tempM{3}; + model.prefvars_chain5c_M4=tempM{4}; + model.prefvars_chain5c_M5=tempM{5}; + model.prefvars_chain5c_M6=tempM{6}; + + clear tempM + + save('tempfile') + n_stochfvars=length(stochfvars); + clearvars -except n_stochfvars + + if n_stochfvars>0 + [ tempM ] = chainsM( n_stochfvars,5 ); + else + tempM=cell(6,1); + end + load('tempfile') + model.stochfvars_chain5c_M1=tempM{1}; + model.stochfvars_chain5c_M2=tempM{2}; + model.stochfvars_chain5c_M3=tempM{3}; + model.stochfvars_chain5c_M4=tempM{4}; + model.stochfvars_chain5c_M5=tempM{5}; + model.stochfvars_chain5c_M6=tempM{6}; + + clear tempM + + save('tempfile') + n_Phivars=length(Phivars); + clearvars -except n_Phivars + + if n_Phivars>0 + [ tempM ] = chainsM( n_Phivars,5 ); + else + tempM=cell(6,1); + end + load('tempfile') + model.Phivars_chain5c_M1=tempM{1}; + model.Phivars_chain5c_M2=tempM{2}; + model.Phivars_chain5c_M3=tempM{3}; + model.Phivars_chain5c_M4=tempM{4}; + model.Phivars_chain5c_M5=tempM{5}; + model.Phivars_chain5c_M6=tempM{6}; + + clear tempM + + + delete('tempfile.mat') +end + +model.count_pre_n=model.pre_n-1; +if model.count_pre_n<0 + model.count_pre_n=0; +end + +model.count_stoch_n=model.stoch_n-1; +if model.count_stoch_n<0 + model.count_stoch_n=0; +end + +totindi=5+8; +totindi=totindi+model.count_pre_n*(1+3+4+6)+1+4+6+9; +totindi=totindi+3; +totindi=totindi+4; +totindi=totindi+2; +totindi=totindi+2; +totindi=totindi+1; +totindi=totindi+9; +totindi=totindi+8; +totindi=totindi+8+model.count_stoch_n*(1+3+4+6)+1+4+6+9; +totindi=totindi+2; +totindi=totindi+9; +totindi=totindi+7; + +model.totindi=totindi; + +rehash; + +model.symparams=symparams; + +cd(currentFolder) \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/shift_center.m b/105/replication_package/solution_methods/taylor_projection/shift_center.m new file mode 100644 index 0000000000000000000000000000000000000000..91a027ef00bba2a737180f01dcaf0b5db90e226f --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/shift_center.m @@ -0,0 +1,76 @@ +function [ coeffs ] = shift_center( coeffs,c0,newc0,order,model ) +%The function shifts the center of the approximating power series from c0 +%to newc0. +% coeffs: vector of Polynomial coefficients +% c0: old center of power series +% newc0: new center of power series +% n_f: number of power series +% n_b: number of terms in power series (excluding symmetric monomials) +% n_x: number of variables +% order: Polynomial order of power series +% U: cell variable with compression matrices +% W: cell variable with uncompression matrices +% +% � Copyright, Oren Levintal, June 13, 2016. + + +n_b=model.n_b; +n_x=model.n_x; +U=model.U; +W=model.W; + +coeffs=reshape(coeffs,[],n_b); +GH0=coeffs(:,1); +if order==1 + GH1=coeffs(:,2:1+n_x); + [ GH0,GH1 ] = shiftpoly( newc0,c0,[],GH0,GH1 ); + coeffs=[GH0,GH1]; + coeffs=coeffs(:); +elseif order==2 + GH1=coeffs(:,2:1+n_x); + GH2=coeffs(:,2+n_x:1+n_x+model.unique2)*W{2}; + [ GH0,GH1,GH2 ] = shiftpoly( newc0,c0,[],GH0,GH1,GH2 ); + coeffs=[GH0,GH1,GH2*U{2}]; + coeffs=coeffs(:); +elseif order==3 + GH1=coeffs(:,2:1+n_x); + GH2=coeffs(:,2+n_x:1+n_x+model.unique2)*W{2}; + GH3=coeffs(:,2+n_x+model.unique2:1+n_x+model.unique2+model.unique3)*W{3}; + [ GH0,GH1,GH2,GH3 ] = shiftpoly( newc0,c0,[],GH0,GH1,GH2,GH3 ); + coeffs=[GH0,GH1,GH2*U{2},GH3*U{3}]; + coeffs=coeffs(:); +elseif order==4 + GH1=coeffs(:,2:1+n_x); + GH2=coeffs(:,2+n_x:1+n_x+model.unique2)*W{2}; + GH3=coeffs(:,2+n_x+model.unique2:1+n_x+model.unique2+model.unique3)*W{3}; + GH4=coeffs(:,2+n_x+model.unique2+model.unique3:1+n_x+model.unique2+model.unique3+model.unique4)*W{4}; + [ GH0,GH1,GH2,GH3,GH4 ] = shiftpoly( newc0,c0,[],GH0,GH1,GH2,GH3,GH4 ); + coeffs=[GH0,GH1,GH2*U{2},GH3*U{3},GH4*U{4}]; + coeffs=coeffs(:); +elseif order==5 + GH1=coeffs(:,2:1+n_x); + GH2=coeffs(:,nchoosek(n_x+1,1)+(1:nchoosek(n_x+1,2)))*W{2}; + GH3=coeffs(:,nchoosek(n_x+2,2)+(1:nchoosek(n_x+2,3)))*W{3}; + GH4=coeffs(:,nchoosek(n_x+3,3)+(1:nchoosek(n_x+3,4)))*W{4}; + GH5=coeffs(:,nchoosek(n_x+4,4)+(1:nchoosek(n_x+4,5)))*W{5}; + [ GH0,GH1,GH2,GH3,GH4,GH5 ] = shiftpoly( newc0,c0,[],GH0,GH1,GH2,GH3,GH4,GH5 ); + coeffs=[GH0,GH1,GH2*U{2},GH3*U{3},GH4*U{4},GH5*U{5}]; + coeffs=coeffs(:); +elseif order==6 + GH1=coeffs(:,2:1+n_x); + GH2=coeffs(:,nchoosek(n_x+1,1)+(1:nchoosek(n_x+1,2)))*W{2}; + GH3=coeffs(:,nchoosek(n_x+2,2)+(1:nchoosek(n_x+2,3)))*W{3}; + GH4=coeffs(:,nchoosek(n_x+3,3)+(1:nchoosek(n_x+3,4)))*W{4}; + GH5=coeffs(:,nchoosek(n_x+4,4)+(1:nchoosek(n_x+4,5)))*W{5}; + GH6=coeffs(:,nchoosek(n_x+5,5)+(1:nchoosek(n_x+5,6)))*W{6}; + [ GH0,GH1,GH2,GH3,GH4,GH5,GH6 ] = shiftpoly( newc0,c0,[],GH0,GH1,GH2,GH3,GH4,GH5,GH6 ); + coeffs=[GH0,GH1,GH2*U{2},GH3*U{3},GH4*U{4},GH5*U{5},GH6*U{6}]; + coeffs=coeffs(:); +elseif order>=7 + error('order must not be larger than 6') +end + +coeffs=full(coeffs); + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/shiftpoly.m b/105/replication_package/solution_methods/taylor_projection/shiftpoly.m new file mode 100644 index 0000000000000000000000000000000000000000..0dbf216e2bd87408a20675871b26add3815ce5ea --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/shiftpoly.m @@ -0,0 +1,71 @@ +function [ G0,varargout ] = shiftpoly( x,c,index,varargin ) +%[newG0,newG1,...]=shiftpoly(x,c,index,G0,G1,...) shifts the center of a given +%polynomial from c to x. The coefficient matrices of the given Polynomial +%are G0,G1,G2,..... Note that G2,G3,... must have symmetric columns. +%Namely, these are the coefficients of the Taylor series about c. +%The output is the coefficients of the new Polynomial. +%If index is empty, the variables of the output Polynomial are the same as +%the original Polynomial. To get a Polynomial in a subset of the original +%variables (treating all other vars as constant), specify the index of the +%new variables in index. +% +% � Copyright, Oren Levintal, June 13, 2016. +% changed on November 29, 2016 - x and c are vectorized. + +x=x(:); +c=c(:); + +N=length(varargin)-1; +n_x=length(x); +if isempty(index) + index=1:n_x; +end + +coeffs=cell2mat(varargin); + +% create cell +cellX=cell(1,N+1); +m=0; +for i=1:N+1 + newm=m+n_x^(i-1); + cellX{i}=sparse(size(coeffs,2),n_x^(i-1)); + cellX{i}(m+1:newm,:)=factorial(i-1)*speye(n_x^(i-1)); + m=newm; +end + +x_c=x-c; +lastkron=1; +m=1; +for i=1:N % i is the Kronecker power of x-c. All N powers need to be calculated + newm=m+n_x^i; + lastkron=kron(lastkron,x_c); + mj=m; + for j=1:N+1-i % j-1 is the derivative order. The i Kronecker power appears in derivatives up to order N+1-i + + newmj=mj+n_x^(i+j-1); + if j==1 + A=1; + else + A=prod(i+1:i+j-1); + end + cellX{j}(mj+1:newmj,:)=A*kron(lastkron,speye(n_x^(j-1))); + mj=newmj; + end + m=newm; +end + +xtilx=speye(n_x); +xtilx=xtilx(:,index); + +G0=coeffs*cellX{1}; + +varargout=cell(1,N); +lastkron=1; +for i=1:N + lastkron=kron(lastkron,xtilx); + varargout{i}=coeffs*cellX{i+1}*lastkron/factorial(i); + +end + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/subsf.m b/105/replication_package/solution_methods/taylor_projection/subsf.m new file mode 100644 index 0000000000000000000000000000000000000000..801aa6d36a7f14a4ef328bd23150bf642cb85801 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/subsf.m @@ -0,0 +1,13 @@ +function [ newf ] = subsf( f,auxvars,auxfuns ) +%Substitute out auxiliary variables. +% +% � Copyright, Oren Levintal, June 13, 2016. + +f_temp=[]; newf=f; +while ~isequal(f_temp,newf) + f_temp=newf; + newf=subs(newf,auxvars,auxfuns); +end + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/tp.m b/105/replication_package/solution_methods/taylor_projection/tp.m new file mode 100644 index 0000000000000000000000000000000000000000..538299eaa8e9f85bb7252e298a2029c0c722febb --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/tp.m @@ -0,0 +1,1139 @@ +function [T,J,model]=tp(coeffs,x0,model,params,eta,c0,nep,P,varargin) + +% This function computes the nonlinear system of Taylor projection and the +% Jacobian. +% Input args: coeffs=Polynomial coefficients (denoted Theta in the paper). +% The coefficients should be provided as a vector of unique Taylor +% coefficients. +% x0=point at which the system is evaluated +% model=variable generated by prepare_tp +% params=parameters of the model +% eta=the matrix eta +% c0=center of the power series. +% nep=a matrix of the realizations of the shocks. each row is a different shock. +% P=a vector of probabilities (weights) of each realization. +% varargin=option to add precomputed variables that are independent of coeffs. +% Output args: T=a vector of the model conditions and the derivatives. +% J=Jacobian of T. +% model=the variable model updated. +% +% � Copyright, Oren Levintal, June 13, 2016. + +order=model.order(1); + +% make sure all inputs are full +coeffs=full(coeffs); +x0=full(x0); +params=full(params); +eta=full(eta); +c0=full(c0); +nep=full(nep); +P=full(P); + +c0_old=c0; +c0_new=x0; + +if c0~=x0 % shift the center of the power series to x0 + warning('shifting center, Jacobian may be incorrect') + [ coeffs ] = shift_center( coeffs,c0_old,c0_new,order,model ); + coeffs=full(coeffs); + c0=c0_new; +end + +if isempty(varargin) + [ g_theta,h_theta,gx_theta,hx_theta,gxxc_theta,hxxc_theta,gxxxc_theta,hxxxc_theta,model ] = precompute(x0,c0,model,order ); +else + g_theta=varargin{1}; + h_theta=varargin{2}; + gx_theta=varargin{3}; + hx_theta=varargin{4}; + gxxc_theta=varargin{5}; + hxxc_theta=varargin{6}; + gxxxc_theta=varargin{7}; + hxxxc_theta=varargin{8}; +end + +indi=5; %count indi from 5, due to precompute. + +if ~isfield(model,'jacobian') + model.jacobian='exact'; +end +if ~isfield(model,'n_ind') + n_ind=1; +else + n_ind=model.n_ind; +end +if ~isfield(model,'maxload') + maxload=intarray(length(P)); +else + maxload=intarray(model.maxload); +end + +params=params(:); +P=P(:); + +n_f=model.n_f; % no. of model conditions +n_x=model.n_x; % no. of state variables +n_y=model.n_y; % no. of control variables +n_x2=model.n_x2; % no. of exogenous state variables +n_x1=model.n_x1; % no. of endogenous state variabels +n_v=model.n_v; % total no. of variables v=(yp,y,xp,x) +n_theta=model.n_theta; % no. of Polynomial coefficients +n_b=model.n_b; % no. of terms in the basis function +n_nodes=size(nep,2); % no. nodes in the discrete shocks +n_z=model.n_z; % no. of auxiliary variables + +coeffs=reshape(coeffs,n_f,n_b); +g_coeffs=coeffs(1:n_y,:); + +%create stochy: index of future control variables that affect stochastic equations +tempv=zeros(n_v,1); +tempv(model.stochfvars)=model.stochfvars; +tempv(n_y+1:end)=0; +stochy=nonzeros(tempv); +n_stochy=length(stochy); +stochg_coeffs=coeffs(stochy,:); + +% U=model.U; + +unique2=[]; unique3=[]; + +prefvars=model.prefvars; % index of variables that affect nonstochastic equations. +stochfvars=model.stochfvars;% index of variables that affect stochastic equations. +n_prefvars=length(prefvars); +n_stochfvars=length(stochfvars); + +% lower block of v_theta, vx_theta and so on + +v_theta_lower_terms=vconcat(vconcat(g_theta,h_theta),sptensor(n_x,n_theta)); + +if order>=1 + vx_theta_lower_terms=vconcat(vconcat(gx_theta,hx_theta),sptensor(n_x,[n_x,n_theta])); +end +if order>=2 + unique2=model.unique2; + vxxc_theta_lower_terms=vconcat(vconcat(gxxc_theta,hxxc_theta),sptensor(n_x,[unique2,n_theta])); +end +if order>=3 + unique3=model.unique3; + vxxxc_theta_lower_terms=vconcat(vconcat(gxxxc_theta,hxxxc_theta),sptensor(n_x,[unique3,n_theta])); +end + +% current state +nx=x0; + +% evaluate policy functions +g=coeffs(1:n_y,1);% only constant term is nonzero +h1=coeffs(n_y+1:end,1); +h=zeros(n_x,1); + +% derivatives of policy functions at x0 (assuming c0=x0) +if order>=1 + gx=coeffs(1:n_y,2:1+n_x); + h1x=coeffs(n_y+1:end,2:1+n_x); +end + +if order>=2 + gxxc=coeffs(1:n_y,2+n_x:1+n_x+unique2)*2; + h1xxc=coeffs(n_y+1:end,2+n_x:1+n_x+unique2)*2; +end +if order>=3 + gxxxc=coeffs(1:n_y,2+n_x+unique2:1+n_x+unique2+unique3)*6; + h1xxxc=coeffs(n_y+1:end,2+n_x+unique2:1+n_x+unique2+unique3)*6; +end + +% control vars +ny=g; + +% STEP 1: COMPUTE NONSTOCHASTIC EQUATIONS AND DERIVATIVES, AND THEIR JACOBIAN + +% build h(x) +h(1:n_x1,1)=h1; % predetermined endogenous state vars +h(n_x1+1:end,1)=Phi_fun(nx,params); % expected value of exogenous state vars. shocks are added later + +% expected value of next period state variables. +nxp=h; + +% derivatives of h at x0 +if order>=1 + hx=vconcat(sptensor(h1x),Phi_d_c1(nx(:)',params,model.Phi_indc)); +end +if order>=2 + hxxc=vconcat(sptensor(h1xxc),Phi_d_c2(nx(:)',params,model.Phi_indc)); +end +if order>=3 + hxxxc=vconcat(sptensor(h1xxxc),Phi_d_c3(nx(:)',params,model.Phi_indc)); +end + +% evaluate residuals R0 +nv=[zeros(n_y,1);ny;nxp;nx]; % model variables, yp are zero for now, and nxp is an expected value. stochastic components will be added later. + +n_u=model.n_u; +nu=zeros(n_u,1); +npreu=preu_fun(nv(model.preuvars),params); % all predetermined u +nu(model.preurows)=npreu; +nz=[nv;nu]; % auxiliary variables +pref=pretilf_fun(nz(model.pretilfzvars),params); % since i already have z, i use pretilf to evaluate f. + + +% compute derivatives of prePI and pretilf w.r.t z (prePI=nonstochastic rows of PI, pretilf=nonstochastic rows of f) + +prePIz_full=prePI_d1(nz',params,model.prePI_ind_u); +pretilfz=pretilf_tilf_d1([nv(prefvars);nu(model.prefuvars)]',params,model.pretilf_ind_u); +if order>=1 + prePIzz_full=prePI_d2(nz',params,model.prePI_ind_u); + pretilfzz=pretilf_tilf_d2([nv(prefvars);nu(model.prefuvars)]',params,model.pretilf_ind_u); +end +if order>=2 + prePIzzz_full=prePI_d3(nz',params,model.prePI_ind_u); + pretilfzzz=pretilf_tilf_d3([nv(prefvars);nu(model.prefuvars)]',params,model.pretilf_ind_u); +end +if order>=3 + prePIzzzz_full=prePI_d4(nz',params,model.prePI_ind_u); + pretilfzzzz=pretilf_tilf_d4([nv(prefvars);nu(model.prefuvars)]',params,model.pretilf_ind_u); +end + +% extract derivatives of prePI w.r.t v from prePIz, prePIzz, ... +if order>=0 + [prePIz,model.ind{indi}]=extract(prePIz_full,model.prefzvars,model.prefzvars,0,model.ind{indi}); + indi=indi+1; + [prePIv,model.ind{indi}]=extract(prePIz_full,model.prefzvars,model.prefvars,0,model.ind{indi}); + indi=indi+1; +end +if order>=1 + [prePIzz,model.ind{indi}]=extract(prePIzz_full,model.prefzvars,model.prefzvars,0,model.ind{indi}); + indi=indi+1; + [prePIvvc,model.ind{indi}]=extract(prePIzz_full,model.prefzvars,model.prefvars,1,model.ind{indi}); + indi=indi+1; +end +if order>=2 + [prePIzzz,model.ind{indi}]=extract(prePIzzz_full,model.prefzvars,model.prefzvars,0,model.ind{indi}); + indi=indi+1; + [prePIvvvc,model.ind{indi}]=extract(prePIzzz_full,model.prefzvars,model.prefvars,1,model.ind{indi}); + indi=indi+1; + if ~isfield(model,'prefvars_chain3c_M2') + [ tempM ] = chainsM( n_prefvars,3 ); + model.prefvars_chain3c_M2=tempM{2}; + clear tempM + end +end +if order>=3 + [prePIzzzz,model.ind{indi}]=extract(prePIzzzz_full,model.prefzvars,model.prefzvars,0,model.ind{indi}); + indi=indi+1; + [prePIvvvvc,model.ind{indi}]=extract(prePIzzzz_full,model.prefzvars,model.prefvars,1,model.ind{indi}); + indi=indi+1; + if ~isfield(model,'prefvars_chain4c_M2') + [ tempM ] = chainsM( n_prefvars,4 ); + model.prefvars_chain4c_M2=tempM{2}; + model.prefvars_chain4c_M3=tempM{3}; + model.prefvars_chain4c_M4=tempM{4}; + clear tempM + end +end + + +% Use high order chain rules to compute derivatives of prePI w.r.t v +totindi=5+8; +if order==0 + indi=totindi; + for i=2:model.pre_n + [prePIv,model.ind{indi}]=chain1_tensor(prePIz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [prefv,model.ind{indi}]=chain1_tensor(pretilfz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; +elseif order==1 + indi=totindi+(model.pre_n-1)*(1)+1; + for i=2:model.pre_n + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + [prePIvvc,model.ind{indi}]=chain2c_tensor(prePIz,prePIzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIv,model.ind{indi}]=chain1_tensor(prePIz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + + [prefv,model.ind{indi}]=chain1_tensor(pretilfz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvc,model.ind{indi}]=chain2c_tensor(pretilfz,pretilfzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [ prefvv,model.ind{indi} ] = uncompressderivs( prefvvc,2,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + +elseif order==2 + indi=totindi+(model.pre_n-1)*(1+3)+1+4; + for i=2:model.pre_n + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + [prePIvvvc,model.ind{indi}]=chain3c_tensor(prePIz,prePIzz,prePIzzz,... + prePIv,prePIvvc,prePIvvvc,model.prefvars_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIvvc,model.ind{indi}]=chain2c_tensor(prePIz,prePIzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIv,model.ind{indi}]=chain1_tensor(prePIz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + + [prefv,model.ind{indi}]=chain1_tensor(pretilfz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvc,model.ind{indi}]=chain2c_tensor(pretilfz,pretilfzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvvc,model.ind{indi}]=chain3c_tensor(pretilfz,pretilfzz,pretilfzzz,... + prePIv,prePIvvc,prePIvvvc,... + model.prefvars_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [ prefvv,model.ind{indi} ] = uncompressderivs( prefvvc,2,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + + [ prefvvv,model.ind{indi} ] = uncompressderivs( prefvvvc,3,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + +elseif order==3 + indi=totindi+(model.pre_n-1)*(1+3+4)+1+4+6; + for i=2:model.pre_n + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + [prePIvvc,model.ind{indi}]=colsort(prePIvvc,model.ind{indi}); + indi=indi+1; + [prePIvvvvc,model.ind{indi}]=chain4c_tensor(prePIz,prePIzz,prePIzzz,prePIzzzz,... + prePIv,prePIvvc,prePIvvvc,prePIvvvvc,... + model.prefvars_chain4c_M2,model.prefvars_chain4c_M3,model.prefvars_chain4c_M4,... + model.ind{indi},n_ind,maxload,'vec',model.prezz,model.maxzz); + indi=indi+1; + [prePIvvvc,model.ind{indi}]=chain3c_tensor(prePIz,prePIzz,prePIzzz,... + prePIv,prePIvvc,prePIvvvc,model.prefvars_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIvvc,model.ind{indi}]=chain2c_tensor(prePIz,prePIzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIv,model.ind{indi}]=chain1_tensor(prePIz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + [prePIvvc,model.ind{indi}]=colsort(prePIvvc,model.ind{indi}); + indi=indi+1; + + [prefv,model.ind{indi}]=chain1_tensor(pretilfz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [prefvvc,model.ind{indi}]=chain2c_tensor(pretilfz,pretilfzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvvc,model.ind{indi}]=chain3c_tensor(pretilfz,pretilfzz,pretilfzzz,... + prePIv,prePIvvc,prePIvvvc,... + model.prefvars_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvvvc,model.ind{indi}]=chain4c_tensor(pretilfz,pretilfzz,pretilfzzz,pretilfzzzz,... + prePIv,prePIvvc,prePIvvvc,prePIvvvvc,... + model.prefvars_chain4c_M2,model.prefvars_chain4c_M3,model.prefvars_chain4c_M4,... + model.ind{indi},n_ind,maxload,'vec',model.pretilfz,model.maxtilfz); + indi=indi+1; + + [ prefvv,model.ind{indi} ] = uncompressderivs( prefvvc,2,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + + [ prefvvv,model.ind{indi} ] = uncompressderivs( prefvvvc,3,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + + [ prefvvvv,model.ind{indi} ] = uncompressderivs( prefvvvvc,4,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; +end +totindi=totindi+(model.pre_n-1)*(1+3+4+6)+1+4+6+9; +indi=totindi; + + +preR0=pref; + +% compute R1 (first order derivatives of R w.r.t x) +if order>=1 + vx=vconcat(sptensor(n_y,n_x),sptensor(gx)); + vx=vconcat(vx,hx); + vx=vconcat(vx,spteye(n_x)); + + prevx=takerows(vx,prefvars); + if isempty(pref) + preR1=zeros(0,n_x); + else + [preR1,model.ind{indi}]=chain1_tensor(prefv,prevx,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + preR1=sptensor2spmat(preR1); + end +end + +% compute R2 (second order derivatives of R w.r.t x) +if order>=2 + vxxc=vconcat(sptensor(n_y,unique2),sptensor(gxxc)); + vxxc=vconcat(vxxc,hxxc); + vxxc=vconcat(vxxc,sptensor(n_x,unique2)); + prevxxc=takerows(vxxc,prefvars); + prevx=colsort(prevx); + if isempty(pref) + preR2=zeros(0,unique2); + else + [preR2,model.ind{indi}]=chain2c_tensor(prefv,prefvv,prevx,prevxxc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + preR2=sptensor2spmat(preR2); + end +end + +% compute R3 (third order derivatives of R w.r.t x) +if order>=3 + vxxxc=vconcat(sptensor(n_y,unique3),sptensor(gxxxc)); + vxxxc=vconcat(vxxxc,hxxxc); + vxxxc=vconcat(vxxxc,sptensor(n_x,unique3)); + prevxxxc=takerows(vxxxc,prefvars); + + if ~isfield(model,'x_chain3c_M2') + [~,W2x]=create_UW(n_x,2); + [U3x,~]=create_UW(n_x,3); + OMEGAx=create_OMEGA(n_x,3); + model.x_chain3c_M2=spmat2sptensor(kron(speye(n_x),W2x)*OMEGAx.OMEGA1*U3x); + clear W2x U3x + end + + if isempty(pref) + preR3=zeros(0,unique3); + else + [preR3,model.ind{indi}]=chain3c_tensor(prefv,prefvv,prefvvv,prevx,prevxxc,prevxxxc,model.x_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + preR3=sptensor2spmat(preR3); + end + +end +totindi=totindi+3; +indi=totindi; +% Jacobian of the nonstochastic equations and derivatives + +v_theta=vconcat(sptensor(n_y,n_theta),v_theta_lower_terms); +prev_theta=takerows(v_theta,prefvars); + +[ preJ0,model.ind{indi} ] = chain0_theta_tensor( prefv,prev_theta,model.ind{indi},n_ind,maxload,'vec' ); +indi=indi+1; +% preJ0=sptensor2spmat(preJ0); + +if order>=1 + vx_theta=vconcat(sptensor(n_y,[n_x,n_theta]),vx_theta_lower_terms); + prevx_theta=takerows(vx_theta,prefvars); + prevx_theta=unfold(prevx_theta); + if isempty(pref) +% preJ1=zeros(0,n_x*n_theta); + preJ1=sptensor(zeros(0,1),zeros(0,2),zeros(1,0),0,[n_x,n_theta]); + else + [ preJ1,model.ind{indi} ] = chain1_theta_tensor( prefv,prefvv,... + prevx,prev_theta,prevx_theta,... + model.ind{indi},n_ind,maxload,'vec' ); + indi=indi+1; +% preJ1=sptensor2spmat(preJ1); + end +end +if order>=2 + vxxc_theta=vconcat(sptensor(n_y,[unique2,n_theta]),vxxc_theta_lower_terms); + prevxxc_theta=takerows(vxxc_theta,prefvars); + prevxxc_theta=unfold(prevxxc_theta); + + if ~isfield(model,'chain2c_theta_M2') + GAMMA=create_GAMMA(n_x,n_theta,2); + U2=create_UW(n_x,2); + model.chain2c_theta_M2=spmat2sptensor(GAMMA.GAMMA1*U2); + clear GAMMA U2 + end + + if isempty(pref) +% preJ2=zeros(0,unique2*n_theta); + preJ2=sptensor(zeros(0,1),zeros(0,2),zeros(1,0),0,[unique2,n_theta]); + else + [ preJ2,model.ind{indi} ] = chain2c_theta_tensor( prefv,prefvv,prefvvv,... + prevx,prevxxc,... + prev_theta,prevx_theta,prevxxc_theta,... + model.chain2c_theta_M2,... + model.ind{indi},n_ind,maxload,'vec' ); + indi=indi+1; +% preJ2=sptensor2spmat(preJ2); + end +end +if order>=3 + vxxxc_theta=vconcat(sptensor(n_y,[unique3,n_theta]),vxxxc_theta_lower_terms); + prevxxxc_theta=takerows(vxxxc_theta,prefvars); + prevxxxc_theta=unfold(prevxxxc_theta); + + if ~isfield(model,'chain3c_theta_M2') + GAMMA=create_GAMMA(n_x,n_theta,3); + [~,W2]=create_UW(n_x,2); + U3=create_UW(n_x,3); + model.chain3c_theta_M2=spmat2sptensor(kron(W2,speye(n_x))*GAMMA.GAMMA2*U3); + model.chain3c_theta_M3=spmat2sptensor(kron(speye(n_x),W2)*GAMMA.GAMMA3*U3); + model.chain3c_theta_M4=spmat2sptensor(kron(speye(n_x),W2)*GAMMA.GAMMA4*U3); + tempind=1:unique2*n_x; + tempmat=speye(unique2*n_x); + model.chain3c_theta_M5=spmat2sptensor(tempmat(:,permute(reshape(tempind,n_x,unique2),[2,1]))*kron(speye(n_x),W2)*GAMMA.GAMMA5*U3); + clear GAMMA W2 U3 GAMMA + + end + + if isempty(pref) +% preJ3=zeros(0,unique3*n_theta); + preJ3=sptensor(zeros(0,1),zeros(0,2),zeros(1,0),0,[unique3,n_theta]); + else + [ preJ3,model.ind{indi} ] = chain3c_theta_tensor( prefv,prefvv,prefvvv,prefvvvv,... + prevx,prevxxc,prevxxxc,... + prev_theta,prevx_theta,prevxxc_theta,prevxxxc_theta,... + model.chain3c_theta_M2,model.chain3c_theta_M3,model.chain3c_theta_M4,model.chain3c_theta_M5,... + model.ind{indi},n_ind,maxload,'vec' ); + indi=indi+1; +% preJ3=sptensor2spmat(preJ3); + end +end +totindi=totindi+4; +indi=totindi; + +% STEP 2: COMPUTE STOCHASTIC EQUATIONS AND DERIVATIVES, AND THEIR JACOBIAN, +% AND TAKE EXPECTED VALUE + +% prepare vectorized expressions for the stochastic part. + +nx_vec=repmat(nx,1,n_nodes); % n_nodes=the number of nodes of the discrete shocks. + +% next period state +nxp_vec=repmat(h,1,n_nodes)+eta*nep; +nxp_c0_vec=nxp_vec-repmat(c0,1,n_nodes); + +nxp_c0=sptensor(nxp_c0_vec(:,1)); % convert to 1D tensor +nxp_c0.vals=nxp_c0_vec'; % assign the correct values in vals. + +if ~isfield(model,'M2') + model.M2=[]; + model.M3=[]; + model.M3x=[]; + model.TW2=[]; + model.TW3=[]; + if order>=2 + model.M2=fold(spmat2sptensor(model.W{2}*model.W{2}'*model.U{2}'),n_x,n_x); + model.TW2=fold(spmat2sptensor(model.W{2}),n_x,n_x); + model.TW2U2=spmat2sptensor(model.W{2}*model.U{2}); + end + if order>=3 + model.M3=fold(spmat2sptensor(model.W{3}*model.W{3}'*model.U{3}'),n_x,n_x,n_x); + model.M3x=fold(spmat2sptensor(3*model.W{3}*kron(model.W{2}'*model.U{2}',speye(n_x))),n_x,n_x,n_x); + model.TW3=fold(spmat2sptensor(model.W{3}),n_x,n_x,n_x); + model.TW3U3=spmat2sptensor(model.W{3}*model.U{3}); + end +end + +if ~isfield(model,'M3') + model.M3=[]; + model.M3x=[]; + model.TW3=[]; +end + +[Xp_vecT,Xpx_vecT,Xpxx_vecT,Xpxxx_vecT,Xpxxxx_vecT,model.ind{indi}]=create_X_tensor(order,nxp_c0,... + model.M2,model.M3,model.M3x,model.TW2,model.TW3,unique2,unique3,model.ind{indi},n_ind,maxload,'vec'); +indi=indi+1; + +if strcmp(model.jacobian,'approximate') + nx_c0=sptensor(n_x,1); + nx_c0.vals=repmat(nx_c0.vals,n_nodes,1); + [X_vecT,Xx_vecT,Xxx_vecT,Xxxx_vecT,Xxxxx_vecT,model.ind{indi}]=create_X_tensor(order,nx_c0,... + model.M2,model.M3,model.M3x,model.TW2,model.TW3,unique2,unique3,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; +end +totindi=totindi+2; +indi=totindi; + + +gp_vec=g_coeffs*Xp_vecT.vals'; + +stochg_coeffsT=sptensor(stochg_coeffs); +[stochgpx_vecT,model.ind{indi}]=contraction1(stochg_coeffsT,Xpx_vecT,model.ind{indi},n_ind,maxload,'vec'); +indi=indi+1; + +% control vars in t+1 +nyp_vec=gp_vec; + +% evaluate residuals R0 +nv_vec=[nyp_vec;repmat(ny,1,n_nodes);nxp_vec;nx_vec]; +nstochv_vec=nv_vec(stochfvars,:); % stochastic vars. + +nstochu_vec=stochu_fun(nv_vec(model.stochuvars,:),params); % all stochastic u vars +nu_vec=repmat(nu,1,n_nodes); +nu_vec(model.stochurows,:)=nstochu_vec; +nz_vec=[nv_vec;nu_vec]; +stochf_vec=stochtilf_fun(nz_vec(model.stochtilfzvars,:),params); + +% compute derivatives of stochPI and stochtilf w.r.t z + +stochPIz_vec=stochPI_d1(nz_vec',params,model.stochPI_ind_u); +prePIz_full.vals=repmat(prePIz_full.vals,n_nodes,1); + +i1=tfind(prePIz_full); +i2=tfind(stochPIz_vec); +PIz_vec=sptensor([i1;i2],[prePIz_full.cols;stochPIz_vec.cols],[prePIz_full.vals,stochPIz_vec.vals],n_z,[n_z]); +stochtilfz_vec=stochtilf_tilf_d1([nv_vec(stochfvars,:);nu_vec(model.stochfuvars,:)]',params,model.stochtilf_ind_u); + + +if order>=1 + stochPIzz_vec=stochPI_d2(nz_vec',params,model.stochPI_ind_u); + prePIzz_full.vals=repmat(prePIzz_full.vals,n_nodes,1); + + i1=tfind(prePIzz_full); + i2=tfind(stochPIzz_vec); + PIzz_vec=sptensor([i1;i2],[prePIzz_full.cols;stochPIzz_vec.cols],[prePIzz_full.vals,stochPIzz_vec.vals],n_z,[n_z,n_z]); + stochtilfzz_vec=stochtilf_tilf_d2([nv_vec(stochfvars,:);nu_vec(model.stochfuvars,:)]',params,model.stochtilf_ind_u); +end +if order>=2 + stochPIzzz_vec=stochPI_d3(nz_vec',params,model.stochPI_ind_u); + prePIzzz_full.vals=repmat(prePIzzz_full.vals,n_nodes,1); + + i1=tfind(prePIzzz_full); + i2=tfind(stochPIzzz_vec); + PIzzz_vec=sptensor([i1;i2],[prePIzzz_full.cols;stochPIzzz_vec.cols],[prePIzzz_full.vals,stochPIzzz_vec.vals],n_z,[n_z,n_z,n_z]); + stochtilfzzz_vec=stochtilf_tilf_d3([nv_vec(stochfvars,:);nu_vec(model.stochfuvars,:)]',params,model.stochtilf_ind_u); +end +if order>=3 + stochPIzzzz_vec=stochPI_d4(nz_vec',params,model.stochPI_ind_u); + prePIzzzz_full.vals=repmat(prePIzzzz_full.vals,n_nodes,1); + + i1=tfind(prePIzzzz_full); + i2=tfind(stochPIzzzz_vec); + PIzzzz_vec=sptensor([i1;i2],[prePIzzzz_full.cols;stochPIzzzz_vec.cols],[prePIzzzz_full.vals,stochPIzzzz_vec.vals],n_z,[n_z,n_z,n_z,n_z]); + stochtilfzzzz_vec=stochtilf_tilf_d4([nv_vec(stochfvars,:);nu_vec(model.stochfuvars,:)]',params,model.stochtilf_ind_u); +end + +totindi=totindi+1; +indi=totindi; + +EstochR0=stochf_vec*P; %expected value of stochR0 +h_thetaT=h_theta; +[chain0_theta_stochgpT,model.ind{indi}]=contraction1(stochgpx_vecT,h_thetaT,model.ind{indi},n_ind,maxload,'vec'); +indi=indi+1; + +totindi=totindi+1; +indi=totindi; + +% compute derivatives of g w.r.t x at next period state (nxp) +if order>=1 + if order>1 + [stochgpxx_vecT,model.ind{indi}]=contraction1(stochg_coeffsT,Xpxx_vecT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + else + stochgpxx_vecT=sptensor(n_stochy,n_x^2,n_nodes); + end + hxT=hx; + [chain1_stochgpT,model.ind{indi}]=contraction1(stochgpx_vecT,hxT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + hx_thetaT=unfold(hx_theta); + + stochgpxx_vecT=fold(stochgpxx_vecT,n_x,n_x); + [chain1_theta_stochgpT,model.ind{indi}]=chain1_theta_tensor(stochgpx_vecT,stochgpxx_vecT,hxT,h_thetaT,hx_thetaT,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; +end +if order>=2 + if order>2 + [stochgpxxx_vecT,model.ind{indi}]=contraction1(stochg_coeffsT,Xpxxx_vecT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + else + stochgpxxx_vecT=sptensor(n_stochy,n_x^3,n_nodes); + end + hxxcT=hxxc; + hxT=colsort(hxT); + [chain2_stochgpT,model.ind{indi}]=chain2c_tensor(stochgpx_vecT,stochgpxx_vecT,hxT,hxxcT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + hxxc_thetaT=unfold(hxxc_theta); + stochgpxxx_vecT=fold(stochgpxxx_vecT,n_x,n_x,n_x); + + [chain2c_theta_stochgpT,model.ind{indi}]=chain2c_theta_tensor(stochgpx_vecT,stochgpxx_vecT,stochgpxxx_vecT,hxT,hxxcT,h_thetaT,hx_thetaT,hxxc_thetaT,... + model.chain2c_theta_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; +end +if order>=3 + if order>3 + [stochgpxxxx_vecT,model.ind{indi}]=contraction1(stochg_coeffsT,Xpxxxx_vecT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + else + stochgpxxxx_vecT=sptensor(n_stochy,n_x^4,n_nodes); + end + hxxxcT=hxxxc; + + [chain3_stochgpT,model.ind{indi}]=chain3c_tensor(stochgpx_vecT,stochgpxx_vecT,stochgpxxx_vecT,... + hxT,hxxcT,hxxxcT,... + model.x_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + hxxxc_thetaT=unfold(hxxxc_theta); + stochgpxxxx_vecT=fold(stochgpxxxx_vecT,n_x,n_x,n_x,n_x); + + [chain3c_theta_stochgpT,model.ind{indi}]=chain3c_theta_tensor(stochgpx_vecT,stochgpxx_vecT,stochgpxxx_vecT,stochgpxxxx_vecT,... + hxT,hxxcT,hxxxcT,h_thetaT,hx_thetaT,hxxc_thetaT,hxxxc_thetaT,... + model.chain3c_theta_M2,model.chain3c_theta_M3,model.chain3c_theta_M4,model.chain3c_theta_M5,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; +end +totindi=totindi+9; +indi=totindi; + + +% extract PIv,Pivv,... from PIz,PIzz,... +if order>=0 + [stochPIz_vec,model.ind{indi}]=extract(PIz_vec,model.stochfzvars,model.stochfzvars,0,model.ind{indi}); + indi=indi+1; + [stochPIv_vec,model.ind{indi}]=extract(PIz_vec,model.stochfzvars,model.stochfvars,0,model.ind{indi}); + indi=indi+1; +end +if order>=1 + [stochPIzz_vec,model.ind{indi}]=extract(PIzz_vec,model.stochfzvars,model.stochfzvars,0,model.ind{indi}); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=extract(PIzz_vec,model.stochfzvars,model.stochfvars,1,model.ind{indi}); + indi=indi+1; +end +if order>=2 + [stochPIzzz_vec,model.ind{indi}]=extract(PIzzz_vec,model.stochfzvars,model.stochfzvars,0,model.ind{indi}); + indi=indi+1; + [stochPIvvvc_vec,model.ind{indi}]=extract(PIzzz_vec,model.stochfzvars,model.stochfvars,1,model.ind{indi}); + indi=indi+1; + if ~isfield(model,'stochfvars_chain3c_M2') + [ tempM ] = chainsM( n_stochfvars,3 ); + model.stochfvars_chain3c_M2=tempM{2}; + clear tempM + end +end +if order>=3 + [stochPIzzzz_vec,model.ind{indi}]=extract(PIzzzz_vec,model.stochfzvars,model.stochfzvars,0,model.ind{indi}); + indi=indi+1; + [stochPIvvvvc_vec,model.ind{indi}]=extract(PIzzzz_vec,model.stochfzvars,model.stochfvars,1,model.ind{indi}); + indi=indi+1; + if ~isfield(model,'stochfvars_chain4c_M2') + [ tempM ] = chainsM( n_stochfvars,4 ); + model.stochfvars_chain4c_M2=tempM{2}; + model.stochfvars_chain4c_M3=tempM{3}; + model.stochfvars_chain4c_M4=tempM{4}; + clear tempM + end +end +totindi=totindi+8; +indi=totindi; + + +% compute derivatives of stochf w.r.t v by high order chain rules, and +% multiply by the weights P (probabilities). + +if order==0 + indi=totindi; + for i=2:model.stoch_n + [stochPIv_vec,model.ind{indi}]=chain1_tensor(stochPIz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [stochfv_vec,model.ind{indi}]=chain1_tensor(stochtilfz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + stochfv_vec.vals=multcol(stochfv_vec.vals,P); +elseif order==1 + indi=totindi+(model.stoch_n-1)*(1)+1; + for i=2:model.stoch_n + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=chain2c_tensor(stochPIz_vec,stochPIzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIv_vec,model.ind{indi}]=chain1_tensor(stochPIz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + + [stochfv_vec,model.ind{indi}]=chain1_tensor(stochtilfz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvc_vec,model.ind{indi}]=chain2c_tensor(stochtilfz_vec,stochtilfzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + stochfv_vec.vals=multcol(stochfv_vec.vals,P); + stochfvvc_vec.vals=multcol(stochfvvc_vec.vals,P); + + [ stochfvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvc_vec,2,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvc_vec + +elseif order==2 + indi=totindi+(model.stoch_n-1)*(1+3)+1+4; + for i=2:model.stoch_n + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvvc_vec,model.ind{indi}]=chain3c_tensor(stochPIz_vec,stochPIzz_vec,stochPIzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,model.stochfvars_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=chain2c_tensor(stochPIz_vec,stochPIzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIv_vec,model.ind{indi}]=chain1_tensor(stochPIz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + + [stochfv_vec,model.ind{indi}]=chain1_tensor(stochtilfz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvc_vec,model.ind{indi}]=chain2c_tensor(stochtilfz_vec,stochtilfzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvvc_vec,model.ind{indi}]=chain3c_tensor(stochtilfz_vec,stochtilfzz_vec,stochtilfzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,... + model.stochfvars_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + stochfv_vec.vals=multcol(stochfv_vec.vals,P); + stochfvvc_vec.vals=multcol(stochfvvc_vec.vals,P); + stochfvvvc_vec.vals=multcol(stochfvvvc_vec.vals,P); + + [ stochfvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvc_vec,2,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvc_vec + + [ stochfvvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvvc_vec,3,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvvc_vec + +elseif order==3 + indi=totindi+(model.stoch_n-1)*(1+3+4)+1+4+6; + for i=2:model.stoch_n + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=colsort(stochPIvvc_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvvvc_vec,model.ind{indi}]=chain4c_tensor(stochPIz_vec,stochPIzz_vec,stochPIzzz_vec,stochPIzzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,stochPIvvvvc_vec,... + model.stochfvars_chain4c_M2,model.stochfvars_chain4c_M3,model.stochfvars_chain4c_M4,... + model.ind{indi},n_ind,maxload,'vec',model.stochzz,model.maxzz); + indi=indi+1; + [stochPIvvvc_vec,model.ind{indi}]=chain3c_tensor(stochPIz_vec,stochPIzz_vec,stochPIzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,model.stochfvars_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=chain2c_tensor(stochPIz_vec,stochPIzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIv_vec,model.ind{indi}]=chain1_tensor(stochPIz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=colsort(stochPIvvc_vec,model.ind{indi}); + indi=indi+1; + + [stochfv_vec,model.ind{indi}]=chain1_tensor(stochtilfz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [stochfvvc_vec,model.ind{indi}]=chain2c_tensor(stochtilfz_vec,stochtilfzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvvc_vec,model.ind{indi}]=chain3c_tensor(stochtilfz_vec,stochtilfzz_vec,stochtilfzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,... + model.stochfvars_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvvvc_vec,model.ind{indi}]=chain4c_tensor(stochtilfz_vec,stochtilfzz_vec,stochtilfzzz_vec,stochtilfzzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,stochPIvvvvc_vec,... + model.stochfvars_chain4c_M2,model.stochfvars_chain4c_M3,model.stochfvars_chain4c_M4,... + model.ind{indi},n_ind,maxload,'vec',model.stochtilfz,model.maxtilfz); + indi=indi+1; + + stochfv_vec.vals=multcol(stochfv_vec.vals,P); + stochfvvc_vec.vals=multcol(stochfvvc_vec.vals,P); + stochfvvvc_vec.vals=multcol(stochfvvvc_vec.vals,P); + stochfvvvvc_vec.vals=multcol(stochfvvvvc_vec.vals,P); + + [ stochfvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvc_vec,2,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvc_vec + + [ stochfvvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvvc_vec,3,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvvc_vec + + [ stochfvvvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvvvc_vec,4,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvvvc_vec + +end +totindi=totindi+8+(model.stoch_n-1)*(1+3+4+6)+1+4+6+9; +indi=totindi; + +temp=reshape(1:n_theta,n_f,n_b); +stochtheta=temp(stochy,:); +stochtheta=stochtheta(:); +n_stochtheta=length(stochtheta); + +% exact/approximate Jacobian of gp,gpx,... +IstochyT=spteye(n_stochy); +if strcmp(model.jacobian,'exact') + [stochgp_stochtheta_vecT,model.ind{indi}]=tkron(ttranspose(Xp_vecT),IstochyT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; +else + [stochgp_stochtheta_vecT,model.ind{indi}]=tkron(ttranspose(X_vecT),IstochyT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; +end + +nnzgp_theta_vecT=unfold(changecols(changerows(stochgp_stochtheta_vecT,stochy,n_y),stochy,n_f,1)); %n_y,n_theta with only nnz values +nnzchain0_theta_gpT=changerows(chain0_theta_stochgpT,stochy,n_y); + +v_theta_lower_terms_vecT=v_theta_lower_terms; +v_theta_lower_terms_vecT.vals=repmat(v_theta_lower_terms_vecT.vals,n_nodes,1); + +v_theta_vecT=vconcat(tplus(nnzchain0_theta_gpT,nnzgp_theta_vecT,maxload),v_theta_lower_terms_vecT); +clear nnzchain0_theta_gpT nnzgp_theta_vecT +stochv_theta_vecT=takerows(v_theta_vecT,stochfvars); + +clear v_theta_vecT + +totindi=totindi+2; +indi=totindi; +% derivatives of v w.r.t x +if order>=1 + vxT=vx; + stochvxT=takerows(vxT,stochfvars(n_stochy+1:end)); + stochvxT.vals=repmat(stochvxT.vals,n_nodes,1); + stochvxT=vconcat(chain1_stochgpT,stochvxT); + + if strcmp(model.jacobian,'exact') + [stochgpx_stochtheta_vecT,model.ind{indi}]=tkron(ttranspose(Xpx_vecT),IstochyT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + else + [stochgpx_stochtheta_vecT,model.ind{indi}]=tkron(ttranspose(Xx_vecT),IstochyT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + stochgpx_stochtheta_vecT=ptr1d(col2ptr(ptr2col(ptr2d(unfold(stochgpx_stochtheta_vecT),n_stochy,n_x),1),2));%n_stochy*n_stochtheta,n_x + % + [chain1_gp_theta_vecT,model.ind{indi}]=contraction1(stochgpx_stochtheta_vecT,hxT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + chain1_gp_theta_vecT=ptr2col(ptr2d(chain1_gp_theta_vecT,n_stochy,n_stochtheta),2);%n_stochy,n_x,n_stochtheta + nnzchain1_gp_theta_vecT=col2ptr(changecols(changerows(chain1_gp_theta_vecT,stochy,n_y),stochtheta,n_theta,2),1); %n_y*n_x,n_theta with only nnz values + + nnzchain1_theta_gpT=col2ptr(changerows(chain1_theta_stochgpT,stochy,n_y),1);% n_y,n_x,n_theta + + vx_theta_lower_terms_vecT=vx_theta_lower_terms; + vx_theta_lower_terms_vecT.vals=repmat(vx_theta_lower_terms_vecT.vals,n_nodes,1); + + vx_theta_upper_terms_vecT=unfold(ptr2col(tplus(nnzchain1_theta_gpT,nnzchain1_gp_theta_vecT,maxload),1)); + clear nnzchain1_theta_gpT nnzchain1_gp_theta_vecT + vx_theta_vecT=vconcat(vx_theta_upper_terms_vecT,unfold(vx_theta_lower_terms_vecT)); + + clear vx_theta_upper_terms_vecT vx_theta_lower_terms_vecT + + stochvx_theta_vecT=takerows(vx_theta_vecT,stochfvars); + + clear vx_theta_vecT +end +if order>=2 + vxxcT=vxxc; + stochvxxcT=takerows(vxxcT,stochfvars(n_stochy+1:end)); + stochvxxcT.vals=repmat(stochvxxcT.vals,n_nodes,1); + stochvxxcT=vconcat(chain2_stochgpT,stochvxxcT); + + if strcmp(model.jacobian,'exact') + [stochgpxx_stochtheta_vecT,model.ind{indi}]=tkron(ttranspose(Xpxx_vecT),IstochyT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + else + [stochgpxx_stochtheta_vecT,model.ind{indi}]=tkron(ttranspose(Xxx_vecT),IstochyT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + + stochgpxx_stochtheta_vecT=ptr1d(col2ptr(ptr2col(ptr2d(unfold(stochgpxx_stochtheta_vecT),n_stochy,n_x^2),1),2));%n_stochy*n_stochtheta,n_x^2 + stochgpxx_stochtheta_vecT=fold(stochgpxx_stochtheta_vecT,n_x,n_x); + + [chain2c_stochgp_stochtheta_vecT,model.ind{indi}]=chain2c_tensor(stochgpx_stochtheta_vecT,stochgpxx_stochtheta_vecT,... + hxT,hxxcT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + chain2c_stochgp_stochtheta_vecT=ptr2col(ptr2d(chain2c_stochgp_stochtheta_vecT,n_stochy,n_stochtheta),2);%n_stochy,unique2,n_stochtheta + nnzchain2c_gp_theta_vecT=col2ptr(changecols(changerows(chain2c_stochgp_stochtheta_vecT,stochy,n_y),stochtheta,n_theta,2),1); %n_y*unique2,n_theta with only nnz values + clear chain2c_stochgp_stochtheta_vecT + + nnzchain2c_theta_gpT=col2ptr(changerows(chain2c_theta_stochgpT,stochy,n_y),1);% n_y,unique2,n_theta + + vxxc_theta_lower_terms_vecT=unfold(vxxc_theta_lower_terms); + vxxc_theta_lower_terms_vecT.vals=repmat(vxxc_theta_lower_terms_vecT.vals,n_nodes,1); + + vxxc_theta_upper_terms_vecT=unfold(ptr2col(tplus(nnzchain2c_theta_gpT,nnzchain2c_gp_theta_vecT,maxload),1)); + clear nnzchain2c_theta_gpT nnzchain2c_gp_theta_vecT + vxxc_theta_vecT=vconcat(vxxc_theta_upper_terms_vecT,vxxc_theta_lower_terms_vecT); + + clear vxxc_theta_upper_terms_vecT vxxc_theta_lower_terms_vecT + + stochvxxc_theta_vecT=takerows(vxxc_theta_vecT,stochfvars); + + clear vxxc_theta_vecT +end +if order>=3 + vxxxcT=vxxxc; + stochvxxxcT=takerows(vxxxcT,stochfvars(n_stochy+1:end)); + stochvxxxcT.vals=repmat(stochvxxxcT.vals,n_nodes,1); + stochvxxxcT=vconcat(chain3_stochgpT,stochvxxxcT); + + if strcmp(model.jacobian,'exact') + [stochgpxxx_stochtheta_vecT,model.ind{indi}]=tkron(ttranspose(Xpxxx_vecT),IstochyT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + else + [stochgpxxx_stochtheta_vecT,model.ind{indi}]=tkron(ttranspose(Xxxx_vecT),IstochyT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + + stochgpxxx_stochtheta_vecT=ptr1d(col2ptr(ptr2col(ptr2d(unfold(stochgpxxx_stochtheta_vecT),n_stochy,n_x^3),1),2));%n_stochy*n_stochtheta,n_x^2 + stochgpxxx_stochtheta_vecT=fold(stochgpxxx_stochtheta_vecT,n_x,n_x,n_x); + + [chain3c_stochgp_stochtheta_vecT,model.ind{indi}]=chain3c_tensor(stochgpx_stochtheta_vecT,stochgpxx_stochtheta_vecT,stochgpxxx_stochtheta_vecT,... + hxT,hxxcT,hxxxcT,... + model.x_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + chain3c_stochgp_stochtheta_vecT=ptr2col(ptr2d(chain3c_stochgp_stochtheta_vecT,n_stochy,n_stochtheta),2);%n_stochy,unique3,n_stochtheta + nnzchain3c_gp_theta_vecT=col2ptr(changecols(changerows(chain3c_stochgp_stochtheta_vecT,stochy,n_y),stochtheta,n_theta,2),1); %n_y*unique3,n_theta with only nnz values + + clear chain3c_stochgp_stochtheta_vecT + + nnzchain3c_theta_gpT=col2ptr(changerows(chain3c_theta_stochgpT,stochy,n_y),1);% n_y,unique3,n_theta + + clear chain3c_theta_stochgpT + + vxxxc_theta_lower_terms_vecT=unfold(vxxxc_theta_lower_terms); + vxxxc_theta_lower_terms_vecT.vals=repmat(vxxxc_theta_lower_terms_vecT.vals,n_nodes,1); + + vxxxc_theta_upper_terms_vecT=unfold(ptr2col(tplus(nnzchain3c_theta_gpT,nnzchain3c_gp_theta_vecT,maxload),1)); + + clear nnzchain3c_theta_gpT nnzchain3c_gp_theta_vecT + vxxxc_theta_vecT=vconcat(vxxxc_theta_upper_terms_vecT,vxxxc_theta_lower_terms_vecT); + + clear vxxxc_theta_upper_terms_vecT vxxxc_theta_lower_terms_vecT + + stochvxxxc_theta_vecT=takerows(vxxxc_theta_vecT,stochfvars); + + clear vxxxc_theta_vecT +end +totindi=totindi+9; +indi=totindi; + +[ EstochJ0,model.ind{indi} ] = chain0_theta_tensor( stochfv_vec,stochv_theta_vecT,model.ind{indi},n_ind,maxload,'sum' ); +indi=indi+1; + +% EstochJ0=sptensor2spmat(EstochJ0); + +% EstochR1,EstochR2,EstochR3,EstochJ1,EstochJ2,EstochJ3 +if order>=1 + [ EstochR1,model.ind{indi} ] = chain1_tensor( stochfv_vec,stochvxT,model.ind{indi},n_ind,maxload,'sum' ); + indi=indi+1; + EstochR1=sptensor2spmat(EstochR1); + + [ EstochJ1,model.ind{indi} ] = chain1_theta_tensor( stochfv_vec,stochfvv_vec,... + stochvxT,stochv_theta_vecT,stochvx_theta_vecT,... + model.ind{indi},n_ind,maxload,'sum' ); + indi=indi+1; +% EstochJ1=sptensor2spmat(EstochJ1); +end +if order>=2 + stochvxT=colsort(stochvxT); + [ EstochR2,model.ind{indi} ] = chain2c_tensor( stochfv_vec,stochfvv_vec,... + stochvxT,stochvxxcT,model.ind{indi},n_ind,maxload,'sum' ); + indi=indi+1; + EstochR2=sptensor2spmat(EstochR2); + + [ EstochJ2,model.ind{indi} ] = chain2c_theta_tensor( stochfv_vec,stochfvv_vec,stochfvvv_vec,... + stochvxT,stochvxxcT,... + stochv_theta_vecT,stochvx_theta_vecT,stochvxxc_theta_vecT,... + model.chain2c_theta_M2,... + model.ind{indi},n_ind,maxload,'sum' ); + indi=indi+1; +% EstochJ2=sptensor2spmat(EstochJ2); + +end +if order>=3 + [ EstochR3,model.ind{indi} ] = chain3c_tensor( stochfv_vec,stochfvv_vec,stochfvvv_vec,... + stochvxT,stochvxxcT,stochvxxxcT,... + model.x_chain3c_M2,... + model.ind{indi},n_ind,maxload,'sum' ); + indi=indi+1; + EstochR3=sptensor2spmat(EstochR3); + + [ EstochJ3,model.ind{indi} ] = chain3c_theta_tensor( stochfv_vec,stochfvv_vec,stochfvvv_vec,stochfvvvv_vec,... + stochvxT,stochvxxcT,stochvxxxcT,... + stochv_theta_vecT,stochvx_theta_vecT,stochvxxc_theta_vecT,stochvxxxc_theta_vecT,... + model.chain3c_theta_M2,model.chain3c_theta_M3,model.chain3c_theta_M4,model.chain3c_theta_M5,... + model.ind{indi},n_ind,maxload,'sum' ); + indi=indi+1; +% EstochJ3=sptensor2spmat(EstochJ3); +end +totindi=totindi+7; + +% build the system and the Jacobian + +R0=spalloc(n_f,1,n_f); + +R0(model.prefrows)=preR0; +R0(model.stochfrows)=EstochR0; + +J0=vconcat(preJ0,EstochJ0); +oldrows=1:J0.tsize(1); +newrows=zeros(1,J0.tsize(1)); +newrows([model.prefrows(:);model.stochfrows(:)])=oldrows; +J0=permuterows(J0,newrows); + +T=R0; +J=J0; + +if order>=1 + R1=spalloc(n_f,n_x,nnz(preR1)+nnz(EstochR1)); + R1(model.prefrows,:)=preR1; + R1(model.stochfrows,:)=EstochR1; + + J1=vconcat(preJ1,EstochJ1); + J1=permuterows(J1,newrows); + + J1=ptr2d(J1,1,n_f); + J1=ptr2col(J1,1); + J1=fold(unfold(J1),n_f*n_x,n_theta); + J1=ptr1d(col2ptr(J1,1)); + + J=vconcat(J,J1); + + T=[T;R1(:)]; +end +if order>=2 + R2=spalloc(n_f,size(preR2,2),nnz(preR2)+nnz(EstochR2)); + R2(model.prefrows,:)=preR2; + R2(model.stochfrows,:)=EstochR2; + + J2=vconcat(preJ2,EstochJ2); + J2=permuterows(J2,newrows); + + J2=ptr2d(J2,1,n_f); + J2=ptr2col(J2,1); + J2=fold(unfold(J2),n_f*unique2,n_theta); + J2=ptr1d(col2ptr(J2,1)); + + J=vconcat(J,J2); + + T=[T;R2(:)]; +end +if order>=3 + R3=spalloc(n_f,size(preR3,2),nnz(preR3)+nnz(EstochR3)); + J3=vconcat(preJ3,EstochJ3); + J3=permuterows(J3,newrows); + + J3=ptr2d(J3,1,n_f); + J3=ptr2col(J3,1); + J3=fold(unfold(J3),n_f*unique3,n_theta); + J3=ptr1d(col2ptr(J3,1)); + + J=vconcat(J,J3); + + R3(model.prefrows,:)=preR3; + R3(model.stochfrows,:)=EstochR3; + + T=[T;R3(:)]; +end + +J=sptensor2spmat(J); + + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/tpMS.m b/105/replication_package/solution_methods/taylor_projection/tpMS.m new file mode 100644 index 0000000000000000000000000000000000000000..23fe2c80ea85b4c2e9a0e9c9bfe3b63348538741 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/tpMS.m @@ -0,0 +1,102 @@ +function [T,J,model]=tpMS(coeffs,x0,model,params,msparams,transition,c0,nep,P) + +if ~isequal(x0,c0) + error('x0 must be equal to c0') +end + +% msparams should have n_regimes columns + +if size(msparams,2)~=model.n_regimes + error('msparams should have n_regimes columns') +end + +msparams=msparams'; + +paramsvec=repmat(params(:)',model.n_regimes^2,1); % n_regimes*n_regimes,[] + +[s,sp]=ndgrid([1:model.n_regimes],[1:model.n_regimes]); +s=s(:); +sp=sp(:); +paramsvec=[paramsvec,msparams(s,:),msparams(sp,:)]; %n_s,n_sp,n_params + +paramsvec=[paramsvec,zeros(model.n_regimes^2,model.n_logicalparams)]; + +coeffs=reshape(full(coeffs),model.n_theta,model.n_regimes); +coeffsvec=coeffs(:,s)'; +coeffspvec=coeffs(:,sp)'; + + + +x0vec=repmat(x0(:)',model.n_regimes^2,1); +c0vec=repmat(c0(:)',model.n_regimes^2,1); + +nep=full(nep); +P=full(P); + +% ms conditions +if isfield(model,'jacobian') + model.jacobian=model.jacobian; +end +[T,J,model]=tpvec(coeffsvec,x0vec,model,paramsvec,c0vec,nep,P,coeffspvec); + + +T.vals=reshape(T.vals,model.n_regimes,model.n_regimes,[]); +T.vals=T.vals.*reshape(repmat(transition,1,size(T.vals,3)),model.n_regimes,model.n_regimes,size(T.vals,3)); % multiply by the transition matrix + +J.vals=reshape(J.vals,model.n_regimes,model.n_regimes,[]); +J.vals=J.vals.*reshape(repmat(transition,1,size(J.vals,3)),model.n_regimes,model.n_regimes,size(J.vals,3)); % multiply by the transition matrix +J.vals=reshape(J.vals,model.n_regimes^2,[]); + +% sum across sp +T.vals=reshape(sum(T.vals,2),model.n_regimes,[]); + +[rows,cols,vals]=tfind(T); +rows=double(rows); +cols=double(cols); + +ncond=prod(T.tsize); +addrows=repmat((0:model.n_regimes-1)*ncond,length(rows),1); +newrows=repmat(rows,model.n_regimes,1)+addrows(:); +vals=vals'; +vals=vals(:); + +Trows=newrows(:); +Tcols=ones(length(Trows),1); +Tvals=vals; +Trowdim=model.n_regimes*ncond; + +[rows,cols,vals]=tfind(J); + +rows=double(rows); +cols=double(cols); + +% Comment: I do not sum across sp. This will be done by the sparse +% function. + +% find cols that belong to current period coeffs and future period coeffs +current_cols=logical(cols<=model.n_theta); +future_cols=logical(cols>model.n_theta); + +newcols=repmat(cols(:)',model.n_regimes^2,1); + +newcols(:,current_cols)=newcols(:,current_cols)+repmat((s(:)-1)*model.n_theta,1,nnz(current_cols)); +newcols(:,future_cols)=newcols(:,future_cols)-model.n_theta+repmat((sp(:)-1)*model.n_theta,1,nnz(future_cols)); + +newrows=repmat(rows(:)',model.n_regimes^2,1); + +newrows=reshape(newrows,model.n_regimes,[]); +newrows=newrows+repmat((0:model.n_regimes-1)'*ncond,1,size(newrows,2)); + +vals=vals(:); + +Jrows=newrows(:); +Jcols=newcols(:); +Jvals=vals; + +Jrowdim=model.n_regimes*ncond; +Jcoldim=model.n_regimes*model.n_theta; + +T=sparse(Trows,Tcols,Tvals,Trowdim,1); +J=sparse(Jrows,Jcols,Jvals,Jrowdim,Jcoldim); + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/tpMSvec.m b/105/replication_package/solution_methods/taylor_projection/tpMSvec.m new file mode 100644 index 0000000000000000000000000000000000000000..ea0c3ed2af3c28872830751c235a7c8843e7768c --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/tpMSvec.m @@ -0,0 +1,145 @@ +function [T,J,model]=tpMSvec(coeffs,x0,model,params,msparams,transition,c0,nep,P) + +% This function is a vectorized version of tpMS. The MS system is computed +% for n_s different values of coeffs/x0/params, column-wise. The MS pattern +% is preserved (i.e. future coeffs are separate from current coeffs) +% INPUTS: +% coeffs (n_s,n_theta,n_regimes) +% x0 (n_s,n_x) +% params (n_s,n_params) +% c0 (n_s,n_x) +% msparams (n_msparams,n_regimes) +% OUTPUTS T and J are sparse tensors. +% (c) Oren Levintal, September 29, 2017. + +if numel(x0)==model.n_x && numel(coeffs)==model.n_theta*model.n_regimes && numel(params)==model.n_params + n_s=1; +else % x0,coeffs,params have a row dimension of 1 or n_s + temp=[size(x0,1),size(coeffs,1),size(params,1),size(c0,1)]; + n_s=max(temp); + if min(temp)~=n_s + error('incompatible s dimension') + end +end + +if ~isequal(x0,c0) + error('x0 must be equal to c0') +end + +% msparams should have n_regimes columns + +if size(msparams,2)~=model.n_regimes + error('msparams should have n_regimes columns') +end + +msparams=msparams'; %n_regimes,n_msparams + +paramsvec=reshape(repmat(params(:)',model.n_regimes^2,1),model.n_regimes^2*n_s,[]); % n_regimes*n_regimes,n_s*n_params + +[s,sp]=ndgrid([1:model.n_regimes],[1:model.n_regimes]); +s=s(:); +sp=sp(:); +paramsvec=[paramsvec,repmat([msparams(s,:),msparams(sp,:)],n_s,1)]; + +paramsvec=[paramsvec,zeros(model.n_regimes^2*n_s,model.n_logicalparams)]; + +coeffs=reshape(full(coeffs),n_s*model.n_theta,model.n_regimes); +coeffsvec=coeffs(:,s); +coeffsvec=reshape(coeffsvec,n_s,model.n_theta,model.n_regimes^2); +coeffsvec=permute(coeffsvec,[3,1,2]); +coeffsvec=reshape(coeffsvec,model.n_regimes^2*n_s,[]); + +coeffspvec=coeffs(:,sp); +coeffspvec=reshape(coeffspvec,n_s,model.n_theta,model.n_regimes^2); +coeffspvec=permute(coeffspvec,[3,1,2]); +coeffspvec=reshape(coeffspvec,model.n_regimes^2*n_s,[]); + + +x0vec=repmat(x0(:)',model.n_regimes^2,1); %n_regimes^2,n_s*n_x +x0vec=reshape(x0vec,model.n_regimes^2*n_s,[]); %n_regimes^2*n_s,n_x +c0vec=repmat(c0(:)',model.n_regimes^2,1); %n_regimes^2,n_s*n_x +c0vec=reshape(c0vec,model.n_regimes^2*n_s,[]); %n_regimes^2*n_s,n_x + +nep=full(nep); +P=full(P); + +% ms conditions +if isfield(model,'jacobian') + model.jacobian=model.jacobian; +end + +% row dimensions should be n_regimes*n_regimes*n_s + +[T,J,model]=tpvec(coeffsvec,x0vec,model,paramsvec,c0vec,nep,P,coeffspvec); + + +T.vals=reshape(T.vals,model.n_regimes,model.n_regimes,[]); +T.vals=T.vals.*reshape(repmat(transition,1,size(T.vals,3)),model.n_regimes,model.n_regimes,size(T.vals,3)); % multiply by the transition matrix + +J.vals=reshape(J.vals,model.n_regimes,model.n_regimes,[]); +J.vals=J.vals.*reshape(repmat(transition,1,size(J.vals,3)),model.n_regimes,model.n_regimes,size(J.vals,3)); % multiply by the transition matrix +J.vals=reshape(J.vals,model.n_regimes^2*n_s,[]); + +% sum across sp and reshape +T.vals=reshape(sum(T.vals,2),model.n_regimes*n_s,[]); + +[rows,cols,vals]=tfind(T); +rows=double(rows); +cols=double(cols); + +ncond=prod(T.tsize); +addrows=repmat((0:model.n_regimes-1)*ncond,length(rows),1); +newrows=repmat(rows,model.n_regimes,1)+addrows(:); +vals=reshape(vals,model.n_regimes,n_s,[]); +vals=permute(vals,[2,3,1]); %n_s,n_vals,n_regimes +vals=reshape(vals,n_s,[]); %n_s,n_vals*n_regimes + + +Trows=newrows(:); +Tcols=ones(length(Trows),1); +Tvals=vals; +Trowdim=model.n_regimes*ncond; + + + + +[rows,cols,vals]=tfind(J); + +rows=double(rows); +cols=double(cols); + +% Comment: I do not sum across sp. This is done later by post-multiplying +% the crs Jacobian matrix (with duplicate entries) by the identity matrix. + +% find cols that belong to current period coeffs and future period coeffs +current_cols=logical(cols<=model.n_theta); +future_cols=logical(cols>model.n_theta); + +newcols=repmat(cols(:)',model.n_regimes^2,1); + +newcols(:,current_cols)=newcols(:,current_cols)+repmat((s(:)-1)*model.n_theta,1,nnz(current_cols)); +newcols(:,future_cols)=newcols(:,future_cols)-model.n_theta+repmat((sp(:)-1)*model.n_theta,1,nnz(future_cols)); + +newrows=repmat(rows(:)',model.n_regimes^2,1); + +newrows=reshape(newrows,model.n_regimes,[]); +newrows=newrows+repmat((0:model.n_regimes-1)'*ncond,1,size(newrows,2)); + +vals=reshape(vals,model.n_regimes^2,n_s,[]); +vals=permute(vals,[2,1,3]); +vals=reshape(vals,n_s,[]); + +Jrows=newrows(:); +Jcols=newcols(:); +Jvals=vals; + +Jrowdim=model.n_regimes*ncond; +Jcoldim=model.n_regimes*model.n_theta; + +T=sptensor(Trows,Tcols,Tvals,Trowdim,1); +J=sptensor(Jrows,Jcols,Jvals,Jrowdim,Jcoldim); +J=contraction1(J,spteye(Jcoldim)); % this function sums across entries with same row and column (like the function sparse where there are duplicate entries) +% T=sparse(Trows,Tcols,Tvals,Trowdim,1); +% J=sparse(Jrows,Jcols,Jvals,Jrowdim,Jcoldim); + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/tpscale.m b/105/replication_package/solution_methods/taylor_projection/tpscale.m new file mode 100644 index 0000000000000000000000000000000000000000..573ab5525c90918f60fc631af8c1bf79cc33f6fc --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/tpscale.m @@ -0,0 +1,46 @@ +function [ scaledT,scaledJ,Wcols,Wrows,model ] = tpscale( weighted_coeffs,x0,model,params,eta,c0,nep,P,Wcols,Wrows,varargin ) +%This function computes the scaled system and its Jacobian. If weights are +%empty, the function computes and returns the weights. Otherwise, the +%supplied weights are used. +% +% � Copyright, Oren Levintal, June 13, 2016. + +order=model.order(1); + +if isempty(Wcols) && isempty(Wrows) + % if weights are not supplied assume no weights. + coeffs=weighted_coeffs; +elseif ~isempty(Wcols) && ~isempty(Wrows) + % if all weights are supplied, unscale weighted_coeffs + coeffs=weighted_coeffs./Wcols; +else + error('missing weights'); +end + +if isempty(varargin) % precomputed variables are not available + [T,J,model]=tp(coeffs,x0,model,params,eta,c0,nep,P); +else + g_theta=varargin{1}; + h_theta=varargin{2}; + gx_theta=varargin{3}; + hx_theta=varargin{4}; + gxxc_theta=varargin{5}; + hxxc_theta=varargin{6}; + gxxxc_theta=varargin{7}; + hxxxc_theta=varargin{8}; + [T,J,model]=tp(coeffs,x0,model,params,eta,c0,nep,P,... + g_theta,h_theta,gx_theta,hx_theta,gxxc_theta,hxxc_theta,gxxxc_theta,hxxxc_theta); +end + +if isempty(Wcols) + Wcols=max(abs(J))'; + Wrows=max(abs([J*spdiags(1./Wcols,0,model.n_theta,model.n_theta)]'))'; +end + +scaledT=T./Wrows; + +scaledJ=spdiags(1./Wrows,0,model.n_theta,model.n_theta)*J*spdiags(1./Wcols,0,model.n_theta,model.n_theta); + + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/tpscaleMS.m b/105/replication_package/solution_methods/taylor_projection/tpscaleMS.m new file mode 100644 index 0000000000000000000000000000000000000000..89c69dfb018688cec454e9f679bca83844fc2d40 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/tpscaleMS.m @@ -0,0 +1,40 @@ +function [ scaledT,scaledJ,Wcols,Wrows,model ] = tpscaleMS( weighted_coeffs,x0,model,params,msparams,transition,c0,nep,P,Wcols,Wrows) +%This function computes the scaled system and its Jacobian. If weights are +%empty, the function computes and returns the weights. Otherwise, the +%supplied weights are used. +% +% � Copyright, Oren Levintal, June 13, 2016. + +order=model.order(1); + +if isempty(Wcols) && isempty(Wrows) + % if weights are not supplied assume no weights. + coeffs=weighted_coeffs; +elseif ~isempty(Wcols) && ~isempty(Wrows) + % if all weights are supplied, unscale weighted_coeffs + coeffs=weighted_coeffs./Wcols; +else + error('missing weights'); +end + +[T,J,model]=tpMS(coeffs,x0,model,params,msparams,transition,c0,nep,P); + +if isempty(Wcols) + Wcols=max(abs(J))'; + if min(Wcols)==0 + Wcols=ones(size(Wcols)); + end + Wrows=max(abs([J*spdiags(1./Wcols,0,model.n_theta*model.n_regimes,model.n_theta*model.n_regimes)]'))'; + if min(Wrows)==0 + Wrows=ones(size(Wrows)); + end +end + +scaledT=T./Wrows; +[mJ,nJ]=size(J); +% scaledJ=spdiags(1./Wrows,0,model.n_theta*model.n_regimes,model.n_theta*model.n_regimes)*J*spdiags(1./Wcols,0,model.n_theta*model.n_regimes,model.n_theta*model.n_regimes); +scaledJ=spdiags(1./Wrows,0,mJ,mJ)*J*spdiags(1./Wcols,0,nJ,nJ); + + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/tpscaleMSi.m b/105/replication_package/solution_methods/taylor_projection/tpscaleMSi.m new file mode 100644 index 0000000000000000000000000000000000000000..ce08d51f3288331bdaa404f621009d8ec6249c9b --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/tpscaleMSi.m @@ -0,0 +1,105 @@ +function [ scaledT,scaledJ,Wcols,Wrows,model ] = tpscaleMSi( weighted_coeffs,x0,model,params,paramsi,msparams,transition,c0,nep,P,Wcols,Wrows) +%This function computes the scaled system and its Jacobian. If weights are +%empty, the function computes and returns the weights. Otherwise, the +%supplied weights are used. +% +% � Copyright, Oren Levintal, June 13, 2016. + +order=model.order(1); + +if isempty(Wcols) && isempty(Wrows) + % if weights are not supplied assume no weights. + coeffs=weighted_coeffs; +elseif ~isempty(Wcols) && ~isempty(Wrows) + % if all weights are supplied, unscale weighted_coeffs + coeffs=weighted_coeffs./Wcols; +else + error('missing weights'); +end + +if ~isempty(paramsi) + n_s=size(paramsi,2); +else + n_s=1; +end + +if ~isfield(model,'active_vars') + coeffs=repmat(coeffs(:)',n_s,1); + coeffs=reshape(coeffs,n_s,model.n_theta,model.n_regimes); +else + coeffs=reshape(coeffs,[],model.n_b); + coeffs=coeffs(model.active_vars(:),:); + coeffs=reshape(coeffs,n_s,[]); +end +x0=repmat(x0(:)',n_s,1); +c0=repmat(c0(:)',n_s,1); + +params=[repmat(params(:)',n_s,1),paramsi']; + +[Ti,Ji,model]=tpMSvec(coeffs,x0,model,params,msparams,transition,c0,nep,P); + +if ~isfield(model,'active_vars') + T=Ti; + T.vals=Ti.vals(1,:); + J=Ji; + J.vals=Ji.vals(1,:); + + for j=2:n_s + Tj=Ti; + Tj.vals=Ti.vals(j,:); + T=vconcat(T,Tj); + Jj=Ji; + Jj.vals=Ji.vals(j,:); + J=vconcat(J,Jj); + end +else + %%%%%%%%%%%%%%% + %%% The coefficients must be of dimensions model.n_vars,n_b, where model.n_vars is + %%% the number of variables, and n_b size + %%% of basis function + %%%%%%%%%%%%%%% + T=Ti; + T.vals=Ti.vals(1,:); + J=Ji; + J.vals=Ji.vals(1,:); + countcoeffs=reshape(1:model.n_vars*model.n_b,[],model.n_b); + J=changecols(J,reshape(countcoeffs(model.active_vars(1,:),:),1,[]),model.n_vars*model.n_b,1); + for j=2:n_s + Tj=Ti; + Tj.vals=Ti.vals(j,:); + T=vconcat(T,Tj); + Jj=Ji; + Jj.vals=Ji.vals(j,:); + Jj=changecols(Jj,reshape(countcoeffs(model.active_vars(j,:),:),1,[]),model.n_vars*model.n_b,1); + J=vconcat(J,Jj); + end +end +T=sptensor2spmat(T); +J=sptensor2spmat(J); + +if isfield(model,'special_code') + T=[T;model.moreT]; + J=[J;model.moreJ]; +end + + +[mJ,nJ]=size(J); + +if isempty(Wcols) + Wcols=max(abs(J))'; + if min(Wcols)==0 + Wcols=ones(size(Wcols)); + end + Wrows=max(abs([J*spdiags(1./Wcols,0,nJ,nJ)]'))'; + if min(Wrows)==0 + Wrows=ones(size(Wrows)); + end +end + +scaledT=T./Wrows; +scaledJ=spdiags(1./Wrows,0,mJ,mJ)*J*spdiags(1./Wcols,0,nJ,nJ); + + + +end + diff --git a/105/replication_package/solution_methods/taylor_projection/tpsolve.m b/105/replication_package/solution_methods/taylor_projection/tpsolve.m new file mode 100644 index 0000000000000000000000000000000000000000..1f8a51bd13dafa1b3068d46474fcdde2391d0a11 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/tpsolve.m @@ -0,0 +1,160 @@ +function [ncoeffs,model,T,J,iter]=tpsolve(coeffs,x0,model,params,varargin) +% function [ncoeffs,model,T,J,iter]=tpsolve(coeffs,x0,model,params,c0,nep,P,tolX,tolF,maxiter,varargin) +if nargin==10 + type='normal'; + c0=varargin{1}; + nep=varargin{2}; + P=varargin{3}; + tolX=varargin{4}; + tolF=varargin{5}; + maxiter=varargin{6}; + OPTIONS=[]; +elseif nargin==11 + type='normal'; + c0=varargin{1}; + nep=varargin{2}; + P=varargin{3}; + tolX=varargin{4}; + tolF=varargin{5}; + maxiter=varargin{6}; + OPTIONS=varargin{7}; +elseif nargin==12 + type='MS'; + msparams=varargin{1}; + transition=varargin{2}; + c0=varargin{3}; + nep=varargin{4}; + P=varargin{5}; + tolX=varargin{6}; + tolF=varargin{7}; + maxiter=varargin{8}; + OPTIONS=[]; +elseif nargin==13 + type='MS'; + msparams=varargin{1}; + transition=varargin{2}; + c0=varargin{3}; + nep=varargin{4}; + P=varargin{5}; + tolX=varargin{6}; + tolF=varargin{7}; + maxiter=varargin{8}; + OPTIONS=varargin{9}; +else + error('wrong number of input arguments') +end + +if isempty(nep) || isempty(P) + P=1; + nep=0; +end + +if strcmp(type,'normal') + coeffs=coeffs(:); + if length(coeffs)~=model.n_theta + error(['The first argument is wrong. The initial guess should be a vector of ' num2str(model.n_theta) ' elements.']) + end + x0=x0(:); + if length(x0)~=model.n_x + error(['The second argument is wrong. The approximation point should be a vector of ' num2str(model.n_x) ' elements (=the number of state variables).']) + end + if ~isstruct(model) + error('The third argument is wrong. It should be a structure generated by prepare_tp.') + elseif ~isfield(model,'n_x') + error('The third argument is wrong. It should be a structure generated by prepare_tp.') + end + +% params=[params(:);zeros(model.n_logicalparams,1)]; + + if length(params)~=model.n_params-model.n_logicalparams + error(['The fourth argument is wrong. The number of model parameters should be ' num2str(model.n_params) '.']) + end + c0=c0(:); + if length(c0)~=model.n_x + error(['The fifth argument is wrong. The center of the approximating polynomial should be a vector of' num2str(model.n_x) ' elements (=the number of state variables).']) + end + if size(nep,1)~=model.n_e + error(['The sixth argument is wrong. It should be a matrix with ' num2str(model.n_e) ' rows (=the number of shocks).']) + end + P=P(:); + if size(nep,2)~=length(P) + error('The sixth or seventh arguments are wrong. The number of columns in the sixth argument should be equal to the number of elements in the seventh argument.') + end + if numel(tolX)~=1 || ~isnumeric(tolX) + error('The eighth argument should be a numeric scalar') + end + if numel(tolF)~=1 || ~isnumeric(tolF) + error('The ninth argument should be a numeric scalar') + end + if numel(maxiter)~=1 || ~isnumeric(maxiter) + error('The tenth argument should be a numeric scalar') + end + + + msparams=zeros(0,1); + transition=1; + if isempty(OPTIONS) + [ncoeffs,model,T,J,iter]=tpsolveMS(coeffs,x0,model,params,msparams,transition,c0,nep,P,tolX,tolF,maxiter); + else + [ncoeffs,model,T,J,iter]=tpsolveMS(coeffs,x0,model,params,msparams,transition,c0,nep,P,tolX,tolF,maxiter,OPTIONS); + end + +else + + if size(coeffs,1)~=model.n_theta || size(coeffs,2)~=model.n_regimes + message=sprintf(['The first argument is wrong. The initial guess should be a ' num2str(model.n_theta) '-by-' num2str(model.n_regimes) ' matrix. \nThe number of polynomial coefficients per regime is ' num2str(model.n_theta) ' and the number of regimes is ' num2str(model.n_regimes)'.']); + error(message); + end + x0=x0(:); + if length(x0)~=model.n_x + error(['The second argument is wrong. The approximation point should be a vector of' num2str(model.n_x) ' elements (=the number of state variables).']) + end + if ~isstruct(model) + error('The third argument is wrong. It should be a structure generated by prepare_tp.') + elseif ~isfield(model,'n_x') + error('The third argument is wrong. It should be a structure generated by prepare_tp.') + end +% params=[params(:);zeros(model.n_logicalparams,1)]; + + if length(params)~=model.n_params_no_ms-model.n_logicalparams + error(['The fourth argument is wrong. The number of model parameters should be ' num2str(model.n_params_no_ms) '.']) + end + if isempty(msparams) + msparams=zeros(0,model.n_regimes); + end + if size(msparams,1)~=model.n_msparams || size(msparams,2)~=model.n_regimes + error(sprintf(['The fifth argument is wrong. It should be a ' num2str(model.n_msparams) '-by-' num2str(model.n_regimes) ' matrix. \nThe number of Markov switching parameters is ' num2str(model.n_msparams) ' and the number of regimes is ' num2str(model.n_regimes) '.'])) + end + if size(transition,1)~=model.n_regimes || size(transition,2)~=model.n_regimes + error(['The sixth argument is wrong. The transition matrix should have ' num2str(model.n_regimes) ' rows and columns.']) + end + c0=c0(:); + if length(c0)~=model.n_x + error(['The seventh argument is wrong. The center of the approximating polynomial should be a vector of' num2str(model.n_x) ' elements (=the number of state variables).']) + end + if size(nep,1)~=model.n_e + error(['The eighth argument is wrong. It should be a matrix with ' num2str(model.n_e) ' rows (=the number of shocks).']) + end + P=P(:); + if size(nep,2)~=length(P) + error('The eighth or ninth arguments are wrong. The number of columns in the eighth argument should be equal to the number of elements in the ninth argument.') + end + if numel(tolX)~=1 || ~isnumeric(tolX) + error('The tenth argument should be a numeric scalar') + end + if numel(tolF)~=1 || ~isnumeric(tolF) + error('The elevnth argument should be a numeric scalar') + end + if numel(maxiter)~=1 || ~isnumeric(maxiter) + error('The twelfth argument should be a numeric scalar') + end + if isempty(OPTIONS) + [ncoeffs,model,T,J,iter]=tpsolveMS(coeffs,x0,model,params,msparams,transition,c0,nep,P,tolX,tolF,maxiter); + else + [ncoeffs,model,T,J,iter]=tpsolveMS(coeffs,x0,model,params,msparams,transition,c0,nep,P,tolX,tolF,maxiter,OPTIONS); + end + + +end + + diff --git a/105/replication_package/solution_methods/taylor_projection/tpsolve2.m b/105/replication_package/solution_methods/taylor_projection/tpsolve2.m new file mode 100644 index 0000000000000000000000000000000000000000..26a119ff32936d4aaa0c471a7f6f7d292ad29334 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/tpsolve2.m @@ -0,0 +1,155 @@ +function [ncoeffs,model,T,J,iter]=tpsolve2(coeffs,x0,model,params,varargin) +% function [ncoeffs,model,T,J,iter]=tpsolve(coeffs,x0,model,params,c0,nep,P,tolX,tolF,maxiter,varargin) +if nargin==10 + type='normal'; + c0=varargin{1}; + nep=varargin{2}; + P=varargin{3}; + tolX=varargin{4}; + tolF=varargin{5}; + maxiter=varargin{6}; + OPTIONS=[]; +elseif nargin==11 + type='normal'; + c0=varargin{1}; + nep=varargin{2}; + P=varargin{3}; + tolX=varargin{4}; + tolF=varargin{5}; + maxiter=varargin{6}; + OPTIONS=varargin{7}; +elseif nargin==12 + type='MS'; + msparams=varargin{1}; + transition=varargin{2}; + c0=varargin{3}; + nep=varargin{4}; + P=varargin{5}; + tolX=varargin{6}; + tolF=varargin{7}; + maxiter=varargin{8}; + OPTIONS=[]; +elseif nargin==13 + type='MS'; + msparams=varargin{1}; + transition=varargin{2}; + c0=varargin{3}; + nep=varargin{4}; + P=varargin{5}; + tolX=varargin{6}; + tolF=varargin{7}; + maxiter=varargin{8}; + OPTIONS=varargin{9}; +else + error('wrong number of input arguments') +end + +if strcmp(type,'normal') + coeffs=coeffs(:); + if length(coeffs)~=model.n_theta + error(['The first argument is wrong. The initial guess should be a vector of ' num2str(model.n_theta) ' elements.']) + end + x0=x0(:); + if length(x0)~=model.n_x + error(['The second argument is wrong. The approximation point should be a vector of ' num2str(model.n_x) ' elements (=the number of state variables).']) + end + if ~isstruct(model) + error('The third argument is wrong. It should be a structure generated by prepare_tp.') + elseif ~isfield(model,'n_x') + error('The third argument is wrong. It should be a structure generated by prepare_tp.') + end + +% params=[params(:);zeros(model.n_logicalparams,1)]; + + if length(params)~=model.n_params-model.n_logicalparams + error(['The fourth argument is wrong. The number of model parameters should be ' num2str(model.n_params) '.']) + end + c0=c0(:); + if length(c0)~=model.n_x + error(['The fifth argument is wrong. The center of the approximating polynomial should be a vector of' num2str(model.n_x) ' elements (=the number of state variables).']) + end + if size(nep,1)~=model.n_e + error(['The sixth argument is wrong. It should be a matrix with ' num2str(model.n_e) ' rows (=the number of shocks).']) + end + P=P(:); + if size(nep,2)~=length(P) + error('The sixth or seventh arguments are wrong. The number of columns in the sixth argument should be equal to the number of elements in the seventh argument.') + end + if numel(tolX)~=1 || ~isnumeric(tolX) + error('The eighth argument should be a numeric scalar') + end + if numel(tolF)~=1 || ~isnumeric(tolF) + error('The ninth argument should be a numeric scalar') + end + if numel(maxiter)~=1 || ~isnumeric(maxiter) + error('The tenth argument should be a numeric scalar') + end + + + msparams=zeros(0,1); + transition=1; + if isempty(OPTIONS) + [ncoeffs,model,T,J,iter]=tpsolveMS2(coeffs,x0,model,params,msparams,transition,c0,nep,P,tolX,tolF,maxiter); + else + [ncoeffs,model,T,J,iter]=tpsolveMS2(coeffs,x0,model,params,msparams,transition,c0,nep,P,tolX,tolF,maxiter,OPTIONS); + end + +else + + if size(coeffs,1)~=model.n_theta || size(coeffs,2)~=model.n_regimes + message=sprintf(['The first argument is wrong. The initial guess should be a ' num2str(model.n_theta) '-by-' num2str(model.n_regimes) ' matrix. \nThe number of polynomial coefficients per regime is ' num2str(model.n_theta) ' and the number of regimes is ' num2str(model.n_regimes)'.']); + error(message); + end + x0=x0(:); + if length(x0)~=model.n_x + error(['The second argument is wrong. The approximation point should be a vector of' num2str(model.n_x) ' elements (=the number of state variables).']) + end + if ~isstruct(model) + error('The third argument is wrong. It should be a structure generated by prepare_tp.') + elseif ~isfield(model,'n_x') + error('The third argument is wrong. It should be a structure generated by prepare_tp.') + end +% params=[params(:);zeros(model.n_logicalparams,1)]; + + if length(params)~=model.n_params_no_ms-model.n_logicalparams + error(['The fourth argument is wrong. The number of model parameters should be ' num2str(model.n_params_no_ms) '.']) + end + if isempty(msparams) + msparams=zeros(0,model.n_regimes); + end + if size(msparams,1)~=model.n_msparams || size(msparams,2)~=model.n_regimes + error(sprintf(['The fifth argument is wrong. It should be a ' num2str(model.n_msparams) '-by-' num2str(model.n_regimes) ' matrix. \nThe number of Markov switching parameters is ' num2str(model.n_msparams) ' and the number of regimes is ' num2str(model.n_regimes) '.'])) + end + if size(transition,1)~=model.n_regimes || size(transition,2)~=model.n_regimes + error(['The sixth argument is wrong. The transition matrix should have ' num2str(model.n_regimes) ' rows and columns.']) + end + c0=c0(:); + if length(c0)~=model.n_x + error(['The seventh argument is wrong. The center of the approximating polynomial should be a vector of' num2str(model.n_x) ' elements (=the number of state variables).']) + end + if size(nep,1)~=model.n_e + error(['The eighth argument is wrong. It should be a matrix with ' num2str(model.n_e) ' rows (=the number of shocks).']) + end + P=P(:); + if size(nep,2)~=length(P) + error('The eighth or ninth arguments are wrong. The number of columns in the eighth argument should be equal to the number of elements in the ninth argument.') + end + if numel(tolX)~=1 || ~isnumeric(tolX) + error('The tenth argument should be a numeric scalar') + end + if numel(tolF)~=1 || ~isnumeric(tolF) + error('The elevnth argument should be a numeric scalar') + end + if numel(maxiter)~=1 || ~isnumeric(maxiter) + error('The twelfth argument should be a numeric scalar') + end + if isempty(OPTIONS) + [ncoeffs,model,T,J,iter]=tpsolveMS2(coeffs,x0,model,params,msparams,transition,c0,nep,P,tolX,tolF,maxiter); + else + [ncoeffs,model,T,J,iter]=tpsolveMS2(coeffs,x0,model,params,msparams,transition,c0,nep,P,tolX,tolF,maxiter,OPTIONS); + end + + +end + + diff --git a/105/replication_package/solution_methods/taylor_projection/tpsolveMS.m b/105/replication_package/solution_methods/taylor_projection/tpsolveMS.m new file mode 100644 index 0000000000000000000000000000000000000000..624c223559ca3bc9b9e59bfdb7b334dee3ee9950 --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/tpsolveMS.m @@ -0,0 +1,151 @@ +function [ncoeffs,model,T,J,iter]=tpsolveMS(coeffs,x0,model,params,msparams,transition,c0,nep,P,tolX,tolF,maxiter,varargin) + +% The function computes the polynomial coefficients by the Newton method or +% by fsolve/lsqnonlin. +% +% � Copyright, Oren Levintal, June 13, 2016. +% Changed on March 19, 2017 - adjusted for Markov switching parameters + + +x0=x0(:); + +params=params(:); + +c0=c0(:); + +P=P(:); + +display=1; +if isfield(model,'display') + if strcmp(model.display,'off') + display=0; + end +end + + +order=model.order(1); + +% make sure all inputs are full +coeffs=full(coeffs); +x0=full(x0); +params=full(params); +msparams=full(msparams); +c0=full(c0); +P=full(P); + +n_x=model.n_x; + +% shift the center of the Polynomials to x0 + +c0_old=c0; +c0_new=x0; +if ~isequal(c0_old,x0) + coeffs=reshape(coeffs,(model.n_y+model.n_x1)*model.n_b,model.n_regimes); + coeffs=reshape(coeffs',model.n_regimes*(model.n_y+model.n_x1),model.n_b); + [ coeffs ] = shift_center( coeffs,c0_old,c0_new,order,model ); + coeffs=reshape(coeffs,model.n_regimes,(model.n_y+model.n_x1)*model.n_b); + coeffs=full(coeffs'); + c0=c0_new; +end +coeffs=coeffs(:); + +% precompute expressions that are independent of coeffs +% [ g_theta,h_theta,gx_theta,hx_theta,gxxc_theta,hxxc_theta,gxxxc_theta,hxxxc_theta,model ] = precompute(x0,c0,model,order ); + +iter=1; + +% start without weights. + +Wcols=[]; Wrows=[]; coeffs=full(coeffs); + +[T,J,Wcols,Wrows,model]=tpscaleMS(coeffs,x0,model,params,msparams,transition,c0,nep,P,Wcols,Wrows); +normT=norm(T); +% rcond(full(J)) +bestT=normT; +best_weighted_coeffs=Wcols.*coeffs; + +if maxiter>0 + ncoeffs=coeffs-full(J\T)./Wcols; + d=ncoeffs-coeffs; + normd=norm(d); + optimality=norm(T'*J,inf); + if display==1 + disp(['iter norm(system) norm(step) optimality measure']) + + disp([' ' num2str(iter) ' ' num2str(normT,'%3.2e') ' ' num2str(normd,'%3.2e') ' ' num2str(optimality,'%3.2e')] ) + end + +else + normd=inf; +end + +% continue to convergence +while normd > max(tolX,eps) && normT>max(tolF,eps) && iter max(tolX,eps) && normT>max(tolF,eps) && iter0 +% Rcond=rcond(full(J)) +% condtol=1e-16; +% if Rcond>condtol + ncoeffs=coeffs-full(J\T)./Wcols; +% else +% warning('doing vpa') +% digits=ceil(-log10(Rcond))+10; +% ncoeffs=coeffs-double(vpa(full(J),digits)\vpa(full(T),digits))./Wcols; +% end + d=ncoeffs-coeffs; + normd=norm(d); + optimality=norm(T'*J,inf); + + if display==1 + disp(['iter norm(system) norm(step) optimality measure']) + + disp([' ' num2str(iter) ' ' num2str(normT,'%3.2e') ' ' num2str(normd,'%3.2e') ' ' num2str(optimality,'%3.2e')] ) + end + +else + normd=inf; +end +% continue to convergence +while normd > max(tolX,eps) && normT>max(tolF,eps) && itercondtol + ncoeffs=coeffs-full(J\T)./Wcols; +% else +% warning('doing vpa') +% digits=ceil(-log10(Rcond))+10; +% ncoeffs=coeffs-double(vpa(full(J),digits)\vpa(full(T),digits))./Wcols; +% end + + d=ncoeffs-coeffs; + optimality=norm(T'*J,inf); + normd=norm(d); + if display==1 + disp([' ' num2str(iter) ' ' num2str(normT,'%3.2e') ' ' num2str(normd,'%3.2e') ' ' num2str(optimality,'%3.2e')] ) + end +end + +coeffs=best_weighted_coeffs./Wcols; + +% if Newton method did not converge with the maximum number of iterations, +% switch to fsolve (default) or lsqnonlin. +if logical(normd < max(tolX,eps) || normT=1 + gx_theta.vals=repmat(gx_theta.vals,n_s,1); + hx_theta.vals=repmat(hx_theta.vals,n_s,1); +end +if order>=2 + gxxc_theta.vals=repmat(gxxc_theta.vals,n_s,1); + hxxc_theta.vals=repmat(hxxc_theta.vals,n_s,1); +end +if order>=3 + gxxxc_theta.vals=repmat(gxxxc_theta.vals,n_s,1); + hxxxc_theta.vals=repmat(hxxxc_theta.vals,n_s,1); +end +if order>=4 + gxxxxc_theta.vals=repmat(gxxxxc_theta.vals,n_s,1); + hxxxxc_theta.vals=repmat(hxxxxc_theta.vals,n_s,1); +end + +if ms==1 + g_theta.tsize(end)=model.n_theta*2; % in ms models we duplicate the Jacobian. The first block corresponds to coefficients of current period, and the second block to next period. + h_theta.tsize(end)=model.n_theta*2; + if order>=1 + gx_theta.tsize(end)=model.n_theta*2; + hx_theta.tsize(end)=model.n_theta*2; + end + if order>=2 + gxxc_theta.tsize(end)=model.n_theta*2; + hxxc_theta.tsize(end)=model.n_theta*2; + end + if order>=3 + gxxxc_theta.tsize(end)=model.n_theta*2; + hxxxc_theta.tsize(end)=model.n_theta*2; + end + if order>=4 + gxxxxc_theta.tsize(end)=model.n_theta*2; + hxxxxc_theta.tsize(end)=model.n_theta*2; + end +end + + +indi=5; %count indi from 5, due to precompute. + + +if ~isfield(model,'n_ind') + n_ind=1; +else + n_ind=model.n_ind; +end +if ~isfield(model,'maxload') + maxload=intarray(length(P)*n_s); +else + maxload=intarray(model.maxload); +end +model.maxload=maxload; + +params=paramsvec; +P=P(:); + +n_f=model.n_f; % no. of model conditions +n_x=model.n_x; % no. of state variables +n_y=model.n_y; % no. of control variables +n_x2=model.n_x2; % no. of exogenous state variables +n_x1=model.n_x1; % no. of endogenous state variabels +n_v=model.n_v; % total no. of variables v=(yp,y,xp,x) +n_theta=model.n_theta; % no. of Polynomial coefficients +n_b=model.n_b; % no. of terms in the basis function +n_nodes=size(nep,2); % no. nodes in the discrete shocks +n_z=model.n_z; % no. of auxiliary variables +n_e=model.n_e; + +n_prefrows=length(model.prefrows); +n_stochfrows=length(model.stochfrows); + +n_params=model.n_params; + +if model.hybrid==1 || model.hybrid==3 + n_params=n_params+n_e; % shocks are treated as parameters +end + +coeffs=reshape(coeffsvec,n_s,[],n_b); +% g_coeffs=coeffs(:,1:n_y,:); + +%create stochy: index of future control variables that affect stochastic equations +tempv=zeros(n_v,1); +tempv(model.stochfvars)=model.stochfvars; +tempv(n_y+1:end)=0; +stochy=nonzeros(tempv); % this is the stochastic y variables that affect f, but it does not include stochastic y variables that affect logical expressions only +n_stochy=length(stochy); +if ms==0 + stochg_coeffs=coeffs(:,stochy,:); +else + coeffspvec=full(reshape(coeffsp,n_s,[],n_b)); + stochg_coeffs=coeffspvec(:,stochy,:); +end + +if ~isfield(model,'ind4') + model.ind4=cell(100+model.count_pre_n+model.count_stoch_n,1); % indices for 4th order computations +end +indi4=1; + +unique2=[]; unique3=[]; unique4=[]; + +prefvars=model.prefvars; % index of variables that affect nonstochastic equations. +stochfvars=model.stochfvars;% index of variables that affect stochastic equations. +n_prefvars=length(prefvars); +n_stochfvars=length(stochfvars); + +if model.pde==3 % compute derivatives of derivs w.r.t x and theta + factor=ms+1; + if order==0 + gx__theta=sptensor(model.n_tildy1st,n_theta*factor,n_s); + else + rows=1:model.n_tildy1st; + rows=rows(:); + cols=n_y+(model.tildy1st_ind); + cols=cols(:); + vals=ones(n_s,length(rows)); + gx__theta=sptensor(rows,cols,vals,model.n_tildy1st,n_theta*factor); + end + if order<=1 + gxx__theta=sptensor(model.n_tildy2nd,n_theta*factor,n_s); + else + rows=1:model.n_tildy2nd; + rows=rows(:); + cols=n_y+n_y*n_x+(1:n_y*model.unique2); + cols=full(reshape(cols,n_y,model.unique2)*model.W{2}); + cols=cols(model.tildy2nd_ind); + cols=cols(:); + vals=2*ones(n_s,length(rows)); + gxx__theta=sptensor(rows,cols,vals,model.n_tildy2nd,n_theta*factor); + end + gx__theta=vconcat(gxx__theta,gx__theta); + g_theta=vconcat(gx__theta,g_theta); % derivatives and levels + if order>=1 + if order==1 + gx_x_theta=sptensor(model.n_tildy1st,[n_x,n_theta*factor],n_s); + else + rows=1:model.n_tildy1st*n_x; + cols=n_y+n_y*n_x+(1:n_y*model.unique2); + cols=full(reshape(cols,n_y,model.unique2)*model.W{2}); + cols=reshape(cols,n_y*n_x,n_x); + cols=cols(model.tildy1st_ind,:); + [rows1,rows2]=ind2sub([model.n_tildy1st,n_x],rows(:)); + rows=rows1(:); + cols=[rows2(:),cols(:)]; + vals=2*ones(n_s,length(rows)); + gx_x_theta=sptensor(rows,cols,vals,model.n_tildy1st,[n_x,n_theta*factor]); + end + if order<=2 + gxx_x_theta=sptensor(model.n_tildy2nd,[n_x,n_theta*factor],n_s); + else + rows=1:model.n_tildy2nd*n_x; + rows=rows(:); + cols=n_y+n_y*n_x+n_y*model.unique2+(1:n_y*model.unique3); + cols=full(reshape(cols,n_y,model.unique3)*model.W{3}); + cols=reshape(cols,n_y*n_x^2,n_x); + cols=cols(model.tildy2nd_ind,:); + cols=cols(:); + [rows1,rows2]=ind2sub([model.n_tildy2nd,n_x],rows(:)); + rows=rows1(:); + cols=[rows2(:),cols(:)]; + vals=6*ones(n_s,length(rows)); + gxx_x_theta=sptensor(rows,cols,vals,model.n_tildy2nd,[n_x,n_theta*factor]); + end + gx_x_theta=vconcat(gxx_x_theta,gx_x_theta); + gx_theta=vconcat(gx_x_theta,gx_theta); + end + if order>=2 + if order==2 + gx_xxc_theta=sptensor(model.n_tildy1st,[model.unique2,n_theta*factor],n_s); + else + rows=1:model.n_tildy1st*model.unique2; + cols=n_y+n_y*n_x+n_y*model.unique2+(1:n_y*model.unique3); + cols=full(reshape(cols,n_y,model.unique3)*model.W{3}); + cols=reshape(cols,n_y*n_x,n_x^2); + cols=cols(model.tildy1st_ind,:); + cols=full(cols*model.U{2}); + + [rows1,rows2]=ind2sub([model.n_tildy1st,model.unique2],rows(:)); + rows=rows1(:); + cols=[rows2(:),cols(:)]; + vals=6*ones(n_s,length(rows)); + gx_xxc_theta=sptensor(rows,cols,vals,model.n_tildy1st,[model.unique2,n_theta*factor]); + end + if order<=3 + gxx_xxc_theta=sptensor(model.n_tildy2nd,[model.unique2,n_theta*factor],n_s); + else + rows=1:model.n_tildy2nd*model.unique2; + rows=rows(:); + cols=n_y+n_y*n_x+n_y*model.unique2+n_y*model.unique3+(1:n_y*model.unique4); + cols=full(reshape(cols,n_y,model.unique4)*model.W{4}); + cols=full(reshape(cols,n_y*n_x^2,n_x^2)*model.U{2}); + cols=cols(model.tildy2nd_ind,:); + cols=cols(:); + [rows1,rows2]=ind2sub([model.n_tildy2nd,model.unique2],rows(:)); + rows=rows1(:); + cols=[rows2(:),cols(:)]; + vals=24*ones(n_s,length(rows)); + gxx_xxc_theta=sptensor(rows,cols,vals,model.n_tildy2nd,[model.unique2,n_theta*factor]); + end + gx_xxc_theta=vconcat(gxx_xxc_theta,gx_xxc_theta); + gxxc_theta=vconcat(gx_xxc_theta,gxxc_theta); + end + if order>=3 + if order==3 + gx_xxxc_theta=sptensor(model.n_tildy1st,[model.unique3,n_theta*factor],n_s); + else + rows=1:model.n_tildy1st*model.unique3; + cols=n_y+n_y*(n_x+model.unique2+model.unique3)+(1:n_y*model.unique4); + cols=full(reshape(cols,n_y,model.unique4)*model.W{4}); + cols=reshape(cols,n_y*n_x,n_x^3); + cols=cols(model.tildy1st_ind,:); + cols=full(cols*model.U{3}); + + [rows1,rows2]=ind2sub([model.n_tildy1st,model.unique3],rows(:)); + rows=rows1(:); + cols=[rows2(:),cols(:)]; + vals=24*ones(n_s,length(rows)); + gx_xxxc_theta=sptensor(rows,cols,vals,model.n_tildy1st,[model.unique3,n_theta*factor]); + end + if order<=4 + gxx_xxxc_theta=sptensor(model.n_tildy2nd,[model.unique3,n_theta*factor],n_s); + else + error('order cannot exceed 4') + end + gx_xxxc_theta=vconcat(gxx_xxxc_theta,gx_xxxc_theta); + gxxxc_theta=vconcat(gx_xxxc_theta,gxxxc_theta); + end + if order>=4 + if order==4 + gx_xxxxc_theta=sptensor(model.n_tildy1st,[model.unique4,n_theta*factor],n_s); + gxx_xxxxc_theta=sptensor(model.n_tildy2nd,[model.unique4,n_theta*factor],n_s); + else + error('order cannot exceed 4') + end + gx_xxxxc_theta=vconcat(gxx_xxxxc_theta,gx_xxxxc_theta); + gxxxxc_theta=vconcat(gx_xxxxc_theta,gxxxxc_theta); + end + if model.pde>=2 + if model.pde==2 + AmatT=feval('AmatT_d1',zeros(n_s,n_y*(1+n_x)),params,model.Amat_ind); + elseif model.pde==3 + AmatT=feval('AmatT_d1',zeros(n_s,n_y+model.n_tildy1st+model.n_tildy2nd),params,model.Amat_ind); + end + g_theta=contraction1(AmatT,g_theta); + if order>=1 + gx_theta=contraction1(AmatT,unfold(gx_theta)); + gx_theta=fold(gx_theta,n_x,n_theta*factor); + end + if order>=2 + gxxc_theta=contraction1(AmatT,unfold(gxxc_theta)); + gxxc_theta=fold(gxxc_theta,model.unique2,n_theta*factor); + end + if order>=3 + gxxxc_theta=contraction1(AmatT,unfold(gxxxc_theta)); + gxxxc_theta=fold(gxxxc_theta,model.unique3,n_theta*factor); + end + if order>=4 + gxxxxc_theta=contraction1(AmatT,unfold(gxxxxc_theta)); + gxxxxc_theta=fold(gxxxxc_theta,model.unique4,n_theta*factor); + end + end +elseif model.pde>=1 % compute derivatives of dy w.r.t x and theta + factor=ms+1; + if order==0 + gx__theta=sptensor(n_y*n_x,n_theta*factor,n_s); + else + rows=1:n_y*n_x; + rows=rows(:); + cols=n_y+(1:n_y*n_x); + cols=cols(:); + vals=ones(n_s,length(rows)); + gx__theta=sptensor(rows,cols,vals,n_y*n_x,n_theta*factor); + end + g_theta=vconcat(gx__theta,g_theta); % derivatives and levels + if order>=1 + if order==1 + gx_x_theta=sptensor(n_y*n_x,[n_x,n_theta*factor],n_s); + else + rows=1:n_y*n_x^2; + cols=n_y+n_y*n_x+(1:n_y*model.unique2); + cols=full(reshape(cols,n_y,model.unique2)*model.W{2}); + [rows1,rows2]=ind2sub([n_y*n_x,n_x],rows(:)); + rows=rows1(:); + cols=[rows2(:),cols(:)]; + vals=2*ones(n_s,length(rows)); + gx_x_theta=sptensor(rows,cols,vals,n_y*n_x,[n_x,n_theta*factor]); + end + gx_theta=vconcat(gx_x_theta,gx_theta); + end + if order>=2 + if order==2 + gx_xxc_theta=sptensor(n_y*n_x,[model.unique2,n_theta*factor],n_s); + else + rows=1:n_y*n_x*model.unique2; + cols=n_y+n_y*n_x+n_y*model.unique2+(1:n_y*model.unique3); + cols=full(reshape(cols,n_y,model.unique3)*model.W{3}); + cols=reshape(cols,n_y*n_x,n_x^2); + cols=full(cols*model.U{2}); + + [rows1,rows2]=ind2sub([n_y*n_x,model.unique2],rows(:)); + rows=rows1(:); + cols=[rows2(:),cols(:)]; + vals=6*ones(n_s,length(rows)); + gx_xxc_theta=sptensor(rows,cols,vals,n_y*n_x,[model.unique2,n_theta*factor]); + end + gxxc_theta=vconcat(gx_xxc_theta,gxxc_theta); + end + if order>=3 + if order==3 + gx_xxxc_theta=sptensor(n_y*n_x,[model.unique3,n_theta*factor],n_s); + else + rows=1:n_y*n_x*model.unique3; + cols=n_y+n_y*(n_x+model.unique2+model.unique3)+(1:n_y*model.unique4); + cols=full(reshape(cols,n_y,model.unique4)*model.W{4}); + cols=reshape(cols,n_y*n_x,n_x^3); + cols=full(cols*model.U{3}); + + [rows1,rows2]=ind2sub([n_y*n_x,model.unique3],rows(:)); + rows=rows1(:); + cols=[rows2(:),cols(:)]; + vals=24*ones(n_s,length(rows)); + gx_xxxc_theta=sptensor(rows,cols,vals,n_y*n_x,[model.unique3,n_theta*factor]); + end + gxxxc_theta=vconcat(gx_xxxc_theta,gxxxc_theta); + end + if order>=4 + if order==4 + gx_xxxxc_theta=sptensor(n_y*n_x,[model.unique4,n_theta*factor],n_s); + else + error('order cannot exceed 4') + end + gxxxxc_theta=vconcat(gx_xxxxc_theta,gxxxxc_theta); + end + if model.pde==2 + AmatT=feval('AmatT_d1',zeros(n_s,n_y*(1+n_x)),params,model.Amat_ind); + + g_theta=contraction1(AmatT,g_theta); + if order>=1 + gx_theta=contraction1(AmatT,unfold(gx_theta)); + gx_theta=fold(gx_theta,n_x,n_theta*factor); + end + if order>=2 + gxxc_theta=contraction1(AmatT,unfold(gxxc_theta)); + gxxc_theta=fold(gxxc_theta,model.unique2,n_theta*factor); + end + if order>=3 + gxxxc_theta=contraction1(AmatT,unfold(gxxxc_theta)); + gxxxc_theta=fold(gxxxc_theta,model.unique3,n_theta*factor); + end + if order>=4 + gxxxxc_theta=contraction1(AmatT,unfold(gxxxxc_theta)); + gxxxxc_theta=fold(gxxxxc_theta,model.unique4,n_theta*factor); + end + end +end +% lower block of v_theta, vx_theta and so on +v_theta_lower_terms=vconcat(vconcat(g_theta,h_theta),sptensor(n_x,(ms+1)*n_theta,n_s)); +if order>=1 + vx_theta_lower_terms=vconcat(vconcat(gx_theta,hx_theta),sptensor(n_x,[n_x,(ms+1)*n_theta],n_s)); +end +if order>=2 + unique2=model.unique2; + vxxc_theta_lower_terms=vconcat(vconcat(gxxc_theta,hxxc_theta),sptensor(n_x,[unique2,(ms+1)*n_theta],n_s)); +end +if order>=3 + unique3=model.unique3; + vxxxc_theta_lower_terms=vconcat(vconcat(gxxxc_theta,hxxxc_theta),sptensor(n_x,[unique3,(ms+1)*n_theta],n_s)); +end +if order>=4 + unique4=model.unique4; + vxxxxc_theta_lower_terms=vconcat(vconcat(gxxxxc_theta,hxxxxc_theta),sptensor(n_x,[unique4,(ms+1)*n_theta],n_s)); +end + + + +% current state +nx=x0vec; + +% evaluate policy functions +% if model.pde==2 +% n_y=model.n_tily; +% end + +g=coeffs(:,1:n_y,1);% only constant term is nonzero +h1=coeffs(:,n_y+1:end,1); +h=zeros(n_s,n_x); + +% derivatives of policy functions at x0 (assuming c0=x0) +if order>=1 + gx=coeffs(:,1:n_y,2:1+n_x); + if model.pde==3 + if order==1 + gx_x=sptensor(model.n_tildy1st,n_x,n_s); + gxx_x=sptensor(model.n_tildy2nd,n_x,n_s); + gx_x=vconcat(gxx_x,gx_x); + end + elseif model.pde>=1 + if order==1 + gx_x=sptensor(n_y*n_x,n_x,n_s); + end + end + tempT=sptensor(reshape(gx(1,:,:),n_y,n_x)); + tempT.vals=reshape(permute(gx,[1,3,2]),n_s,n_x*n_y); % permute is needed because tensors are in row format + gx=tempT; + + + h1x=coeffs(:,n_y+1:end,2:1+n_x); + tempT=sptensor(reshape(h1x(1,:,:),n_x1,n_x)); + tempT.vals=reshape(permute(h1x,[1,3,2]),n_s,n_x*n_x1); % permute is needed because tensors are in row format + h1x=tempT; +end + +if order>=2 + gxxc=coeffs(:,1:n_y,2+n_x:1+n_x+unique2)*2; + if model.pde==3 + gx_x=full(reshape(gxxc,n_s*n_y,unique2)*model.W{2}); + gx_x=reshape(gx_x,n_s,n_y*n_x,n_x); + gx_x=gx_x(:,model.tildy1st_ind,:); + tempT=sptensor(reshape(gx_x(1,:,:),model.n_tildy1st,n_x)); + tempT.vals=reshape(permute(gx_x,[1,3,2]),n_s,n_x*model.n_tildy1st); % permute is needed because tensors are in row format + gx_x=tempT; + if order==2 + gx_xxc=sptensor(model.n_tildy1st,unique2,n_s); + gxx_x=sptensor(model.n_tildy2nd,n_x,n_s); + gxx_xxc=sptensor(model.n_tildy2nd,unique2,n_s); + gx_x=vconcat(gxx_x,gx_x); + gx_xxc=vconcat(gxx_xxc,gx_xxc); + + end + elseif model.pde>=1 + gx_x=full(reshape(gxxc,n_s*n_y,unique2)*model.W{2}); + gx_x=reshape(gx_x,n_s,n_y*n_x,n_x); + tempT=sptensor(reshape(gx_x(1,:,:),n_y*n_x,n_x)); + tempT.vals=reshape(permute(gx_x,[1,3,2]),n_s,n_x*n_y*n_x); % permute is needed because tensors are in row format + gx_x=tempT; + if order==2 + gx_xxc=sptensor(n_y*n_x,unique2,n_s); + end + end + tempT=sptensor(reshape(gxxc(1,:,:),n_y,unique2)); + tempT.vals=reshape(permute(gxxc,[1,3,2]),n_s,unique2*n_y); % permute is needed because tensors are in row format + gxxc=tempT; + + h1xxc=coeffs(:,n_y+1:end,2+n_x:1+n_x+unique2)*2; + tempT=sptensor(reshape(h1xxc(1,:,:),n_x1,unique2)); + tempT.vals=reshape(permute(h1xxc,[1,3,2]),n_s,unique2*n_x1); % permute is needed because tensors are in row format + h1xxc=tempT; +end +if order>=3 + gxxxc=coeffs(:,1:n_y,2+n_x+unique2:1+n_x+unique2+unique3)*6; + if model.pde==3 + gx_xx=full(reshape(gxxxc,n_s*n_y,unique3)*model.W{3}); + gx_xx=reshape(gx_xx,n_s*n_y*n_x,n_x^2); + gx_xxc=full(gx_xx*model.U{2}); + gx_xxc=reshape(gx_xxc,n_s,n_y*n_x,unique2); + gx_xxc=gx_xxc(:,model.tildy1st_ind,:); + tempT=sptensor(reshape(gx_xxc(1,:,:),model.n_tildy1st,unique2)); + tempT.vals=reshape(permute(gx_xxc,[1,3,2]),n_s,unique2*model.n_tildy1st); % permute is needed because tensors are in row format + gx_xxc=tempT; + + gxx_x=full(reshape(gxxxc,n_s*n_y,unique3)*model.W{3}); + gxx_x=reshape(gxx_x,n_s,n_y*n_x^2,n_x); + gxx_x=gxx_x(:,model.tildy2nd_ind,:); + tempT=sptensor(reshape(gxx_x(1,:,:),model.n_tildy2nd,n_x)); + tempT.vals=reshape(permute(gxx_x,[1,3,2]),n_s,n_x*model.n_tildy2nd); % permute is needed because tensors are in row format + gxx_x=tempT; + + if order==3 + gx_xxxc=sptensor(model.n_tildy1st,unique3,n_s); + gxx_xxc=sptensor(model.n_tildy2nd,unique2,n_s); + gxx_xxxc=sptensor(model.n_tildy2nd,unique3,n_s); + gx_x=vconcat(gxx_x,gx_x); + gx_xxc=vconcat(gxx_xxc,gx_xxc); + gx_xxxc=vconcat(gxx_xxxc,gx_xxxc); + end + elseif model.pde>=1 + gx_xx=full(reshape(gxxxc,n_s*n_y,unique3)*model.W{3}); + gx_xxc=full(reshape(gx_xx,n_s*n_y*n_x,n_x^2)*model.U{2}); + gx_xxc=reshape(gx_xxc,n_s,n_y*n_x,unique2); + tempT=sptensor(reshape(gx_xxc(1,:,:),n_y*n_x,unique2)); + tempT.vals=reshape(permute(gx_xxc,[1,3,2]),n_s,unique2*n_y*n_x); % permute is needed because tensors are in row format + gx_xxc=tempT; + if order==3 + gx_xxxc=sptensor(n_y*n_x,unique3,n_s); + end + end + tempT=sptensor(reshape(gxxxc(1,:,:),n_y,unique3)); + tempT.vals=reshape(permute(gxxxc,[1,3,2]),n_s,unique3*n_y); % permute is needed because tensors are in row format + gxxxc=tempT; + + h1xxxc=coeffs(:,n_y+1:end,2+n_x+unique2:1+n_x+unique2+unique3)*6; + tempT=sptensor(reshape(h1xxxc(1,:,:),n_x1,unique3)); + tempT.vals=reshape(permute(h1xxxc,[1,3,2]),n_s,unique3*n_x1); % permute is needed because tensors are in row format + h1xxxc=tempT; +end +if order>=4 + gxxxxc=coeffs(:,1:n_y,2+n_x+unique2+unique3:1+n_x+unique2+unique3+unique4)*24; + if model.pde==3 + gx_xxx=full(reshape(gxxxxc,n_s*n_y,unique4)*model.W{4}); + gx_xxx=reshape(gx_xxx,n_s*n_y*n_x,n_x^3); + gx_xxxc=full(gx_xxx*model.U{3}); + gx_xxxc=reshape(gx_xxxc,n_s,n_y*n_x,unique3); + gx_xxxc=gx_xxxc(:,model.tildy1st_ind,:); + tempT=sptensor(reshape(gx_xxxc(1,:,:),model.n_tildy1st,unique3)); + tempT.vals=reshape(permute(gx_xxxc,[1,3,2]),n_s,unique3*model.n_tildy1st); % permute is needed because tensors are in row format + gx_xxxc=tempT; + + gxx_xx=full(reshape(gxxxxc,n_s*n_y,unique4)*model.W{4}); + gxx_xx=reshape(gxx_xx,n_s*n_y*n_x^2,n_x^2); + gxx_xxc=full(gxx_xx*model.U{2}); + gxx_xxc=reshape(gxx_xxc,n_s,n_y*n_x^2,unique2); + gxx_xxc=gxx_xxc(:,model.tildy2nd_ind,:); + tempT=sptensor(reshape(gxx_xxc(1,:,:),model.n_tildy2nd,unique2)); + tempT.vals=reshape(permute(gxx_xxc,[1,3,2]),n_s,unique2*model.n_tildy2nd); % permute is needed because tensors are in row format + gxx_xxc=tempT; + + if order==4 + gx_xxxxc=sptensor(model.n_tildy1st,unique4,n_s); + gxx_xxxc=sptensor(model.n_tildy2nd,unique3,n_s); + gxx_xxxxc=sptensor(model.n_tildy2nd,unique4,n_s); + gx_x=vconcat(gxx_x,gx_x); + gx_xxc=vconcat(gxx_xxc,gx_xxc); + gx_xxxc=vconcat(gxx_xxxc,gx_xxxc); + gx_xxxxc=vconcat(gxx_xxxxc,gx_xxxxc); + end + elseif model.pde>=1 + gx_xxx=full(reshape(gxxxxc,n_s*n_y,unique4)*model.W{4}); + gx_xxxc=full(reshape(gx_xxx,n_s*n_y*n_x,n_x^3)*model.U{3}); + gx_xxxc=reshape(gx_xxxc,n_s,n_y*n_x,unique3); + tempT=sptensor(reshape(gx_xxxc(1,:,:),n_y*n_x,unique3)); + tempT.vals=reshape(permute(gx_xxxc,[1,3,2]),n_s,unique3*n_y*n_x); % permute is needed because tensors are in row format + gx_xxxc=tempT; + if order==4 + gx_xxxxc=sptensor(n_y*n_x,unique4,n_s); + end + end + tempT=sptensor(reshape(gxxxxc(1,:,:),n_y,unique4)); + tempT.vals=reshape(permute(gxxxxc,[1,3,2]),n_s,unique4*n_y); % permute is needed because tensors are in row format + gxxxxc=tempT; + + h1xxxxc=coeffs(:,n_y+1:end,2+n_x+unique2+unique3:1+n_x+unique2+unique3+unique4)*24; + tempT=sptensor(reshape(h1xxxxc(1,:,:),n_x1,unique4)); + tempT.vals=reshape(permute(h1xxxxc,[1,3,2]),n_s,unique4*n_x1); % permute is needed because tensors are in row format + h1xxxxc=tempT; +end +% control vars +if model.pde==0 + ny=g; +elseif model.pde==3 + if order==0 + ny=full([zeros(1,model.n_tildy2nd+model.n_tildy1st),g]); + elseif order==1 + temp=reshape(permute(reshape(gx.vals,n_s,n_x,n_y),[1,3,2]),n_s,n_y*n_x); + temp=temp(:,model.tildy1st_ind); + ny=full([zeros(n_s,model.n_tildy2nd),temp,g]); + elseif order>=2 + temp1=reshape(permute(reshape(gx.vals,n_s,n_x,n_y),[1,3,2]),n_s,n_y*n_x); + temp1=temp1(:,model.tildy1st_ind); + temp2=reshape(permute(reshape(gxxc.vals,n_s,unique2,n_y),[1,3,2]),n_s*n_y,unique2); + temp2=full(temp2*model.W{2}); + temp2=reshape(temp2,n_s,n_y*n_x^2); + temp2=temp2(:,model.tildy2nd_ind); + ny=full([temp2,temp1,g]); + end +else + if order==0 + ny=full([zeros(1,n_y*n_x),g]); + else + ny=full([reshape(permute(reshape(gx.vals,n_s,n_x,n_y),[1,3,2]),n_s,n_y*n_x),g]); + end +end + +if model.pde>=2 +% n_y=old_n_y; + tildy_tily=ny; + if model.pde==2 + tildy_tilyT=sptensor(zeros(n_y*(1+n_x),1)); + else + tildy_tilyT=sptensor(zeros(n_y+model.n_tildy1st+model.n_tildy2nd,1)); + end + tildy_tilyT.vals=tildy_tily; + nyT=contraction1(AmatT,tildy_tilyT); % this is the vector of the original [dy;y] + ny=nyT.vals; +end +% STEP 1: COMPUTE NONSTOCHASTIC EQUATIONS AND DERIVATIVES, AND THEIR JACOBIAN + +% build h(x) +h(:,1:n_x1,1)=h1; % predetermined endogenous state vars + +if model.hybrid==0 + uname=['Phi' model.uname '_fun']; + h(:,n_x1+1:end,1)=feval(uname,nx,params); % expected value of exogenous state vars. shocks are added later + + % derivatives of h at x0 + if order>=1 + hx=vconcat(h1x,Phi_d_c1(nx,params,model.Phi_indc)); + end + if order>=2 + hxxc=vconcat(h1xxc,Phi_d_c2(nx,params,model.Phi_indc)); + end + if order>=3 + hxxxc=vconcat(h1xxxc,Phi_d_c3(nx,params,model.Phi_indc)); + end + if order>=4 + hxxxxc=vconcat(h1xxxxc,Phi_d_c4(nx,params,model.Phi_indc)); + end +else + % derivatives of h at x0 + if order>=1 + hx=vconcat(h1x,sptensor(n_x2,n_x,n_s)); + end + if order>=2 + hxxc=vconcat(h1xxc,sptensor(n_x2,model.unique2,n_s)); + end + if order>=3 + hxxxc=vconcat(h1xxxc,sptensor(n_x2,model.unique3,n_s)); + end + if order>=4 + hxxxxc=vconcat(h1xxxxc,sptensor(n_x2,model.unique4,n_s)); + end +end + +% expected value of next period state variables. +nxp=h; + +% evaluate residuals R0 +if model.pde==0 + nv=[zeros(n_s,n_y),ny,nxp,nx]; % model variables, yp are zero for now, and nxp is an expected value. stochastic components will be added later. +elseif model.pde==1 + nv=[zeros(n_s,n_y*(n_x+1)),ny,nxp,nx]; +elseif model.pde>=2 + nv=[zeros(n_s,model.n_y_extended),ny,nxp,nx]; +end + +n_u=model.n_u; +nu=zeros(n_s,n_u); +uname=['preu' model.uname '_fun']; +npreu=feval(uname,nv(:,model.preuvars),params); % all predetermined u +nu(:,model.preurows)=npreu; + +% This block is not necessary, because f is independent of x2p (they are treated +% as auxiliary variables and substituted out) +% if model.hybrid==1 +% nxp(:,n_x1+1:end)=nu(:,end-n_x2+1:end); % last block of auxiliary variables are the hybrid state variables +% nv=[zeros(n_s,n_y),ny,nxp,nx]; +% end + +nz=[nv,nu]; % auxiliary variables +params(:,model.logical_params_loc)=double(logical(nz(:,model.logical_zvars)>0)); + +if isempty(model.prefrows) + preR0=sptensor(0,1,n_s); + preR1=sptensor(0,n_x,n_s); + preR2=sptensor(0,unique2,n_s); + preR3=sptensor(0,unique3,n_s); + preR4=sptensor(0,unique4,n_s); + preJ0=sptensor(0,(ms+1)*n_theta,n_s); + preJ1=sptensor(0,[n_x,(ms+1)*n_theta],n_s); + preJ2=sptensor(0,[unique2,(ms+1)*n_theta],n_s); + preJ3=sptensor(0,[unique3,(ms+1)*n_theta],n_s); + preJ4=sptensor(0,[unique4,(ms+1)*n_theta],n_s); + + % compute variables that will be necessary later + uname=['prePI' model.uname '_d1']; + + prePIz_full=feval(uname,nz,params,model.prePI_ind_u); + if order>=1 + uname=['prePI' model.uname '_d2']; + prePIzz_full=feval(uname,nz,params,model.prePI_ind_u); + vx=vconcat(sptensor(n_y,n_x,n_s),gx); + vx=vconcat(vx,hx); + vx=vconcat(vx,spteye(n_x,n_s)); + + end + if order>=2 + uname=['prePI' model.uname '_d3']; + prePIzzz_full=feval(uname,nz,params,model.prePI_ind_u); + if ~isfield(model,'chain2c_theta_M2') + GAMMA=create_GAMMA(n_x,(ms+1)*n_theta,2); + U2=create_UW(n_x,2); + model.chain2c_theta_M2=spmat2sptensor(GAMMA.GAMMA1*U2); + clear GAMMA U2 + end + vxxc=vconcat(sptensor(n_y,unique2,n_s),gxxc); + vxxc=vconcat(vxxc,hxxc); + vxxc=vconcat(vxxc,sptensor(n_x,unique2,n_s)); + end + if order>=3 + uname=['prePI' model.uname '_d4']; + prePIzzzz_full=feval(uname,nz,params,model.prePI_ind_u); + if ~isfield(model,'x_chain3c_M2') + [~,W2x]=create_UW(n_x,2); + [U3x,~]=create_UW(n_x,3); + OMEGAx=create_OMEGA(n_x,3); + model.x_chain3c_M2=spmat2sptensor(kron(speye(n_x),W2x)*OMEGAx.OMEGA1*U3x); + clear W2x U3x + end + if ~isfield(model,'chain3c_theta_M2') + GAMMA=create_GAMMA(n_x,(ms+1)*n_theta,3); + [~,W2]=create_UW(n_x,2); + U3=create_UW(n_x,3); + model.chain3c_theta_M2=spmat2sptensor(kron(W2,speye(n_x))*GAMMA.GAMMA2*U3); + model.chain3c_theta_M3=spmat2sptensor(kron(speye(n_x),W2)*GAMMA.GAMMA3*U3); + model.chain3c_theta_M4=spmat2sptensor(kron(speye(n_x),W2)*GAMMA.GAMMA4*U3); + tempind=1:unique2*n_x; + tempmat=speye(unique2*n_x); + model.chain3c_theta_M5=spmat2sptensor(tempmat(:,permute(reshape(tempind,n_x,unique2),[2,1]))*kron(speye(n_x),W2)*GAMMA.GAMMA5*U3); + clear GAMMA W2 U3 GAMMA + + end + vxxxc=vconcat(sptensor(n_y,unique3,n_s),gxxxc); + vxxxc=vconcat(vxxxc,hxxxc); + vxxxc=vconcat(vxxxc,sptensor(n_x,unique3,n_s)); + + end + if order>=4 + uname=['prePI' model.uname '_d5']; + prePIzzzzz_full=feval(uname,nz,params,model.prePI_ind_u); + if ~isfield(model,'x_chain3c_M2') + [~,W2x]=create_UW(n_x,2); + [U3x,~]=create_UW(n_x,3); + OMEGAx=create_OMEGA(n_x,3); + model.x_chain3c_M2=spmat2sptensor(kron(speye(n_x),W2x)*OMEGAx.OMEGA1*U3x); + clear W2x U3x + end + if ~isfield(model,'chain3c_theta_M2') + GAMMA=create_GAMMA(n_x,(ms+1)*n_theta,3); + [~,W2]=create_UW(n_x,2); + U3=create_UW(n_x,3); + model.chain3c_theta_M2=spmat2sptensor(kron(W2,speye(n_x))*GAMMA.GAMMA2*U3); + model.chain3c_theta_M3=spmat2sptensor(kron(speye(n_x),W2)*GAMMA.GAMMA3*U3); + model.chain3c_theta_M4=spmat2sptensor(kron(speye(n_x),W2)*GAMMA.GAMMA4*U3); + tempind=1:unique2*n_x; + tempmat=speye(unique2*n_x); + model.chain3c_theta_M5=spmat2sptensor(tempmat(:,permute(reshape(tempind,n_x,unique2),[2,1]))*kron(speye(n_x),W2)*GAMMA.GAMMA5*U3); + clear GAMMA W2 U3 GAMMA + + end + vxxxxc=vconcat(sptensor(n_y,unique4,n_s),gxxxxc); + vxxxxc=vconcat(vxxxxc,hxxxxc); + vxxxxc=vconcat(vxxxxc,sptensor(n_x,unique4,n_s)); + + end +% v_theta=[]; + v_theta=sptensor(0,(ms+1)*n_theta,n_s); + if model.hybrid==3 + v_theta=vconcat(sptensor(n_y,(ms+1)*n_theta,n_s),v_theta_lower_terms); + if order>=1 + vx_theta=vconcat(sptensor(n_y,[n_x,(ms+1)*n_theta],n_s),vx_theta_lower_terms); + end + if order>=2 + vxxc_theta=vconcat(sptensor(n_y,[unique2,(ms+1)*n_theta],n_s),vxxc_theta_lower_terms); + end + if order>=3 + vxxxc_theta=vconcat(sptensor(n_y,[unique3,(ms+1)*n_theta],n_s),vxxxc_theta_lower_terms); + end + if order>=4 + vxxxxc_theta=vconcat(sptensor(n_y,[unique4,(ms+1)*n_theta],n_s),vxxxxc_theta_lower_terms); + if ~isfield(model,'x_chain4c_M2') + [~,W2new]=create_UW(unique2,2); + [~,W2x]=create_UW(n_x,2); + [~,W3x]=create_UW(n_x,3); + [U4x,~]=create_UW(n_x,4); + OMEGAx=create_OMEGA(n_x,4); + model.x_chain4c_M2=spmat2sptensor(kron(W2x,W2x)*OMEGAx.OMEGA2*U4x); + model.x_chain4c_M3=spmat2sptensor(kron(speye(n_x),W3x)*OMEGAx.OMEGA3*U4x); + model.x_chain4c_M4=spmat2sptensor(W2new*kron(W2x,W2x)*OMEGAx.OMEGA4*U4x); + clear W2new W2x W3x U4x OMEGAx + end + if ~isfield(model,'chain4c_theta_M2') + GAMMA=create_GAMMA(n_x,(ms+1)*n_theta,4); + [~,W2]=create_UW(n_x,2); + [~,W3]=create_UW(n_x,3); + U4=create_UW(n_x,4); + [~,W2new]=create_UW(unique2,2); + model.chain4c_theta_M2=spmat2sptensor(kron(W3,speye(n_x))*GAMMA.GAMMA16*U4); + model.chain4c_theta_M3=spmat2sptensor(kron(W2,W2)*GAMMA.GAMMA2*U4); + model.chain4c_theta_M5=spmat2sptensor(kron(speye(n_x^2),W2)*GAMMA.GAMMA17*GAMMA.GAMMA2*U4); + model.chain4c_theta_M6=spmat2sptensor(kron(speye(n_x),W3)*GAMMA.GAMMA3*U4); + model.chain4c_theta_M9=spmat2sptensor(W2new*kron(W2,W2)*GAMMA.GAMMA4*U4); + model.chain4c_theta_M10=spmat2sptensor(kron(W2,W2)*GAMMA.GAMMA18*GAMMA.GAMMA4*U4); + + clear GAMMA W2 W3 U4 W2new + + end + end + end + + totindi=5+8; + totindi=totindi+model.count_pre_n*(1+3+4+6)+1+4+6+9; + totindi=totindi+3; + totindi=totindi+4; + + indi=totindi; +else + + fname=['pretilf' model.fname '_fun']; + pref=feval(fname,nz(:,model.pretilfzvars),params); % since i already have z, i use pretilf to evaluate f. + + + % compute derivatives of prePI and pretilf w.r.t z (prePI=nonstochastic rows of PI, pretilf=nonstochastic rows of f) + uname=['prePI' model.uname '_d1']; + prePIz_full=feval(uname,nz,params,model.prePI_ind_u); + + fname=['pretilf' model.fname '_tilf_d1']; + pretilfz=feval(fname,[nv(:,prefvars),nu(:,model.prefuvars)],params,model.pretilf_ind_u); + if order>=1 + uname=['prePI' model.uname '_d2']; + prePIzz_full=feval(uname,nz,params,model.prePI_ind_u); + fname=['pretilf' model.fname '_tilf_d2']; + pretilfzz=feval(fname,[nv(:,prefvars),nu(:,model.prefuvars)],params,model.pretilf_ind_u); + end + if order>=2 + uname=['prePI' model.uname '_d3']; + prePIzzz_full=feval(uname,nz,params,model.prePI_ind_u); + fname=['pretilf' model.fname '_tilf_d3']; + pretilfzzz=feval(fname,[nv(:,prefvars),nu(:,model.prefuvars)],params,model.pretilf_ind_u); + end + if order>=3 + uname=['prePI' model.uname '_d4']; + prePIzzzz_full=feval(uname,nz,params,model.prePI_ind_u); + fname=['pretilf' model.fname '_tilf_d4']; + pretilfzzzz=feval(fname,[nv(:,prefvars),nu(:,model.prefuvars)],params,model.pretilf_ind_u); + end + if order>=4 + uname=['prePI' model.uname '_d5']; + prePIzzzzz_full=feval(uname,nz,params,model.prePI_ind_u); + fname=['pretilf' model.fname '_tilf_d5']; + pretilfzzzzz=feval(fname,[nv(:,prefvars),nu(:,model.prefuvars)],params,model.pretilf_ind_u); + end + + % extract derivatives of prePI w.r.t v from prePIz, prePIzz, ... + if order>=0 + [prePIz,model.ind{indi}]=extract(prePIz_full,model.prefzvars,model.prefzvars,0,model.ind{indi}); + indi=indi+1; + [prePIv,model.ind{indi}]=extract(prePIz_full,model.prefzvars,model.prefvars,0,model.ind{indi}); + indi=indi+1; + end + if order>=1 + [prePIzz,model.ind{indi}]=extract(prePIzz_full,model.prefzvars,model.prefzvars,0,model.ind{indi}); + indi=indi+1; + [prePIvvc,model.ind{indi}]=extract(prePIzz_full,model.prefzvars,model.prefvars,1,model.ind{indi}); + indi=indi+1; + end + if order>=2 + [prePIzzz,model.ind{indi}]=extract(prePIzzz_full,model.prefzvars,model.prefzvars,0,model.ind{indi}); + indi=indi+1; + [prePIvvvc,model.ind{indi}]=extract(prePIzzz_full,model.prefzvars,model.prefvars,1,model.ind{indi}); + indi=indi+1; + if ~isfield(model,'prefvars_chain3c_M2') + [ tempM ] = chainsM( n_prefvars,3 ); + model.prefvars_chain3c_M2=tempM{2}; + clear tempM + end + end + if order>=3 + [prePIzzzz,model.ind{indi}]=extract(prePIzzzz_full,model.prefzvars,model.prefzvars,0,model.ind{indi}); + indi=indi+1; + [prePIvvvvc,model.ind{indi}]=extract(prePIzzzz_full,model.prefzvars,model.prefvars,1,model.ind{indi}); + indi=indi+1; + if ~isfield(model,'prefvars_chain4c_M2') + [ tempM ] = chainsM( n_prefvars,4 ); + model.prefvars_chain4c_M2=tempM{2}; + model.prefvars_chain4c_M3=tempM{3}; + model.prefvars_chain4c_M4=tempM{4}; + clear tempM + end + end + if order>=4 + [prePIzzzzz,model.ind4{indi4}]=extract(prePIzzzzz_full,model.prefzvars,model.prefzvars,0,model.ind4{indi4}); + indi4=indi4+1; + [prePIvvvvvc,model.ind4{indi4}]=extract(prePIzzzzz_full,model.prefzvars,model.prefvars,1,model.ind4{indi4}); + indi4=indi4+1; + end + + % Use high order chain rules to compute derivatives of prePI w.r.t v + totindi=5+8; + if order==0 + indi=totindi; + for i=2:model.pre_n + [prePIv,model.ind{indi}]=chain1_tensor(prePIz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [prefv,model.ind{indi}]=chain1_tensor(pretilfz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + model.prefv=prefv; + elseif order==1 + indi=totindi+model.count_pre_n*(1)+1; + for i=2:model.pre_n + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + [prePIvvc,model.ind{indi}]=chain2c_tensor(prePIz,prePIzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIv,model.ind{indi}]=chain1_tensor(prePIz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + + [prefv,model.ind{indi}]=chain1_tensor(pretilfz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvc,model.ind{indi}]=chain2c_tensor(pretilfz,pretilfzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [ prefvv,model.ind{indi} ] = uncompressderivs( prefvvc,2,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + + model.prefv=prefv; + model.prefvv=prefvv; + + elseif order==2 + indi=totindi+model.count_pre_n*(1+3)+1+4; + for i=2:model.pre_n +% tic + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + [prePIvvvc,model.ind{indi}]=chain3c_tensor(prePIz,prePIzz,prePIzzz,... + prePIv,prePIvvc,prePIvvvc,model.prefvars_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIvvc,model.ind{indi}]=chain2c_tensor(prePIz,prePIzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIv,model.ind{indi}]=chain1_tensor(prePIz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; +% toc + end + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + + [prefv,model.ind{indi}]=chain1_tensor(pretilfz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvc,model.ind{indi}]=chain2c_tensor(pretilfz,pretilfzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvvc,model.ind{indi}]=chain3c_tensor(pretilfz,pretilfzz,pretilfzzz,... + prePIv,prePIvvc,prePIvvvc,... + model.prefvars_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [ prefvv,model.ind{indi} ] = uncompressderivs( prefvvc,2,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + + [ prefvvv,model.ind{indi} ] = uncompressderivs( prefvvvc,3,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + + model.prefv=prefv; + model.prefvv=prefvv; + model.prefvvv=prefvvv; + + elseif order==3 + indi=totindi+model.count_pre_n*(1+3+4)+1+4+6; +% tic + for i=2:model.pre_n + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + [prePIvvc,model.ind{indi}]=colsort(prePIvvc,model.ind{indi}); + indi=indi+1; + [prePIvvvvc,model.ind{indi}]=chain4c_tensor(prePIz,prePIzz,prePIzzz,prePIzzzz,... + prePIv,prePIvvc,prePIvvvc,prePIvvvvc,... + model.prefvars_chain4c_M2,model.prefvars_chain4c_M3,model.prefvars_chain4c_M4,... + model.ind{indi},n_ind,maxload,'vec',model.prezz,model.maxzz); + indi=indi+1; + [prePIvvvc,model.ind{indi}]=chain3c_tensor(prePIz,prePIzz,prePIzzz,... + prePIv,prePIvvc,prePIvvvc,model.prefvars_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIvvc,model.ind{indi}]=chain2c_tensor(prePIz,prePIzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIv,model.ind{indi}]=chain1_tensor(prePIz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end +% toc + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + [prePIvvc,model.ind{indi}]=colsort(prePIvvc,model.ind{indi}); + indi=indi+1; + + [prefv,model.ind{indi}]=chain1_tensor(pretilfz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [prefvvc,model.ind{indi}]=chain2c_tensor(pretilfz,pretilfzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvvc,model.ind{indi}]=chain3c_tensor(pretilfz,pretilfzz,pretilfzzz,... + prePIv,prePIvvc,prePIvvvc,... + model.prefvars_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvvvc,model.ind{indi}]=chain4c_tensor(pretilfz,pretilfzz,pretilfzzz,pretilfzzzz,... + prePIv,prePIvvc,prePIvvvc,prePIvvvvc,... + model.prefvars_chain4c_M2,model.prefvars_chain4c_M3,model.prefvars_chain4c_M4,... + model.ind{indi},n_ind,maxload,'vec',model.pretilfz,model.maxtilfz); + indi=indi+1; + + [ prefvv,model.ind{indi} ] = uncompressderivs( prefvvc,2,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + + [ prefvvv,model.ind{indi} ] = uncompressderivs( prefvvvc,3,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + + [ prefvvvv,model.ind{indi} ] = uncompressderivs( prefvvvvc,4,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + + model.prefv=prefv; + model.prefvv=prefvv; + model.prefvvv=prefvvv; + model.prefvvvv=prefvvvv; + + + elseif order==4 + indi=totindi+model.count_pre_n*(1+3+4)+1+4+6; + for i=2:model.pre_n + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + [prePIvvc,model.ind{indi}]=colsort(prePIvvc,model.ind{indi}); + indi=indi+1; + [prePIvvvvvc,model.ind4{indi4}]=chain5c_tensor(prePIz,prePIzz,prePIzzz,prePIzzzz,prePIzzzzz,... + prePIv,prePIvvc,prePIvvvc,prePIvvvvc,prePIvvvvvc,... + model.prefvars_chain5c_M1,model.prefvars_chain5c_M2,model.prefvars_chain5c_M3,model.prefvars_chain5c_M4,model.prefvars_chain5c_M5,model.prefvars_chain5c_M6,... + model.ind4{indi4},n_ind,maxload,'vec',model.prezz,model.maxzz); + indi4=indi4+1; + [prePIvvvvc,model.ind{indi}]=chain4c_tensor(prePIz,prePIzz,prePIzzz,prePIzzzz,... + prePIv,prePIvvc,prePIvvvc,prePIvvvvc,... + model.prefvars_chain4c_M2,model.prefvars_chain4c_M3,model.prefvars_chain4c_M4,... + model.ind{indi},n_ind,maxload,'vec',model.prezz,model.maxzz); + indi=indi+1; + [prePIvvvc,model.ind{indi}]=chain3c_tensor(prePIz,prePIzz,prePIzzz,... + prePIv,prePIvvc,prePIvvvc,model.prefvars_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIvvc,model.ind{indi}]=chain2c_tensor(prePIz,prePIzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prePIv,model.ind{indi}]=chain1_tensor(prePIz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [prePIv,model.ind{indi}]=colsort(prePIv,model.ind{indi}); + indi=indi+1; + [prePIvvc,model.ind{indi}]=colsort(prePIvvc,model.ind{indi}); + indi=indi+1; + + [prefv,model.ind{indi}]=chain1_tensor(pretilfz,prePIv,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [prefvvc,model.ind{indi}]=chain2c_tensor(pretilfz,pretilfzz,prePIv,prePIvvc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvvc,model.ind{indi}]=chain3c_tensor(pretilfz,pretilfzz,pretilfzzz,... + prePIv,prePIvvc,prePIvvvc,... + model.prefvars_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [prefvvvvc,model.ind{indi}]=chain4c_tensor(pretilfz,pretilfzz,pretilfzzz,pretilfzzzz,... + prePIv,prePIvvc,prePIvvvc,prePIvvvvc,... + model.prefvars_chain4c_M2,model.prefvars_chain4c_M3,model.prefvars_chain4c_M4,... + model.ind{indi},n_ind,maxload,'vec',model.pretilfz,model.maxtilfz); + indi=indi+1; + + [prefvvvvvc,model.ind4{indi4}]=chain5c_tensor(pretilfz,pretilfzz,pretilfzzz,pretilfzzzz,pretilfzzzzz,... + prePIv,prePIvvc,prePIvvvc,prePIvvvvc,prePIvvvvvc,... + model.prefvars_chain5c_M1,model.prefvars_chain5c_M2,model.prefvars_chain5c_M3,model.prefvars_chain5c_M4,model.prefvars_chain5c_M5,model.prefvars_chain5c_M6,... + model.ind4{indi4},n_ind,maxload,'vec',model.pretilfz,model.maxtilfz); + indi4=indi4+1; + + [ prefvv,model.ind{indi} ] = uncompressderivs( prefvvc,2,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + + [ prefvvv,model.ind{indi} ] = uncompressderivs( prefvvvc,3,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + + [ prefvvvv,model.ind{indi} ] = uncompressderivs( prefvvvvc,4,n_prefvars,model.fv(model.prefrows,prefvars),model.ind{indi} ); + indi=indi+1; + + [ prefvvvvv,model.ind4{indi4} ] = uncompressderivs( prefvvvvvc,5,n_prefvars,model.fv(model.prefrows,prefvars),model.ind4{indi4} ); + indi4=indi4+1; + + model.prefv=prefv; + model.prefvv=prefvv; + model.prefvvv=prefvvv; + model.prefvvvv=prefvvvv; + + end + totindi=totindi+model.count_pre_n*(1+3+4+6)+1+4+6+9; + indi=totindi; + + if model.steady_state==1 + if size(prefv.vals,1)~=1 + error('cannot compute steady state on vectorized tensors') + end + nzprefv=prefv; + nzprefv.vals(:)=1; + nzprefv=sptensor2spmat(nzprefv); + nzprefv_full=zeros(n_prefrows,model.n_v); + nzprefv_full(:,model.prefvars)=full(nzprefv); + nzprefv_full(:,2*model.n_y+(1:model.n_x1))=nzprefv_full(:,2*model.n_y+(1:model.n_x1))+nzprefv_full(:,2*model.n_y+model.n_x+(1:model.n_x1)); + nzprefv=nzprefv_full(:,model.prefvars); + [i,j]=find(nzprefv); + + prefv=sptensor2spmat(prefv); + prefv_full=zeros(n_prefrows,model.n_v); + prefv_full(:,model.prefvars)=full(prefv); + prefv_full(:,2*model.n_y+(1:model.n_x1))=prefv_full(:,2*model.n_y+(1:model.n_x1))+prefv_full(:,2*model.n_y+model.n_x+(1:model.n_x1)); + prefv=prefv_full(:,model.prefvars); + + vals=prefv(logical(nzprefv(:))); + + prefv=sptensor(i(:),j(:),vals(:)',size(prefv,1),size(prefv,2)); + end + + tempT=sptensor(zeros(n_prefrows,1)); + tempT.vals=full(pref); % n_s,n_prefrows + preR0=tempT; + + % compute R1 (first order derivatives of R w.r.t x) + if order>=1 + if model.pde==0 + vx=vconcat(sptensor(n_y,n_x,n_s),gx); + elseif model.pde==1 + vx=vconcat(sptensor(n_y*(n_x+1),n_x,n_s),gx_x); + vx=vconcat(vx,gx); + elseif model.pde>=2 + gx_x_gx=contraction1(AmatT,vconcat(gx_x,gx)); + vx=vconcat(sptensor(model.n_y_extended,n_x,n_s),gx_x_gx); + end + vx=vconcat(vx,hx); + vx=vconcat(vx,spteye(n_x,n_s)); + model.vx=vx; + + prevx=takerows(vx,prefvars); + if isempty(pref) + preR1=sptensor(0,n_x,n_s); + else + [preR1,model.ind{indi}]=chain1_tensor(prefv,prevx,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + end + + % compute R2 (second order derivatives of R w.r.t x) + if order>=2 + if model.pde==0 + vxxc=vconcat(sptensor(n_y,unique2,n_s),gxxc); + elseif model.pde==1 + vxxc=vconcat(sptensor(n_y*(n_x+1),unique2,n_s),gx_xxc); + vxxc=vconcat(vxxc,gxxc); + elseif model.pde>=2 + gx_xxc_gxxc=contraction1(AmatT,vconcat(gx_xxc,gxxc)); + vxxc=vconcat(sptensor(model.n_y_extended,unique2,n_s),gx_xxc_gxxc); + end + vxxc=vconcat(vxxc,hxxc); + vxxc=vconcat(vxxc,sptensor(n_x,unique2,n_s)); + model.vxxc=vxxc; + prevxxc=takerows(vxxc,prefvars); + [prevx,model.ind4{indi4}]=colsort(prevx,model.ind4{indi4}); % i use model.ind4 because i forgot to put it in model.ind + indi4=indi4+1; + if isempty(pref) + preR2=sptensor(0,unique2,n_s); + else + [preR2,model.ind{indi}]=chain2c_tensor(prefv,prefvv,prevx,prevxxc,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + end + + % compute R3 (third order derivatives of R w.r.t x) + if order>=3 + if model.pde==0 + vxxxc=vconcat(sptensor(n_y,unique3,n_s),gxxxc); + elseif model.pde==1 + vxxxc=vconcat(sptensor(n_y*(n_x+1),unique3,n_s),gx_xxxc); + vxxxc=vconcat(vxxxc,gxxxc); + elseif model.pde>=2 + gx_xxxc_gxxxc=contraction1(AmatT,vconcat(gx_xxxc,gxxxc)); + vxxxc=vconcat(sptensor(model.n_y_extended,unique3,n_s),gx_xxxc_gxxxc); + end + vxxxc=vconcat(vxxxc,hxxxc); + vxxxc=vconcat(vxxxc,sptensor(n_x,unique3,n_s)); + model.vxxxc=vxxxc; + prevxxxc=takerows(vxxxc,prefvars); + + if ~isfield(model,'x_chain3c_M2') + [~,W2x]=create_UW(n_x,2); + [U3x,~]=create_UW(n_x,3); + OMEGAx=create_OMEGA(n_x,3); + model.x_chain3c_M2=spmat2sptensor(kron(speye(n_x),W2x)*OMEGAx.OMEGA1*U3x); + clear W2x U3x OMEGAx + end + + if isempty(pref) + preR3=sptensor(0,unique3,n_s); + else + [preR3,model.ind{indi}]=chain3c_tensor(prefv,prefvv,prefvvv,prevx,prevxxc,prevxxxc,model.x_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + + end + + % compute R4 (fourth order derivatives of R w.r.t x) + if order>=4 + if model.pde==0 + vxxxxc=vconcat(sptensor(n_y,unique4,n_s),gxxxxc); + elseif model.pde==1 + vxxxxc=vconcat(sptensor(n_y*(n_x+1),unique4,n_s),gx_xxxxc); + vxxxxc=vconcat(vxxxxc,gxxxxc); + elseif model.pde>=2 + gx_xxxxc_gxxxxc=contraction1(AmatT,vconcat(gx_xxxxc,gxxxxc)); + vxxxxc=vconcat(sptensor(model.n_y_extended,unique4,n_s),gx_xxxxc_gxxxxc); + end + vxxxxc=vconcat(vxxxxc,hxxxxc); + vxxxxc=vconcat(vxxxxc,sptensor(n_x,unique4,n_s)); + model.vxxxxc=vxxxxc; + prevxxxxc=takerows(vxxxxc,prefvars); + + if ~isfield(model,'x_chain4c_M2') + [~,W2new]=create_UW(unique2,2); + [~,W2x]=create_UW(n_x,2); + [~,W3x]=create_UW(n_x,3); + [U4x,~]=create_UW(n_x,4); + OMEGAx=create_OMEGA(n_x,4); + model.x_chain4c_M2=spmat2sptensor(kron(W2x,W2x)*OMEGAx.OMEGA2*U4x); + model.x_chain4c_M3=spmat2sptensor(kron(speye(n_x),W3x)*OMEGAx.OMEGA3*U4x); + model.x_chain4c_M4=spmat2sptensor(W2new*kron(W2x,W2x)*OMEGAx.OMEGA4*U4x); + clear W2new W2x W3x U4x OMEGAx + end + + if isempty(pref) + preR4=sptensor(0,unique4,n_s); + else + [prevxxc,model.ind4{indi4}]=colsort(prevxxc,model.ind4{indi4}); + indi4=indi4+1; + + [preR4,model.ind4{indi4}]=chain4c_tensor(prefv,prefvv,prefvvv,prefvvvv,prevx,prevxxc,prevxxxc,prevxxxxc,... + model.x_chain4c_M2,model.x_chain4c_M3,model.x_chain4c_M4,model.ind4{indi4},n_ind,maxload,'vec'); + indi4=indi4+1; + end + + end + totindi=totindi+3; + indi=totindi; + % Jacobian of the nonstochastic equations and derivatives + + if model.pde==0 + v_theta=vconcat(sptensor(n_y,(ms+1)*n_theta,n_s),v_theta_lower_terms); + elseif model.pde==1 + v_theta=vconcat(sptensor(n_y*(n_x+1),(ms+1)*n_theta,n_s),v_theta_lower_terms); + elseif model.pde>=2 + v_theta=vconcat(sptensor(model.n_y_extended,(ms+1)*n_theta,n_s),v_theta_lower_terms); + end + + prev_theta=takerows(v_theta,prefvars); + + [ preJ0,model.ind{indi} ] = chain0_theta_tensor( prefv,prev_theta,model.ind{indi},n_ind,maxload,'vec' ); + indi=indi+1; + + if order>=1 + if model.pde==0 + vx_theta=vconcat(sptensor(n_y,[n_x,(ms+1)*n_theta],n_s),vx_theta_lower_terms); + elseif model.pde==1 + vx_theta=vconcat(sptensor(n_y*(n_x+1),[n_x,(ms+1)*n_theta],n_s),vx_theta_lower_terms); + elseif model.pde>=2 + vx_theta=vconcat(sptensor(model.n_y_extended,[n_x,(ms+1)*n_theta],n_s),vx_theta_lower_terms); + end + model.vx_theta=vx_theta; + prevx_theta=takerows(vx_theta,prefvars); + prevx_theta=unfold(prevx_theta); + if isempty(pref) + preJ1=sptensor(zeros(0,1),zeros(0,2),zeros(n_s,0),0,[n_x,(ms+1)*n_theta]); + else + [ preJ1,model.ind{indi} ] = chain1_theta_tensor( prefv,prefvv,... + prevx,prev_theta,prevx_theta,... + model.ind{indi},n_ind,maxload,'vec' ); + indi=indi+1; + end + end + if order>=2 + if model.pde==0 + vxxc_theta=vconcat(sptensor(n_y,[unique2,(ms+1)*n_theta],n_s),vxxc_theta_lower_terms); + elseif model.pde==1 + vxxc_theta=vconcat(sptensor(n_y*(n_x+1),[unique2,(ms+1)*n_theta],n_s),vxxc_theta_lower_terms); + elseif model.pde>=2 + vxxc_theta=vconcat(sptensor(model.n_y_extended,[unique2,(ms+1)*n_theta],n_s),vxxc_theta_lower_terms); + end + model.vxxc_theta=vxxc_theta; + prevxxc_theta=takerows(vxxc_theta,prefvars); + prevxxc_theta=unfold(prevxxc_theta); + + if ~isfield(model,'chain2c_theta_M2') + GAMMA=create_GAMMA(n_x,(ms+1)*n_theta,2); + U2=create_UW(n_x,2); + model.chain2c_theta_M2=spmat2sptensor(GAMMA.GAMMA1*U2); + clear GAMMA U2 + end + + if isempty(pref) + preJ2=sptensor(zeros(0,1),zeros(0,2),zeros(n_s,0),0,[unique2,(ms+1)*n_theta]); + else + [ preJ2,model.ind{indi} ] = chain2c_theta_tensor( prefv,prefvv,prefvvv,... + prevx,prevxxc,... + prev_theta,prevx_theta,prevxxc_theta,... + model.chain2c_theta_M2,... + model.ind{indi},n_ind,maxload,'vec' ); + indi=indi+1; + end + end + if order>=3 + if model.pde==0 + vxxxc_theta=vconcat(sptensor(n_y,[unique3,(ms+1)*n_theta],n_s),vxxxc_theta_lower_terms); + elseif model.pde==1 + vxxxc_theta=vconcat(sptensor(n_y*(n_x+1),[unique3,(ms+1)*n_theta],n_s),vxxxc_theta_lower_terms); + elseif model.pde>=2 + vxxxc_theta=vconcat(sptensor(model.n_y_extended,[unique3,(ms+1)*n_theta],n_s),vxxxc_theta_lower_terms); + end + model.vxxxc_theta=vxxxc_theta; + prevxxxc_theta=takerows(vxxxc_theta,prefvars); + prevxxxc_theta=unfold(prevxxxc_theta); + + if ~isfield(model,'chain3c_theta_M2') + GAMMA=create_GAMMA(n_x,(ms+1)*n_theta,3); + [~,W2]=create_UW(n_x,2); + U3=create_UW(n_x,3); + model.chain3c_theta_M2=spmat2sptensor(kron(W2,speye(n_x))*GAMMA.GAMMA2*U3); + model.chain3c_theta_M3=spmat2sptensor(kron(speye(n_x),W2)*GAMMA.GAMMA3*U3); + model.chain3c_theta_M4=spmat2sptensor(kron(speye(n_x),W2)*GAMMA.GAMMA4*U3); + tempind=1:unique2*n_x; + tempmat=speye(unique2*n_x); + model.chain3c_theta_M5=spmat2sptensor(tempmat(:,permute(reshape(tempind,n_x,unique2),[2,1]))*kron(speye(n_x),W2)*GAMMA.GAMMA5*U3); + clear GAMMA W2 U3 + + end + + if isempty(pref) + preJ3=sptensor(zeros(0,1),zeros(0,2),zeros(n_s,0),0,[unique3,(ms+1)*n_theta]); + else + [ preJ3,model.ind{indi} ] = chain3c_theta_tensor( prefv,prefvv,prefvvv,prefvvvv,... + prevx,prevxxc,prevxxxc,... + prev_theta,prevx_theta,prevxxc_theta,prevxxxc_theta,... + model.chain3c_theta_M2,model.chain3c_theta_M3,model.chain3c_theta_M4,model.chain3c_theta_M5,... + model.ind{indi},n_ind,maxload,'vec' ); + indi=indi+1; + end + end + if order>=4 + if model.pde==0 + vxxxxc_theta=vconcat(sptensor(n_y,[unique4,(ms+1)*n_theta],n_s),vxxxxc_theta_lower_terms); + elseif model.pde==1 + vxxxxc_theta=vconcat(sptensor(n_y*(n_x+1),[unique4,(ms+1)*n_theta],n_s),vxxxxc_theta_lower_terms); + elseif model.pde>=2 + vxxxxc_theta=vconcat(sptensor(model.n_y_extended,[unique4,(ms+1)*n_theta],n_s),vxxxxc_theta_lower_terms); + end + model.vxxxxc_theta=vxxxxc_theta; + prevxxxxc_theta=takerows(vxxxxc_theta,prefvars); + prevxxxxc_theta=unfold(prevxxxxc_theta); + + if ~isfield(model,'chain4c_theta_M2') + GAMMA=create_GAMMA(n_x,(ms+1)*n_theta,4); + [~,W2]=create_UW(n_x,2); + [~,W3]=create_UW(n_x,3); + U4=create_UW(n_x,4); + [~,W2new]=create_UW(unique2,2); + model.chain4c_theta_M2=spmat2sptensor(kron(W3,speye(n_x))*GAMMA.GAMMA16*U4); + model.chain4c_theta_M3=spmat2sptensor(kron(W2,W2)*GAMMA.GAMMA2*U4); + model.chain4c_theta_M5=spmat2sptensor(kron(speye(n_x^2),W2)*GAMMA.GAMMA17*GAMMA.GAMMA2*U4); + model.chain4c_theta_M6=spmat2sptensor(kron(speye(n_x),W3)*GAMMA.GAMMA3*U4); + model.chain4c_theta_M9=spmat2sptensor(W2new*kron(W2,W2)*GAMMA.GAMMA4*U4); + model.chain4c_theta_M10=spmat2sptensor(kron(W2,W2)*GAMMA.GAMMA18*GAMMA.GAMMA4*U4); + + clear GAMMA W2 W3 U4 W2new + + end + + if isempty(pref) + preJ4=sptensor(zeros(0,1),zeros(0,2),zeros(n_s,0),0,[unique4,(ms+1)*n_theta]); + else + [ preJ4,model.ind4{indi4} ] = chain4c_theta_tensor( prefv,prefvv,prefvvv,prefvvvv,prefvvvvv,... + prevx,prevxxc,prevxxxc,prevxxxxc,... + prev_theta,prevx_theta,prevxxc_theta,prevxxxc_theta,prevxxxxc_theta,... + model.chain4c_theta_M2,model.chain4c_theta_M3,model.chain4c_theta_M5,model.chain4c_theta_M6,model.chain4c_theta_M9,model.chain4c_theta_M10,... + model.ind4{indi4},n_ind,maxload,'vec' ); + indi4=indi4+1; + end + end + totindi=totindi+4; + indi=totindi; +end + +% STEP 2: COMPUTE STOCHASTIC EQUATIONS AND DERIVATIVES, AND THEIR JACOBIAN, +% AND TAKE EXPECTED VALUE + +% prepare vectorized expressions for the stochastic part. +if isempty(model.stochfrows) + EstochR0=sptensor(0,1,n_s); + EstochR1=sptensor(0,n_x,n_s); + EstochR2=sptensor(0,unique2,n_s); + EstochR3=sptensor(0,unique3,n_s); + EstochR4=sptensor(0,unique4,n_s); + EstochJ0=sptensor(0,(ms+1)*n_theta,n_s); + EstochJ1=sptensor(0,[n_x,(ms+1)*n_theta],n_s); + EstochJ2=sptensor(0,[unique2,(ms+1)*n_theta],n_s); + EstochJ3=sptensor(0,[unique3,(ms+1)*n_theta],n_s); + EstochJ4=sptensor(0,[unique4,(ms+1)*n_theta],n_s); +else + nx_vec=repmat(nx(:)',n_nodes,1); % n_nodes=the number of nodes of the discrete shocks. + nx_vec=reshape(nx_vec,n_nodes*n_s,[]); + + % next period state + if model.hybrid==0 + nxp_vec=repmat(h(:),1,n_nodes)+reshape(etavec,[],n_e)*nep; %n_s*n_x,n_nodes + elseif model.hybrid==1 + h_vec=repmat(h(:),1,n_nodes); %n_s*n_x,n_nodes + + params_vec=[repmat(nep',n_s,1),reshape(repmat(reshape(params(:,n_e+1:end),1,[]),n_nodes,1),n_nodes*n_s,[])]; %n_nodes*n_s,n_params + uname=['Phi' model.uname '_fun']; + tempvars=[nx,ny,nu(:,model.preurows)]; %n_s,n_x+n_y + tempvars=reshape(repmat(tempvars(:)',n_nodes,1),n_nodes*n_s,[]); %n_s*n_nodes,n_x+n_y+n_preurows + Phi_vec=feval(uname,tempvars,params_vec); %n_s*n_nodes,n_x2 + Phi_vec=permute(reshape(Phi_vec,n_s,n_nodes,n_x2),[1,3,2]); %n_s,n_x2,n_nodes + h_vec=reshape(h_vec,n_s,n_x,n_nodes); + h_vec(:,n_x1+1:end,:)=Phi_vec; + h_vec=reshape(h_vec,n_s*n_x,n_nodes); + nxp_vec=h_vec+reshape(etavec,[],n_e)*nep; %n_s*n_x,n_nodes + elseif model.hybrid==3 + h_vec=repmat(h(:),1,n_nodes); %n_s*n_x,n_nodes + + params_vec=[repmat(nep',n_s,1),reshape(repmat(reshape(params(:,n_e+1:end),1,[]),n_nodes,1),n_nodes*n_s,[])]; %n_nodes*n_s,n_params + uname=['Phi' model.uname '_fun']; + tempvars=nz(:,model.Phizvars); %n_s,n_x+n_y + tempvars=reshape(repmat(tempvars(:)',n_nodes,1),n_nodes*n_s,[]); %n_nodes*n_s,n_x+n_y+n_preurows + Phi_vec=feval(uname,tempvars,params_vec); %n_nodes*n_s,n_x2 + Phi_vec=permute(reshape(Phi_vec,n_nodes,n_s,n_x2),[2,3,1]); %n_s,n_x2,n_nodes + h_vec=reshape(h_vec,n_s,n_x,n_nodes); + h_vec(:,n_x1+1:end,:)=Phi_vec; + h_vec=reshape(h_vec,n_s*n_x,n_nodes); + nxp_vec=h_vec+reshape(etavec,[],n_e)*nep; %n_s*n_x,n_nodes + end + + nxp_c0_vec=nxp_vec-reshape(repmat(c0vec,1,n_nodes),n_s*n_x,n_nodes); + + nxp_vec_permuted=reshape(permute(reshape(nxp_vec,n_s,n_x,n_nodes),[3,1,2]),n_nodes*n_s,n_x); + + tempxp=1:n_x; + tempxp=tempxp(:); + nxp_c0=sptensor(tempxp); % convert to 1D tensor + tempvals=reshape(nxp_c0_vec,n_s,n_x,n_nodes); + tempvals=permute(tempvals,[3,1,2]); + tempvals=reshape(tempvals,n_nodes*n_s,n_x); + nxp_c0.vals=tempvals; % assign the correct values in vals. + + if ~isfield(model,'M2') + model.M2=[]; + model.M3=[]; + model.M3x=[]; + model.TW2=[]; + model.TW3=[]; + model.M4=[]; + model.M4x=[]; + model.M4xx=[]; + model.M4xxx=[]; + if order>=2 + model.M2=fold(spmat2sptensor(model.W{2}*model.W{2}'*model.U{2}'),n_x,n_x); + model.TW2=fold(spmat2sptensor(model.W{2}),n_x,n_x); + model.TW2U2=spmat2sptensor(model.W{2}*model.U{2}); + end + if order>=3 + model.M3=fold(spmat2sptensor(model.W{3}*model.W{3}'*model.U{3}'),n_x,n_x,n_x); + model.M3x=fold(spmat2sptensor(3*model.W{3}*kron(model.W{2}'*model.U{2}',speye(n_x))),n_x,n_x,n_x); + model.TW3=fold(spmat2sptensor(model.W{3}),n_x,n_x,n_x); + model.TW3U3=spmat2sptensor(model.W{3}*model.U{3}); + end + if order>=4 + model.M4=fold(spmat2sptensor(model.W{4}*model.W{4}'*model.U{4}'),n_x,n_x,n_x,n_x); + model.M4x=fold(spmat2sptensor(4*model.W{4}*kron(model.W{3}'*model.U{3}',speye(n_x))),n_x,n_x,n_x,n_x); + model.M4xx=fold(spmat2sptensor(12*model.W{4}*kron(model.W{2}'*model.U{2}',speye(n_x^2))),n_x,n_x,n_x,n_x); + model.M4xxx=fold(spmat2sptensor(24*model.W{4}),n_x,n_x,n_x,n_x); + end + end + + [Xp_vecT,Xpx_vecT,Xpxx_vecT,Xpxxx_vecT,Xpxxxx_vecT,Xpxxxxx_vecT,model.ind{indi}]=create_X_tensor(order,nxp_c0,... + model.M2,model.M3,model.M3x,model.TW2,model.TW3,model.M4,model.M4x,model.M4xx,model.M4xxx,unique2,unique3,unique4,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + if strcmp(model.jacobian,'approximate') + nx_c0=sptensor(n_x,1); + nx_c0.vals=repmat(nx_c0.vals,n_nodes*n_s,1); + [X_vecT,Xx_vecT,Xxx_vecT,Xxxx_vecT,Xxxxx_vecT,Xxxxxx_vecT,model.ind{indi}]=create_X_tensor(order,nx_c0,... + model.M2,model.M3,model.M3x,model.TW2,model.TW3,model.M4,model.M4x,model.M4xx,model.M4xxx,unique2,unique3,unique4,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + totindi=totindi+2; + indi=totindi; + + + stochg_coeffsT=sptensor(ones(n_stochy,n_b)); + tempvals=stochg_coeffs; %n_s,n_stochy,n_b + tempvals=permute(tempvals,[1,3,2]); % n_s,n_b,n_stochy + tempvals=repmat(tempvals(:)',n_nodes,1); % n_nodes,n_s*n_b*n_stochy + tempvals=reshape(tempvals,n_nodes*n_s,n_b*n_stochy); + stochg_coeffsT.vals=tempvals; + + if model.n_logicalparams==0 + [stochgp_vecT,model.ind{indi}]=contraction1(stochg_coeffsT,Xp_vecT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + gp_vec=changerows(stochgp_vecT,stochy,n_y); + temp=zeros(n_nodes*n_s,n_y); + temp(:,stochy)=gp_vec.vals; + else + g_coeffsT=sptensor(ones(n_y,n_b)); + g_coeffs=coeffspvec(:,1:n_y,:); + + tempvals=g_coeffs; %n_s,n_y,n_b + tempvals=permute(tempvals,[1,3,2]); % n_s,n_b,n_y + tempvals=repmat(tempvals(:)',n_nodes,1); % n_nodes,n_s*n_b*n_y + tempvals=reshape(tempvals,n_nodes*n_s,n_b*n_y); + g_coeffsT.vals=tempvals; + + [gp_vecT,model.ind{indi}]=contraction1(g_coeffsT,Xp_vecT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + gp_vec=changerows(gp_vecT,1:n_y,n_y); + temp=zeros(n_nodes*n_s,n_y); + temp(:,1:n_y)=gp_vec.vals; + + end + gp_vec=temp; % n_nodes*n_s,n_y + + [stochgpx_vecT,model.ind{indi}]=contraction1(stochg_coeffsT,Xpx_vecT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + % control vars in t+1 + nyp_vec=gp_vec; + + % evaluate residuals R0 + nv_vec=[nyp_vec,reshape(repmat(ny(:)',n_nodes,1),n_nodes*n_s,[]),nxp_vec_permuted,nx_vec]; + % nstochv_vec=nv_vec(:,stochfvars); % stochastic vars. + + if model.hybrid==0 + params_vec=reshape(repmat(params(:)',n_nodes,1),n_nodes*n_s,n_params); + end + + uname=['stochu' model.uname '_fun']; + nstochu_vec=feval(uname,nv_vec(:,model.stochuvars),params_vec); % all stochastic u vars + nu_vec=reshape(repmat(nu(:)',n_nodes,1),n_nodes*n_s,[]); + + nu_vec(:,model.stochurows)=nstochu_vec; + nz_vec=[nv_vec,nu_vec]; + params_vec(:,model.logical_params_loc)=double(logical(nz_vec(:,model.logical_zvars)>0)); + + fname=['stochtilf' model.fname '_fun']; + stochf_vec=feval(fname,nz_vec(:,model.stochtilfzvars),params_vec); + + % compute derivatives of stochPI and stochtilf w.r.t z + uname=['stochPI' model.uname '_d1']; + stochPIz_vec=feval(uname,nz_vec,params_vec,model.stochPI_ind_u); + prePIz_full.vals=reshape(repmat(prePIz_full.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + i1=tfind(prePIz_full); + i2=tfind(stochPIz_vec); + PIz_vec=sptensor([i1;i2],[prePIz_full.cols;stochPIz_vec.cols],[prePIz_full.vals,stochPIz_vec.vals],n_z,[n_z]); + + fname=['stochtilf' model.fname '_tilf_d1']; + stochtilfz_vec=feval(fname,[nv_vec(:,stochfvars),nu_vec(:,model.stochfuvars)],params_vec,model.stochtilf_ind_u); + + + if order>=1 + uname=['stochPI' model.uname '_d2']; + stochPIzz_vec=feval(uname,nz_vec,params_vec,model.stochPI_ind_u); + prePIzz_full.vals=reshape(repmat(prePIzz_full.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + i1=tfind(prePIzz_full); + i2=tfind(stochPIzz_vec); + PIzz_vec=sptensor([i1;i2],[prePIzz_full.cols;stochPIzz_vec.cols],[prePIzz_full.vals,stochPIzz_vec.vals],n_z,[n_z,n_z]); + + fname=['stochtilf' model.fname '_tilf_d2']; + stochtilfzz_vec=feval(fname,[nv_vec(:,stochfvars),nu_vec(:,model.stochfuvars)],params_vec,model.stochtilf_ind_u); + end + if order>=2 + uname=['stochPI' model.uname '_d3']; + stochPIzzz_vec=feval(uname,nz_vec,params_vec,model.stochPI_ind_u); + prePIzzz_full.vals=reshape(repmat(prePIzzz_full.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + i1=tfind(prePIzzz_full); + i2=tfind(stochPIzzz_vec); + PIzzz_vec=sptensor([i1;i2],[prePIzzz_full.cols;stochPIzzz_vec.cols],[prePIzzz_full.vals,stochPIzzz_vec.vals],n_z,[n_z,n_z,n_z]); + fname=['stochtilf' model.fname '_tilf_d3']; + stochtilfzzz_vec=feval(fname,[nv_vec(:,stochfvars),nu_vec(:,model.stochfuvars)],params_vec,model.stochtilf_ind_u); + end + if order>=3 + uname=['stochPI' model.uname '_d4']; + stochPIzzzz_vec=feval(uname,nz_vec,params_vec,model.stochPI_ind_u); + prePIzzzz_full.vals=reshape(repmat(prePIzzzz_full.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + i1=tfind(prePIzzzz_full); + i2=tfind(stochPIzzzz_vec); + PIzzzz_vec=sptensor([i1;i2],[prePIzzzz_full.cols;stochPIzzzz_vec.cols],[prePIzzzz_full.vals,stochPIzzzz_vec.vals],n_z,[n_z,n_z,n_z,n_z]); + fname=['stochtilf' model.fname '_tilf_d4']; + stochtilfzzzz_vec=feval(fname,[nv_vec(:,stochfvars),nu_vec(:,model.stochfuvars)],params_vec,model.stochtilf_ind_u); + end + if order>=4 + uname=['stochPI' model.uname '_d5']; + stochPIzzzzz_vec=feval(uname,nz_vec,params_vec,model.stochPI_ind_u); + prePIzzzzz_full.vals=reshape(repmat(prePIzzzzz_full.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + i1=tfind(prePIzzzzz_full); + i2=tfind(stochPIzzzzz_vec); + PIzzzzz_vec=sptensor([i1;i2],[prePIzzzzz_full.cols;stochPIzzzzz_vec.cols],[prePIzzzzz_full.vals,stochPIzzzzz_vec.vals],n_z,[n_z,n_z,n_z,n_z,n_z]); + fname=['stochtilf' model.fname '_tilf_d5']; + stochtilfzzzzz_vec=feval(fname,[nv_vec(:,stochfvars),nu_vec(:,model.stochfuvars)],params_vec,model.stochtilf_ind_u); + end + + totindi=totindi+2; + indi=totindi; + + % stochf_vec is n_nodes*n_s,n_stochf + EstochR0=P'*reshape(stochf_vec,n_nodes,[]); %expected value of stochR0 + EstochR0=reshape(EstochR0,n_s,[]); + + tempT=sptensor(zeros(n_stochfrows,1)); + tempT.vals=full(EstochR0); + EstochR0=tempT; + + % compute derivatives of Phi w.r.t x and theta for a model with hybrid + % state variables + if model.hybrid==1 || model.hybrid==3 + get_hybridPhi_derivs_v; + get_hybridPhi_derivs_x_theta; + + end + + + h_thetaT=h_theta; + h_thetaT.vals=reshape(repmat(h_thetaT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + if model.hybrid==1 || model.hybrid==3 % add Phitheta + h_thetaT=vconcat(takerows(h_thetaT,1:n_x1),Phitheta); + end + + [chain0_theta_stochgpT,model.ind{indi}]=contraction1(stochgpx_vecT,h_thetaT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + totindi=totindi+1; + indi=totindi; + + % compute derivatives of g w.r.t x at next period state (nxp) + if order>=1 + if order>1 + [stochgpxx_vecT,model.ind{indi}]=contraction1(stochg_coeffsT,Xpxx_vecT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + else + stochgpxx_vecT=sptensor(n_stochy,n_x^2,n_nodes); + end + hxT=hx; + hxT.vals=reshape(repmat(hxT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + if model.hybrid==1 || model.hybrid==3 % add Phix + hxT=vconcat(takerows(hxT,1:n_x1),Phix); + end + + [chain1_stochgpT,model.ind{indi}]=contraction1(stochgpx_vecT,hxT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + hx_thetaT=unfold(hx_theta); + hx_thetaT.vals=reshape(repmat(hx_thetaT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + if model.hybrid==1 || model.hybrid==3 % add Phixtheta + hx_thetaT=vconcat(takerows(hx_thetaT,1:n_x1),unfold(Phixtheta)); + end + + + stochgpxx_vecT=fold(stochgpxx_vecT,n_x,n_x); + [chain1_theta_stochgpT,model.ind{indi}]=chain1_theta_tensor(stochgpx_vecT,stochgpxx_vecT,hxT,h_thetaT,hx_thetaT,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + if order>=2 + if order>2 + [stochgpxxx_vecT,model.ind{indi}]=contraction1(stochg_coeffsT,Xpxxx_vecT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + else + stochgpxxx_vecT=sptensor(n_stochy,n_x^3,n_nodes); + end + hxxcT=hxxc; + hxxcT.vals=reshape(repmat(hxxcT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + if model.hybrid==1 || model.hybrid==3 % add Phixxc + hxxcT=vconcat(takerows(hxxcT,1:n_x1),Phixxc); + end + + [hxT,model.ind4{indi4}]=colsort(hxT,model.ind4{indi4}); + indi4=indi4+1; + [chain2_stochgpT,model.ind{indi}]=chain2c_tensor(stochgpx_vecT,stochgpxx_vecT,hxT,hxxcT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + hxxc_thetaT=unfold(hxxc_theta); + hxxc_thetaT.vals=reshape(repmat(hxxc_thetaT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + if model.hybrid==1 || model.hybrid==3 % add Phixxctheta + hxxc_thetaT=vconcat(takerows(hxxc_thetaT,1:n_x1),unfold(Phixxctheta)); + end + + stochgpxxx_vecT=fold(stochgpxxx_vecT,n_x,n_x,n_x); + + [chain2c_theta_stochgpT,model.ind{indi}]=chain2c_theta_tensor(stochgpx_vecT,stochgpxx_vecT,stochgpxxx_vecT,hxT,hxxcT,h_thetaT,hx_thetaT,hxxc_thetaT,... + model.chain2c_theta_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + if order>=3 + if order>3 + [stochgpxxxx_vecT,model.ind{indi}]=contraction1(stochg_coeffsT,Xpxxxx_vecT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + else + stochgpxxxx_vecT=sptensor(n_stochy,n_x^4,n_nodes); + end + hxxxcT=hxxxc; + hxxxcT.vals=reshape(repmat(hxxxcT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + if model.hybrid==1 || model.hybrid==3 % add Phixxxc + hxxxcT=vconcat(takerows(hxxxcT,1:n_x1),Phixxxc); + end + + [chain3_stochgpT,model.ind{indi}]=chain3c_tensor(stochgpx_vecT,stochgpxx_vecT,stochgpxxx_vecT,... + hxT,hxxcT,hxxxcT,... + model.x_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + hxxxc_thetaT=unfold(hxxxc_theta); + hxxxc_thetaT.vals=reshape(repmat(hxxxc_thetaT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + if model.hybrid==1 || model.hybrid==3 % add Phixxxctheta + hxxxc_thetaT=vconcat(takerows(hxxxc_thetaT,1:n_x1),unfold(Phixxxctheta)); + end + + stochgpxxxx_vecT=fold(stochgpxxxx_vecT,n_x,n_x,n_x,n_x); + + [chain3c_theta_stochgpT,model.ind{indi}]=chain3c_theta_tensor(stochgpx_vecT,stochgpxx_vecT,stochgpxxx_vecT,stochgpxxxx_vecT,... + hxT,hxxcT,hxxxcT,h_thetaT,hx_thetaT,hxxc_thetaT,hxxxc_thetaT,... + model.chain3c_theta_M2,model.chain3c_theta_M3,model.chain3c_theta_M4,model.chain3c_theta_M5,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + if order>=4 + if order>4 + [stochgpxxxxx_vecT,model.ind4{indi4}]=contraction1(stochg_coeffsT,Xpxxxxx_vecT,model.ind4{indi4},n_ind,maxload,'vec'); + indi4=indi4+1; + else + stochgpxxxxx_vecT=sptensor(n_stochy,n_x^5,n_nodes); + end + hxxxxcT=hxxxxc; + hxxxxcT.vals=reshape(repmat(hxxxxcT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + if model.hybrid==1 || model.hybrid==3 % add Phixxxxc + hxxxxcT=vconcat(takerows(hxxxxcT,1:n_x1),Phixxxxc); + end + + [hxxcT,model.ind4{indi4}]=colsort(hxxcT,model.ind4{indi4}); + indi4=indi4+1; + + [chain4_stochgpT,model.ind4{indi4}]=chain4c_tensor(stochgpx_vecT,stochgpxx_vecT,stochgpxxx_vecT,stochgpxxxx_vecT,... + hxT,hxxcT,hxxxcT,hxxxxcT,... + model.x_chain4c_M2,model.x_chain4c_M3,model.x_chain4c_M4,model.ind4{indi4},n_ind,maxload,'vec'); + indi4=indi4+1; + + hxxxxc_thetaT=unfold(hxxxxc_theta); + hxxxxc_thetaT.vals=reshape(repmat(hxxxxc_thetaT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + if model.hybrid==1 || model.hybrid==3 % add Phixxxxctheta + hxxxxc_thetaT=vconcat(takerows(hxxxxc_thetaT,1:n_x1),unfold(Phixxxxctheta)); + end + + stochgpxxxxx_vecT=fold(stochgpxxxxx_vecT,n_x,n_x,n_x,n_x,n_x); + + [chain4c_theta_stochgpT,model.ind4{indi4}]=chain4c_theta_tensor(stochgpx_vecT,stochgpxx_vecT,stochgpxxx_vecT,stochgpxxxx_vecT,stochgpxxxxx_vecT,... + hxT,hxxcT,hxxxcT,hxxxxcT,h_thetaT,hx_thetaT,hxxc_thetaT,hxxxc_thetaT,hxxxxc_thetaT,... + model.chain4c_theta_M2,model.chain4c_theta_M3,model.chain4c_theta_M5,model.chain4c_theta_M6,model.chain4c_theta_M9,model.chain4c_theta_M10,... + model.ind4{indi4},n_ind,maxload,'vec'); + indi4=indi4+1; + end + totindi=totindi+9; + indi=totindi; + + % extract PIv,Pivv,... from PIz,PIzz,... + if order>=0 + [stochPIz_vec,model.ind{indi}]=extract(PIz_vec,model.stochfzvars,model.stochfzvars,0,model.ind{indi}); + indi=indi+1; + [stochPIv_vec,model.ind{indi}]=extract(PIz_vec,model.stochfzvars,model.stochfvars,0,model.ind{indi}); + indi=indi+1; + end + if order>=1 + [stochPIzz_vec,model.ind{indi}]=extract(PIzz_vec,model.stochfzvars,model.stochfzvars,0,model.ind{indi}); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=extract(PIzz_vec,model.stochfzvars,model.stochfvars,1,model.ind{indi}); + indi=indi+1; + end + if order>=2 + [stochPIzzz_vec,model.ind{indi}]=extract(PIzzz_vec,model.stochfzvars,model.stochfzvars,0,model.ind{indi}); + indi=indi+1; + [stochPIvvvc_vec,model.ind{indi}]=extract(PIzzz_vec,model.stochfzvars,model.stochfvars,1,model.ind{indi}); + indi=indi+1; + if ~isfield(model,'stochfvars_chain3c_M2') + [ tempM ] = chainsM( n_stochfvars,3 ); + model.stochfvars_chain3c_M2=tempM{2}; + clear tempM + end + end + if order>=3 + [stochPIzzzz_vec,model.ind{indi}]=extract(PIzzzz_vec,model.stochfzvars,model.stochfzvars,0,model.ind{indi}); + indi=indi+1; + [stochPIvvvvc_vec,model.ind{indi}]=extract(PIzzzz_vec,model.stochfzvars,model.stochfvars,1,model.ind{indi}); + indi=indi+1; + if ~isfield(model,'stochfvars_chain4c_M2') + [ tempM ] = chainsM( n_stochfvars,4 ); + model.stochfvars_chain4c_M2=tempM{2}; + model.stochfvars_chain4c_M3=tempM{3}; + model.stochfvars_chain4c_M4=tempM{4}; + clear tempM + end + end + if order>=4 + [stochPIzzzzz_vec,model.ind4{indi4}]=extract(PIzzzzz_vec,model.stochfzvars,model.stochfzvars,0,model.ind4{indi4}); + indi4=indi4+1; + [stochPIvvvvvc_vec,model.ind4{indi4}]=extract(PIzzzzz_vec,model.stochfzvars,model.stochfvars,1,model.ind4{indi4}); + indi4=indi4+1; + end + totindi=totindi+8; + indi=totindi; + + + % compute derivatives of stochf w.r.t v by high order chain rules, and + % multiply by the weights P (probabilities). + Pvec=repmat(P(:),n_s,1); + if order==0 + indi=totindi; + for i=2:model.stoch_n + [stochPIv_vec,model.ind{indi}]=chain1_tensor(stochPIz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [stochfv_vec,model.ind{indi}]=chain1_tensor(stochtilfz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + stochfv_vec.vals=multcol(stochfv_vec.vals,Pvec); + + model.stochfv_vec=stochfv_vec; + + elseif order==1 + indi=totindi+model.count_stoch_n*(1)+1; + for i=2:model.stoch_n + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=chain2c_tensor(stochPIz_vec,stochPIzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIv_vec,model.ind{indi}]=chain1_tensor(stochPIz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + + [stochfv_vec,model.ind{indi}]=chain1_tensor(stochtilfz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvc_vec,model.ind{indi}]=chain2c_tensor(stochtilfz_vec,stochtilfzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + stochfv_vec.vals=multcol(stochfv_vec.vals,Pvec); + stochfvvc_vec.vals=multcol(stochfvvc_vec.vals,Pvec); + + [ stochfvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvc_vec,2,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvc_vec + + elseif order==2 + indi=totindi+model.count_stoch_n*(1+3)+1+4; + for i=2:model.stoch_n + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvvc_vec,model.ind{indi}]=chain3c_tensor(stochPIz_vec,stochPIzz_vec,stochPIzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,model.stochfvars_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=chain2c_tensor(stochPIz_vec,stochPIzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIv_vec,model.ind{indi}]=chain1_tensor(stochPIz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + + [stochfv_vec,model.ind{indi}]=chain1_tensor(stochtilfz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvc_vec,model.ind{indi}]=chain2c_tensor(stochtilfz_vec,stochtilfzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvvc_vec,model.ind{indi}]=chain3c_tensor(stochtilfz_vec,stochtilfzz_vec,stochtilfzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,... + model.stochfvars_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + stochfv_vec.vals=multcol(stochfv_vec.vals,Pvec); + stochfvvc_vec.vals=multcol(stochfvvc_vec.vals,Pvec); + stochfvvvc_vec.vals=multcol(stochfvvvc_vec.vals,Pvec); + + [ stochfvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvc_vec,2,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvc_vec + + [ stochfvvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvvc_vec,3,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvvc_vec + + elseif order==3 + indi=totindi+model.count_stoch_n*(1+3+4)+1+4+6; + for i=2:model.stoch_n + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=colsort(stochPIvvc_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvvvc_vec,model.ind{indi}]=chain4c_tensor(stochPIz_vec,stochPIzz_vec,stochPIzzz_vec,stochPIzzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,stochPIvvvvc_vec,... + model.stochfvars_chain4c_M2,model.stochfvars_chain4c_M3,model.stochfvars_chain4c_M4,... + model.ind{indi},n_ind,maxload,'vec',model.stochzz,model.maxzz); + indi=indi+1; + [stochPIvvvc_vec,model.ind{indi}]=chain3c_tensor(stochPIz_vec,stochPIzz_vec,stochPIzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,model.stochfvars_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=chain2c_tensor(stochPIz_vec,stochPIzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIv_vec,model.ind{indi}]=chain1_tensor(stochPIz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=colsort(stochPIvvc_vec,model.ind{indi}); + indi=indi+1; + + [stochfv_vec,model.ind{indi}]=chain1_tensor(stochtilfz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [stochfvvc_vec,model.ind{indi}]=chain2c_tensor(stochtilfz_vec,stochtilfzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvvc_vec,model.ind{indi}]=chain3c_tensor(stochtilfz_vec,stochtilfzz_vec,stochtilfzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,... + model.stochfvars_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvvvc_vec,model.ind{indi}]=chain4c_tensor(stochtilfz_vec,stochtilfzz_vec,stochtilfzzz_vec,stochtilfzzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,stochPIvvvvc_vec,... + model.stochfvars_chain4c_M2,model.stochfvars_chain4c_M3,model.stochfvars_chain4c_M4,... + model.ind{indi},n_ind,maxload,'vec',model.stochtilfz,model.maxtilfz); + indi=indi+1; + + stochfv_vec.vals=multcol(stochfv_vec.vals,Pvec); + stochfvvc_vec.vals=multcol(stochfvvc_vec.vals,Pvec); + stochfvvvc_vec.vals=multcol(stochfvvvc_vec.vals,Pvec); + stochfvvvvc_vec.vals=multcol(stochfvvvvc_vec.vals,Pvec); + + [ stochfvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvc_vec,2,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvc_vec + + [ stochfvvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvvc_vec,3,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvvc_vec + + [ stochfvvvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvvvc_vec,4,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvvvc_vec + elseif order==4 + indi=totindi+model.count_stoch_n*(1+3+4)+1+4+6; + for i=2:model.stoch_n + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=colsort(stochPIvvc_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvvvvc_vec,model.ind4{indi4}]=chain5c_tensor(stochPIz_vec,stochPIzz_vec,stochPIzzz_vec,stochPIzzzz_vec,stochPIzzzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,stochPIvvvvc_vec,stochPIvvvvvc_vec,... + model.stochfvars_chain5c_M1,model.stochfvars_chain5c_M2,model.stochfvars_chain5c_M3,model.stochfvars_chain5c_M4,model.stochfvars_chain5c_M5,model.stochfvars_chain5c_M6,... + model.ind4{indi4},n_ind,maxload,'vec',model.stochzz,model.maxzz); + indi4=indi4+1; + [stochPIvvvvc_vec,model.ind{indi}]=chain4c_tensor(stochPIz_vec,stochPIzz_vec,stochPIzzz_vec,stochPIzzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,stochPIvvvvc_vec,... + model.stochfvars_chain4c_M2,model.stochfvars_chain4c_M3,model.stochfvars_chain4c_M4,... + model.ind{indi},n_ind,maxload,'vec',model.stochzz,model.maxzz); + indi=indi+1; + [stochPIvvvc_vec,model.ind{indi}]=chain3c_tensor(stochPIz_vec,stochPIzz_vec,stochPIzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,model.stochfvars_chain3c_M2,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=chain2c_tensor(stochPIz_vec,stochPIzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochPIv_vec,model.ind{indi}]=chain1_tensor(stochPIz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + [stochPIv_vec,model.ind{indi}]=colsort(stochPIv_vec,model.ind{indi}); + indi=indi+1; + [stochPIvvc_vec,model.ind{indi}]=colsort(stochPIvvc_vec,model.ind{indi}); + indi=indi+1; + + [stochfv_vec,model.ind{indi}]=chain1_tensor(stochtilfz_vec,stochPIv_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + [stochfvvc_vec,model.ind{indi}]=chain2c_tensor(stochtilfz_vec,stochtilfzz_vec,stochPIv_vec,stochPIvvc_vec,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvvc_vec,model.ind{indi}]=chain3c_tensor(stochtilfz_vec,stochtilfzz_vec,stochtilfzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,... + model.stochfvars_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + [stochfvvvvc_vec,model.ind{indi}]=chain4c_tensor(stochtilfz_vec,stochtilfzz_vec,stochtilfzzz_vec,stochtilfzzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,stochPIvvvvc_vec,... + model.stochfvars_chain4c_M2,model.stochfvars_chain4c_M3,model.stochfvars_chain4c_M4,... + model.ind{indi},n_ind,maxload,'vec',model.stochtilfz,model.maxtilfz); + indi=indi+1; + [stochfvvvvvc_vec,model.ind4{indi4}]=chain5c_tensor(stochtilfz_vec,stochtilfzz_vec,stochtilfzzz_vec,stochtilfzzzz_vec,stochtilfzzzzz_vec,... + stochPIv_vec,stochPIvvc_vec,stochPIvvvc_vec,stochPIvvvvc_vec,stochPIvvvvvc_vec,... + model.stochfvars_chain5c_M1,model.stochfvars_chain5c_M2,model.stochfvars_chain5c_M3,model.stochfvars_chain5c_M4,model.stochfvars_chain5c_M5,model.stochfvars_chain5c_M6,... + model.ind4{indi4},n_ind,maxload,'vec',model.stochtilfz,model.maxtilfz); + indi4=indi4+1; + + stochfv_vec.vals=multcol(stochfv_vec.vals,Pvec); + stochfvvc_vec.vals=multcol(stochfvvc_vec.vals,Pvec); + stochfvvvc_vec.vals=multcol(stochfvvvc_vec.vals,Pvec); + stochfvvvvc_vec.vals=multcol(stochfvvvvc_vec.vals,Pvec); + stochfvvvvvc_vec.vals=multcol(stochfvvvvvc_vec.vals,Pvec); + + [ stochfvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvc_vec,2,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvc_vec + + [ stochfvvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvvc_vec,3,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvvc_vec + + [ stochfvvvv_vec,model.ind{indi} ] = uncompressderivs( stochfvvvvc_vec,4,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind{indi} ); + indi=indi+1; + clear stochfvvvvc_vec + + [ stochfvvvvv_vec,model.ind4{indi4} ] = uncompressderivs( stochfvvvvvc_vec,5,n_stochfvars,model.fv(model.stochfrows,stochfvars),model.ind4{indi4} ); + indi4=indi4+1; + clear stochfvvvvvc_vec + + end + totindi=totindi+8+model.count_stoch_n*(1+3+4+6)+1+4+6+9; + indi=totindi; + + + if model.steady_state==1 + if size(stochfv_vec.vals,1)~=1 + error('cannot compute steady state on vectorized tensors') + end + nzstochfv=stochfv_vec; + nzstochfv.vals(:)=1; + nzstochfv=sptensor2spmat(nzstochfv); + nzstochfv_full=zeros(n_stochfrows,model.n_v); + nzstochfv_full(:,model.stochfvars)=full(nzstochfv); + nzstochfv_full(:,2*model.n_y+(1:model.n_x1))=nzstochfv_full(:,2*model.n_y+(1:model.n_x1))+nzstochfv_full(:,2*model.n_y+model.n_x+(1:model.n_x1)); + nzstochfv=nzstochfv_full(:,model.stochfvars); + [i,j]=find(nzstochfv); + + stochfv=sptensor2spmat(stochfv_vec); + stochfv_full=zeros(n_stochfrows,model.n_v); + stochfv_full(:,model.stochfvars)=full(stochfv); + stochfv_full(:,2*model.n_y+(1:model.n_x1))=stochfv_full(:,2*model.n_y+(1:model.n_x1))+stochfv_full(:,2*model.n_y+model.n_x+(1:model.n_x1)); + stochfv=stochfv_full(:,model.stochfvars); + + vals=stochfv(logical(nzstochfv(:))); + + stochfv_vec=sptensor(i(:),j(:),vals(:)',size(stochfv,1),size(stochfv,2)); + end + + + temp=reshape((1:n_theta)+ms*n_theta,[],n_b); + stochtheta=temp(stochy,:); + stochtheta=stochtheta(:); + n_stochtheta=length(stochtheta); + + % exact/approximate Jacobian of gp,gpx,... + IstochyT=spteye(n_stochy); + if strcmp(model.jacobian,'exact') + [stochgp_stochtheta_vecT,model.ind{indi}]=tkron(ttranspose(Xp_vecT),IstochyT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + else + [stochgp_stochtheta_vecT,model.ind{indi}]=tkron(ttranspose(X_vecT),IstochyT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + + if ms==0 + nnzgp_theta_vecT=unfold(changecols(changerows(stochgp_stochtheta_vecT,stochy,n_y),stochy,n_y+n_x1,1)); %n_y,n_theta with only nnz values + else + + nnzgp_theta_vecT=unfold(changecols(changerows(unfold(stochgp_stochtheta_vecT),stochy,n_y),stochtheta,(ms+1)*n_theta,1)); %n_y,n_theta with only nnz values + end + nnzchain0_theta_gpT=changerows(chain0_theta_stochgpT,stochy,n_y); + + v_theta_lower_terms_vecT=v_theta_lower_terms; + v_theta_lower_terms_vecT.vals=reshape(repmat(v_theta_lower_terms_vecT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + if model.hybrid==3 % not necessary for model.hybrid==1 because x2p does not appear in any of the equations + temp=vconcat(takerows(v_theta_lower_terms_vecT,1:n_y+n_x1),Phitheta); + temp=vconcat(temp,takerows(v_theta_lower_terms_vecT,n_y+n_x+(1:n_x))); + v_theta_lower_terms_vecT=temp; + end + + v_theta_vecT=vconcat(tplus(nnzchain0_theta_gpT,nnzgp_theta_vecT,maxload),v_theta_lower_terms_vecT); + clear nnzchain0_theta_gpT nnzgp_theta_vecT + stochv_theta_vecT=takerows(v_theta_vecT,stochfvars); + + clear v_theta_vecT + + totindi=totindi+2; + indi=totindi; + % derivatives of v w.r.t x + if order>=1 + vxT=vx; + if model.hybrid==0 || model.hybrid==1 + stochvxT=takerows(vxT,stochfvars(n_stochy+1:end)); + stochvxT.vals=reshape(repmat(stochvxT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + elseif model.hybrid==3 + vxT.vals=reshape(repmat(vxT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + temp=vconcat(takerows(vxT,1:2*n_y+n_x1),Phix); + temp=vconcat(temp,takerows(vxT,2*n_y+n_x+(1:n_x))); + vxT=temp; + stochvxT=takerows(vxT,stochfvars(n_stochy+1:end)); + end + stochvxT=vconcat(chain1_stochgpT,stochvxT); + + if strcmp(model.jacobian,'exact') + [stochgpx_stochtheta_vecT,model.ind{indi}]=tkron(ttranspose(Xpx_vecT),IstochyT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + else + [stochgpx_stochtheta_vecT,model.ind{indi}]=tkron(ttranspose(Xx_vecT),IstochyT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + + stochgpx_stochtheta_vecT=ptr1d(col2ptr(ptr2col(ptr2d(unfold(stochgpx_stochtheta_vecT),n_stochy,n_x),1),2));%n_stochy*n_stochtheta,n_x + % + [chain1_gp_theta_vecT,model.ind{indi}]=contraction1(stochgpx_stochtheta_vecT,hxT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + chain1_gp_theta_vecT=ptr2col(ptr2d(chain1_gp_theta_vecT,n_stochy,n_stochtheta),2);%n_stochy,n_x,n_stochtheta + nnzchain1_gp_theta_vecT=col2ptr(changecols(changerows(chain1_gp_theta_vecT,stochy,n_y),stochtheta,(ms+1)*n_theta,2),1); %n_y*n_x,n_theta with only nnz values + + nnzchain1_theta_gpT=col2ptr(changerows(chain1_theta_stochgpT,stochy,n_y),1);% n_y,n_x,n_theta + + vx_theta_lower_terms_vecT=vx_theta_lower_terms; + vx_theta_lower_terms_vecT.vals=reshape(repmat(vx_theta_lower_terms_vecT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + if model.hybrid==3 + temp=vconcat(takerows(vx_theta_lower_terms_vecT,1:n_y+n_x1),Phixtheta); + temp=vconcat(temp,takerows(vx_theta_lower_terms_vecT,n_y+n_x+(1:n_x))); + vx_theta_lower_terms_vecT=temp; + end + + vx_theta_upper_terms_vecT=unfold(ptr2col(tplus(nnzchain1_theta_gpT,nnzchain1_gp_theta_vecT,maxload),1)); + clear nnzchain1_theta_gpT nnzchain1_gp_theta_vecT + vx_theta_vecT=vconcat(vx_theta_upper_terms_vecT,unfold(vx_theta_lower_terms_vecT)); + + clear vx_theta_upper_terms_vecT vx_theta_lower_terms_vecT + + stochvx_theta_vecT=takerows(vx_theta_vecT,stochfvars); + + clear vx_theta_vecT + end + if order>=2 + vxxcT=vxxc; + if model.hybrid==0 || model.hybrid==1 + stochvxxcT=takerows(vxxcT,stochfvars(n_stochy+1:end)); + stochvxxcT.vals=reshape(repmat(stochvxxcT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + elseif model.hybrid==3 + vxxcT.vals=reshape(repmat(vxxcT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + temp=vconcat(takerows(vxxcT,1:2*n_y+n_x1),Phixxc); + temp=vconcat(temp,takerows(vxxcT,2*n_y+n_x+(1:n_x))); + vxxcT=temp; + stochvxxcT=takerows(vxxcT,stochfvars(n_stochy+1:end)); + end + + stochvxxcT=vconcat(chain2_stochgpT,stochvxxcT); + + if strcmp(model.jacobian,'exact') + [stochgpxx_stochtheta_vecT,model.ind{indi}]=tkron(ttranspose(Xpxx_vecT),IstochyT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + else + [stochgpxx_stochtheta_vecT,model.ind{indi}]=tkron(ttranspose(Xxx_vecT),IstochyT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + + stochgpxx_stochtheta_vecT=ptr1d(col2ptr(ptr2col(ptr2d(unfold(stochgpxx_stochtheta_vecT),n_stochy,n_x^2),1),2));%n_stochy*n_stochtheta,n_x^2 + stochgpxx_stochtheta_vecT=fold(stochgpxx_stochtheta_vecT,n_x,n_x); + + [chain2c_stochgp_stochtheta_vecT,model.ind{indi}]=chain2c_tensor(stochgpx_stochtheta_vecT,stochgpxx_stochtheta_vecT,... + hxT,hxxcT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + chain2c_stochgp_stochtheta_vecT=ptr2col(ptr2d(chain2c_stochgp_stochtheta_vecT,n_stochy,n_stochtheta),2);%n_stochy,unique2,n_stochtheta + nnzchain2c_gp_theta_vecT=col2ptr(changecols(changerows(chain2c_stochgp_stochtheta_vecT,stochy,n_y),stochtheta,(ms+1)*n_theta,2),1); %n_y*unique2,n_theta with only nnz values + clear chain2c_stochgp_stochtheta_vecT + + nnzchain2c_theta_gpT=col2ptr(changerows(chain2c_theta_stochgpT,stochy,n_y),1);% n_y,unique2,n_theta + + vxxc_theta_lower_terms_vecT=unfold(vxxc_theta_lower_terms); + vxxc_theta_lower_terms_vecT.vals=reshape(repmat(vxxc_theta_lower_terms_vecT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + if model.hybrid==3 + temp=vconcat(takerows(vxxc_theta_lower_terms_vecT,1:n_y+n_x1),unfold(Phixxctheta)); + temp=vconcat(temp,takerows(vxxc_theta_lower_terms_vecT,n_y+n_x+(1:n_x))); + vxxc_theta_lower_terms_vecT=temp; + end + + vxxc_theta_upper_terms_vecT=unfold(ptr2col(tplus(nnzchain2c_theta_gpT,nnzchain2c_gp_theta_vecT,maxload),1)); + clear nnzchain2c_theta_gpT nnzchain2c_gp_theta_vecT + vxxc_theta_vecT=vconcat(vxxc_theta_upper_terms_vecT,vxxc_theta_lower_terms_vecT); + + clear vxxc_theta_upper_terms_vecT vxxc_theta_lower_terms_vecT + + stochvxxc_theta_vecT=takerows(vxxc_theta_vecT,stochfvars); + + clear vxxc_theta_vecT + end + if order>=3 + vxxxcT=vxxxc; + if model.hybrid==0 || model.hybrid==1 + stochvxxxcT=takerows(vxxxcT,stochfvars(n_stochy+1:end)); + stochvxxxcT.vals=reshape(repmat(stochvxxxcT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + elseif model.hybrid==3 + vxxxcT.vals=reshape(repmat(vxxxcT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + temp=vconcat(takerows(vxxxcT,1:2*n_y+n_x1),Phixxxc); + temp=vconcat(temp,takerows(vxxxcT,2*n_y+n_x+(1:n_x))); + vxxxcT=temp; + stochvxxxcT=takerows(vxxxcT,stochfvars(n_stochy+1:end)); + end + + + stochvxxxcT=vconcat(chain3_stochgpT,stochvxxxcT); + + if strcmp(model.jacobian,'exact') + [stochgpxxx_stochtheta_vecT,model.ind{indi}]=tkron(ttranspose(Xpxxx_vecT),IstochyT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + else + [stochgpxxx_stochtheta_vecT,model.ind{indi}]=tkron(ttranspose(Xxxx_vecT),IstochyT,model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + end + + + stochgpxxx_stochtheta_vecT=ptr1d(col2ptr(ptr2col(ptr2d(unfold(stochgpxxx_stochtheta_vecT),n_stochy,n_x^3),1),2));%n_stochy*n_stochtheta,n_x^2 + stochgpxxx_stochtheta_vecT=fold(stochgpxxx_stochtheta_vecT,n_x,n_x,n_x); + + [chain3c_stochgp_stochtheta_vecT,model.ind{indi}]=chain3c_tensor(stochgpx_stochtheta_vecT,stochgpxx_stochtheta_vecT,stochgpxxx_stochtheta_vecT,... + hxT,hxxcT,hxxxcT,... + model.x_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec'); + indi=indi+1; + + chain3c_stochgp_stochtheta_vecT=ptr2col(ptr2d(chain3c_stochgp_stochtheta_vecT,n_stochy,n_stochtheta),2);%n_stochy,unique3,n_stochtheta + nnzchain3c_gp_theta_vecT=col2ptr(changecols(changerows(chain3c_stochgp_stochtheta_vecT,stochy,n_y),stochtheta,(ms+1)*n_theta,2),1); %n_y*unique3,n_theta with only nnz values + + clear chain3c_stochgp_stochtheta_vecT + + nnzchain3c_theta_gpT=col2ptr(changerows(chain3c_theta_stochgpT,stochy,n_y),1);% n_y,unique3,n_theta + + clear chain3c_theta_stochgpT + + vxxxc_theta_lower_terms_vecT=unfold(vxxxc_theta_lower_terms); + vxxxc_theta_lower_terms_vecT.vals=reshape(repmat(vxxxc_theta_lower_terms_vecT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + if model.hybrid==3 + temp=vconcat(takerows(vxxxc_theta_lower_terms_vecT,1:n_y+n_x1),unfold(Phixxxctheta)); + temp=vconcat(temp,takerows(vxxxc_theta_lower_terms_vecT,n_y+n_x+(1:n_x))); + vxxxc_theta_lower_terms_vecT=temp; + end + + vxxxc_theta_upper_terms_vecT=unfold(ptr2col(tplus(nnzchain3c_theta_gpT,nnzchain3c_gp_theta_vecT,maxload),1)); + + clear nnzchain3c_theta_gpT nnzchain3c_gp_theta_vecT + vxxxc_theta_vecT=vconcat(vxxxc_theta_upper_terms_vecT,vxxxc_theta_lower_terms_vecT); + + clear vxxxc_theta_upper_terms_vecT vxxxc_theta_lower_terms_vecT + + stochvxxxc_theta_vecT=takerows(vxxxc_theta_vecT,stochfvars); + + clear vxxxc_theta_vecT + end + if order>=4 + vxxxxcT=vxxxxc; + if model.hybrid==0 || model.hybrid==1 + stochvxxxxcT=takerows(vxxxxcT,stochfvars(n_stochy+1:end)); + stochvxxxxcT.vals=reshape(repmat(stochvxxxxcT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + elseif model.hybrid==3 + vxxxxcT.vals=reshape(repmat(vxxxxcT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + temp=vconcat(takerows(vxxxxcT,1:2*n_y+n_x1),Phixxxxc); + temp=vconcat(temp,takerows(vxxxxcT,2*n_y+n_x+(1:n_x))); + vxxxxcT=temp; + stochvxxxxcT=takerows(vxxxxcT,stochfvars(n_stochy+1:end)); + end + + stochvxxxxcT=vconcat(chain4_stochgpT,stochvxxxxcT); + + if strcmp(model.jacobian,'exact') + [stochgpxxxx_stochtheta_vecT,model.ind4{indi4}]=tkron(ttranspose(Xpxxxx_vecT),IstochyT,model.ind4{indi4},n_ind,maxload,'vec'); + indi4=indi4+1; + else + [stochgpxxxx_stochtheta_vecT,model.ind4{indi4}]=tkron(ttranspose(Xxxxx_vecT),IstochyT,model.ind4{indi4},n_ind,maxload,'vec'); + indi4=indi4+1; + end + + + stochgpxxxx_stochtheta_vecT=ptr1d(col2ptr(ptr2col(ptr2d(unfold(stochgpxxxx_stochtheta_vecT),n_stochy,n_x^4),1),2));%n_stochy*n_stochtheta,n_x^4 + stochgpxxxx_stochtheta_vecT=fold(stochgpxxxx_stochtheta_vecT,n_x,n_x,n_x,n_x); + + [chain4c_stochgp_stochtheta_vecT,model.ind4{indi4}]=chain4c_tensor(stochgpx_stochtheta_vecT,stochgpxx_stochtheta_vecT,stochgpxxx_stochtheta_vecT,stochgpxxxx_stochtheta_vecT,... + hxT,hxxcT,hxxxcT,hxxxxcT,... + model.x_chain4c_M2,model.x_chain4c_M3,model.x_chain4c_M4,... + model.ind4{indi4},n_ind,maxload,'vec'); + indi4=indi4+1; + + chain4c_stochgp_stochtheta_vecT=ptr2col(ptr2d(chain4c_stochgp_stochtheta_vecT,n_stochy,n_stochtheta),2);%n_stochy,unique4,n_stochtheta + nnzchain4c_gp_theta_vecT=col2ptr(changecols(changerows(chain4c_stochgp_stochtheta_vecT,stochy,n_y),stochtheta,(ms+1)*n_theta,2),1); %n_y*unique4,n_theta with only nnz values + + clear chain4c_stochgp_stochtheta_vecT + + nnzchain4c_theta_gpT=col2ptr(changerows(chain4c_theta_stochgpT,stochy,n_y),1);% n_y,unique4,n_theta + + clear chain4c_theta_stochgpT + + vxxxxc_theta_lower_terms_vecT=unfold(vxxxxc_theta_lower_terms); + vxxxxc_theta_lower_terms_vecT.vals=reshape(repmat(vxxxxc_theta_lower_terms_vecT.vals(:)',n_nodes,1),n_nodes*n_s,[]); + + if model.hybrid==3 + temp=vconcat(takerows(vxxxxc_theta_lower_terms_vecT,1:n_y+n_x1),unfold(Phixxxxctheta)); + temp=vconcat(temp,takerows(vxxxxc_theta_lower_terms_vecT,n_y+n_x+(1:n_x))); + vxxxxc_theta_lower_terms_vecT=temp; + end + + vxxxxc_theta_upper_terms_vecT=unfold(ptr2col(tplus(nnzchain4c_theta_gpT,nnzchain4c_gp_theta_vecT,maxload),1)); + + clear nnzchain4c_theta_gpT nnzchain4c_gp_theta_vecT + vxxxxc_theta_vecT=vconcat(vxxxxc_theta_upper_terms_vecT,vxxxxc_theta_lower_terms_vecT); + + clear vxxxxc_theta_upper_terms_vecT vxxxxc_theta_lower_terms_vecT + + stochvxxxxc_theta_vecT=takerows(vxxxxc_theta_vecT,stochfvars); + + clear vxxxxc_theta_vecT + end + totindi=totindi+9; + indi=totindi; + + [ EstochJ0,model.ind{indi} ] = chain0_theta_tensor( stochfv_vec,stochv_theta_vecT,model.ind{indi},n_ind,maxload,'vec' ); + indi=indi+1; + + EstochJ0.vals=reshape(sum(reshape(EstochJ0.vals,n_nodes,[]),1),n_s,[]); + + if order>=1 + [ EstochR1,model.ind{indi} ] = chain1_tensor( stochfv_vec,stochvxT,model.ind{indi},n_ind,maxload,'vec' ); + indi=indi+1; + EstochR1.vals=reshape(sum(reshape(EstochR1.vals,n_nodes,[]),1),n_s,[]); + + + + [ EstochJ1,model.ind{indi} ] = chain1_theta_tensor( stochfv_vec,stochfvv_vec,... + stochvxT,stochv_theta_vecT,stochvx_theta_vecT,... + model.ind{indi},n_ind,maxload,'vec' ); + indi=indi+1; + EstochJ1.vals=reshape(sum(reshape(EstochJ1.vals,n_nodes,[]),1),n_s,[]); + end + if order>=2 + [stochvxT,model.ind4{indi4}]=colsort(stochvxT,model.ind4{indi4}); + indi4=indi4+1; + [ EstochR2,model.ind{indi} ] = chain2c_tensor( stochfv_vec,stochfvv_vec,... + stochvxT,stochvxxcT,model.ind{indi},n_ind,maxload,'vec' ); + indi=indi+1; + EstochR2.vals=reshape(sum(reshape(EstochR2.vals,n_nodes,[]),1),n_s,[]); + + [ EstochJ2,model.ind{indi} ] = chain2c_theta_tensor( stochfv_vec,stochfvv_vec,stochfvvv_vec,... + stochvxT,stochvxxcT,... + stochv_theta_vecT,stochvx_theta_vecT,stochvxxc_theta_vecT,... + model.chain2c_theta_M2,... + model.ind{indi},n_ind,maxload,'vec' ); + indi=indi+1; + EstochJ2.vals=reshape(sum(reshape(EstochJ2.vals,n_nodes,[]),1),n_s,[]); + end + if order>=3 + [ EstochR3,model.ind{indi} ] = chain3c_tensor( stochfv_vec,stochfvv_vec,stochfvvv_vec,... + stochvxT,stochvxxcT,stochvxxxcT,... + model.x_chain3c_M2,... + model.ind{indi},n_ind,maxload,'vec' ); + indi=indi+1; + EstochR3.vals=reshape(sum(reshape(EstochR3.vals,n_nodes,[]),1),n_s,[]); + + [ EstochJ3,model.ind{indi} ] = chain3c_theta_tensor( stochfv_vec,stochfvv_vec,stochfvvv_vec,stochfvvvv_vec,... + stochvxT,stochvxxcT,stochvxxxcT,... + stochv_theta_vecT,stochvx_theta_vecT,stochvxxc_theta_vecT,stochvxxxc_theta_vecT,... + model.chain3c_theta_M2,model.chain3c_theta_M3,model.chain3c_theta_M4,model.chain3c_theta_M5,... + model.ind{indi},n_ind,maxload,'vec' ); + indi=indi+1; + EstochJ3.vals=reshape(sum(reshape(EstochJ3.vals,n_nodes,[]),1),n_s,[]); + end + if order>=4 + [stochvxxcT,model.ind4{indi4}]=colsort(stochvxxcT,model.ind4{indi4}); + indi4=indi4+1; + [ EstochR4,model.ind4{indi4} ] = chain4c_tensor( stochfv_vec,stochfvv_vec,stochfvvv_vec,stochfvvvv_vec,... + stochvxT,stochvxxcT,stochvxxxcT,stochvxxxxcT,... + model.x_chain4c_M2,model.x_chain4c_M3,model.x_chain4c_M4,... + model.ind4{indi4},n_ind,maxload,'vec' ); + indi4=indi4+1; + EstochR4.vals=reshape(sum(reshape(EstochR4.vals,n_nodes,[]),1),n_s,[]); + + [ EstochJ4,model.ind4{indi4} ] = chain4c_theta_tensor( stochfv_vec,stochfvv_vec,stochfvvv_vec,stochfvvvv_vec,stochfvvvvv_vec,... + stochvxT,stochvxxcT,stochvxxxcT,stochvxxxxcT,... + stochv_theta_vecT,stochvx_theta_vecT,stochvxxc_theta_vecT,stochvxxxc_theta_vecT,stochvxxxxc_theta_vecT,... + model.chain4c_theta_M2,model.chain4c_theta_M3,model.chain4c_theta_M5,model.chain4c_theta_M6,model.chain4c_theta_M9,model.chain4c_theta_M10,... + model.ind4{indi4},n_ind,maxload,'vec' ); + indi4=indi4+1; + EstochJ4.vals=reshape(sum(reshape(EstochJ4.vals,n_nodes,[]),1),n_s,[]); + end + totindi=totindi+7; +end + +% build the system and the Jacobian + +R0=vconcat(preR0,EstochR0); +oldrows=1:R0.tsize(1); +newrows=zeros(1,R0.tsize(1)); +newrows([model.prefrows(:);model.stochfrows(:)])=oldrows; +R0=permuterows(R0,newrows); + +J0=vconcat(preJ0,EstochJ0); +J0=permuterows(J0,newrows); + + + +T=R0; +J=J0; + +if order>=1 + R1=vconcat(preR1,EstochR1); + R1=permuterows(R1,newrows); + + R1=ptr2d(R1,1,n_f); + R1=ptr2col(R1,1); + R1=fold(unfold(R1),n_f*n_x,1); + R1=ptr1d(col2ptr(R1,1)); + + T=vconcat(T,R1); + + J1=vconcat(preJ1,EstochJ1); + J1=permuterows(J1,newrows); + + J1=ptr2d(J1,1,n_f); + J1=ptr2col(J1,1); + J1=fold(unfold(J1),n_f*n_x,(ms+1)*n_theta); + J1=ptr1d(col2ptr(J1,1)); + + J=vconcat(J,J1); +end +if order>=2 + R2=vconcat(preR2,EstochR2); + R2=permuterows(R2,newrows); + + R2=ptr2d(R2,1,n_f); + R2=ptr2col(R2,1); + R2=fold(unfold(R2),n_f*unique2,1); + R2=ptr1d(col2ptr(R2,1)); + + T=vconcat(T,R2); + + J2=vconcat(preJ2,EstochJ2); + J2=permuterows(J2,newrows); + + J2=ptr2d(J2,1,n_f); + J2=ptr2col(J2,1); + J2=fold(unfold(J2),n_f*unique2,(ms+1)*n_theta); + J2=ptr1d(col2ptr(J2,1)); + + J=vconcat(J,J2); +end +if order>=3 + R3=vconcat(preR3,EstochR3); + R3=permuterows(R3,newrows); + + R3=ptr2d(R3,1,n_f); + R3=ptr2col(R3,1); + R3=fold(unfold(R3),n_f*unique3,1); + R3=ptr1d(col2ptr(R3,1)); + + T=vconcat(T,R3); + + J3=vconcat(preJ3,EstochJ3); + J3=permuterows(J3,newrows); + + J3=ptr2d(J3,1,n_f); + J3=ptr2col(J3,1); + J3=fold(unfold(J3),n_f*unique3,(ms+1)*n_theta); + J3=ptr1d(col2ptr(J3,1)); + + J=vconcat(J,J3); + +end +if order>=4 + R4=vconcat(preR4,EstochR4); + R4=permuterows(R4,newrows); + + R4=ptr2d(R4,1,n_f); + R4=ptr2col(R4,1); + R4=fold(unfold(R4),n_f*unique4,1); + R4=ptr1d(col2ptr(R4,1)); + + T=vconcat(T,R4); + + J4=vconcat(preJ4,EstochJ4); + J4=permuterows(J4,newrows); + + J4=ptr2d(J4,1,n_f); + J4=ptr2col(J4,1); + J4=fold(unfold(J4),n_f*unique4,(ms+1)*n_theta); + J4=ptr1d(col2ptr(J4,1)); + + J=vconcat(J,J4); + +end +model.coeffs=coeffs; +model.nv=nv; +model.v_theta=v_theta; + +if isfield(model,'special_code') + eval(model.special_code); +end + +end \ No newline at end of file diff --git a/105/replication_package/solution_methods/taylor_projection/uncompressderivs.m b/105/replication_package/solution_methods/taylor_projection/uncompressderivs.m new file mode 100644 index 0000000000000000000000000000000000000000..4e65aa707b1f4821f7c7cd82450ea0bf5591860e --- /dev/null +++ b/105/replication_package/solution_methods/taylor_projection/uncompressderivs.m @@ -0,0 +1,92 @@ +function [ derivs_uncompressed,ind ] = uncompressderivs( derivs,order,n_v,nnzmat,ind ) +%derivs is a sparse tensor that stores unique derivatives of function f w.r.t v. +%order=derivative order +%n_v=length(v); +%nnzmat= a matrix that stores variables that affect f. +%ind=auxiliary index +% +% � Copyright, Oren Levintal, June 13, 2016. +% on January 20, 2017 - extended to fifth order +% on September 12, 2017 - bug corrected for the case of empty tensors. +l=derivs.tsize(1); +if isempty(ind) + original_derivs=derivs; + if size(derivs.ptr,2)>1 + error('2D ptr not supported') + end + + n_vals=size(derivs.vals,2); + derivs.vals=1:n_vals; + sortind=zeros(1,n_vals*factorial(order)); + newcols=zeros(n_vals*factorial(order),order); + nz=1; + newptr=zeros(l+1,1); + newptr(1)=nz; + subinds='i1'; + subindsvec='i1(:)'; + for j=2:order + subinds=[subinds ',i' num2str(j)]; + subindsvec=[subindsvec ',i' num2str(j) '(:)']; + end + for i=1:l + deriv_i=takerows(derivs,i); % take row i + nnzmati=nnzmat(i,:); + ni=nnz(nnzmati); + % convert from compress form to unique form without using c2u + % function because it takes n_v^order memory, and i want only + % ni^order. + eval(['[' subinds ']=ndgrid(find(nnzmati));']) + eval(['nnzind=sub2ind(repmat(n_v,1,order),' subindsvec ');']) + nnzind=sparse(nnzind,ones(length(nnzind),1),ones(length(nnzind),1),n_v^order,1); + [loc,nnzind]=nnz_UW(n_v,order,nnzind,'ind'); + smat=sparse(loc,ones(length(loc),1),nnzind,nchoosek(n_v+order-1,order),1); + eval(['[' subinds ']=ind2sub(repmat(n_v,1,order),full(smat(deriv_i.cols)));']) + eval(['allind=[' subindsvec '];']) + deriv_i.cols=intarray(allind); % this is the unique form + %%%% + % change column indices + deriv_i.cols=intarray(nnzmati(deriv_i.cols)); + deriv_i.tsize=intarray([1,repmat(ni,1,order)]); + if ni>0 % if column dimension is nonzero (which is the normal case) + % u2c + deriv_i=u2c(deriv_i); + [~,W]=create_UW(ni,order); + deriv_i=contraction1(unfold(deriv_i),spmat2sptensor(W)); + end + %change column indices back to original + if order==2 + deriv_i=fold(deriv_i,ni,ni); + elseif order==3 + deriv_i=fold(deriv_i,ni,ni,ni); + elseif order==4 + deriv_i=fold(deriv_i,ni,ni,ni,ni); + elseif order==5 + deriv_i=fold(deriv_i,ni,ni,ni,ni,ni); + else + error('order should be between 2 and 5') + end + temp=find(nnzmati); + deriv_i.cols=temp(deriv_i.cols); + + n_valsi=size(deriv_i.vals,2); + sortind(nz:nz+n_valsi-1)=deriv_i.vals; + newcols(nz:nz+n_valsi-1,:)=deriv_i.cols; + nz=nz+n_valsi; + newptr(i+1)=nz; + end + + ind.sortind=sortind(1:nz-1); + ind.newcols=intarray(newcols(1:nz-1,:)); + ind.ptr=intarray(newptr); + derivs=original_derivs; +end + +derivs_uncompressed=sptensor; +derivs_uncompressed.vals=derivs.vals(:,ind.sortind); +derivs_uncompressed.cols=ind.newcols; +derivs_uncompressed.ptr=ind.ptr; +derivs_uncompressed.tsize=intarray([l,repmat(n_v,1,order)]); + + +end + diff --git a/105/should_reproduce.txt b/105/should_reproduce.txt new file mode 100644 index 0000000000000000000000000000000000000000..49384932f5fa6a36368d9c797e8088319871df4e --- /dev/null +++ b/105/should_reproduce.txt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ffcf205a879662dcb27e51b78cc5b41710889af588695d45808c69245dbb184 +size 74