From d5d6e8beb0f1f5d7f4118d7b5b2d08438a4d4925 Mon Sep 17 00:00:00 2001
From: Houtan Bastani <houtan@dynare.org>
Date: Thu, 23 Aug 2018 13:56:58 +0200
Subject: [PATCH] simplify updating of RHS variables for trend component and
 var models

---
 src/DynamicModel.cc | 31 +++++++++++++++++++++++++++++++
 src/DynamicModel.hh |  4 ++++
 src/ModFile.cc      |  3 +--
 3 files changed, 36 insertions(+), 2 deletions(-)

diff --git a/src/DynamicModel.cc b/src/DynamicModel.cc
index 3a5f78a1..1cc250a1 100644
--- a/src/DynamicModel.cc
+++ b/src/DynamicModel.cc
@@ -3455,6 +3455,37 @@ DynamicModel::runTrendTest(const eval_context_t &eval_context)
   testTrendDerivativesEqualToZero(eval_context);
 }
 
+void
+DynamicModel::updateVarAndTrendModelRhs() const
+{
+  for (int i = 0; i < 2; i++)
+    {
+      map<string, vector<int>> eqnums;
+      if (i == 0)
+        eqnums = var_model_table.getEqNums();
+      else if (i == 1)
+        eqnums = trend_component_model_table.getEqNums();
+
+      map<string, vector<set<pair<int, int>>>> rhsr;
+      for (const auto & it : eqnums)
+        {
+          vector<set<pair<int, int>>> rhs;
+          for (auto eqn : it.second)
+            {
+              set<pair<int, int>> rhs_set;
+              equations[eqn]->get_arg2()->collectDynamicVariables(SymbolType::endogenous, rhs_set);
+              rhs.push_back(rhs_set);
+            }
+          rhsr[it.first] = rhs;
+        }
+
+      if (i == 0)
+        var_model_table.setRhs(rhsr);
+      else if (i == 1)
+        trend_component_model_table.setRhs(rhsr);
+    }
+}
+
 void
 DynamicModel::fillVarModelTable() const
 {
diff --git a/src/DynamicModel.hh b/src/DynamicModel.hh
index da8d6397..30bdc162 100644
--- a/src/DynamicModel.hh
+++ b/src/DynamicModel.hh
@@ -312,6 +312,10 @@ public:
   void fillVarModelTable() const;
   void fillVarModelTableFromOrigModel(StaticModel &static_model) const;
 
+  //! Update the rhs references in the var model and trend component tables
+  //! after substitution of auxiliary variables
+  void updateVarAndTrendModelRhs() const;
+
   //! Add aux equations (and aux variables) for variables declared in var_model
   //! at max order if they don't already exist
   void addEquationsForVar();
diff --git a/src/ModFile.cc b/src/ModFile.cc
index 70e2eb65..77a071dc 100644
--- a/src/ModFile.cc
+++ b/src/ModFile.cc
@@ -580,8 +580,7 @@ ModFile::transformPass(bool nostrict, bool stochastic, bool compute_xrefs, const
       dynamic_model.substituteEndoLagGreaterThanTwo(true);
     }
 
-  dynamic_model.fillVarModelTable();
-  dynamic_model.fillTrendComponentModelTable();
+  dynamic_model.updateVarAndTrendModelRhs();
 
   if (differentiate_forward_vars)
     dynamic_model.differentiateForwardVars(differentiate_forward_vars_subset);
-- 
GitLab