From 4aa1ff1f7358ab2e300d6787588afd61cbc8e1c6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Villemot?= <sebastien@dynare.org>
Date: Mon, 12 Dec 2022 13:17:16 +0100
Subject: [PATCH] Sparse representation: fix bug in output of indices in driver
 and JSON files

Jacobian column numbers were incorrect (it would return internal derivation
IDs).

Ref. dynare#1859
---
 src/ModelTree.hh | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/src/ModelTree.hh b/src/ModelTree.hh
index 6e2a6046..84a5d60b 100644
--- a/src/ModelTree.hh
+++ b/src/ModelTree.hh
@@ -2247,8 +2247,9 @@ ModelTree::writeDriverSparseIndicesHelper(ostream &output) const
       output << "M_." << model_name << "_g" << i << "_sparse_indices = int32([";
       for (const auto &[vidx, d] : derivatives[i])
         {
-          for (int it : vidx)
-            output << it+1 << ' ';
+          for (bool row_number {true}; // First element of vidx is row number
+               int it : vidx)
+            output << (exchange(row_number, false) ? it : getJacobianCol(it, true))+1 << ' ';
           output << ';' << endl;
         }
       output << "]);" << endl;
@@ -2304,9 +2305,10 @@ ModelTree::writeJsonSparseIndicesHelper(ostream &output) const
           for (bool printed_something2 {false};
                int it : vidx)
             {
-              if (exchange(printed_something2, true))
+              if (printed_something2)
                 output << ", ";
-              output << it+1;
+              // First element of vidx is row number
+              output << (exchange(printed_something2, true) ? getJacobianCol(it, true) : it)+1;
             }
           output << ']' << endl;
         }
-- 
GitLab