From b43d52278d881b06e507483d0183b2881543b42f Mon Sep 17 00:00:00 2001
From: Johannes Pfeifer <jpfeifer@gmx,de>
Date: Thu, 25 Sep 2014 08:48:35 +0200
Subject: [PATCH] Deal with NaN and Inf in Hessian of dynamic model

Checks for these cases in stochastic_solvers.m to prevent cryptic crashes in dll-files later on
---
 matlab/print_info.m         |  4 ++++
 matlab/stochastic_solvers.m | 24 ++++++++++++++++++++++++
 2 files changed, 28 insertions(+)

diff --git a/matlab/print_info.m b/matlab/print_info.m
index a4b775d39..0ec5e3788 100644
--- a/matlab/print_info.m
+++ b/matlab/print_info.m
@@ -68,6 +68,10 @@ if ~noprint
         error(['k_order_pert was unable to compute the solution'])
       case 10
         error(['The Jacobian of the dynamic model contains Inf. For more information, use options_.debug.'])
+      case 11
+        error('The Hessian of the dynamic model used for second order solutions must not contain Inf')
+      case 12
+        error('The Hessian of the dynamic model used for second order solutions must not contain NaN')
       case 19
         error('The steadystate file did not compute the steady state')
       case 20
diff --git a/matlab/stochastic_solvers.m b/matlab/stochastic_solvers.m
index 2738afc29..8f22a025c 100644
--- a/matlab/stochastic_solvers.m
+++ b/matlab/stochastic_solvers.m
@@ -113,6 +113,30 @@ elseif options_.order == 2
         hessian1 = sparse(hessian1(:,1), hessian1(:,2), hessian1(:,3), ...
                           size(jacobia_, 1), size(jacobia_, 2)*size(jacobia_, 2));
     end
+    [infrow,infcol]=find(isinf(hessian1));
+    if options_.debug
+        if ~isempty(infrow)     
+        fprintf('\nSTOCHASTIC_SOLVER: The Hessian of the dynamic model contains Inf.\n')
+        fprintf('STOCHASTIC_SOLVER: Try running model_diagnostics to find the source of the problem.\n')
+        save([M_.fname '_debug.mat'],'hessian1')
+        end
+    end
+    if ~isempty(infrow)
+        info(1)=11;
+        return
+    end
+    [nanrow,nancol]=find(isnan(hessian1));
+    if options_.debug
+        if ~isempty(nanrow)     
+            fprintf('\nSTOCHASTIC_SOLVER: The Hessian of the dynamic model contains NaN.\n')
+            fprintf('STOCHASTIC_SOLVER: Try running model_diagnostics to find the source of the problem.\n')
+            save([M_.fname '_debug.mat'],'hessian1')
+        end
+    end
+    if ~isempty(nanrow)
+        info(1)=12;
+        return
+    end    
 end
 
 [infrow,infcol]=find(isinf(jacobia_));
-- 
GitLab