File: dynamic_atoms.cc

package info (click to toggle)
dynare 5.3-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 77,852 kB
  • sloc: cpp: 94,481; ansic: 28,551; pascal: 14,532; sh: 5,453; objc: 4,671; yacc: 4,442; makefile: 2,923; lex: 1,612; python: 677; ruby: 469; lisp: 156; xml: 22
file content (617 lines) | stat: -rw-r--r-- 15,662 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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
202
203
204
205
206
207
208
209
210
211
212
213
214
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
348
349
350
351
352
353
354
355
356
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
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
452
453
454
455
456
457
458
459
460
461
462
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
495
496
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
557
558
559
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
/*
 * Copyright © 2005 Ondra Kamenik
 * Copyright © 2019 Dynare Team
 *
 * 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 <https://www.gnu.org/licenses/>.
 */

#include "utils/cc/exception.hh"
#include "dynamic_atoms.hh"

using namespace ogp;

void
NameStorage::insert(string name)
{
  if (!query(name))
    {
      name_store.push_back(name);
      name_set.insert(std::move(name));
    }
}

void
NameStorage::print() const
{
  for (auto i : name_store)
    std::cout << i << '\n';
}

void
Constants::import_constants(const Constants &c, OperationTree &otree, Tintintmap &tmap)
{
  for (auto it : c.cmap)
    {
      int told = it.first;
      int tnew = otree.add_nulary();
      tmap.emplace(told, tnew);
      add_constant(tnew, it.second);
    }
}

void
Constants::setValues(EvalTree &et) const
{
  for (const auto &it : cmap)
    et.set_nulary(it.first, it.second);
}

void
Constants::add_constant(int t, double val)
{
  cmap.emplace(t, val);
  cinvmap.emplace(val, t);
}

bool
Constants::is_constant(int t) const
{
  if (t < OperationTree::num_constants)
    return true;
  auto it = cmap.find(t);
  return (it != cmap.end());
}

double
Constants::get_constant_value(int t) const
{
  auto it = cmap.find(t);
  if (it != cmap.end())
    return it->second;
  else
    throw ogu::Exception(__FILE__, __LINE__,
                         "Tree index is not constant in Constants::get_constant_value");
}

int
Constants::check(const string &str) const
{
  double d = std::stod(str);
  auto it = cinvmap.find(d);
  if (it != cinvmap.end())
    return it->second;
  else
    return -1;
}

void
Constants::print() const
{
  for (const auto &it : cmap)
    std::cout << "$" << it.first << ":  " << it.second << "\n";
}

int
DynamicAtoms::check(const string &name) const
{
  if (is_string_constant(name))
    return Constants::check(name);

  return check_variable(name);
}

int
DynamicAtoms::check_variable(const string &name) const
{
  string str;
  int ll;
  parse_variable(name, str, ll);
  auto it = vars.find(str);

  if (it != vars.end())
    {
      const Tlagmap &lmap = it->second;
      auto itt = lmap.find(ll);
      if (itt != lmap.end())
        return itt->second;
    }
  return -1;
}

void
DynamicAtoms::assign(const string &name, int t)
{
  if (is_string_constant(name))
    assign_constant(name, t);
  else
    assign_variable(name, t);
}

void
DynamicAtoms::assign_constant(const string &name, int t)
{
  double val = std::stod(name);
  add_constant(t, val);
}

// parse the name and then call assing_variable(varname, ll, t)

void
DynamicAtoms::assign_variable(const string &name, int t)
{
  int ll;
  string str;
  parse_variable(name, str, ll);
  // here str is just name without lead/lag
  varnames.insert(str);

  assign_variable(str, ll, t);
}

void
DynamicAtoms::assign_variable(const string &varname, int ll, int t)
{
  if (indices.end() != indices.find(t))
    throw ogu::Exception(__FILE__, __LINE__,
                         "Attempt to assign already allocated tree index");

  auto it = vars.find(varname);
  if (it != vars.end())
    {
      Tlagmap &lmap = it->second;
      if (lmap.end() != lmap.find(ll))
        throw ogu::Exception(__FILE__, __LINE__,
                             "Attempt to assign already allocated variable");
      lmap.emplace(ll, t);
    }
  else
    {
      Tlagmap lmap;
      lmap.emplace(ll, t);
      vars.emplace(varname, lmap);
    }
  indices.emplace(t, varname);

  nv++;
  minlag = std::min(ll, minlag);
  maxlead = std::max(ll, maxlead);
}

void
DynamicAtoms::unassign_variable(const string &varname, int ll, int t)
{
  auto it = vars.find(varname);
  if (it != vars.end())
    {
      Tlagmap &lmap = it->second;
      auto itt = lmap.find(ll);
      if (itt != lmap.end())
        {
          if (itt->second == t)
            {
              // erase it from the lagmap; if it becomes empty,
              // erase the lagmap from varmap
              lmap.erase(itt);
              if (lmap.size() == 0)
                vars.erase(it);
              // erase it from the indices
              auto ittt = indices.find(t);
              if (ittt != indices.end())
                indices.erase(ittt);

              nv--;
              if (ll == minlag || ll == maxlead)
                update_minmaxll();
            }
          else
            throw ogu::Exception(__FILE__, __LINE__,
                                 "Tree index inconsistent in DynamicAtoms::unassign_variable");
        }
      else
        throw ogu::Exception(__FILE__, __LINE__,
                             "Lead/lag of the variable not found in DynamicAtoms::unassign_variable");
    }
  else
    throw ogu::Exception(__FILE__, __LINE__,
                         "Variable not found in DynamicAtoms::unassign_variable");
}

void
DynamicAtoms::update_minmaxll()
{
  minlag = std::numeric_limits<int>::max();
  maxlead = std::numeric_limits<int>::min();
  for (const auto &it : vars)
    {
      const Tlagmap &lmap = it.second;
      for (auto itt : lmap)
        {
          int ll = itt.first;
          minlag = std::min(ll, minlag);
          maxlead = std::max(ll, maxlead);
        }
    }
}

vector<int>
DynamicAtoms::variables() const
{
  vector<int> res;
  for (const auto &var : vars)
    {
      const Tlagmap &lmap = var.second;
      for (auto itt : lmap)
        res.push_back(itt.second);
    }
  return res;
}

void
DynamicAtoms::varspan(int t, int &mlead, int &mlag) const
{
  auto it = indices.find(t);
  if (indices.end() == it)
    {
      mlead = std::numeric_limits<int>::min();
      mlag = std::numeric_limits<int>::max();
      return;
    }
  varspan(it->second, mlead, mlag);
}

void
DynamicAtoms::varspan(const string &name, int &mlead, int &mlag) const
{
  auto it = vars.find(name);
  if (vars.end() == it)
    {
      mlead = std::numeric_limits<int>::min();
      mlag = std::numeric_limits<int>::max();
      return;
    }
  const Tlagmap &lmap = it->second;
  auto beg = lmap.begin();
  auto end = lmap.rbegin();
  mlag = beg->first;
  mlead = end->first;
}

void
DynamicAtoms::varspan(const vector<string> &names, int &mlead, int &mlag) const
{
  mlead = std::numeric_limits<int>::min();
  mlag = std::numeric_limits<int>::max();
  for (const auto &name : names)
    {
      int lag, lead;
      varspan(name, lead, lag);
      mlead = std::max(lead, mlead);
      mlag = std::min(lag, mlag);
    }
}

bool
DynamicAtoms::is_named_atom(int t) const
{
  return indices.end() != indices.find(t);
}

int
DynamicAtoms::index(const string &name, int ll) const
{
  auto it = vars.find(name);
  if (vars.end() != it)
    {
      const Tlagmap &lmap = it->second;
      auto itt = lmap.find(ll);
      if (lmap.end() != itt)
        return itt->second;
    }
  return -1;
}

bool
DynamicAtoms::is_referenced(const string &name) const
{
  return vars.find(name) != vars.end();
}

const DynamicAtoms::Tlagmap &
DynamicAtoms::lagmap(const string &name) const
{
  auto it = vars.find(name);
  if (vars.end() == it)
    throw ogu::Exception(__FILE__, __LINE__,
                         std::string("Couldn't find the name ")
                         + name + " in DynamicAtoms::lagmap");
  return it->second;
}

const string &
DynamicAtoms::name(int t) const
{
  auto it = indices.find(t);
  if (indices.end() == it)
    throw ogu::Exception(__FILE__, __LINE__,
                         "Couldn't find tree index in DynamicAtoms::name");
  return it->second;
}

int
DynamicAtoms::lead(int t) const
{
  const string &nam = name(t);
  const Tlagmap &lmap = lagmap(nam);
  auto it = lmap.begin();
  while (it != lmap.end() && it->second != t)
    ++it;
  if (lmap.end() == it)
    throw ogu::Exception(__FILE__, __LINE__,
                         "Couldn't find the three index in DynamicAtoms::lead");
  return it->first;
}

void
DynamicAtoms::print() const
{
  std::cout << "names:\n";
  varnames.print();
  std::cout << "constants:\n";
  Constants::print();
  std::cout << "variables:\n";
  for (const auto &var : vars)
    {
      const Tlagmap &lmap = var.second;
      for (auto itt : lmap)
        std::cout << "$" << itt.second << ": " << var.first << "(" << itt.first << ")\n";
    }
  std::cout << "indices:\n";
  for (auto indice : indices)
    std::cout << "t=" << indice.first << u8" ⇒ " << indice.second << "\n";
}

/** Note that the str has been parsed by the lexicographic
 * analyzer. It can be either a variable or a double. So it is easy to
 * recognize it by the first character. */
bool
DynamicAtoms::is_string_constant(const string &str)
{
  return str[0] == '.' || str[0] == '-' || (str[0] >= '0' && str[0] <= '9');
}

VarOrdering::VarOrdering(const VarOrdering &vo, const vector<string> &vnames,
                         const DynamicAtoms &a)
  : n_stat(vo.n_stat), n_pred(vo.n_pred), n_both(vo.n_both), n_forw(vo.n_forw),
    der_atoms(vo.der_atoms), positions(vo.positions),
    outer2y(vo.outer2y), y2outer(vo.y2outer), varnames(vnames), atoms(a)
{
}

bool
VarOrdering::check(int t) const
{
  return positions.find(t) != positions.end();
}

int
VarOrdering::get_pos_of(int t) const
{
  auto it = positions.find(t);
  if (it != positions.end())
    return it->second;
  else
    throw ogu::Exception(__FILE__, __LINE__,
                         "Couldn't find the tree index in VarOrdering::get_pos_of");
}

void
VarOrdering::do_general(ord_type ordering)
{
  // auxiliary vectors for setting der_atoms and map
  vector<int> pred_minus;
  vector<int> both_minus;
  vector<int> stat;
  vector<int> pred_pad;
  vector<int> both_pad;
  vector<int> forw_pad;
  vector<int> both_plus;
  vector<int> forw_plus;

  // auxiliary vectors for setting y2outer and outer2y
  vector<int> y2o_stat;
  vector<int> y2o_pred;
  vector<int> y2o_both;
  vector<int> y2o_forw;

  for (unsigned int i = 0; i < varnames.size(); i++)
    {
      const string &ss = varnames[i];
      int lead;
      int lag;
      atoms.varspan(ss, lead, lag);
      if (lag == 0 && lead == 0)
        {
          stat.push_back(atoms.index(ss, 0));
          y2o_stat.push_back(i);
        }
      else if (lag == -1 && lead < 1)
        {
          pred_minus.push_back(atoms.index(ss, -1));
          pred_pad.push_back(atoms.index(ss, 0));
          y2o_pred.push_back(i);
        }
      else if (lag > -1 && lead == 1)
        {
          forw_pad.push_back(atoms.index(ss, 0));
          forw_plus.push_back(atoms.index(ss, 1));
          y2o_forw.push_back(i);
        }
      else if (lag == -1 && lead == 1)
        {
          both_minus.push_back(atoms.index(ss, -1));
          both_pad.push_back(atoms.index(ss, 0));
          both_plus.push_back(atoms.index(ss, 1));
          y2o_both.push_back(i);
        }
      else
        throw ogu::Exception(__FILE__, __LINE__,
                             "A wrong lag/lead of a variable in VarOrdering::do_pbspbfbf");
    }

  // here we fill ords according to ordering
  vector<int> *ords[8];
  if (ordering == pbspbfbf)
    {
      ords[0] = &pred_minus;
      ords[1] = &both_minus;
      ords[2] = &stat;
      ords[3] = &pred_pad;
      ords[4] = &both_pad;
      ords[5] = &forw_pad;
      ords[6] = &both_plus;
      ords[7] = &forw_plus;
    }
  else if (ordering == bfspbfpb)
    {
      ords[0] = &both_plus;
      ords[1] = &forw_plus;
      ords[2] = &stat;
      ords[3] = &pred_pad;
      ords[4] = &both_pad;
      ords[5] = &forw_pad;
      ords[6] = &pred_minus;
      ords[7] = &both_minus;
    }
  else // BEWARE: when implementing a new ordering, check also the code below setting y2outer
    throw ogu::Exception(__FILE__, __LINE__,
                         "Ordering not implemented in VarOrdering::do_general");

  // make der_atoms and positions
  int off = 0;
  for (auto &ord : ords)
    for (unsigned int j = 0; j < ord->size(); j++, off++)
      if ((*ord)[j] != -1)
        {
          der_atoms.push_back((*ord)[j]);
          positions.emplace((*ord)[j], off);
        }

  // set integer constants
  n_stat = stat.size();
  n_pred = pred_pad.size();
  n_both = both_pad.size();
  n_forw = forw_pad.size();

  // make y2outer mapping
  y2outer.insert(y2outer.end(), y2o_stat.begin(), y2o_stat.end());
  y2outer.insert(y2outer.end(), y2o_pred.begin(), y2o_pred.end());
  y2outer.insert(y2outer.end(), y2o_both.begin(), y2o_both.end());
  y2outer.insert(y2outer.end(), y2o_forw.begin(), y2o_forw.end());
  // make outer2y mapping
  outer2y.resize(y2outer.size(), -1);
  for (unsigned int i = 0; i < y2outer.size(); i++)
    outer2y[y2outer[i]] = i;
}

void
VarOrdering::do_increasing_time()
{
  // get maxlead and minlag of the variables
  int mlag, mlead;
  atoms.varspan(varnames, mlead, mlag);
  // setup the matrix of tree indices, if there is no occurrence,
  // the index is set to -1
  vector<int> ll_init(varnames.size(), -1);
  vector<vector<int>> tree_ind(mlead-mlag+1, ll_init);
  for (unsigned int iv = 0; iv < varnames.size(); iv++)
    {
      try
        {
          const DynamicAtoms::Tlagmap &lmap = atoms.lagmap(varnames[iv]);
          for (auto it : lmap)
            {
              int ll = it.first;
              int t = it.second;
              tree_ind[ll-mlag][iv] = t;
            }
        }
      catch (const ogu::Exception &e)
        {
          // ignore the error of not found variable in the tree
        }
    }

  // setup der_atoms and positions
  for (int ll = mlag; ll <= mlead; ll++)
    for (unsigned int iv = 0; iv < varnames.size(); iv++)
      {
        int t = tree_ind[ll-mlag][iv];
        if (t != -1)
          {
            der_atoms.push_back(t);
            int pos = (ll-mlag)*varnames.size() + iv;
            positions.emplace(t, pos);
          }
      }

  // set outer2y and y2outer to identities
  for (unsigned int iv = 0; iv < varnames.size(); iv++)
    {
      outer2y.push_back(iv);
      y2outer.push_back(iv);
    }

  // set n_stat, n_pred, n_both, and n_forw
  for (auto varname : varnames)
    {
      int mmlag, mmlead;
      atoms.varspan(varname, mmlead, mmlag);
      if (mmlead == 0 && mmlag == 0)
        n_stat++;
      else if (mmlead <= 0 && mmlag < 0)
        n_pred++;
      else if (mmlead > 0 && mmlag >= 0)
        n_forw++;
      else if (mmlead > 0 && mmlag < 0)
        n_both++;
      else if (mmlead < mmlag)
        // variable does not occur in the tree, cound as static
        n_stat++;
      else
        throw ogu::Exception(__FILE__, __LINE__,
                             "A wrong lag/lead of a variable in VarOrdering::do_increasing_time");
    }
}

void
VarOrdering::print() const
{
  std::cout << "nstat=" << n_stat << ", npred=" << n_pred << ", nboth=" << n_both
            << ", nforw=" << n_forw << "\n"
            << "der_atoms:\n";
  for (int der_atom : der_atoms)
    std::cout << " " << der_atom;
  std::cout << "\nmap:\n";
  for (auto position : positions)
    std::cout << " [" << position.first << u8"→" << position.second << "]";
  std::cout << "\ny2outer:\n";
  for (int i : y2outer)
    std::cout << " " <<  i;
  std::cout << "\nouter2y:\n";
  for (int i : outer2y)
    std::cout << " " << i;
  std::cout << "\n";
}