From 61632ef28fc8602dde3ca02b7b7a1a2a2042b7a2 Mon Sep 17 00:00:00 2001
From: Marco Ratto <marco.ratto@ec.europa.eu>
Date: Tue, 25 Jan 2022 10:27:47 +0100
Subject: [PATCH] marginal_density.m: make computation of log(det(sigma))
 robust numerically

---
 matlab/marginal_density.m | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/matlab/marginal_density.m b/matlab/marginal_density.m
index 489fb8cf61..8bca13e668 100644
--- a/matlab/marginal_density.m
+++ b/matlab/marginal_density.m
@@ -69,7 +69,14 @@ parameter_names = bayestopt_.name;
 save([M_.dname filesep 'Output' filesep M_.fname '_mean.mat'],'xparam1','hh','parameter_names','SIGMA');
 
 fprintf('Estimation::marginal density: I''m computing the posterior log marginal density (modified harmonic mean)... ');
-logdetSIGMA = log(det(SIGMA));
+try 
+    % use this robust option to avoid inf/nan
+    logdetSIGMA = 2*sum(log(diag(chol(SIGMA)))); 
+catch
+    % in case SIGMA is not positive definite
+    logdetSIGMA = nan;
+    fprintf('Estimation::marginal density: the covariance of MCMC draws is not positive definite. You may have too few MCMC draws.');
+end
 invSIGMA = hh;
 marginal = zeros(9,2);
 linee = 0;
-- 
GitLab