From 627dd92c649dbb93057a9fe58ec03e1a7c216089 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Villemot?= <sebastien@dynare.org>
Date: Wed, 26 Oct 2022 17:33:26 +0200
Subject: [PATCH] Block decomposition: bugfix with temporary terms when mfs=3
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

In an “evaluate” block, the LHS of a renormalized equation (such as “log(x)=…”)
could be associated to a temporary term that would then be incorrectly
computed: that temporary term would be evaluated *before* (and not after) the
evaluation of the associated variable (“x” in the example).
---
 src/ModelTree.cc | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/src/ModelTree.cc b/src/ModelTree.cc
index c38ab8dd..4c13693d 100644
--- a/src/ModelTree.cc
+++ b/src/ModelTree.cc
@@ -988,7 +988,16 @@ ModelTree::computeBlockTemporaryTerms()
       blocks_temporary_terms[blk].resize(blocks[blk].size + 1);
       for (int eq = 0; eq < blocks[blk].size; eq++)
         {
-          if (eq < blocks[blk].getRecursiveSize() && isBlockEquationRenormalized(blk, eq))
+          /* It is important to compute temporary terms of the renormalized
+             equation if the latter is going to be used in the output files.
+             Otherwise, for an equation of the form log(x) = RHS, a temporary
+             term could be associated to log(x), and since it would be
+             associated to this equation, it would be printed and thus computed
+             *before* x is actually evaluated, and thus would be incorrect. */
+          if ((blocks[blk].simulation_type == BlockSimulationType::evaluateBackward
+               || blocks[blk].simulation_type == BlockSimulationType::evaluateForward
+               || eq < blocks[blk].getRecursiveSize())
+              && isBlockEquationRenormalized(blk, eq))
             getBlockEquationRenormalizedExpr(blk, eq)->computeBlockTemporaryTerms(blk, eq, blocks_temporary_terms, reference_count);
           else
             getBlockEquationExpr(blk, eq)->computeBlockTemporaryTerms(blk, eq, blocks_temporary_terms, reference_count);
-- 
GitLab