dr1.m 26.9 KB
Newer Older
1
function [dr,info,M_,options_,oo_] = dr1(dr,task,M_,options_,oo_)
2
3
% function [dr,info,M_,options_,oo_] = dr1(dr,task,M_,options_,oo_)
% computes the reduced form solution of a rational expectation model (first or second order
4
% approximation of the stochastic model around the deterministic steady state). 
5
6
%
% INPUTS
7
8
9
10
11
12
13
%   dr         [matlab structure] Decision rules for stochastic simulations.
%   task       [integer]          if task = 0 then dr1 computes decision rules.
%                                 if task = 1 then dr1 computes eigenvalues.
%   M_         [matlab structure] Definition of the model.           
%   options_   [matlab structure] Global options.
%   oo_        [matlab structure] Results 
%    
14
% OUTPUTS
15
16
17
18
19
20
21
22
%   dr         [matlab structure] Decision rules for stochastic simulations.
%   info       [integer]          info=1: the model doesn't define current variables uniquely
%                                 info=2: problem in mjdgges.dll info(2) contains error code. 
%                                 info=3: BK order condition not satisfied info(2) contains "distance"
%                                         absence of stable trajectory.
%                                 info=4: BK order condition not satisfied info(2) contains "distance"
%                                         indeterminacy.
%                                 info=5: BK rank condition not satisfied.
23
%                                 info=6: The jacobian matrix evaluated at the steady state is complex.        
24
25
26
%   M_         [matlab structure]            
%   options_   [matlab structure]
%   oo_        [matlab structure]
27
28
29
%  
% ALGORITHM
%   ...
30
%    
31
% SPECIAL REQUIREMENTS
32
%   none.
33
%  
34

35
% Copyright (C) 1996-2011 Dynare Team
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
51

52
53
info = 0;

54
55
56
57
if M_.maximum_endo_lag == 0 && options_.order > 1
    error(['2nd and 3rd order approximation not implemented for purely forward models'])
end

58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
if options_.k_order_solver;
    dr = set_state_space(dr,M_);
    [dr,info] = k_order_pert(dr,M_,options_,oo_);
    oo_.dr = dr;
    return;
end

xlen = M_.maximum_endo_lead + M_.maximum_endo_lag + 1;
klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1;
iyv = M_.lead_lag_incidence';
iyv = iyv(:);
iyr0 = find(iyv) ;
it_ = M_.maximum_lag + 1 ;

if M_.exo_nbr == 0
    oo_.exo_steady_state = [] ;
end

% expanding system for Optimal Linear Regulator
if options_.ramsey_policy
    if isfield(M_,'orig_model')
        orig_model = M_.orig_model;
        M_.endo_nbr = orig_model.endo_nbr;
        M_.orig_endo_nbr = orig_model.orig_endo_nbr;
        M_.aux_vars = orig_model.aux_vars;
        M_.endo_names = orig_model.endo_names;
        M_.lead_lag_incidence = orig_model.lead_lag_incidence;
        M_.maximum_lead = orig_model.maximum_lead;
        M_.maximum_endo_lead = orig_model.maximum_endo_lead;
        M_.maximum_lag = orig_model.maximum_lag;
        M_.maximum_endo_lag = orig_model.maximum_endo_lag;
89
        oo_.steady_state = oo_.steady_state(1:M_.endo_nbr);
90
    end
91
92
93
94

    if options_.steadystate_flag
        k_inst = [];
        instruments = options_.instruments;
MichelJuillard's avatar
MichelJuillard committed
95
96
        inst_nbr = size(options_.instruments);
        for i = 1:inst_nbr
97
98
99
100
            k_inst = [k_inst; strmatch(options_.instruments(i,:), ...
                                       M_.endo_names,'exact')];
        end
        ys = oo_.steady_state;
MichelJuillard's avatar
MichelJuillard committed
101
        if inst_nbr == 1
102
           nl_func = @(x) dyn_ramsey_static_(x,M_,options_,oo_,it_);
MichelJuillard's avatar
MichelJuillard committed
103
104
105
106
107
108
           inst_val = fzero(nl_func,oo_.steady_state(k_inst));
        else
            [inst_val,info1] = dynare_solve('dyn_ramsey_static_', ...
                                            oo_.steady_state(k_inst),0, ...
                                            M_,options_,oo_,it_);
        end
109
        M_.params = evalin('base','M_.params;');
110
111
112
113
        ys(k_inst) = inst_val;
        [x,check] = feval([M_.fname '_steadystate'],...
                          ys,[oo_.exo_steady_state; ...
                            oo_.exo_det_steady_state]);
114
        M_.params = evalin('base','M_.params;');
115
116
117
118
119
120
        if size(x,1) < M_.endo_nbr 
            if length(M_.aux_vars) > 0
                x = add_auxiliary_variables_to_steadystate(x,M_.aux_vars,...
                                                           M_.fname,...
                                                           oo_.exo_steady_state,...
                                                           oo_.exo_det_steady_state,...
121
122
                                                           M_.params,...
                                                           options_.bytecode);
123
124
125
126
127
128
            else
                error([M_.fname '_steadystate.m doesn''t match the model']);
            end
        end
        oo_.steady_state = x;
        [junk,junk,multbar] = dyn_ramsey_static_(oo_.steady_state(k_inst),M_,options_,oo_,it_);
MichelJuillard's avatar
MichelJuillard committed
129
        oo_.steady_state = [x(1:M_.orig_endo_nbr); multbar];
130
    else
MichelJuillard's avatar
MichelJuillard committed
131
132
%        xx = oo_.steady_state([1:M_.orig_endo_nbr (M_.orig_endo_nbr+M_.orig_eq_nbr+1):end]);
        xx = oo_.steady_state(1:M_.orig_endo_nbr);
133
134
135
136
        [xx,info1] = dynare_solve('dyn_ramsey_static_', ...
                                                xx,0,M_,options_,oo_,it_);
        [junk,junk,multbar] = dyn_ramsey_static_(xx,M_,options_,oo_,it_);
        oo_.steady_state = [xx; multbar];
137
    end
138
    
139
140
141
142
143
    check1 = max(abs(feval([M_.fname '_static'],...
                           oo_.steady_state,...
                           [oo_.exo_steady_state; ...
                        oo_.exo_det_steady_state], M_.params))) > options_.dynatol ;
    if check1
144
145
146
        info(1) = 20;
        info(2) = check1'*check1;
        return
147
    end
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
    dr.ys = oo_.steady_state;
end    
klen = M_.maximum_lag + M_.maximum_lead + 1;
iyv = M_.lead_lag_incidence';
iyv = iyv(:);
iyr0 = find(iyv) ;
it_ = M_.maximum_lag + 1 ;

if M_.exo_nbr == 0
    oo_.exo_steady_state = [] ;
end

it_ = M_.maximum_lag + 1;
z = repmat(dr.ys,1,klen);
if ~options_.bytecode
    z = z(iyr0) ;
end;
if options_.order == 1
    if (options_.bytecode)
        [chck, junk, loc_dr] = bytecode('dynamic','evaluate', z,[oo_.exo_simul ...
                            oo_.exo_det_simul], M_.params, dr.ys, 1);
        jacobia_ = [loc_dr.g1 loc_dr.g1_x loc_dr.g1_xd];
    else
        [junk,jacobia_] = feval([M_.fname '_dynamic'],z,[oo_.exo_simul ...
                            oo_.exo_det_simul], M_.params, dr.ys, it_);
173
    end;
174
175
176
177
178
179
180
181
182
183
184
185
186
187
elseif options_.order == 2
    if (options_.bytecode)
        [chck, junk, loc_dr] = bytecode('dynamic','evaluate', z,[oo_.exo_simul ...
                            oo_.exo_det_simul], M_.params, dr.ys, 1);
        jacobia_ = [loc_dr.g1 loc_dr.g1_x];
    else
        [junk,jacobia_,hessian1] = feval([M_.fname '_dynamic'],z,...
                                         [oo_.exo_simul ...
                            oo_.exo_det_simul], M_.params, dr.ys, it_);
    end;
    if options_.use_dll
        % In USE_DLL mode, the hessian is in the 3-column sparse representation
        hessian1 = sparse(hessian1(:,1), hessian1(:,2), hessian1(:,3), ...
                          size(jacobia_, 1), size(jacobia_, 2)*size(jacobia_, 2));
188
189
    end
end
190

191
192
193
if options_.debug
    save([M_.fname '_debug.mat'],'jacobia_')
end
194

195
196
197
198
199
if ~all(isfinite(jacobia_(:)))
    info(1) = 6;
    info(2) = 1;
    return
elseif ~isreal(jacobia_)
200
201
    if max(max(abs(imag(jacobia_)))) < 1e-15
        jacobia_ = real(jacobia_);
202
    else
203
204
        info(1) = 6;
        info(2) = sum(sum(imag(jacobia_).^2));
205
        return
206
    end
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
end

dr=set_state_space(dr,M_);
kstate = dr.kstate;
kad = dr.kad;
kae = dr.kae;
nstatic = dr.nstatic;
nfwrd = dr.nfwrd;
npred = dr.npred;
nboth = dr.nboth;
order_var = dr.order_var;
nd = size(kstate,1);
nz = nnz(M_.lead_lag_incidence);

sdyn = M_.endo_nbr - nstatic;
222

223
224
225
226
227
[junk,cols_b,cols_j] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+1, ...
                                                  order_var));
b = zeros(M_.endo_nbr,M_.endo_nbr);
b(:,cols_b) = jacobia_(:,cols_j);

228
if M_.maximum_endo_lead == 0
229
    % backward models: simplified code exist only at order == 1
sebastien's avatar
sebastien committed
230
    % If required, use AIM solver if not check only
231
232
233
234
    if options_.order > 1
        error(['2nd and 3rd order approximation not implemented for purely ' ...
               'backward models'])
    end
sebastien's avatar
sebastien committed
235
236
237
238
    if (options_.aim_solver == 1) && (task == 0)
        if options_.order > 1
            error('Option "aim_solver" is incompatible with order >= 2')
        end
239
        try
240
            [dr,aimcode]=dynAIMsolver1(jacobia_,M_,dr);
241
            if aimcode ~=1
242
                info(1) = convertAimCodeToInfo(aimcode);
243
244
245
246
                info(2) = 1.0e+8;
                return
            end
        catch
sebastien's avatar
sebastien committed
247
            disp(lasterror.message)
248
            error('Problem with AIM solver - Try to remove the "aim_solver" option');
249
        end
250
251
    else % use original Dynare solver
        [k1,junk,k2] = find(kstate(:,4));
252
253
254
        dr.ghx(:,k1) = -b\jacobia_(:,k2);
        % with simul, the Jacobian doesn't contain derivatives w.r. to shocks
        if size(jacobia_,2) > nz
255
            dr.ghu = -b\jacobia_(:,nz+1:end);
256
        end
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
    end % if not use AIM or not...
    dr.eigval = eig(transition_matrix(dr));
    dr.rank = 0;
    if any(abs(dr.eigval) > options_.qz_criterium)
        temp = sort(abs(dr.eigval));
        nba = nnz(abs(dr.eigval) > options_.qz_criterium);
        temp = temp(nd-nba+1:nd)-1-options_.qz_criterium;
        info(1) = 3;
        info(2) = temp'*temp;
    end
    if options_.loglinear == 1
        klags = find(M_.lead_lag_incidence(1,:));
        dr.ghx = repmat(1./dr.ys,1,size(dr.ghx,2)).*dr.ghx.* ...
                 repmat(dr.ys(klags),size(dr.ghx,1),1);
        dr.ghu = repmat(1./dr.ys,1,size(dr.ghu,2)).*dr.ghu;
    end
    return
end
275

276
277
278
279
280
281
282
%forward--looking models
if nstatic > 0
    [Q,R] = qr(b(:,1:nstatic));
    aa = Q'*jacobia_;
else
    aa = jacobia_;
end
283

284
285
286
287
288
289
290
% If required, use AIM solver if not check only
if (options_.aim_solver == 1) && (task == 0)
    if options_.order > 1
        error('Option "aim_solver" is incompatible with order >= 2')
    end
    try
        [dr,aimcode]=dynAIMsolver1(aa,M_,dr);
291

292
293
294
        % reuse some of the bypassed code and tests that may be needed 
        
        if aimcode ~=1
295
            info(1) = convertAimCodeToInfo(aimcode);
296
            info(2) = 1.0e+8;
297
298
            return
        end
299
300
301
        [A,B] =transition_matrix(dr);
        dr.eigval = eig(A);
        sdim = sum( abs(dr.eigval) < options_.qz_criterium );
302
303
304
305
306
307
308
        nba = nd-sdim;

        nyf = sum(kstate(:,2) > M_.maximum_endo_lag+1);
        if nba ~= nyf
            temp = sort(abs(dr.eigval));
            if nba > nyf
                temp = temp(nd-nba+1:nd-nyf)-1-options_.qz_criterium;
adjemian's avatar
adjemian committed
309
                info(1) = 3;
310
311
312
313
314
315
316
            elseif nba < nyf;
                temp = temp(nd-nyf+1:nd-nba)-1-options_.qz_criterium;
                info(1) = 4;
            end
            info(2) = temp'*temp;
            return
        end
317
318
319
320
321
322
323
324
325
326
327
    catch
        disp(lasterror.message)
        error('Problem with AIM solver - Try to remove the "aim_solver" option')
    end
else  % use original Dynare solver
    k1 = M_.lead_lag_incidence(find([1:klen] ~= M_.maximum_endo_lag+1),:);
    a = aa(:,nonzeros(k1'));
    b(:,cols_b) = aa(:,cols_j);
    b10 = b(1:nstatic,1:nstatic);
    b11 = b(1:nstatic,nstatic+1:end);
    b2 = b(nstatic+1:end,nstatic+1:end);
328

329
330
331
    % buildind D and E
    d = zeros(nd,nd) ;
    e = d ;
332

333
334
335
336
337
338
339
340
341
342
343
344
345
346
    k = find(kstate(:,2) >= M_.maximum_endo_lag+2 & kstate(:,3));
    d(1:sdyn,k) = a(nstatic+1:end,kstate(k,3)) ;
    k1 = find(kstate(:,2) == M_.maximum_endo_lag+2);
    e(1:sdyn,k1) =  -b2(:,kstate(k1,1)-nstatic);
    k = find(kstate(:,2) <= M_.maximum_endo_lag+1 & kstate(:,4));
    e(1:sdyn,k) = -a(nstatic+1:end,kstate(k,4)) ;
    k2 = find(kstate(:,2) == M_.maximum_endo_lag+1);
    k2 = k2(~ismember(kstate(k2,1),kstate(k1,1)));
    d(1:sdyn,k2) = b2(:,kstate(k2,1)-nstatic);

    if ~isempty(kad)
        for j = 1:size(kad,1)
            d(sdyn+j,kad(j)) = 1 ;
            e(sdyn+j,kae(j)) = 1 ;
347
348
        end
    end
349
350
351
352
353
354

    % 1) if mjdgges.dll (or .mexw32 or ....) doesn't exit, 
    % matlab/qz is added to the path. There exists now qz/mjdgges.m that 
    % contains the calls to the old Sims code 
    % 2) In  global_initialization.m, if mjdgges.m is visible exist(...)==2, 
    % this means that the DLL isn't avaiable and use_qzdiv is set to 1
355
    
356
357
358
359
    if isempty(options_.qz_criterium)
        error('I cannot solve the model because qz_criterium option is empty!')
    end

360
361
    [err,ss,tt,w,sdim,dr.eigval,info1] = mjdgges(e,d,options_.qz_criterium);
    mexErrCheck('mjdgges', err);
362
363
364
365

    if info1
        info(1) = 2;
        info(2) = info1;
Houtan Bastani's avatar
Houtan Bastani committed
366
        info(3) = size(e,2);
367
        return
sebastien's avatar
sebastien committed
368
    end
369
370
371
372
373
374
375
376
377
378
379

    nba = nd-sdim;

    nyf = sum(kstate(:,2) > M_.maximum_endo_lag+1);

    if task == 1
        dr.rank = rank(w(1:nyf,nd-nyf+1:end));
        % Under Octave, eig(A,B) doesn't exist, and
        % lambda = qz(A,B) won't return infinite eigenvalues
        if ~exist('OCTAVE_VERSION')
            dr.eigval = eig(e,d);
380
        end
381
382
383
384
385
        for i=1:nd
            if abs(ss(i,i)) < 1e-6 && abs(tt(i,i)) < 1e-6
                info(7) = 1;
            end
        end
386
        return
387
    end
388
389

    if nba ~= nyf
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
        sorted_roots = sort(abs(dr.eigval));
        if isfield(options_,'indeterminacy_continuity')
            if options_.indeterminacy_msv == 1
                [ss,tt,w,q] = qz(e',d');
                [ss,tt,w,q] = reorder(ss,tt,w,q);
                ss = ss';
                tt = tt';
                w  = w';
                nba = nyf;
            end
        else
            if nba > nyf
                temp = sorted_roots(nd-nba+1:nd-nyf)-1-options_.qz_criterium;
                info(1) = 3;
            elseif nba < nyf;
                temp = sorted_roots(nd-nyf+1:nd-nba)-1-options_.qz_criterium;
                info(1) = 4;
            end
            info(2) = temp'*temp;
            return
410
        end
411
    end
412
413
414
415
416
417
418
419

    np = nd - nyf;
    n2 = np + 1;
    n3 = nyf;
    n4 = n3 + 1;
    % derivatives with respect to dynamic state variables
    % forward variables
    w1 =w(1:n3,n2:nd);
420
    if ~isscalar(w1) && (condest(w1) > 1e9)
421
        % condest() fails on a scalar under Octave
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
        info(1) = 5;
        info(2) = condest(w1);
        return;
    else
        gx = -w1'\w(n4:nd,n2:nd)';
    end  

    % predetermined variables
    hx = w(1:n3,1:np)'*gx+w(n4:nd,1:np)';
    hx = (tt(1:np,1:np)*hx)\(ss(1:np,1:np)*hx);

    k1 = find(kstate(n4:nd,2) == M_.maximum_endo_lag+1);
    k2 = find(kstate(1:n3,2) == M_.maximum_endo_lag+2);
    dr.ghx = [hx(k1,:); gx(k2(nboth+1:end),:)];

    %lead variables actually present in the model
    j3 = nonzeros(kstate(:,3));
    j4  = find(kstate(:,3));
    % derivatives with respect to exogenous variables
    if M_.exo_nbr
        fu = aa(:,nz+(1:M_.exo_nbr));
        a1 = b;
        aa1 = [];
        if nstatic > 0
            aa1 = a1(:,1:nstatic);
        end
        dr.ghu = -[aa1 a(:,j3)*gx(j4,1:npred)+a1(:,nstatic+1:nstatic+ ...
                                                 npred) a1(:,nstatic+npred+1:end)]\fu;
    else
        dr.ghu = [];
452
    end
453
454
455
456
457
458
459
460
461

    % static variables
    if nstatic > 0
        temp = -a(1:nstatic,j3)*gx(j4,:)*hx;
        j5 = find(kstate(n4:nd,4));
        temp(:,j5) = temp(:,j5)-a(1:nstatic,nonzeros(kstate(:,4)));
        temp = b10\(temp-b11*dr.ghx);
        dr.ghx = [temp; dr.ghx];
        temp = [];
462
    end
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
end % if not use AIM and ....
    % End of if... and if not... main AIM Blocks, continue as per usual...

if options_.loglinear == 1
    k = find(dr.kstate(:,2) <= M_.maximum_endo_lag+1);
    klag = dr.kstate(k,[1 2]);
    k1 = dr.order_var;
    
    dr.ghx = repmat(1./dr.ys(k1),1,size(dr.ghx,2)).*dr.ghx.* ...
             repmat(dr.ys(k1(klag(:,1)))',size(dr.ghx,1),1);
    dr.ghu = repmat(1./dr.ys(k1),1,size(dr.ghu,2)).*dr.ghu;
end

if options_.aim_solver ~= 1 && options_.use_qzdiv
    %% Necessary when using Sims' routines for QZ
    gx = real(gx);
    hx = real(hx);
    dr.ghx = real(dr.ghx);
    dr.ghu = real(dr.ghu);
end

%exogenous deterministic variables
if M_.exo_det_nbr > 0
    f1 = sparse(jacobia_(:,nonzeros(M_.lead_lag_incidence(M_.maximum_endo_lag+2:end,order_var))));
    f0 = sparse(jacobia_(:,nonzeros(M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var))));
    fudet = sparse(jacobia_(:,nz+M_.exo_nbr+1:end));
    M1 = inv(f0+[zeros(M_.endo_nbr,nstatic) f1*gx zeros(M_.endo_nbr,nyf-nboth)]);
    M2 = M1*f1;
    dr.ghud = cell(M_.exo_det_length,1);
    dr.ghud{1} = -M1*fudet;
    for i = 2:M_.exo_det_length
        dr.ghud{i} = -M2*dr.ghud{i-1}(end-nyf+1:end,:);
495
    end
496
end
sebastien's avatar
sebastien committed
497

498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
if options_.order == 1
    return
end

% Second order
%tempex = oo_.exo_simul ;

%hessian = real(hessext('ff1_',[z; oo_.exo_steady_state]))' ;
kk = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1));
if M_.maximum_endo_lag > 0
    kk = [cumsum(M_.lead_lag_incidence(1:M_.maximum_endo_lag,order_var),1); kk];
end
kk = kk';
kk = find(kk(:));
nk = size(kk,1) + M_.exo_nbr + M_.exo_det_nbr;
k1 = M_.lead_lag_incidence(:,order_var);
k1 = k1';
k1 = k1(:);
k1 = k1(kk);
k2 = find(k1);
kk1(k1(k2)) = k2;
kk1 = [kk1 length(k1)+1:length(k1)+M_.exo_nbr+M_.exo_det_nbr];
kk = reshape([1:nk^2],nk,nk);
kk1 = kk(kk1,kk1);
%[junk,junk,hessian] = feval([M_.fname '_dynamic'],z, oo_.exo_steady_state);
hessian(:,kk1(:)) = hessian1;
clear hessian1

%oo_.exo_simul = tempex ;
%clear tempex

n1 = 0;
n2 = np;
zx = zeros(np,np);
zu=zeros(np,M_.exo_nbr);
for i=2:M_.maximum_endo_lag+1
    k1 = sum(kstate(:,2) == i);
    zx(n1+1:n1+k1,n2-k1+1:n2)=eye(k1);
    n1 = n1+k1;
    n2 = n2-k1;
end
kk = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1));
k0 = [1:M_.endo_nbr];
gx1 = dr.ghx;
hu = dr.ghu(nstatic+[1:npred],:);
zx = [zx; gx1];
zu = [zu; dr.ghu];
for i=1:M_.maximum_endo_lead
    k1 = find(kk(i+1,k0) > 0);
    zu = [zu; gx1(k1,1:npred)*hu];
    gx1 = gx1(k1,:)*hx;
    zx = [zx; gx1];
    kk = kk(:,k0);
    k0 = k1;
end
zx=[zx; zeros(M_.exo_nbr,np);zeros(M_.exo_det_nbr,np)];
zu=[zu; eye(M_.exo_nbr);zeros(M_.exo_det_nbr,M_.exo_nbr)];
[nrzx,nczx] = size(zx);

557
[err, rhs] = sparse_hessian_times_B_kronecker_C(hessian,zx,options_.threads.kronecker.sparse_hessian_times_B_kronecker_C);
558
559
mexErrCheck('sparse_hessian_times_B_kronecker_C', err);
rhs = -rhs;
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591

%lhs
n = M_.endo_nbr+sum(kstate(:,2) > M_.maximum_endo_lag+1 & kstate(:,2) < M_.maximum_endo_lag+M_.maximum_endo_lead+1);
A = zeros(n,n);
B = zeros(n,n);
A(1:M_.endo_nbr,1:M_.endo_nbr) = jacobia_(:,M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var));
% variables with the highest lead
k1 = find(kstate(:,2) == M_.maximum_endo_lag+M_.maximum_endo_lead+1);
if M_.maximum_endo_lead > 1
    k2 = find(kstate(:,2) == M_.maximum_endo_lag+M_.maximum_endo_lead);
    [junk,junk,k3] = intersect(kstate(k1,1),kstate(k2,1));
else
    k2 = [1:M_.endo_nbr];
    k3 = kstate(k1,1);
end
% Jacobian with respect to the variables with the highest lead
B(1:M_.endo_nbr,end-length(k2)+k3) = jacobia_(:,kstate(k1,3)+M_.endo_nbr);
offset = M_.endo_nbr;
k0 = [1:M_.endo_nbr];
gx1 = dr.ghx;
for i=1:M_.maximum_endo_lead-1
    k1 = find(kstate(:,2) == M_.maximum_endo_lag+i+1);
    [k2,junk,k3] = find(kstate(k1,3));
    A(1:M_.endo_nbr,offset+k2) = jacobia_(:,k3+M_.endo_nbr);
    n1 = length(k1);
    A(offset+[1:n1],nstatic+[1:npred]) = -gx1(kstate(k1,1),1:npred);
    gx1 = gx1*hx;
    A(offset+[1:n1],offset+[1:n1]) = eye(n1);
    n0 = length(k0);
    E = eye(n0);
    if i == 1
        [junk,junk,k4]=intersect(kstate(k1,1),[1:M_.endo_nbr]);
592
    else
593
        [junk,junk,k4]=intersect(kstate(k1,1),kstate(k0,1));
594
    end
595
596
597
598
599
600
601
602
603
604
605
606
    i1 = offset-n0+n1;
    B(offset+[1:n1],offset-n0+[1:n0]) = -E(k4,:);
    k0 = k1;
    offset = offset + n1;
end
[junk,k1,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+M_.maximum_endo_lead+1,order_var));
A(1:M_.endo_nbr,nstatic+1:nstatic+npred)=...
    A(1:M_.endo_nbr,nstatic+[1:npred])+jacobia_(:,k2)*gx1(k1,1:npred);
C = hx;
D = [rhs; zeros(n-M_.endo_nbr,size(rhs,2))];


607
608
[err, dr.ghxx] = gensylv(2,A,B,C,D);
mexErrCheck('gensylv', err);
609
610
611
612
613
614
615
616

%ghxu
%rhs
hu = dr.ghu(nstatic+1:nstatic+npred,:);
%kk = reshape([1:np*np],np,np);
%kk = kk(1:npred,1:npred);
%rhs = -hessian*kron(zx,zu)-f1*dr.ghxx(end-nyf+1:end,kk(:))*kron(hx(1:npred,:),hu(1:npred,:));

617
[err, rhs] = sparse_hessian_times_B_kronecker_C(hessian,zx,zu,options_.threads.kronecker.sparse_hessian_times_B_kronecker_C);
618
mexErrCheck('sparse_hessian_times_B_kronecker_C', err);
619
620
621
622
623
624
625

nyf1 = sum(kstate(:,2) == M_.maximum_endo_lag+2);
hu1 = [hu;zeros(np-npred,M_.exo_nbr)];
%B1 = [B(1:M_.endo_nbr,:);zeros(size(A,1)-M_.endo_nbr,size(B,2))];
[nrhx,nchx] = size(hx);
[nrhu1,nchu1] = size(hu1);

626
[err, abcOut] = A_times_B_kronecker_C(dr.ghxx,hx,hu1,options_.threads.kronecker.A_times_B_kronecker_C);
627
628
mexErrCheck('A_times_B_kronecker_C', err);
B1 = B*abcOut;
629
630
631
632
633
634
635
636
637
638
639
rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1;


%lhs
dr.ghxu = A\rhs;

%ghuu
%rhs
kk = reshape([1:np*np],np,np);
kk = kk(1:npred,1:npred);

640
[err, rhs] = sparse_hessian_times_B_kronecker_C(hessian,zu,options_.threads.kronecker.sparse_hessian_times_B_kronecker_C);
641
mexErrCheck('sparse_hessian_times_B_kronecker_C', err);
642

643
[err, B1] = A_times_B_kronecker_C(B*dr.ghxx,hu1,options_.threads.kronecker.A_times_B_kronecker_C);
644
mexErrCheck('A_times_B_kronecker_C', err);
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1;

%lhs
dr.ghuu = A\rhs;

dr.ghxx = dr.ghxx(1:M_.endo_nbr,:);
dr.ghxu = dr.ghxu(1:M_.endo_nbr,:);
dr.ghuu = dr.ghuu(1:M_.endo_nbr,:);


% dr.ghs2
% derivatives of F with respect to forward variables
% reordering predetermined variables in diminishing lag order
O1 = zeros(M_.endo_nbr,nstatic);
O2 = zeros(M_.endo_nbr,M_.endo_nbr-nstatic-npred);
LHS = jacobia_(:,M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var));
RHS = zeros(M_.endo_nbr,M_.exo_nbr^2);
kk = find(kstate(:,2) == M_.maximum_endo_lag+2);
gu = dr.ghu; 
guu = dr.ghuu; 
Gu = [dr.ghu(nstatic+[1:npred],:); zeros(np-npred,M_.exo_nbr)];
Guu = [dr.ghuu(nstatic+[1:npred],:); zeros(np-npred,M_.exo_nbr*M_.exo_nbr)];
E = eye(M_.endo_nbr);
M_.lead_lag_incidenceordered = flipud(cumsum(flipud(M_.lead_lag_incidence(M_.maximum_endo_lag+1:end,order_var)),1));
if M_.maximum_endo_lag > 0
    M_.lead_lag_incidenceordered = [cumsum(M_.lead_lag_incidence(1:M_.maximum_endo_lag,order_var),1); M_.lead_lag_incidenceordered];
end
M_.lead_lag_incidenceordered = M_.lead_lag_incidenceordered';
M_.lead_lag_incidenceordered = M_.lead_lag_incidenceordered(:);
k1 = find(M_.lead_lag_incidenceordered);
M_.lead_lag_incidenceordered(k1) = [1:length(k1)]';
M_.lead_lag_incidenceordered =reshape(M_.lead_lag_incidenceordered,M_.endo_nbr,M_.maximum_endo_lag+M_.maximum_endo_lead+1)';
kh = reshape([1:nk^2],nk,nk);
kp = sum(kstate(:,2) <= M_.maximum_endo_lag+1);
E1 = [eye(npred); zeros(kp-npred,npred)];
H = E1;
hxx = dr.ghxx(nstatic+[1:npred],:);
for i=1:M_.maximum_endo_lead
    for j=i:M_.maximum_endo_lead
        [junk,k2a,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+j+1,order_var));
        [junk,k3a,k3] = ...
            find(M_.lead_lag_incidenceordered(M_.maximum_endo_lag+j+1,:));
        nk3a = length(k3a);
688
        [err, B1] = sparse_hessian_times_B_kronecker_C(hessian(:,kh(k3,k3)),gu(k3a,:),options_.threads.kronecker.sparse_hessian_times_B_kronecker_C);
689
        mexErrCheck('sparse_hessian_times_B_kronecker_C', err);
690
        RHS = RHS + jacobia_(:,k2)*guu(k2a,:)+B1;
691
    end
692
693
694
    % LHS
    [junk,k2a,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+i+1,order_var));
    LHS = LHS + jacobia_(:,k2)*(E(k2a,:)+[O1(k2a,:) dr.ghx(k2a,:)*H O2(k2a,:)]);
695
    
696
697
698
    if i == M_.maximum_endo_lead 
        break
    end
699
    
700
701
702
    kk = find(kstate(:,2) == M_.maximum_endo_lag+i+1);
    gu = dr.ghx*Gu;
    [nrGu,ncGu] = size(Gu);
703
    [err, G1] = A_times_B_kronecker_C(dr.ghxx,Gu,options_.threads.kronecker.A_times_B_kronecker_C);
704
    mexErrCheck('A_times_B_kronecker_C', err);
705
    [err, G2] = A_times_B_kronecker_C(hxx,Gu,options_.threads.kronecker.A_times_B_kronecker_C);
706
    mexErrCheck('A_times_B_kronecker_C', err);
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
    guu = dr.ghx*Guu+G1;
    Gu = hx*Gu;
    Guu = hx*Guu;
    Guu(end-npred+1:end,:) = Guu(end-npred+1:end,:) + G2;
    H = E1 + hx*H;
end
RHS = RHS*M_.Sigma_e(:);
dr.fuu = RHS;
%RHS = -RHS-dr.fbias;
RHS = -RHS;
dr.ghs2 = LHS\RHS;

% deterministic exogenous variables
if M_.exo_det_nbr > 0
    hud = dr.ghud{1}(nstatic+1:nstatic+npred,:);
    zud=[zeros(np,M_.exo_det_nbr);dr.ghud{1};gx(:,1:npred)*hud;zeros(M_.exo_nbr,M_.exo_det_nbr);eye(M_.exo_det_nbr)];
    R1 = hessian*kron(zx,zud);
    dr.ghxud = cell(M_.exo_det_length,1);
    kf = [M_.endo_nbr-nyf+1:M_.endo_nbr];
    kp = nstatic+[1:npred];
    dr.ghxud{1} = -M1*(R1+f1*dr.ghxx(kf,:)*kron(dr.ghx(kp,:),dr.ghud{1}(kp,:)));
    Eud = eye(M_.exo_det_nbr);
    for i = 2:M_.exo_det_length
        hudi = dr.ghud{i}(kp,:);
        zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)];
        R2 = hessian*kron(zx,zudi);
        dr.ghxud{i} = -M2*(dr.ghxud{i-1}(kf,:)*kron(hx,Eud)+dr.ghxx(kf,:)*kron(dr.ghx(kp,:),dr.ghud{i}(kp,:)))-M1*R2;
734
    end
735
736
737
738
739
740
741
742
743
744
745
    R1 = hessian*kron(zu,zud);
    dr.ghudud = cell(M_.exo_det_length,1);
    kf = [M_.endo_nbr-nyf+1:M_.endo_nbr];
    
    dr.ghuud{1} = -M1*(R1+f1*dr.ghxx(kf,:)*kron(dr.ghu(kp,:),dr.ghud{1}(kp,:)));
    Eud = eye(M_.exo_det_nbr);
    for i = 2:M_.exo_det_length
        hudi = dr.ghud{i}(kp,:);
        zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)];
        R2 = hessian*kron(zu,zudi);
        dr.ghuud{i} = -M2*dr.ghxud{i-1}(kf,:)*kron(hu,Eud)-M1*R2;
michel's avatar
michel committed
746
    end
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
    R1 = hessian*kron(zud,zud);
    dr.ghudud = cell(M_.exo_det_length,M_.exo_det_length);
    dr.ghudud{1,1} = -M1*R1-M2*dr.ghxx(kf,:)*kron(hud,hud);
    for i = 2:M_.exo_det_length
        hudi = dr.ghud{i}(nstatic+1:nstatic+npred,:);
        zudi=[zeros(np,M_.exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi+dr.ghud{i-1}(kf,:);zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)];
        R2 = hessian*kron(zudi,zudi);
        dr.ghudud{i,i} = -M2*(dr.ghudud{i-1,i-1}(kf,:)+...
                              2*dr.ghxud{i-1}(kf,:)*kron(hudi,Eud) ...
                              +dr.ghxx(kf,:)*kron(hudi,hudi))-M1*R2;
        R2 = hessian*kron(zud,zudi);
        dr.ghudud{1,i} = -M2*(dr.ghxud{i-1}(kf,:)*kron(hud,Eud)+...
                              dr.ghxx(kf,:)*kron(hud,hudi))...
            -M1*R2;
        for j=2:i-1
            hudj = dr.ghud{j}(kp,:);
            zudj=[zeros(np,M_.exo_det_nbr);dr.ghud{j};gx(:,1:npred)*hudj;zeros(M_.exo_nbr+M_.exo_det_nbr,M_.exo_det_nbr)];
            R2 = hessian*kron(zudj,zudi);
            dr.ghudud{j,i} = -M2*(dr.ghudud{j-1,i-1}(kf,:)+dr.ghxud{j-1}(kf,:)* ...
                                  kron(hudi,Eud)+dr.ghxud{i-1}(kf,:)* ...
                                  kron(hudj,Eud)+dr.ghxx(kf,:)*kron(hudj,hudi))-M1*R2;
768
769
        end
        
770
    end
771
end