Debian Codegraph @

mex/sources/k_order_perturbation/k_order_perturbation.cc

raw symbols SCIP
1 /*
2 * Copyright © 2008-2026 Dynare Team
3 *
4 * This file is part of Dynare.
5 *
6 * Dynare is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * Dynare is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with Dynare. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20 /* Defines the entry point for the k-order perturbation application DLL.
21
22 See matlab/mex/k_order_perturbation.m for a description of inputs and
23 outputs.
24 */
25
26 #include "dynamic_dll.hh"
27 #include "dynamic_m.hh"
28 #include "k_ord_dynare.hh"
29
30 #include "SylvException.hh"
31 #include "approximation.hh"
32 #include "dynare_exception.hh"
33 #include "exception.hh"
34 #include "kord_exception.hh"
35 #include "tl_exception.hh"
36
37 #include <algorithm>
38 #include <cassert>
39
40 #include "dynmex.h"
41
42 /* Vector for storing field names like “g_0”, “g_1”, …
43 A static structure is needed since MATLAB apparently does not create its own
44 copy of the strings (contrary to what is said at:
45 https://fr.mathworks.com/matlabcentral/answers/315937-mxcreatestructarray-and-mxcreatestructmatrix-field-name-memory-management
46 ) */
47 std::vector<std::string> g_fieldnames;
48
49 /* Convert MATLAB Dynare endo and exo names cell array to a vector<string> array of
50 string pointers. */
51 std::vector<std::string>
52 DynareMxArrayToString(const mxArray* mxFldp)
53 {
54 assert(mxIsCell(mxFldp));
55 std::vector<std::string> r;
56 for (size_t i = 0; i < mxGetNumberOfElements(mxFldp); i++)
57 {
58 const mxArray* cell_mx = mxGetCell(mxFldp, i);
59 if (!(cell_mx && mxIsChar(cell_mx)))
60 mexErrMsgTxt("Cell is not a character array");
61 r.emplace_back(mxArrayToString(cell_mx));
62 }
63
64 return r;
65 }
66
67 void
68 copy_derivatives(mxArray* destin, const Symmetry& sym, const FGSContainer& derivs,
69 const char* fieldname)
70 {
71 const FGSTensor& x = derivs.get(sym);
72 auto x_unfolded = x.unfold();
73 int n = x_unfolded->nrows();
74 int m = x_unfolded->ncols();
75 mxArray* tmp = mxCreateDoubleMatrix(n, m, mxREAL);
76 std::ranges::copy_n(x_unfolded->getData().base(), n * m, mxGetDoubles(tmp));
77 mxSetField(destin, 0, fieldname, tmp);
78 }
79
80 extern "C"
81 {
82
83 void
84 mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
85 {
86 if (nrhs != 3 || nlhs < 1 || nlhs > 2)
87 mexErrMsgTxt("Must have exactly 3 input parameters and takes 1 or 2 output parameters.");
88
89 // Give explicit names to input arguments
90 const mxArray* dr_mx = prhs[0];
91 const mxArray* M_mx = prhs[1];
92 const mxArray* options_mx = prhs[2];
93
94 auto get_int_field = [](const mxArray* struct_mx, const std::string& fieldname) {
95 mxArray* field_mx = mxGetField(struct_mx, 0, fieldname.c_str());
96 if (!(field_mx && mxIsScalar(field_mx) && mxIsNumeric(field_mx)))
97 mexErrMsgTxt(("Field `" + fieldname + "' should be a numeric scalar").c_str());
98 return static_cast<int>(mxGetScalar(field_mx));
99 };
100
101 // Extract various fields from options_
102 const int kOrder = get_int_field(options_mx, "order");
103 if (kOrder < 1)
104 mexErrMsgTxt("options_.order must be at least 1");
105
106 const mxArray* use_dll_mx = mxGetField(options_mx, 0, "use_dll");
107 if (!(use_dll_mx && mxIsLogicalScalar(use_dll_mx)))
108 mexErrMsgTxt("options_.use_dll should be a logical scalar");
109 bool use_dll = static_cast<bool>(mxGetScalar(use_dll_mx));
110
111 double qz_criterium = 1 + 1e-6;
112 const mxArray* qz_criterium_mx = mxGetField(options_mx, 0, "qz_criterium");
113 if (qz_criterium_mx && mxIsScalar(qz_criterium_mx) && mxIsNumeric(qz_criterium_mx))
114 qz_criterium = mxGetScalar(qz_criterium_mx);
115
116 const mxArray* threads_mx = mxGetField(options_mx, 0, "threads");
117 if (!threads_mx)
118 mexErrMsgTxt("Can't find field options_.threads");
119 const mxArray* num_threads_mx = mxGetField(threads_mx, 0, "k_order_perturbation");
120 if (!(num_threads_mx && mxIsScalar(num_threads_mx) && mxIsNumeric(num_threads_mx)))
121 mexErrMsgTxt("options_.threads.k_order_perturbation be a numeric scalar");
122 int num_threads = static_cast<int>(mxGetScalar(num_threads_mx));
123
124 const mxArray* debug_mx = mxGetField(options_mx, 0, "debug");
125 if (!(debug_mx && mxIsLogicalScalar(debug_mx)))
126 mexErrMsgTxt("options_.debug should be a logical scalar");
127 bool debug = static_cast<bool>(mxGetScalar(debug_mx));
128
129 const mxArray* pruning_mx = mxGetField(options_mx, 0, "pruning");
130 if (!(pruning_mx && mxIsLogicalScalar(pruning_mx)))
131 mexErrMsgTxt("options_.pruning should be a logical scalar");
132 bool pruning = static_cast<bool>(mxGetScalar(pruning_mx));
133
134 const mxArray* verbosity_mx = mxGetField(options_mx, 0, "verbosity");
135 if (!(verbosity_mx && mxIsScalar(verbosity_mx) && mxIsNumeric(verbosity_mx)))
136 mexErrMsgTxt("options_.verbosity should be a numeric scalar");
137 int verbosity {static_cast<int>(mxGetScalar(verbosity_mx))};
138
139 // Extract various fields from M_
140 const mxArray* fname_mx = mxGetField(M_mx, 0, "fname");
141 if (!(fname_mx && mxIsChar(fname_mx) && mxGetM(fname_mx) == 1))
142 mexErrMsgTxt("M_.fname should be a character string");
143 std::string fname {mxArrayToString(fname_mx)};
144
145 const mxArray* params_mx = mxGetField(M_mx, 0, "params");
146 if (!(params_mx && mxIsDouble(params_mx) && !mxIsComplex(params_mx) && !mxIsSparse(params_mx)))
147 mexErrMsgTxt("M_.params should be a real dense array");
148 Vector modParams {ConstVector {params_mx}};
149 if (!modParams.isFinite())
150 mexErrMsgTxt("M_.params contains NaN or Inf");
151
152 const mxArray* sigma_e_mx = mxGetField(M_mx, 0, "Sigma_e");
153 if (!(sigma_e_mx && mxIsDouble(sigma_e_mx) && !mxIsComplex(sigma_e_mx)
154 && !mxIsSparse(sigma_e_mx) && mxGetM(sigma_e_mx) == mxGetN(sigma_e_mx)))
155 mexErrMsgTxt("M_.Sigma_e should be a real dense square matrix");
156 TwoDMatrix vCov {ConstTwoDMatrix {sigma_e_mx}};
157 if (!vCov.isFinite())
158 mexErrMsgTxt("M_.Sigma_e contains NaN or Inf");
159
160 const int nStat = get_int_field(M_mx, "nstatic");
161 const int nPred = get_int_field(M_mx, "npred");
162 const int nBoth = get_int_field(M_mx, "nboth");
163 const int nForw = get_int_field(M_mx, "nfwrd");
164
165 const int nExog = get_int_field(M_mx, "exo_nbr");
166 const int nEndo = get_int_field(M_mx, "endo_nbr");
167 const int nPar = get_int_field(M_mx, "param_nbr");
168
169 const mxArray* endo_names_mx = mxGetField(M_mx, 0, "endo_names");
170 if (!(endo_names_mx && mxIsCell(endo_names_mx)
171 && mxGetNumberOfElements(endo_names_mx) == static_cast<size_t>(nEndo)))
172 mexErrMsgTxt("M_.endo_names should be a cell array of M_.endo_nbr elements");
173 std::vector<std::string> endoNames = DynareMxArrayToString(endo_names_mx);
174
175 const mxArray* exo_names_mx = mxGetField(M_mx, 0, "exo_names");
176 if (!(exo_names_mx && mxIsCell(exo_names_mx)
177 && mxGetNumberOfElements(exo_names_mx) == static_cast<size_t>(nExog)))
178 mexErrMsgTxt("M_.exo_names should be a cell array of M_.exo_nbr elements");
179 std::vector<std::string> exoNames = DynareMxArrayToString(exo_names_mx);
180
181 const mxArray* dynamic_tmp_nbr_mx = mxGetField(M_mx, 0, "dynamic_tmp_nbr");
182 if (!(dynamic_tmp_nbr_mx && mxIsDouble(dynamic_tmp_nbr_mx) && !mxIsComplex(dynamic_tmp_nbr_mx)
183 && !mxIsSparse(dynamic_tmp_nbr_mx)
184 && mxGetNumberOfElements(dynamic_tmp_nbr_mx) >= static_cast<size_t>(kOrder + 1)))
185 mexErrMsgTxt("M_.dynamic_tmp_nbr should be a real dense array with strictly more elements "
186 "than the order of derivation");
187 int ntt = std::accumulate(mxGetDoubles(dynamic_tmp_nbr_mx),
188 mxGetDoubles(dynamic_tmp_nbr_mx) + kOrder + 1, 0);
189
190 // Extract various fields from dr
191 const mxArray* ys_mx = mxGetField(dr_mx, 0, "ys"); // and not in order of dr.order_var
192 if (!(ys_mx && mxIsDouble(ys_mx) && !mxIsComplex(ys_mx) && !mxIsSparse(ys_mx)))
193 mexErrMsgTxt("dr.ys should be a real dense array");
194 Vector ySteady {ConstVector {ys_mx}};
195 if (!ySteady.isFinite())
196 mexErrMsgTxt("dr.ys contains NaN or Inf");
197
198 const mxArray* order_var_mx = mxGetField(dr_mx, 0, "order_var");
199 if (!(order_var_mx && mxIsDouble(order_var_mx) && !mxIsComplex(order_var_mx)
200 && !mxIsSparse(order_var_mx)
201 && mxGetNumberOfElements(order_var_mx) == static_cast<size_t>(nEndo)))
202 mexErrMsgTxt("dr.order_var should be a real dense array of M_.endo_nbr elements");
203 std::vector<int> dr_order(nEndo);
204 std::ranges::transform(mxGetDoubles(order_var_mx), mxGetDoubles(order_var_mx) + nEndo,
205 dr_order.begin(), [](double x) { return static_cast<int>(x) - 1; });
206
207 // Retrieve sparse indices for dynamic model
208
209 const mxArray* dynamic_g1_sparse_rowval_mx = mxGetField(M_mx, 0, "dynamic_g1_sparse_rowval");
210 if (!(dynamic_g1_sparse_rowval_mx && mxIsInt32(dynamic_g1_sparse_rowval_mx)))
211 mexErrMsgTxt("M_.dynamic_g1_sparse_rowval should be an int32 array");
212
213 const mxArray* dynamic_g1_sparse_colval_mx = mxGetField(M_mx, 0, "dynamic_g1_sparse_colval");
214 if (!(dynamic_g1_sparse_colval_mx && mxIsInt32(dynamic_g1_sparse_colval_mx)))
215 mexErrMsgTxt("M_.dynamic_g1_sparse_colval should be an int32 array");
216
217 const mxArray* dynamic_g1_sparse_colptr_mx = mxGetField(M_mx, 0, "dynamic_g1_sparse_colptr");
218 if (!(dynamic_g1_sparse_colptr_mx && mxIsInt32(dynamic_g1_sparse_colptr_mx)))
219 mexErrMsgTxt("M_.dynamic_g1_sparse_colptr should be an int32 array");
220
221 std::vector<const mxArray*> dynamic_gN_sparse_indices;
222 for (int o {2}; o <= kOrder; o++)
223 {
224 using namespace std::string_literals;
225 auto fieldname {"dynamic_g"s + std::to_string(o) + "_sparse_indices"};
226 const mxArray* indices = mxGetField(M_mx, 0, fieldname.c_str());
227 if (!(indices && mxIsInt32(indices)))
228 mexErrMsgTxt(("M_."s + fieldname + " should be an int32 array").c_str());
229 dynamic_gN_sparse_indices.push_back(indices);
230 }
231
232 const int nSteps
233 = 0; // Dynare++ solving steps, for time being default to 0 = deterministic steady state
234
235 try
236 {
237 // Journal is not written on-disk, unless options_.debug = true (see #1735)
238 Journal journal;
239 if (debug)
240 journal = Journal {fname + ".jnl"};
241
242 std::unique_ptr<DynamicModelAC> dynamicModelFile;
243 if (use_dll)
244 dynamicModelFile = std::make_unique<DynamicModelDLL>(
245 fname, kOrder, dynamic_g1_sparse_rowval_mx, dynamic_g1_sparse_colval_mx,
246 dynamic_g1_sparse_colptr_mx, dynamic_gN_sparse_indices, ntt);
247 else
248 dynamicModelFile = std::make_unique<DynamicModelMFile>(
249 fname, kOrder, dynamic_g1_sparse_rowval_mx, dynamic_g1_sparse_colval_mx,
250 dynamic_g1_sparse_colptr_mx, dynamic_gN_sparse_indices);
251
252 // intiate tensor library
253 TLStatic::init(kOrder, nStat + 2 * nPred + 3 * nBoth + 2 * nForw + nExog);
254
255 // Initialize thread pool
256 thread_pool::initialize(num_threads);
257
258 // make KordpDynare object
259 KordpDynare dynare(endoNames, exoNames, nExog, nPar, ySteady, vCov, modParams, nStat, nPred,
260 nForw, nBoth, nSteps, kOrder, journal, std::move(dynamicModelFile),
261 dr_order);
262
263 // construct main K-order approximation class
264 Approximation app(dynare, journal, nSteps, false, pruning, qz_criterium);
265 // run stochastic steady
266 app.walkStochSteady();
267
268 const FoldDecisionRule& fdr = app.getFoldDecisionRule();
269
270 // Add possibly missing field names
271 for (int i = static_cast<int>(g_fieldnames.size()); i <= kOrder; i++)
272 g_fieldnames.emplace_back("g_" + std::to_string(i));
273 // Create structure for storing derivatives in Dynare++ format
274 std::vector<const char*> g_fieldnames_c(kOrder + 1);
275 for (int i = 0; i <= kOrder; i++)
276 g_fieldnames_c[i] = g_fieldnames[i].c_str();
277
278 if (pruning)
279 {
280 auto g_fieldnames_pruning_c = g_fieldnames_c;
281 g_fieldnames_pruning_c.push_back("pruning");
282 plhs[0] = mxCreateStructMatrix(1, 1, kOrder + 2, g_fieldnames_pruning_c.data());
283 }
284 else
285 plhs[0] = mxCreateStructMatrix(1, 1, kOrder + 1, g_fieldnames_c.data());
286
287 // Fill that structure
288 for (int i = 0; i <= kOrder; i++)
289 {
290 const FFSTensor& t = fdr.get(Symmetry {i});
291 mxArray* tmp = mxCreateDoubleMatrix(t.nrows(), t.ncols(), mxREAL);
292 const ConstVector& vec = t.getData();
293 assert(vec.skip() == 1);
294 std::ranges::copy_n(vec.base(), vec.length(), mxGetDoubles(tmp));
295 mxSetField(plhs[0], 0, g_fieldnames_c[i], tmp);
296 }
297
298 // Filling the output elements for pruning
299 if (pruning)
300 {
301 const UnfoldDecisionRule& udr_pruning = app.getUnfoldDecisionRulePruning();
302
303 mxArray* dr_pruning = mxCreateStructMatrix(1, 1, kOrder + 1, g_fieldnames_c.data());
304 mxSetField(plhs[0], 0, "pruning", dr_pruning);
305
306 // Fill that structure
307 for (int i = 0; i <= kOrder; i++)
308 {
309 const UFSTensor& t = udr_pruning.get(Symmetry {i});
310 mxArray* tmp = mxCreateDoubleMatrix(t.nrows(), t.ncols(), mxREAL);
311 const ConstVector& vec = t.getData();
312 assert(vec.skip() == 1);
313 std::ranges::copy_n(vec.base(), vec.length(), mxGetDoubles(tmp));
314 mxSetField(dr_pruning, 0, g_fieldnames_c[i], tmp);
315 }
316 }
317
318 if (nlhs > 1)
319 {
320 /* Return as 3rd argument a struct containing derivatives in Dynare
321 format (unfolded matrices, without Taylor coefficient) up to 3rd
322 order */
323 const FGSContainer& derivs = app.get_rule_ders();
324
325 size_t nfields = (kOrder == 1 ? 2 : (kOrder == 2 ? 6 : 12));
326 const char* c_fieldnames[] = {"gy", "gu", "gyy", "gyu", "guu", "gss",
327 "gyyy", "gyyu", "gyuu", "guuu", "gyss", "guss"};
328 plhs[1] = mxCreateStructMatrix(1, 1, nfields, c_fieldnames);
329
330 copy_derivatives(plhs[1], Symmetry {1, 0, 0, 0}, derivs, "gy");
331 copy_derivatives(plhs[1], Symmetry {0, 1, 0, 0}, derivs, "gu");
332 if (kOrder >= 2)
333 {
334 copy_derivatives(plhs[1], Symmetry {2, 0, 0, 0}, derivs, "gyy");
335 copy_derivatives(plhs[1], Symmetry {0, 2, 0, 0}, derivs, "guu");
336 copy_derivatives(plhs[1], Symmetry {1, 1, 0, 0}, derivs, "gyu");
337 copy_derivatives(plhs[1], Symmetry {0, 0, 0, 2}, derivs, "gss");
338 }
339 if (kOrder >= 3)
340 {
341 copy_derivatives(plhs[1], Symmetry {3, 0, 0, 0}, derivs, "gyyy");
342 copy_derivatives(plhs[1], Symmetry {0, 3, 0, 0}, derivs, "guuu");
343 copy_derivatives(plhs[1], Symmetry {2, 1, 0, 0}, derivs, "gyyu");
344 copy_derivatives(plhs[1], Symmetry {1, 2, 0, 0}, derivs, "gyuu");
345 copy_derivatives(plhs[1], Symmetry {1, 0, 0, 2}, derivs, "gyss");
346 copy_derivatives(plhs[1], Symmetry {0, 1, 0, 2}, derivs, "guss");
347 }
348 }
349 }
350 catch (const KordException& e)
351 {
352 if (verbosity > 0)
353 e.print();
354 mexErrMsgTxt(
355 ("dynare:k_order_perturbation: Caught Kord exception: " + e.get_message()).c_str());
356 }
357 catch (const TLException& e)
358 {
359 if (verbosity > 0)
360 e.print();
361 mexErrMsgTxt("dynare:k_order_perturbation: Caught TL exception");
362 }
363 catch (SylvException& e)
364 {
365 if (verbosity > 0)
366 e.printMessage();
367 mexErrMsgTxt("dynare:k_order_perturbation: Caught Sylv exception");
368 }
369 catch (const DynareException& e)
370 {
371 mexErrMsgTxt(
372 ("dynare:k_order_perturbation: Caught KordDynare exception: " + e.message()).c_str());
373 }
374 catch (const ogu::Exception& e)
375 {
376 mexErrMsgTxt(
377 ("dynare:k_order_perturbation: Caught general exception: " + e.message()).c_str());
378 }
379 } // end of mexFunction()
380 } // end of extern C