ExprNode.cc 50 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
 * Copyright (C) 2007-2008 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 <http://www.gnu.org/licenses/>.
 */

#include <iostream>
#include <iterator>
#include <algorithm>

24
#include <cmath>
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

#include "ExprNode.hh"
#include "DataTree.hh"

ExprNode::ExprNode(DataTree &datatree_arg) : datatree(datatree_arg)
{
  // Add myself to datatree
  datatree.node_list.push_back(this);

  // Set my index and increment counter
  idx = datatree.node_counter++;
}

ExprNode::~ExprNode()
{
}

NodeID
ExprNode::getDerivative(int varID)
{
  // Return zero if derivative is necessarily null (using symbolic a priori)
  set<int>::const_iterator it = non_null_derivatives.find(varID);
  if (it == non_null_derivatives.end())
    return datatree.Zero;

  // If derivative is stored in cache, use the cached value, otherwise compute it (and cache it)
  map<int, NodeID>::const_iterator it2 = derivatives.find(varID);
  if (it2 != derivatives.end())
    return it2->second;
  else
    {
      NodeID d = computeDerivative(varID);
      derivatives[varID] = d;
      return d;
    }
}

int
ExprNode::precedence(ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const
{
  // For a constant, a variable, or a unary op, the precedence is maximal
  return 100;
}

int
ExprNode::cost(const temporary_terms_type &temporary_terms, bool is_matlab) const
{
  // For a terminal node, the cost is null
  return 0;
}

void
ExprNode::computeTemporaryTerms(map<NodeID, int> &reference_count,
                                temporary_terms_type &temporary_terms,
                                bool is_matlab) const
{
  // Nothing to do for a terminal node
}

void
ExprNode::computeTemporaryTerms(map<NodeID, int> &reference_count,
                                temporary_terms_type &temporary_terms,
                                map<NodeID, int> &first_occurence,
                                int Curr_block,
                                Model_Block *ModelBlock,
                                map_idx_type &map_idx) const
{
  // Nothing to do for a terminal node
}

void
ExprNode::writeOutput(ostream &output)
{
  writeOutput(output, oMatlabOutsideModel, temporary_terms_type());
}

NumConstNode::NumConstNode(DataTree &datatree_arg, int id_arg) :
  ExprNode(datatree_arg),
  id(id_arg)
{
  // Add myself to the num const map
  datatree.num_const_node_map[id] = this;

  // All derivatives are null, so non_null_derivatives is left empty
}

NodeID
NumConstNode::computeDerivative(int varID)
{
  return datatree.Zero;
}

void
NumConstNode::writeOutput(ostream &output, ExprNodeOutputType output_type,
                          const temporary_terms_type &temporary_terms) const
{
  temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<NumConstNode *>(this));
  if (it != temporary_terms.end())
    if (output_type == oCDynamicModelSparseDLL)
      output << "T" << idx << "[it_]";
    else if (output_type == oMatlabDynamicModelSparse)
      output << "T" << idx << "(it_)";
    else
      output << "T" << idx;
  else
    output << datatree.num_constants.get(id);
}

double
NumConstNode::eval(const eval_context_type &eval_context) const throw (EvalException)
{
  return(datatree.num_constants.getDouble(id));
}

void
NumConstNode::compile(ofstream &CompileCode, bool lhs_rhs, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms, map_idx_type map_idx) const
{
  //CompileCode.write(reinterpret_cast<char *>(&FLDT), sizeof(FLDT));
  /*temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<NumConstNode *>(this));
  if (it != temporary_terms.end())
    {
      CompileCode.write(&FLDT, sizeof(FLDT));
      idl=
      CompileCode.write(reinterpret_cast<char *>(&idl),sizeof(idl));
    }
  else
    {*/
      CompileCode.write(&FLDC, sizeof(FLDC));
      double vard=atof(datatree.num_constants.get(id).c_str());
#ifdef DEBUGC
      cout << "FLDC " << vard << "\n";
#endif
      CompileCode.write(reinterpret_cast<char *>(&vard),sizeof(vard));
    /*}*/
}


void
163
NumConstNode::collectEndogenous(set<pair<int, int> > &result) const
164
165
166
{
}

ferhat's avatar
ferhat committed
167
168
169
170
171
172
void
NumConstNode::collectExogenous(set<pair<int, int> > &result) const
{
}


173
VariableNode::VariableNode(DataTree &datatree_arg, int symb_id_arg, SymbolType type_arg, int lag_arg) :
174
175
176
177
178
179
180
181
182
183
184
  ExprNode(datatree_arg),
  symb_id(symb_id_arg),
  type(type_arg),
  lag(lag_arg)
{
  // Add myself to the variable map
  datatree.variable_node_map[make_pair(make_pair(symb_id, type), lag)] = this;

  // Add myself to the variable table if necessary and initialize var_id
  if (type == eEndogenous
      || type == eExogenousDet
185
      || type == eExogenous)
186
187
188
189
    var_id = datatree.variable_table.addVariable(type, symb_id, lag);
  else
    var_id = -1;

sebastien's avatar
sebastien committed
190
191
192
193
  // It makes sense to allow a lead/lag on parameters: during steady state calibration, endogenous and parameters can be swapped
  if ((type == eModelLocalVariable || type == eModFileLocalVariable || type == eUnknownFunction) && lag != 0)
    {
      cerr << "Attempt to construct a VariableNode for local variable or unknown function with non-zero lead/lag" << endl;
194
      exit(EXIT_FAILURE);
sebastien's avatar
sebastien committed
195
196
    }

197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
  // Fill in non_null_derivatives
  switch(type)
    {
    case eEndogenous:
    case eExogenous:
    case eExogenousDet:
      // For a variable, the only non-null derivative is with respect to itself
      non_null_derivatives.insert(var_id);
      break;
    case eParameter:
      // All derivatives are null, do nothing
      break;
    case eModelLocalVariable:
      // Non null derivatives are those of the value of the local parameter
      non_null_derivatives = datatree.local_variables_table[symb_id]->non_null_derivatives;
      break;
    case eModFileLocalVariable:
      // Such a variable is never derived
      break;
    case eUnknownFunction:
      cerr << "Attempt to construct a VariableNode with an unknown function name" << endl;
218
      exit(EXIT_FAILURE);
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
    }
}

NodeID
VariableNode::computeDerivative(int varID)
{
  switch(type)
    {
    case eEndogenous:
    case eExogenous:
    case eExogenousDet:
      if (varID == var_id)
        return datatree.One;
      else
        return datatree.Zero;
    case eParameter:
      return datatree.Zero;
    case eModelLocalVariable:
      return datatree.local_variables_table[symb_id]->getDerivative(varID);
    case eModFileLocalVariable:
      cerr << "ModFileLocalVariable is not derivable" << endl;
240
      exit(EXIT_FAILURE);
241
242
    case eUnknownFunction:
      cerr << "Impossible case!" << endl;
243
      exit(EXIT_FAILURE);
244
245
    }
  cerr << "Impossible case!" << endl;
246
  exit(EXIT_FAILURE);
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
}

void
VariableNode::writeOutput(ostream &output, ExprNodeOutputType output_type,
                          const temporary_terms_type &temporary_terms) const
{
  // If node is a temporary term
#ifdef DEBUGC
  cout << "write_ouput output_type=" << output_type << "\n";
#endif
  temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<VariableNode *>(this));
  if (it != temporary_terms.end())
    {
      if (output_type == oCDynamicModelSparseDLL)
        output << "T" << idx << "[it_]";
      else if (output_type == oMatlabDynamicModelSparse)
        output << "T" << idx << "(it_)";
      else
        output << "T" << idx;
      return;
    }

  int i;
  switch(type)
    {
    case eParameter:
      if (output_type == oMatlabOutsideModel)
        output << "M_.params" << "(" << symb_id + 1 << ")";
      else
        output << "params" << LPAR(output_type) << symb_id + OFFSET(output_type) << RPAR(output_type);
      break;

    case eModelLocalVariable:
    case eModFileLocalVariable:
281
      if(output_type==oMatlabDynamicModelSparse || output_type==oMatlabStaticModelSparse)
282
283
284
        datatree.local_variables_table[symb_id]->writeOutput(output, output_type,temporary_terms);
      else
        output << datatree.symbol_table.getNameByID(type, symb_id);
285
286
287
288
289
290
291
      break;

    case eEndogenous:
      switch(output_type)
        {
        case oMatlabDynamicModel:
        case oCDynamicModel:
sebastien's avatar
sebastien committed
292
          i = datatree.variable_table.getDynJacobianCol(var_id) + OFFSET(output_type);
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
          output <<  "y" << LPAR(output_type) << i << RPAR(output_type);
          break;
        case oMatlabStaticModel:
        case oMatlabStaticModelSparse:
        case oCStaticModel:
          i = symb_id + OFFSET(output_type);
          output <<  "y" << LPAR(output_type) << i << RPAR(output_type);
          break;
        case oCDynamicModelSparseDLL:
          if (lag > 0)
            output << "y" << LPAR(output_type) << "(it_+" << lag << ")*y_size+" << symb_id << RPAR(output_type);
          else if (lag < 0)
            output << "y" << LPAR(output_type) << "(it_" << lag << ")*y_size+" << symb_id << RPAR(output_type);
          else
            output << "y" << LPAR(output_type) << "Per_y_+" << symb_id << RPAR(output_type);
          break;
        case oMatlabDynamicModelSparse:
          i = symb_id + OFFSET(output_type);
          if (lag > 0)
            output << "y" << LPAR(output_type) << "it_+" << lag << ", " << i << RPAR(output_type);
          else if (lag < 0)
            output << "y" << LPAR(output_type) << "it_" << lag << ", " << i << RPAR(output_type);
          else
            output << "y" << LPAR(output_type) << "it_, " << i << RPAR(output_type);
          break;
        case oMatlabOutsideModel:
          output << "oo_.steady_state" << "(" << symb_id + 1 << ")";
          break;
        }
      break;

    case eExogenous:
      i = symb_id + OFFSET(output_type);
      switch(output_type)
        {
        case oMatlabDynamicModel:
        case oMatlabDynamicModelSparse:
          if (lag > 0)
            output <<  "x(it_+" << lag << ", " << i << ")";
          else if (lag < 0)
            output <<  "x(it_" << lag << ", " << i << ")";
          else
            output <<  "x(it_, " << i << ")";
          break;
        case oCDynamicModel:
        case oCDynamicModelSparseDLL:
          if (lag == 0)
            output <<  "x[it_+" << i << "*nb_row_x]";
          else if (lag > 0)
            output <<  "x[it_+" << lag << "+" << i << "*nb_row_x]";
          else
            output <<  "x[it_" << lag << "+" << i << "*nb_row_x]";
          break;
        case oMatlabStaticModel:
        case oMatlabStaticModelSparse:
        case oCStaticModel:
          output << "x" << LPAR(output_type) << i << RPAR(output_type);
          break;
        case oMatlabOutsideModel:
          if (lag != 0)
            {
              cerr << "VariableNode::writeOutput: lag != 0 for exogenous variable outside model scope!" << endl;
355
              exit(EXIT_FAILURE);
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
            }
          output <<  "oo_.exo_steady_state" << "(" << i << ")";
          break;
        }
      break;

    case eExogenousDet:
      i = symb_id + datatree.symbol_table.exo_nbr + OFFSET(output_type);
      switch(output_type)
        {
        case oMatlabDynamicModel:
        case oMatlabDynamicModelSparse:
          if (lag > 0)
            output <<  "x(it_+" << lag << ", " << i << ")";
          else if (lag < 0)
            output <<  "x(it_" << lag << ", " << i << ")";
          else
            output <<  "x(it_, " << i << ")";
          break;
        case oCDynamicModel:
        case oCDynamicModelSparseDLL:
          if (lag == 0)
            output <<  "x[it_+" << i << "*nb_row_xd]";
          else if (lag > 0)
            output <<  "x[it_+" << lag << "+" << i << "*nb_row_xd]";
          else
            output <<  "x[it_" << lag << "+" << i << "*nb_row_xd]";
          break;
        case oMatlabStaticModel:
        case oMatlabStaticModelSparse:
        case oCStaticModel:
          output << "x" << LPAR(output_type) << i << RPAR(output_type);
          break;
        case oMatlabOutsideModel:
          if (lag != 0)
            {
              cerr << "VariableNode::writeOutput: lag != 0 for exogenous determistic variable outside model scope!" << endl;
393
              exit(EXIT_FAILURE);
394
395
396
397
398
399
400
401
            }
          output <<  "oo_.exo_det_steady_state" << "(" << symb_id + 1 << ")";
          break;
        }
      break;

    case eUnknownFunction:
      cerr << "Impossible case" << endl;
402
      exit(EXIT_FAILURE);
403
404
405
406
407
408
409
410
411
    }
}

double
VariableNode::eval(const eval_context_type &eval_context) const throw (EvalException)
{
  // ModelTree::evaluateJacobian need to have the initval values applied to lead/lagged variables also
  /*if (lag != 0)
    throw EvalException();*/
412
413
  /*if(type==eModelLocalVariable)
    cout << "eModelLocalVariable = " << symb_id << "\n";*/
414
415
  eval_context_type::const_iterator it = eval_context.find(make_pair(symb_id, type));
  if (it == eval_context.end())
416
417
418
419
    {
      //cout << "unknonw variable type = " << type << "  simb_id = " << symb_id << "\n";
      throw EvalException();
    }
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

  return it->second;
}

void
VariableNode::compile(ofstream &CompileCode, bool lhs_rhs, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms, map_idx_type map_idx) const
{
  // If node is a temporary term
  /*temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<VariableNode *>(this));
  if (it != temporary_terms.end())
    {
      CompileCode.write(&FLDT, sizeof(FLDT));
      int var=temporary_terms.count(const_cast<VariableNode *>(this))-1;
      CompileCode.write(reinterpret_cast<char *>(&var), sizeof(var));
      return;
    }*/
  int i, lagl;
#ifdef DEBUGC
  cout << "output_type=" << output_type << "\n";
#endif
  if(!lhs_rhs)
    CompileCode.write(&FLDV, sizeof(FLDV));
  else
    CompileCode.write(&FSTPV, sizeof(FSTPV));
  char typel=(char)type;
  CompileCode.write(&typel, sizeof(typel));
  switch(type)
    {
    case eParameter:
      i = symb_id + OFFSET(output_type);
      CompileCode.write(reinterpret_cast<char *>(&i), sizeof(i));
#ifdef DEBUGC
      cout << "FLD Param[ " << i << ", symb_id=" << symb_id << "]\n";
#endif
      break;
    case eEndogenous :
      i = symb_id + OFFSET(output_type);
      CompileCode.write(reinterpret_cast<char *>(&i), sizeof(i));
      lagl=lag;
      CompileCode.write(reinterpret_cast<char *>(&lagl), sizeof(lagl));
      break;
    case eExogenous :
      i = symb_id + OFFSET(output_type);
      CompileCode.write(reinterpret_cast<char *>(&i), sizeof(i));
      lagl=lag;
      CompileCode.write(reinterpret_cast<char *>(&lagl), sizeof(lagl));
      break;
    case eExogenousDet:
      i = symb_id + datatree.symbol_table.exo_nbr + OFFSET(output_type);
      CompileCode.write(reinterpret_cast<char *>(&i), sizeof(i));
      lagl=lag;
      CompileCode.write(reinterpret_cast<char *>(&lagl), sizeof(lagl));
      break;
    case eModelLocalVariable:
    case eModFileLocalVariable:
475
476
      datatree.local_variables_table[symb_id]->compile(CompileCode, lhs_rhs, output_type, temporary_terms, map_idx);
      break;
477
    case eUnknownFunction:
478
      cerr << "Impossible case: eUnknownFuncion" << endl;
479
      exit(EXIT_FAILURE);
480
481
482
483
    }
}

void
484
VariableNode::collectEndogenous(set<pair<int, int> > &result) const
485
486
{
  if (type == eEndogenous)
487
    result.insert(make_pair(symb_id, lag));
488
489
  else if (type == eModelLocalVariable)
    datatree.local_variables_table[symb_id]->collectEndogenous(result);
490
491
}

ferhat's avatar
ferhat committed
492
493
494
495
496
void
VariableNode::collectExogenous(set<pair<int, int> > &result) const
{
  if (type == eExogenous)
    result.insert(make_pair(symb_id, lag));
497
498
  else if (type == eModelLocalVariable)
    datatree.local_variables_table[symb_id]->collectExogenous(result);
ferhat's avatar
ferhat committed
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
UnaryOpNode::UnaryOpNode(DataTree &datatree_arg, UnaryOpcode op_code_arg, const NodeID arg_arg) :
  ExprNode(datatree_arg),
  arg(arg_arg),
  op_code(op_code_arg)
{
  // Add myself to the unary op map
  datatree.unary_op_node_map[make_pair(arg, op_code)] = this;

  // Non-null derivatives are those of the argument
  non_null_derivatives = arg->non_null_derivatives;
}

NodeID
UnaryOpNode::computeDerivative(int varID)
{
  NodeID darg = arg->getDerivative(varID);

  NodeID t11, t12, t13;

  switch(op_code)
    {
    case oUminus:
      return datatree.AddUMinus(darg);
    case oExp:
      return datatree.AddTimes(darg, this);
    case oLog:
      return datatree.AddDivide(darg, arg);
    case oLog10:
      t11 = datatree.AddExp(datatree.One);
      t12 = datatree.AddLog10(t11);
      t13 = datatree.AddDivide(darg, arg);
      return datatree.AddTimes(t12, t13);
    case oCos:
      t11 = datatree.AddSin(arg);
      t12 = datatree.AddUMinus(t11);
      return datatree.AddTimes(darg, t12);
    case oSin:
      t11 = datatree.AddCos(arg);
      return datatree.AddTimes(darg, t11);
    case oTan:
      t11 = datatree.AddTimes(this, this);
      t12 = datatree.AddPlus(t11, datatree.One);
      return datatree.AddTimes(darg, t12);
    case oAcos:
      t11 = datatree.AddSin(this);
      t12 = datatree.AddDivide(darg, t11);
      return datatree.AddUMinus(t12);
    case oAsin:
      t11 = datatree.AddCos(this);
      return datatree.AddDivide(darg, t11);
    case oAtan:
      t11 = datatree.AddTimes(arg, arg);
      t12 = datatree.AddPlus(datatree.One, t11);
      return datatree.AddDivide(darg, t12);
    case oCosh:
      t11 = datatree.AddSinH(arg);
      return datatree.AddTimes(darg, t11);
    case oSinh:
      t11 = datatree.AddCosH(arg);
      return datatree.AddTimes(darg, t11);
    case oTanh:
      t11 = datatree.AddTimes(this, this);
      t12 = datatree.AddMinus(datatree.One, t11);
      return datatree.AddTimes(darg, t12);
    case oAcosh:
      t11 = datatree.AddSinH(this);
      return datatree.AddDivide(darg, t11);
    case oAsinh:
      t11 = datatree.AddCosH(this);
      return datatree.AddDivide(darg, t11);
    case oAtanh:
      t11 = datatree.AddTimes(arg, arg);
      t12 = datatree.AddMinus(datatree.One, t11);
      return datatree.AddTimes(darg, t12);
    case oSqrt:
      t11 = datatree.AddPlus(this, this);
      return datatree.AddDivide(darg, t11);
    }
  cerr << "Impossible case!" << endl;
581
  exit(EXIT_FAILURE);
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
}

int
UnaryOpNode::cost(const temporary_terms_type &temporary_terms, bool is_matlab) const
{
  // For a temporary term, the cost is null
  temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<UnaryOpNode *>(this));
  if (it != temporary_terms.end())
    return 0;

  int cost = arg->cost(temporary_terms, is_matlab);

  if (is_matlab)
    // Cost for Matlab files
    switch(op_code)
      {
      case oUminus:
        return cost + 70;
      case oExp:
        return cost + 160;
      case oLog:
        return cost + 300;
      case oLog10:
        return cost + 16000;
      case oCos:
      case oSin:
      case oCosh:
        return cost + 210;
      case oTan:
        return cost + 230;
      case oAcos:
        return cost + 300;
      case oAsin:
        return cost + 310;
      case oAtan:
        return cost + 140;
      case oSinh:
        return cost + 240;
      case oTanh:
        return cost + 190;
      case oAcosh:
        return cost + 770;
      case oAsinh:
        return cost + 460;
      case oAtanh:
        return cost + 350;
      case oSqrt:
        return cost + 570;
      }
  else
    // Cost for C files
    switch(op_code)
      {
      case oUminus:
        return cost + 3;
      case oExp:
      case oAcosh:
        return cost + 210;
      case oLog:
        return cost + 137;
      case oLog10:
        return cost + 139;
      case oCos:
      case oSin:
        return cost + 160;
      case oTan:
        return cost + 170;
      case oAcos:
      case oAtan:
        return cost + 190;
      case oAsin:
        return cost + 180;
      case oCosh:
      case oSinh:
      case oTanh:
        return cost + 240;
      case oAsinh:
        return cost + 220;
      case oAtanh:
        return cost + 150;
      case oSqrt:
        return cost + 90;
      }
  cerr << "Impossible case!" << endl;
666
  exit(EXIT_FAILURE);
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
}

void
UnaryOpNode::computeTemporaryTerms(map<NodeID, int> &reference_count,
                                   temporary_terms_type &temporary_terms,
                                   bool is_matlab) const
{
  NodeID this2 = const_cast<UnaryOpNode *>(this);

  map<NodeID, int>::iterator it = reference_count.find(this2);
  if (it == reference_count.end())
    {
      reference_count[this2] = 1;
      arg->computeTemporaryTerms(reference_count, temporary_terms, is_matlab);
    }
  else
    {
      reference_count[this2]++;
      if (reference_count[this2] * cost(temporary_terms, is_matlab) > MIN_COST(is_matlab))
        temporary_terms.insert(this2);
    }
}

void
UnaryOpNode::computeTemporaryTerms(map<NodeID, int> &reference_count,
                                   temporary_terms_type &temporary_terms,
                                   map<NodeID, int> &first_occurence,
                                   int Curr_block,
                                   Model_Block *ModelBlock,
                                   map_idx_type &map_idx) const
{
  NodeID this2 = const_cast<UnaryOpNode *>(this);
  map<NodeID, int>::iterator it = reference_count.find(this2);
  if (it == reference_count.end())
    {
      reference_count[this2] = 1;
      first_occurence[this2] = Curr_block;
      arg->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, Curr_block, ModelBlock, map_idx);
    }
  else
    {
      reference_count[this2]++;
      if (reference_count[this2] * cost(temporary_terms, false) > MIN_COST_C)
        {
          temporary_terms.insert(this2);
          ModelBlock->Block_List[first_occurence[this2]].Temporary_terms->insert(this2);
        }
    }
}

void
UnaryOpNode::writeOutput(ostream &output, ExprNodeOutputType output_type,
                         const temporary_terms_type &temporary_terms) const
{
  // If node is a temporary term
  temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<UnaryOpNode *>(this));
  if (it != temporary_terms.end())
    {
      if (output_type == oCDynamicModelSparseDLL)
        output << "T" << idx << "[it_]";
      else if (output_type == oMatlabDynamicModelSparse)
        output << "T" << idx << "(it_)";
      else
        output << "T" << idx;
      return;
    }

  // Always put parenthesis around uminus nodes
  if (op_code == oUminus)
    output << "(";

  switch(op_code)
    {
    case oUminus:
      output << "-";
      break;
    case oExp:
      output << "exp";
      break;
    case oLog:
      output << "log";
      break;
    case oLog10:
      output << "log10";
      break;
    case oCos:
      output << "cos";
      break;
    case oSin:
      output << "sin";
      break;
    case oTan:
      output << "tan";
      break;
    case oAcos:
      output << "acos";
      break;
    case oAsin:
      output << "asin";
      break;
    case oAtan:
      output << "atan";
      break;
    case oCosh:
      output << "cosh";
      break;
    case oSinh:
      output << "sinh";
      break;
    case oTanh:
      output << "tanh";
      break;
    case oAcosh:
      output << "acosh";
      break;
    case oAsinh:
      output << "asinh";
      break;
    case oAtanh:
      output << "atanh";
      break;
    case oSqrt:
      output << "sqrt";
      break;
    }

  bool close_parenthesis = false;

  /* Enclose argument with parentheses if:
     - current opcode is not uminus, or
     - current opcode is uminus and argument has lowest precedence
  */
  if (op_code != oUminus
      || (op_code == oUminus
          && arg->precedence(output_type, temporary_terms) < precedence(output_type, temporary_terms)))
    {
      output << "(";
      close_parenthesis = true;
    }

  // Write argument
  arg->writeOutput(output, output_type, temporary_terms);

  if (close_parenthesis)
    output << ")";

  // Close parenthesis for uminus
  if (op_code == oUminus)
    output << ")";
}

double
UnaryOpNode::eval_opcode(UnaryOpcode op_code, double v) throw (EvalException)
{
  switch(op_code)
    {
    case oUminus:
      return(-v);
    case oExp:
      return(exp(v));
    case oLog:
      return(log(v));
    case oLog10:
      return(log10(v));
    case oCos:
      return(cos(v));
    case oSin:
      return(sin(v));
    case oTan:
      return(tan(v));
    case oAcos:
      return(acos(v));
    case oAsin:
      return(asin(v));
    case oAtan:
      return(atan(v));
    case oCosh:
      return(cosh(v));
    case oSinh:
      return(sinh(v));
    case oTanh:
      return(tanh(v));
    case oAcosh:
      return(acosh(v));
    case oAsinh:
      return(asinh(v));
    case oAtanh:
      return(atanh(v));
    case oSqrt:
      return(sqrt(v));
    }
  // Impossible
  throw EvalException();
}

double
UnaryOpNode::eval(const eval_context_type &eval_context) const throw (EvalException)
{
  double v = arg->eval(eval_context);

  return eval_opcode(op_code, v);
}

void
UnaryOpNode::compile(ofstream &CompileCode, bool lhs_rhs, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms, map_idx_type map_idx) const
{
  temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<UnaryOpNode *>(this));
  if (it != temporary_terms.end())
    {
      CompileCode.write(&FLDT, sizeof(FLDT));
      int var=map_idx[idx];
      CompileCode.write(reinterpret_cast<char *>(&var), sizeof(var));
      return;
    }
  arg->compile(CompileCode, lhs_rhs, output_type, temporary_terms, map_idx);
  CompileCode.write(&FUNARY, sizeof(FUNARY));
  UnaryOpcode op_codel=op_code;
  CompileCode.write(reinterpret_cast<char *>(&op_codel), sizeof(op_codel));
}

void
888
UnaryOpNode::collectEndogenous(set<pair<int, int> > &result) const
889
{
890
  arg->collectEndogenous(result);
891
892
}

ferhat's avatar
ferhat committed
893
894
895
896
897
898
899
void
UnaryOpNode::collectExogenous(set<pair<int, int> > &result) const
{
  arg->collectExogenous(result);
}


900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
BinaryOpNode::BinaryOpNode(DataTree &datatree_arg, const NodeID arg1_arg,
                           BinaryOpcode op_code_arg, const NodeID arg2_arg) :
  ExprNode(datatree_arg),
  arg1(arg1_arg),
  arg2(arg2_arg),
  op_code(op_code_arg)
{
  datatree.binary_op_node_map[make_pair(make_pair(arg1, arg2), op_code)] = this;

  // Non-null derivatives are the union of those of the arguments
  // Compute set union of arg1->non_null_derivatives and arg2->non_null_derivatives
  set_union(arg1->non_null_derivatives.begin(),
            arg1->non_null_derivatives.end(),
            arg2->non_null_derivatives.begin(),
            arg2->non_null_derivatives.end(),
            inserter(non_null_derivatives, non_null_derivatives.begin()));
}

NodeID
BinaryOpNode::computeDerivative(int varID)
{
  NodeID darg1 = arg1->getDerivative(varID);
  NodeID darg2 = arg2->getDerivative(varID);

  NodeID t11, t12, t13, t14, t15;

  switch(op_code)
    {
    case oPlus:
      return datatree.AddPlus(darg1, darg2);
    case oMinus:
      return datatree.AddMinus(darg1, darg2);
    case oTimes:
      t11 = datatree.AddTimes(darg1, arg2);
      t12 = datatree.AddTimes(darg2, arg1);
      return datatree.AddPlus(t11, t12);
    case oDivide:
      t11 = datatree.AddTimes(darg1, arg2);
      t12 = datatree.AddTimes(darg2, arg1);
      t13 = datatree.AddMinus(t11, t12);
      t14 = datatree.AddTimes(arg2, arg2);
      return datatree.AddDivide(t13, t14);
    case oLess:
    case oGreater:
    case oLessEqual:
    case oGreaterEqual:
    case oEqualEqual:
    case oDifferent:
      return datatree.Zero;
    case oPower:
      if (darg2 == datatree.Zero)
        {
          if (darg1 == datatree.Zero)
            return datatree.Zero;
          else
            {
              t11 = datatree.AddMinus(arg2, datatree.One);
              t12 = datatree.AddPower(arg1, t11);
              t13 = datatree.AddTimes(arg2, t12);
              return datatree.AddTimes(darg1, t13);
            }
        }
      else
        {
          t11 = datatree.AddLog(arg1);
          t12 = datatree.AddTimes(darg2, t11);
          t13 = datatree.AddTimes(darg1, arg2);
          t14 = datatree.AddDivide(t13, arg1);
          t15 = datatree.AddPlus(t12, t14);
          return datatree.AddTimes(t15, this);
        }
    case oMax:
      t11 = datatree.AddGreater(arg1,arg2);
      t12 = datatree.AddTimes(t11,darg1);
      t13 = datatree.AddMinus(datatree.One,t11);
      t14 = datatree.AddTimes(t13,darg2);
      return datatree.AddPlus(t14,t12);
    case oMin:
      t11 = datatree.AddGreater(arg2,arg1);
      t12 = datatree.AddTimes(t11,darg1);
      t13 = datatree.AddMinus(datatree.One,t11);
      t14 = datatree.AddTimes(t13,darg2);
      return datatree.AddPlus(t14,t12);
    case oEqual:
      return datatree.AddMinus(darg1, darg2);
    }
  cerr << "Impossible case!" << endl;
987
  exit(EXIT_FAILURE);
988
989
990
991
992
993
994
995
996
997
998
999
1000
}

int
BinaryOpNode::precedence(ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const
{
  temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<BinaryOpNode *>(this));
  // A temporary term behaves as a variable
  if (it != temporary_terms.end())
    return 100;

  switch(op_code)
    {
    case oEqual:
For faster browsing, not all history is shown. View entire blame