1 /*
2  * Copyright © 2003-2019 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 <http://www.gnu.org/licenses/>.
18  */
19 
20 #ifndef _SYMBOLTABLE_HH
21 #define _SYMBOLTABLE_HH
22 
23 using namespace std;
24 
25 #include <map>
26 #include <string>
27 #include <utility>
28 #include <vector>
29 #include <set>
30 #include <ostream>
31 
32 #include "CodeInterpreter.hh"
33 #include "ExprNode.hh"
34 
35 using expr_t = class ExprNode *;
36 
37 //! Types of auxiliary variables
38 enum class AuxVarType
39   {
40    endoLead = 0, //!< Substitute for endo leads >= 2
41    endoLag = 1, //!< Substitute for endo lags >= 2
42    exoLead = 2, //!< Substitute for exo leads >= 1
43    exoLag = 3, //!< Substitute for exo lags >= 1
44    expectation = 4, //!< Substitute for Expectation Operator
45    diffForward = 5, //!< Substitute for the differentiate of a forward variable
46    multiplier = 6, //!< Multipliers for FOC of Ramsey Problem
47    varModel = 7, //!< Variable for var_model with order > abs(min_lag()) present in model
48    diff = 8, //!< Variable for Diff operator
49    diffLag = 9, //!< Variable for timing between Diff operators
50    unaryOp = 10, //!< Variable for allowing the undiff operator to work when diff was taken of unary op, eg diff(log(x))
51    diffLead = 11 //!< Variable for timing between Diff operators
52   };
53 
54 //! Information on some auxiliary variables
55 class AuxVarInfo
56 {
57 private:
58   int symb_id; //!< Symbol ID of the auxiliary variable
59   AuxVarType type; //!< Its type
60   int orig_symb_id; //!< Symbol ID of the endo of the original model represented by this aux var. Only used for avEndoLag and avExoLag.
61   int orig_lead_lag; //!< Lead/lag of the endo of the original model represented by this aux var. Only used for avEndoLag and avExoLag.
62   int equation_number_for_multiplier; //!< Stores the original constraint equation number associated with this aux var. Only used for avMultiplier.
63   int information_set; //! Argument of expectation operator. Only used for avExpectation.
64   expr_t expr_node; //! Auxiliary variable definition
65   string unary_op; //! Used with AuxUnaryOp
66 public:
67   AuxVarInfo(int symb_id_arg, AuxVarType type_arg, int orig_symb_id, int orig_lead_lag, int equation_number_for_multiplier_arg, int information_set_arg, expr_t expr_node_arg, string unary_op_arg);
68   int
get_symb_id() const69   get_symb_id() const
70   {
71     return symb_id;
72   };
73   AuxVarType
get_type() const74   get_type() const
75   {
76     return type;
77   };
78   int
get_type_id() const79   get_type_id() const
80   {
81     return static_cast<int>(type);
82   }
83   int
get_orig_symb_id() const84   get_orig_symb_id() const
85   {
86     return orig_symb_id;
87   };
88   int
get_orig_lead_lag() const89   get_orig_lead_lag() const
90   {
91     return orig_lead_lag;
92   };
93   int
get_equation_number_for_multiplier() const94   get_equation_number_for_multiplier() const
95   {
96     return equation_number_for_multiplier;
97   };
98   int
get_information_set() const99   get_information_set() const
100   {
101     return information_set;
102   };
103   expr_t
get_expr_node() const104   get_expr_node() const
105   {
106     return expr_node;
107   };
108   string
get_unary_op() const109   get_unary_op() const
110   {
111     return unary_op;
112   };
113 };
114 
115 //! Stores the symbol table
116 /*!
117   A symbol is given by its name, and is internally represented by a unique integer.
118 
119   When method freeze() is called, computes a distinct sequence of IDs for some types
120   (endogenous, exogenous, parameters), which are used by the Matlab/Octave functions.
121   We call these "type specific IDs".
122 
123   Also manages a TeX name for each symbol, which by default is an empty string.
124 */
125 class SymbolTable
126 {
127 private:
128   //! Has method freeze() been called?
129   bool frozen{false};
130 
131   using symbol_table_type = map<string, int>;
132   //! Maps strings to symbol IDs
133   symbol_table_type symbol_table;
134 
135   //! Maps IDs to names
136   vector<string> name_table;
137   //! Maps IDs to TeX names
138   vector<string> tex_name_table;
139   //! Maps IDs to string names of variables
140   vector<string> long_name_table;
141   //! Maps IDs to a pair containing the partition and the partition value
142   map<int, map<string, string>> partition_value_map;
143   //! Maps IDs to types
144   vector<SymbolType> type_table;
145 
146   //! Maps symbol IDs to type specific IDs
147   vector<int> type_specific_ids;
148 
149   //! Maps type specific IDs of endogenous to symbol IDs
150   vector<int> endo_ids;
151   //! Maps type specific IDs of exogenous to symbol IDs
152   vector<int> exo_ids;
153   //! Maps type specific IDs of exogenous deterministic to symbol IDs
154   vector<int> exo_det_ids;
155   //! Maps type specific IDs of parameters to symbol IDs
156   vector<int> param_ids;
157   //! Information about auxiliary variables
158   vector<AuxVarInfo> aux_vars;
159 
160   //! Stores the predetermined variables (by symbol IDs)
161   set<int> predetermined_variables;
162 
163   //! Stores the list of observed variables
164   vector<int> varobs;
165 
166   //! Stores the list of observed exogenous variables
167   vector<int> varexobs;
168 
169 public:
170   //! Thrown when trying to access an unknown symbol (by name)
171   class UnknownSymbolNameException
172   {
173   public:
174     //! Symbol name
175     string name;
UnknownSymbolNameException(string name_arg)176     explicit UnknownSymbolNameException(string name_arg) : name{move(name_arg)}
177     {
178     }
179   };
180   //! Thrown when trying to access an unknown symbol (by id)
181   class UnknownSymbolIDException
182   {
183   public:
184     //! Symbol ID
185     int id;
UnknownSymbolIDException(int id_arg)186     explicit UnknownSymbolIDException(int id_arg) : id{id_arg}
187     {
188     }
189   };
190   //! Thrown when trying to access an unknown type specific ID
191   class UnknownTypeSpecificIDException
192   {
193   public:
194     int tsid;
195     SymbolType type;
UnknownTypeSpecificIDException(int tsid_arg,SymbolType type_arg)196     UnknownTypeSpecificIDException(int tsid_arg, SymbolType type_arg) : tsid{tsid_arg}, type{type_arg}
197     {
198     }
199   };
200   //! Thrown when trying to declare a symbol twice
201   class AlreadyDeclaredException
202   {
203   public:
204     //! Symbol name
205     string name;
206     //! Was the previous declaration done with the same symbol type ?
207     bool same_type;
AlreadyDeclaredException(string name_arg,bool same_type_arg)208     AlreadyDeclaredException(string name_arg, bool same_type_arg) : name{move(name_arg)}, same_type{same_type_arg}
209     {
210     }
211   };
212   //! Thrown when table is frozen and trying to modify it
213   class FrozenException
214   {
215   };
216   //! Thrown when trying to use the result of freeze() while this method has not yet been called
217   class NotYetFrozenException
218   {
219   };
220   //! Thrown when searchAuxiliaryVars() failed
221   class SearchFailedException
222   {
223   public:
224     int orig_symb_id, orig_lead_lag, symb_id;
SearchFailedException(int orig_symb_id_arg,int orig_lead_lag_arg)225     SearchFailedException(int orig_symb_id_arg, int orig_lead_lag_arg) : orig_symb_id{orig_symb_id_arg},
226                                                                          orig_lead_lag{orig_lead_lag_arg}
227     {
228     }
SearchFailedException(int symb_id_arg)229     explicit SearchFailedException(int symb_id_arg) : symb_id{symb_id_arg}
230     {
231     }
232   };
233 
234 private:
235   //! Factorized code for adding aux lag variables
236   int addLagAuxiliaryVarInternal(bool endo, int orig_symb_id, int orig_lead_lag, expr_t arg) noexcept(false);
237   //! Factorized code for adding aux lead variables
238   int addLeadAuxiliaryVarInternal(bool endo, int index, expr_t arg) noexcept(false);
239   //! Factorized code for Json writing
240   void writeJsonVarVector(ostream &output, const vector<int> &varvec) const;
241   //! Factorized code for asserting that 0 <= symb_id <= symbol_table.size()
242   inline void validateSymbID(int symb_id) const noexcept(false);
243 public:
244   //! Add a symbol
245   /*! Returns the symbol ID */
246   int addSymbol(const string &name, SymbolType type, const string &tex_name, const vector<pair<string, string>> &partition_value) noexcept(false);
247   //! Add a symbol without its TeX name (will be equal to its name)
248   /*! Returns the symbol ID */
249   int addSymbol(const string &name, SymbolType type) noexcept(false);
250   //! Adds an auxiliary variable for endogenous with lead >= 2
251   /*!
252     \param[in] index Used to construct the variable name
253     \return the symbol ID of the new symbol */
254   int addEndoLeadAuxiliaryVar(int index, expr_t arg) noexcept(false);
255   //! Adds an auxiliary variable for endogenous with lag >= 2
256   /*!
257     \param[in] orig_symb_id symbol ID of the endogenous declared by the user that this new variable will represent
258     \param[in] orig_lead_lag lag value such that this new variable will be equivalent to orig_symb_id(orig_lead_lag)
259     \return the symbol ID of the new symbol */
260   int addEndoLagAuxiliaryVar(int orig_symb_id, int orig_lead_lag, expr_t arg) noexcept(false);
261   //! Adds an auxiliary variable for endogenous with lead >= 1
262   /*!
263     \param[in] index Used to construct the variable name
264     \return the symbol ID of the new symbol */
265   int addExoLeadAuxiliaryVar(int index, expr_t arg) noexcept(false);
266   //! Adds an auxiliary variable for exogenous with lag >= 1
267   /*!
268     \param[in] orig_symb_id symbol ID of the exogenous declared by the user that this new variable will represent
269     \param[in] orig_lead_lag lag value such that this new variable will be equivalent to orig_symb_id(orig_lead_lag)
270     \return the symbol ID of the new symbol */
271   int addExoLagAuxiliaryVar(int orig_symb_id, int orig_lead_lag, expr_t arg) noexcept(false);
272   //! Adds an auxiliary variable for the expectation operator
273   /*!
274     \param[in] information_set information set (possibly negative) of the expectation operator
275     \param[in] index Used to construct the variable name
276     \return the symbol ID of the new symbol
277   */
278   int addExpectationAuxiliaryVar(int information_set, int index, expr_t arg) noexcept(false);
279   //! Adds an auxiliary variable for the multiplier for the FOCs of the Ramsey Problem
280   /*!
281     \param[in] index Used to construct the variable name
282     \return the symbol ID of the new symbol
283   */
284   int addMultiplierAuxiliaryVar(int index) noexcept(false);
285   //! Adds an auxiliary variable for the (time) differentiate of a forward var
286   /*!
287     \param[in] orig_symb_id The symb_id of the forward variable
288     \return the symbol ID of the new symbol
289   */
290   int addDiffForwardAuxiliaryVar(int orig_symb_id, expr_t arg) noexcept(false);
291   //! Searches auxiliary variables which are substitutes for a given symbol_id and lead/lag
292   /*!
293     The search is only performed among auxiliary variables of endo/exo lag.
294     \return the symbol ID of the auxiliary variable
295     Throws an exception if match not found.
296   */
297   int searchAuxiliaryVars(int orig_symb_id, int orig_lead_lag) const noexcept(false);
298   //! Serches aux_vars for the aux var represented by aux_var_symb_id and returns its associated orig_symb_id
299   int getOrigSymbIdForAuxVar(int aux_var_symb_id) const noexcept(false);
300   //! Searches for diff aux var and finds the original lag associated with this variable
301   int getOrigLeadLagForDiffAuxVar(int diff_aux_var_symb_id) const noexcept(false);
302   //! Searches for diff aux var and finds the symb id associated with this variable
303   int getOrigSymbIdForDiffAuxVar(int diff_aux_var_symb_id) const noexcept(false);
304   //! Adds an auxiliary variable when var_model is used with an order that is greater in absolute value
305   //! than the largest lag present in the model.
306   int addVarModelEndoLagAuxiliaryVar(int orig_symb_id, int orig_lead_lag, expr_t expr_arg) noexcept(false);
307   //! Adds an auxiliary variable when the diff operator is encountered
308   int addDiffAuxiliaryVar(int index, expr_t expr_arg) noexcept(false);
309   int addDiffAuxiliaryVar(int index, expr_t expr_arg, int orig_symb_id, int orig_lag) noexcept(false);
310   //! Takes care of timing between diff statements
311   int addDiffLagAuxiliaryVar(int index, expr_t expr_arg, int orig_symb_id, int orig_lag) noexcept(false);
312   //! Takes care of timing between diff statements
313   int addDiffLeadAuxiliaryVar(int index, expr_t expr_arg, int orig_symb_id, int orig_lead) noexcept(false);
314   //! An Auxiliary variable for a unary op
315   int addUnaryOpAuxiliaryVar(int index, expr_t expr_arg, string unary_op, int orig_symb_id = -1, int orig_lag = 0) noexcept(false);
316   //! Returns the number of auxiliary variables
317   int
AuxVarsSize() const318   AuxVarsSize() const
319   {
320     return aux_vars.size();
321   };
322   //! Retruns expr_node for an auxiliary variable
323   expr_t getAuxiliaryVarsExprNode(int symb_id) const noexcept(false);
324   //! Tests if symbol already exists
325   inline bool exists(const string &name) const;
326   //! Get symbol name (by ID)
327   inline string getName(int id) const noexcept(false);
328   //! Get TeX name
329   inline string getTeXName(int id) const noexcept(false);
330   //! Get long name
331   inline string getLongName(int id) const noexcept(false);
332   //! Returns true if the partition name is the first encountered for the type of variable represented by id
333   bool isFirstOfPartitionForType(int id) const noexcept(false);
334   //! Returns a list of partitions and symbols that belong to that partition
335   map<string, map<int, string>> getPartitionsForType(SymbolType st) const noexcept(false);
336   //! Get type (by ID)
337   inline SymbolType getType(int id) const noexcept(false);
338   //! Get type (by name)
339   inline SymbolType getType(const string &name) const noexcept(false);
340   //! Get ID (by name)
341   inline int getID(const string &name) const noexcept(false);
342   //! Get ID (by type specific ID)
343   int getID(SymbolType type, int tsid) const noexcept(false);
344   //! Freeze symbol table
345   void freeze() noexcept(false);
346   //! unreeze symbol table
347   //! Used after having written JSON files
348   void unfreeze();
349   //! Change the type of a symbol
350   void changeType(int id, SymbolType newtype) noexcept(false);
351   //! Get type specific ID (by symbol ID)
352   inline int getTypeSpecificID(int id) const noexcept(false);
353   //! Get type specific ID (by symbol name)
354   inline int getTypeSpecificID(const string &name) const noexcept(false);
355   //! Get number of endogenous variables
356   inline int endo_nbr() const noexcept(false);
357   //! Get number of exogenous variables
358   inline int exo_nbr() const noexcept(false);
359   //! Get number of exogenous deterministic variables
360   inline int exo_det_nbr() const noexcept(false);
361   //! Get number of parameters
362   inline int param_nbr() const noexcept(false);
363   //! Returns the greatest symbol ID (the smallest is zero)
364   inline int maxID();
365   //! Get number of user-declared endogenous variables (without the auxiliary variables)
366   inline int orig_endo_nbr() const noexcept(false);
367   //! Write output of this class
368   void writeOutput(ostream &output) const noexcept(false);
369   //! Write JSON Output
370   void writeJsonOutput(ostream &output) const;
371   //! Write Julia output of this class
372   void writeJuliaOutput(ostream &output) const noexcept(false);
373   //! Mark a symbol as predetermined variable
374   void markPredetermined(int symb_id) noexcept(false);
375   //! Test if a given symbol is a predetermined variable
376   bool isPredetermined(int symb_id) const noexcept(false);
377   //! Return the number of predetermined variables
378   int predeterminedNbr() const;
379   //! Add an observed variable
380   void addObservedVariable(int symb_id) noexcept(false);
381   //! Return the number of observed variables
382   int observedVariablesNbr() const;
383   //! Is a given symbol in the set of observed variables
384   bool isObservedVariable(int symb_id) const;
385   //! Return the index of a given observed variable in the vector of all observed variables
386   int getObservedVariableIndex(int symb_id) const;
387   //! Add an observed exogenous variable
388   void addObservedExogenousVariable(int symb_id) noexcept(false);
389   //! Return the number of observed exogenous variables
390   int observedExogenousVariablesNbr() const;
391   //! Is a given symbol in the set of observed exogenous variables
392   bool isObservedExogenousVariable(int symb_id) const;
393   //! Return the index of a given observed exogenous variable in the vector of all observed variables
394   int getObservedExogenousVariableIndex(int symb_id) const;
395   vector <int> getTrendVarIds() const;
396   //! Get list of exogenous variables
397   set <int> getExogenous() const;
398   //! Get list of exogenous variables
399   set <int> getObservedExogenous() const;
400   //! Get list of endogenous variables
401   set <int> getEndogenous() const;
402   //! Is a given symbol an auxiliary variable
403   bool isAuxiliaryVariable(int symb_id) const;
404   //! Is a given symbol an auxiliary variable but not a Lagrange multiplier
405   bool isAuxiliaryVariableButNotMultiplier(int symb_id) const;
406   //! Is a given symbol a diff, diff lead, or diff lag auxiliary variable
407   bool isDiffAuxiliaryVariable(int symb_id) const;
408   //! Get list of endogenous variables without aux vars
409   set <int> getOrigEndogenous() const;
410   //! Returns the original symbol corresponding to this variable
411   /* If symb_id is not an auxiliary var, returns symb_id. Otherwise,
412      repeatedly call getOrigSymbIDForAuxVar() until an original
413      (non-auxiliary) variable is found. */
414   int getUltimateOrigSymbID(int symb_id) const;
415   //! If this is a Lagrange multiplier, return its associated equation number; otherwise return -1
416   int getEquationNumberForMultiplier(int symb_id) const;
417 };
418 
419 inline void
validateSymbID(int symb_id) const420 SymbolTable::validateSymbID(int symb_id) const noexcept(false)
421 {
422   if (symb_id < 0 || symb_id > static_cast<int>(symbol_table.size()))
423     throw UnknownSymbolIDException(symb_id);
424 }
425 
426 inline bool
exists(const string & name) const427 SymbolTable::exists(const string &name) const
428 {
429   return symbol_table.find(name) != symbol_table.end();
430 }
431 
432 inline string
getName(int id) const433 SymbolTable::getName(int id) const noexcept(false)
434 {
435   validateSymbID(id);
436   return name_table[id];
437 }
438 
439 inline string
getTeXName(int id) const440 SymbolTable::getTeXName(int id) const noexcept(false)
441 {
442   validateSymbID(id);
443   return tex_name_table[id];
444 }
445 
446 inline string
getLongName(int id) const447 SymbolTable::getLongName(int id) const noexcept(false)
448 {
449   validateSymbID(id);
450   return long_name_table[id];
451 }
452 
453 inline SymbolType
getType(int id) const454 SymbolTable::getType(int id) const noexcept(false)
455 {
456   validateSymbID(id);
457   return type_table[id];
458 }
459 
460 inline SymbolType
getType(const string & name) const461 SymbolTable::getType(const string &name) const noexcept(false)
462 {
463   return getType(getID(name));
464 }
465 
466 inline int
getID(const string & name) const467 SymbolTable::getID(const string &name) const noexcept(false)
468 {
469   if (auto iter = symbol_table.find(name);
470       iter != symbol_table.end())
471     return iter->second;
472   else
473     throw UnknownSymbolNameException(name);
474 }
475 
476 inline int
getTypeSpecificID(int id) const477 SymbolTable::getTypeSpecificID(int id) const noexcept(false)
478 {
479   if (!frozen)
480     throw NotYetFrozenException();
481 
482   validateSymbID(id);
483 
484   return type_specific_ids[id];
485 }
486 
487 inline int
getTypeSpecificID(const string & name) const488 SymbolTable::getTypeSpecificID(const string &name) const noexcept(false)
489 {
490   return getTypeSpecificID(getID(name));
491 }
492 
493 inline int
endo_nbr() const494 SymbolTable::endo_nbr() const noexcept(false)
495 {
496   if (!frozen)
497     throw NotYetFrozenException();
498 
499   return endo_ids.size();
500 }
501 
502 inline int
exo_nbr() const503 SymbolTable::exo_nbr() const noexcept(false)
504 {
505   if (!frozen)
506     throw NotYetFrozenException();
507 
508   return exo_ids.size();
509 }
510 
511 inline int
exo_det_nbr() const512 SymbolTable::exo_det_nbr() const noexcept(false)
513 {
514   if (!frozen)
515     throw NotYetFrozenException();
516 
517   return exo_det_ids.size();
518 }
519 
520 inline int
param_nbr() const521 SymbolTable::param_nbr() const noexcept(false)
522 {
523   if (!frozen)
524     throw NotYetFrozenException();
525 
526   return param_ids.size();
527 }
528 
529 inline int
maxID()530 SymbolTable::maxID()
531 {
532   return symbol_table.size() - 1;
533 }
534 
535 inline int
orig_endo_nbr() const536 SymbolTable::orig_endo_nbr() const noexcept(false)
537 {
538   return endo_nbr() - aux_vars.size();
539 }
540 
541 #endif
542