dynare3.cc 12.4 KB
Newer Older
1 2 3
#include <sstream>
#include <fstream>

4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include "dynare3.hh"
#include "dynare_exception.hh"
#include "planner_builder.hh"
#include "forw_subst_builder.hh"

#include "utils/cc/exception.hh"
#include "parser/cc/parser_exception.hh"
#include "parser/cc/atom_substitutions.hh"
#include "../tl/cc/tl_exception.hh"
#include "../kord/kord_exception.hh"

#ifndef DYNVERSION
# define DYNVERSION "unknown"
#endif

/**************************************************************************************/
/*       DynareNameList class                                                         */
/**************************************************************************************/
22 23
std::vector<int>
DynareNameList::selectIndices(const std::vector<const char *> &ns) const
24
{
25
  std::vector<int> res;
26
  for (auto n : ns)
27 28
    {
      int j = 0;
29
      while (j < getNum() && strcmp(getName(j), n) != 0)
30 31 32
        j++;
      if (j == getNum())
        throw DynareException(__FILE__, __LINE__,
33
                              std::string("Couldn't find name for ") + n
34 35 36 37 38 39 40 41 42 43 44
                              +" in DynareNameList::selectIndices");
      res.push_back(j);
    }
  return res;
}

/**************************************************************************************/
/*       Dynare class                                                                 */
/**************************************************************************************/

Dynare::Dynare(const char *modname, int ord, double sstol, Journal &jr)
45 46
  : journal(jr), model(nullptr), ysteady(nullptr), md(1), dnl(nullptr), denl(nullptr), dsnl(nullptr),
    fe(nullptr), fde(nullptr), ss_tol(sstol)
47
{
48 49
  std::ifstream f{modname};
  if (f.fail())
50
    throw DynareException(__FILE__, __LINE__, std::string{"Could not open model file "}+modname);
51 52 53 54 55 56

  std::ostringstream buffer;
  buffer << f.rdbuf();
  std::string contents{buffer.str()};

  try
57
    {
58
      model = new ogdyn::DynareParser(contents.c_str(), contents.length(), ord);
59
    }
60
  catch (const ogp::ParserException &pe)
61
    {
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
      // Compute line and column, given the offset in the file
      int line = 1;
      int col = 0;
      size_t i = 0;
      while (i < contents.length() && i < (size_t) pe.offset())
        {
          if (contents[i] == '\n')
            {
              line++;
              col = 0;
            }
          i++;
          col++;
        }
      throw DynareException(pe.message(), modname, line, col);
77
    }
78 79 80 81 82 83 84
  ysteady = new Vector(model->getAtoms().ny());
  dnl = new DynareNameList(*this);
  denl = new DynareExogNameList(*this);
  dsnl = new DynareStateNameList(*this, *dnl, *denl);
  fe = new ogp::FormulaEvaluator(model->getParser());
  fde = new ogp::FormulaDerEvaluator(model->getParser());
  writeModelInfo(journal);
85 86 87 88 89 90 91
}

Dynare::Dynare(const char **endo, int num_endo,
               const char **exo, int num_exo,
               const char **par, int num_par,
               const char *equations, int len, int ord,
               double sstol, Journal &jr)
92 93
  : journal(jr), model(nullptr), ysteady(nullptr), md(1), dnl(nullptr), denl(nullptr), dsnl(nullptr),
    fe(nullptr), fde(nullptr), ss_tol(sstol)
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
{
  try
    {
      model = new ogdyn::DynareSPModel(endo, num_endo, exo, num_exo, par, num_par,
                                       equations, len, ord);
    }
  catch (const ogp::ParserException &pe)
    {
      throw DynareException(pe.message(), pe.offset());
    }
  ysteady = new Vector(model->getAtoms().ny());
  dnl = new DynareNameList(*this);
  denl = new DynareExogNameList(*this);
  dsnl = new DynareStateNameList(*this, *dnl, *denl);
  fe = new ogp::FormulaEvaluator(model->getParser());
  fde = new ogp::FormulaDerEvaluator(model->getParser());
  writeModelInfo(journal);
}

Dynare::Dynare(const Dynare &dynare)
114 115 116
  : journal(dynare.journal), model(nullptr),
    ysteady(nullptr), md(dynare.md),
    dnl(nullptr), denl(nullptr), dsnl(nullptr), fe(nullptr), fde(nullptr),
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 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 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
    ss_tol(dynare.ss_tol)
{
  model = dynare.model->clone();
  ysteady = new Vector(*(dynare.ysteady));
  dnl = new DynareNameList(*this);
  denl = new DynareExogNameList(*this);
  dsnl = new DynareStateNameList(*this, *dnl, *denl);
  fe = new ogp::FormulaEvaluator(model->getParser());
  fde = new ogp::FormulaDerEvaluator(model->getParser());
}

Dynare::~Dynare()
{
  if (model)
    delete model;
  if (ysteady)
    delete ysteady;
  if (dnl)
    delete dnl;
  if (dsnl)
    delete dsnl;
  if (denl)
    delete denl;
  if (fe)
    delete fe;
  if (fde)
    delete fde;
}

void
Dynare::writeMat(mat_t *fd, const char *prefix) const
{
  char tmp[100];
  sprintf(tmp, "%s_vars", prefix);
  getAllEndoNames().writeMat(fd, tmp);
  getAllEndoNames().writeMatIndices(fd, prefix);
  sprintf(tmp, "%s_state_vars", prefix);
  getStateNames().writeMat(fd, tmp);
  sprintf(tmp, "%s_shocks", prefix);
  getExogNames().writeMat(fd, tmp);
  getExogNames().writeMatIndices(fd, prefix);
  sprintf(tmp, "%s_vcov_exo", prefix);
  model->getVcov().writeMat(fd, tmp);
  TwoDMatrix aux(1, 1);
  sprintf(tmp, "%s_nstat", prefix);
  aux.get(0, 0) = nstat();
  aux.writeMat(fd, tmp);
  sprintf(tmp, "%s_npred", prefix);
  aux.get(0, 0) = npred();
  aux.writeMat(fd, tmp);
  sprintf(tmp, "%s_nboth", prefix);
  aux.get(0, 0) = nboth();
  aux.writeMat(fd, tmp);
  sprintf(tmp, "%s_nforw", prefix);
  aux.get(0, 0) = nforw();
  aux.writeMat(fd, tmp);
}

void
Dynare::writeDump(const std::string &basename) const
{
  std::string fname(basename);
  fname += ".dump";
  std::ofstream out(fname.c_str());
  model->dump_model(out);
  out.close();
}

void
Dynare::solveDeterministicSteady(Vector &steady)
{
  JournalRecordPair pa(journal);
  pa << "Non-linear solver for deterministic steady state" << endrec;
  steady = (const Vector &) model->getInit();
  DynareVectorFunction dvf(*this);
  DynareJacobian dj(*this);
  ogu::NLSolver nls(dvf, dj, 500, ss_tol, journal);
  int iter;
  if (!nls.solve(steady, iter))
    throw DynareException(__FILE__, __LINE__,
                          "Could not obtain convergence in non-linear solver");
}

// evaluate system at given y_t=y_{t+1}=y_{t-1}, and given shocks x_t
void
202
Dynare::evaluateSystem(Vector &out, const ConstVector &yy, const Vector &xx)
203 204 205 206 207 208 209 210 211 212
{
  ConstVector yym(yy, nstat(), nys());
  ConstVector yyp(yy, nstat()+npred(), nyss());
  evaluateSystem(out, yym, yy, yyp, xx);
}

// evaluate system at given y^*_{t-1}, y_t, y^{**}_{t+1} and at
// exogenous x_t, all three vectors yym, yy, and yyp have the
// respective lengths of y^*_{t-1}, y_t, y^{**}_{t+1}
void
213 214
Dynare::evaluateSystem(Vector &out, const ConstVector &yym, const ConstVector &yy,
                       const ConstVector &yyp, const Vector &xx)
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
{
  ogdyn::DynareAtomValues dav(model->getAtoms(), model->getParams(), yym, yy, yyp, xx);
  DynareEvalLoader del(model->getAtoms(), out);
  fe->eval(dav, del);
}

void
Dynare::calcDerivatives(const Vector &yy, const Vector &xx)
{
  ConstVector yym(yy, nstat(), nys());
  ConstVector yyp(yy, nstat()+npred(), nyss());
  ogdyn::DynareAtomValues dav(model->getAtoms(), model->getParams(), yym, yy, yyp, xx);
  DynareDerEvalLoader ddel(model->getAtoms(), md, model->getOrder());
  for (int iord = 1; iord <= model->getOrder(); iord++)
    fde->eval(dav, ddel, iord);
}

void
Dynare::calcDerivativesAtSteady()
{
  Vector xx(nexog());
  xx.zeros();
  calcDerivatives(*ysteady, xx);
}

void
Dynare::writeModelInfo(Journal &jr) const
{
  // write info on variables
  {
    JournalRecordPair rp(journal);
    rp << "Information on variables" << endrec;
    JournalRecord rec1(journal);
    rec1 << "Number of endogenous:            " << ny() << endrec;
    JournalRecord rec2(journal);
    rec2 << "Number of exogenous:             " << nexog() << endrec;
    JournalRecord rec3(journal);
    rec3 << "Number of static:                " << nstat() << endrec;
    JournalRecord rec4(journal);
    rec4 << "Number of predetermined:         " << npred()+nboth() << endrec;
    JournalRecord rec5(journal);
    rec5 << "Number of forward looking:       " << nforw()+nboth() << endrec;
    JournalRecord rec6(journal);
    rec6 << "Number of both:                  " << nboth() << endrec;
  }

  // write info on planner variables
  const ogdyn::PlannerInfo *pinfo = model->get_planner_info();
  if (pinfo)
    {
      JournalRecordPair rp(journal);
      rp << "Information on planner variables" << endrec;
      JournalRecord rec1(journal);
      rec1 << "Number of Lagrange multipliers:  " << pinfo->num_lagrange_mults << endrec;
      JournalRecord rec2(journal);
      rec2 << "Number of auxiliary variables:   " << pinfo->num_aux_variables << endrec;
      JournalRecord rec3(journal);
      rec3 << "Number of new terms in the tree: " << pinfo->num_new_terms << endrec;
    }

  // write info on forward substitutions
  const ogdyn::ForwSubstInfo *finfo = model->get_forw_subst_info();
  if (finfo)
    {
      JournalRecordPair rp(journal);
      rp << "Information on forward substitutions" << endrec;
      JournalRecord rec1(journal);
      rec1 << "Number of affected equations:    " << finfo->num_affected_equations << endrec;
      JournalRecord rec2(journal);
      rec2 << "Number of substituted terms:     " << finfo->num_subst_terms << endrec;
      JournalRecord rec3(journal);
      rec3 << "Number of auxiliary variables:   " << finfo->num_aux_variables << endrec;
      JournalRecord rec4(journal);
      rec4 << "Number of new terms in the tree: " << finfo->num_new_terms << endrec;
    }

  // write info on substitutions
  const ogp::SubstInfo *sinfo = model->get_subst_info();
  if (sinfo)
    {
      JournalRecordPair rp(journal);
      rp << "Information on substitutions" << endrec;
      JournalRecord rec1(journal);
      rec1 << "Number of substitutions:         " << sinfo->num_substs << endrec;
    }
}

DynareNameList::DynareNameList(const Dynare &dynare)
{
  for (int i = 0; i < dynare.ny(); i++)
    {
      int j = dynare.model->getAtoms().y2outer_endo()[i];
      const char *name = dynare.model->getAtoms().get_endovars()[j];
      names.push_back(name);
    }
}

DynareStateNameList::DynareStateNameList(const Dynare &dynare, const DynareNameList &dnl,
                                         const DynareExogNameList &denl)
{
  for (int i = 0; i < dynare.nys(); i++)
    names.push_back(dnl.getName(i+dynare.nstat()));
  for (int i = 0; i < dynare.nexog(); i++)
    names.push_back(denl.getName(i));
}

DynareExogNameList::DynareExogNameList(const Dynare &dynare)
{
  for (int i = 0; i < dynare.nexog(); i++)
    {
      int j = dynare.model->getAtoms().y2outer_exo()[i];
      const char *name = dynare.model->getAtoms().get_exovars()[j];
      names.push_back(name);
    }
}

DynareEvalLoader::DynareEvalLoader(const ogp::FineAtoms &a, Vector &out)
  : Vector(out)
{
  if (a.ny() != out.length())
    throw DynareException(__FILE__, __LINE__, "Wrong length of out vector in DynareEvalLoader constructor");
}

/** This clears the container of model derivatives and initializes it
 * inserting empty sparse tensors up to the given order. */
DynareDerEvalLoader::DynareDerEvalLoader(const ogp::FineAtoms &a,
                                         TensorContainer<FSSparseTensor> &mod_ders,
                                         int order)
  : atoms(a), md(mod_ders)
{
  md.clear();
  for (int iord = 1; iord <= order; iord++)
    {
348
      auto *t = new FSSparseTensor(iord, atoms.ny()+atoms.nys()+atoms.nyss()+atoms.nexo(), atoms.ny());
349 350 351 352 353 354 355
      md.insert(t);
    }
}

void
DynareDerEvalLoader::load(int i, int iord, const int *vars, double res)
{
356
  FSSparseTensor *t = md.get(Symmetry{iord});
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
  IntSequence s(iord, 0);
  for (int j = 0; j < iord; j++)
    s[j] = atoms.get_pos_of_all(vars[j]);
  t->insert(s, i, res);
}

DynareJacobian::DynareJacobian(Dynare &dyn)
  : Jacobian(dyn.ny()), d(dyn)
{
  zeros();
}

void
DynareJacobian::eval(const Vector &yy)
{
  ogdyn::DynareSteadyAtomValues
    dav(d.getModel().getAtoms(), d.getModel().getParams(), yy);
  zeros();
  d.fde->eval(dav, *this, 1);
}

void
DynareJacobian::load(int i, int iord, const int *vars, double res)
{
  if (iord != 1)
    throw DynareException(__FILE__, __LINE__,
                          "Derivative order different from order=1 in DynareJacobian::load");

  int t = vars[0];
  int j = d.getModel().getAtoms().get_pos_of_all(t);
  if (j < d.nyss())
    get(i, j+d.nstat()+d.npred()) += res;
  else if (j < d.nyss()+d.ny())
    get(i, j-d.nyss()) += res;
  else if (j < d.nyss()+d.ny()+d.nys())
    get(i, j-d.nyss()-d.ny()+d.nstat()) += res;
}

void
DynareVectorFunction::eval(const ConstVector &in, Vector &out)
{
  check_for_eval(in, out);
  Vector xx(d.nexog());
  xx.zeros();
  d.evaluateSystem(out, in, xx);
}